{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== '免费Z-image图片生成' && linkText !== '免费Z-image图片生成' ) { link.textContent = '免费Z-image图片生成'; link.href = 'https://zimage.run'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== 'Vibevoice' ) { link.textContent = 'Vibevoice'; link.href = 'https://vibevoice.info/'; replacedLinks.add(link); } // 替换Pricing链接 - 仅替换一次 else if ( (linkHref.includes('/pricing') || linkHref === '/pricing' || linkText === 'Pricing' || linkText.match(/^s*Pricings*$/i)) && linkText !== '免费去水印' ) { link.textContent = '免费去水印'; link.href = 'https://sora2watermarkremover.net/'; replacedLinks.add(link); } // 替换Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) && linkText !== 'GitHub加速' ) { link.textContent = 'GitHub加速'; link.href = 'https://githubproxy.cc'; replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, '免费Z-image图片生成'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \\n\\n\\\"\\\"\\\"\\n\\n_TERM_COLORS = {\\\"256color\\\": ColorSystem.EIGHT_BIT, \\\"16color\\\": ColorSystem.STANDARD}\\n\\n\\n@dataclass\\nclass ConsoleOptions:\\n \\\"\\\"\\\"Options for __rich_console__ method.\\\"\\\"\\\"\\n\\n legacy_windows: bool\\n \\\"\\\"\\\"legacy_windows: flag for legacy windows.\\\"\\\"\\\"\\n min_width: int\\n \\\"\\\"\\\"Minimum width of renderable.\\\"\\\"\\\"\\n max_width: int\\n \\\"\\\"\\\"Maximum width of renderable.\\\"\\\"\\\"\\n is_terminal: bool\\n \\\"\\\"\\\"True if the target is a terminal, otherwise False.\\\"\\\"\\\"\\n encoding: str\\n \\\"\\\"\\\"Encoding of terminal.\\\"\\\"\\\"\\n justify: Optional[JustifyMethod] = None\\n \\\"\\\"\\\"Justify value override for renderable.\\\"\\\"\\\"\\n overflow: Optional[OverflowMethod] = None\\n \\\"\\\"\\\"Overflow value override for renderable.\\\"\\\"\\\"\\n no_wrap: Optional[bool] = False\\n \\\"\\\"\\\"\\\"Disable wrapping for text.\\\"\\\"\\\"\\n\\n @property\\n def ascii_only(self) -> bool:\\n \\\"\\\"\\\"Check if renderables should use ascii only.\\\"\\\"\\\"\\n return not self.encoding.startswith(\\\"utf\\\")\\n\\n def update(\\n self,\\n width: int = None,\\n min_width: int = None,\\n max_width: int = None,\\n justify: JustifyMethod = None,\\n overflow: OverflowMethod = None,\\n no_wrap: bool = None,\\n ) -> \\\"ConsoleOptions\\\":\\n \\\"\\\"\\\"Update values, return a copy.\\\"\\\"\\\"\\n options = replace(self)\\n if width is not None:\\n options.min_width = options.max_width = width\\n if min_width is not None:\\n options.min_width = min_width\\n if max_width is not None:\\n options.max_width = max_width\\n if justify is not None:\\n options.justify = justify\\n if overflow is not None:\\n options.overflow = overflow\\n if no_wrap is not None:\\n options.no_wrap = no_wrap\\n return options\\n\\n\\n@runtime_checkable\\nclass RichCast(Protocol):\\n \\\"\\\"\\\"An object that may be 'cast' to a console renderable.\\\"\\\"\\\"\\n\\n def __rich__(self) -> Union[\\\"ConsoleRenderable\\\", str]: # pragma: no cover\\n ...\\n\\n\\n@runtime_checkable\\nclass ConsoleRenderable(Protocol):\\n \\\"\\\"\\\"An object that supports the console protocol.\\\"\\\"\\\"\\n\\n def __rich_console__(\\n self, console: \\\"Console\\\", options: \\\"ConsoleOptions\\\"\\n ) -> \\\"RenderResult\\\": # pragma: no cover\\n ...\\n\\n\\nRenderableType = Union[ConsoleRenderable, RichCast, str]\\n\\\"\\\"\\\"A type that may be rendered by Console.\\\"\\\"\\\"\\n\\nRenderResult = Iterable[Union[RenderableType, Segment]]\\n\\\"\\\"\\\"The result of calling a __rich_console__ method.\\\"\\\"\\\"\\n\\n\\n_null_highlighter = NullHighlighter()\\n\\n\\nclass CaptureError(Exception):\\n \\\"\\\"\\\"An error in the Capture context manager.\\\"\\\"\\\"\\n\\n\\nclass Capture:\\n \\\"\\\"\\\"Context manager to capture the result of printing to the console.\\n See :meth:`~rich.console.Console.capture` for how to use.\\n\\n Args:\\n console (Console): A console instance to capture output.\\n \\\"\\\"\\\"\\n\\n def __init__(self, console: \\\"Console\\\") -> None:\\n self._console = console\\n self._result: Optional[str] = None\\n\\n def __enter__(self) -> \\\"Capture\\\":\\n self._console.begin_capture()\\n return self\\n\\n def __exit__(self, exc_type, exc_val, exc_tb) -> None:\\n self._result = self._console.end_capture()\\n\\n def get(self) -> str:\\n \\\"\\\"\\\"Get the result of the capture.\\\"\\\"\\\"\\n if self._result is None:\\n raise CaptureError(\\n \\\"Capture result is not available until context manager exits.\\\"\\n )\\n return self._result\\n\\n\\nclass ThemeContext:\\n \\\"\\\"\\\"A context manager to use a temporary theme. See :meth:`~rich.console.Console.theme` for usage.\\\"\\\"\\\"\\n\\n def __init__(self, console: \\\"Console\\\", theme: Theme, inherit: bool = True) -> None:\\n self.console = console\\n self.theme = theme\\n self.inherit = inherit\\n\\n def __enter__(self) -> \\\"ThemeContext\\\":\\n self.console.push_theme(self.theme)\\n return self\\n\\n def __exit__(self, exc_type, exc_val, exc_tb) -> None:\\n self.console.pop_theme()\\n\\n\\nclass PagerContext:\\n \\\"\\\"\\\"A context manager that 'pages' content. See :meth:`~rich.console.Console.pager` for usage.\\\"\\\"\\\"\\n\\n def __init__(\\n self,\\n console: \\\"Console\\\",\\n pager: Pager = None,\\n styles: bool = False,\\n links: bool = False,\\n ) -> None:\\n self._console = console\\n self.pager = SystemPager() if pager is None else pager\\n self.styles = styles\\n self.links = links\\n\\n def __enter__(self) -> \\\"PagerContext\\\":\\n self._console._enter_buffer()\\n return self\\n\\n def __exit__(self, exc_type, exc_val, exc_tb) -> None:\\n if exc_type is None:\\n with self._console._lock:\\n buffer: List[Segment] = self._console._buffer[:]\\n del self._console._buffer[:]\\n segments: Iterable[Segment] = buffer\\n if not self.styles:\\n segments = Segment.strip_styles(segments)\\n elif not self.links:\\n segments = Segment.strip_links(segments)\\n content = self._console._render_buffer(segments)\\n self.pager.show(content)\\n self._console._exit_buffer()\\n\\n\\nclass RenderGroup:\\n \\\"\\\"\\\"Takes a group of renderables and returns a renderable object that renders the group.\\n\\n Args:\\n renderables (Iterable[RenderableType]): An iterable of renderable objects.\\n\\n \\\"\\\"\\\"\\n\\n def __init__(self, *renderables: \\\"RenderableType\\\", fit: bool = True) -> None:\\n self._renderables = renderables\\n self.fit = fit\\n self._render: Optional[List[RenderableType]] = None\\n\\n @property\\n def renderables(self) -> List[\\\"RenderableType\\\"]:\\n if self._render is None:\\n self._render = list(self._renderables)\\n return self._render\\n\\n def __rich_measure__(self, console: \\\"Console\\\", max_width: int) -> \\\"Measurement\\\":\\n if self.fit:\\n return measure_renderables(console, self.renderables, max_width)\\n else:\\n return Measurement(max_width, max_width)\\n\\n def __rich_console__(\\n self, console: \\\"Console\\\", options: \\\"ConsoleOptions\\\"\\n ) -> RenderResult:\\n yield from self.renderables\\n\\n\\ndef render_group(fit: bool = False) -> Callable:\\n \\\"\\\"\\\"A decorator that turns an iterable of renderables in to a group.\\\"\\\"\\\"\\n\\n def decorator(method):\\n \\\"\\\"\\\"Convert a method that returns an iterable of renderables in to a RenderGroup.\\\"\\\"\\\"\\n\\n @wraps(method)\\n def _replace(*args, **kwargs):\\n renderables = method(*args, **kwargs)\\n return RenderGroup(*renderables, fit=fit)\\n\\n return _replace\\n\\n return decorator\\n\\n\\nclass ConsoleDimensions(NamedTuple):\\n \\\"\\\"\\\"Size of the terminal.\\\"\\\"\\\"\\n\\n width: int\\n \\\"\\\"\\\"The width of the console in 'cells'.\\\"\\\"\\\"\\n height: int\\n \\\"\\\"\\\"The height of the console in lines.\\\"\\\"\\\"\\n\\n\\ndef _is_jupyter() -> bool: # pragma: no cover\\n \\\"\\\"\\\"Check if we're running in a Jupyter notebook.\\\"\\\"\\\"\\n try:\\n get_ipython # type: ignore\\n except NameError:\\n return False\\n shell = get_ipython().__class__.__name__ # type: ignore\\n if shell == \\\"ZMQInteractiveShell\\\":\\n return True # Jupyter notebook or qtconsole\\n elif shell == \\\"TerminalInteractiveShell\\\":\\n return False # Terminal running IPython\\n else:\\n return False # Other type (?)\\n\\n\\nCOLOR_SYSTEMS = {\\n \\\"standard\\\": ColorSystem.STANDARD,\\n \\\"256\\\": ColorSystem.EIGHT_BIT,\\n \\\"truecolor\\\": ColorSystem.TRUECOLOR,\\n \\\"windows\\\": ColorSystem.WINDOWS,\\n}\\n\\n\\n_COLOR_SYSTEMS_NAMES = {system: name for name, system in COLOR_SYSTEMS.items()}\\n\\n\\n@dataclass\\nclass ConsoleThreadLocals(threading.local):\\n \\\"\\\"\\\"Thread local values for Console context.\\\"\\\"\\\"\\n\\n theme_stack: ThemeStack\\n buffer: List[Segment] = field(default_factory=list)\\n buffer_index: int = 0\\n\\n\\nclass RenderHook(ABC):\\n \\\"\\\"\\\"Provides hooks in to the render process.\\\"\\\"\\\"\\n\\n @abstractmethod\\n def process_renderables(\\n self, renderables: List[ConsoleRenderable]\\n ) -> List[ConsoleRenderable]:\\n \\\"\\\"\\\"Called with a list of objects to render.\\n\\n This method can return a new list of renderables, or modify and return the same list.\\n\\n Args:\\n renderables (List[ConsoleRenderable]): A number of renderable objects.\\n\\n Returns:\\n List[ConsoleRenderable]: A replacement list of renderables.\\n \\\"\\\"\\\"\\n\\n\\n_windows_console_features: Optional[\\\"WindowsConsoleFeatures\\\"] = None\\n\\n\\ndef get_windows_console_features() -> \\\"WindowsConsoleFeatures\\\": # pragma: no cover\\n global _windows_console_features\\n if _windows_console_features is not None:\\n return _windows_console_features\\n from ._windows import get_windows_console_features\\n\\n _windows_console_features = get_windows_console_features()\\n return _windows_console_features\\n\\n\\ndef detect_legacy_windows() -> bool:\\n \\\"\\\"\\\"Detect legacy Windows.\\\"\\\"\\\"\\n return WINDOWS and not get_windows_console_features().vt\\n\\n\\nif detect_legacy_windows(): # pragma: no cover\\n from colorama import init\\n\\n init()\\n\\n\\nclass Console:\\n \\\"\\\"\\\"A high level console interface.\\n\\n Args:\\n color_system (str, optional): The color system supported by your terminal,\\n either ``\\\"standard\\\"``, ``\\\"256\\\"`` or ``\\\"truecolor\\\"``. Leave as ``\\\"auto\\\"`` to autodetect.\\n force_terminal (Optional[bool], optional): Enable/disable terminal control codes, or None to auto-detect terminal. Defaults to None.\\n force_jupyter (Optional[bool], optional): Enable/disable Jupyter rendering, or None to auto-detect Jupyter. Defaults to None.\\n theme (Theme, optional): An optional style theme object, or ``None`` for default theme.\\n file (IO, optional): A file object where the console should write to. Defaults to stdout.\\n width (int, optional): The width of the terminal. Leave as default to auto-detect width.\\n height (int, optional): The height of the terminal. Leave as default to auto-detect height.\\n record (bool, optional): Boolean to enable recording of terminal output,\\n required to call :meth:`export_html` and :meth:`export_text`. Defaults to False.\\n markup (bool, optional): Boolean to enable :ref:`console_markup`. Defaults to True.\\n emoji (bool, optional): Enable emoji code. Defaults to True.\\n highlight (bool, optional): Enable automatic highlighting. Defaults to True.\\n log_time (bool, optional): Boolean to enable logging of time by :meth:`log` methods. Defaults to True.\\n log_path (bool, optional): Boolean to enable the logging of the caller by :meth:`log`. Defaults to True.\\n log_time_format (str, optional): Log time format if ``log_time`` is enabled. Defaults to \\\"[%X] \\\".\\n highlighter (HighlighterType, optional): Default highlighter.\\n legacy_windows (bool, optional): Enable legacy Windows mode, or ``None`` to auto detect. Defaults to ``None``.\\n safe_box (bool, optional): Restrict box options that don't render on legacy Windows.\\n \\\"\\\"\\\"\\n\\n def __init__(\\n self,\\n *,\\n color_system: Optional[\\n Literal[\\\"auto\\\", \\\"standard\\\", \\\"256\\\", \\\"truecolor\\\", \\\"windows\\\"]\\n ] = \\\"auto\\\",\\n force_terminal: bool = None,\\n force_jupyter: bool = None,\\n theme: Theme = None,\\n file: IO[str] = None,\\n width: int = None,\\n height: int = None,\\n tab_size: int = 8,\\n record: bool = False,\\n markup: bool = True,\\n emoji: bool = True,\\n highlight: bool = True,\\n log_time: bool = True,\\n log_path: bool = True,\\n log_time_format: str = \\\"[%X]\\\",\\n highlighter: Optional[\\\"HighlighterType\\\"] = ReprHighlighter(),\\n legacy_windows: bool = None,\\n safe_box: bool = True,\\n _environ: Dict[str, str] = None,\\n ):\\n # Copy of os.environ allows us to replace it for testing\\n self._environ = os.environ if _environ is None else _environ\\n\\n self.is_jupyter = _is_jupyter() if force_jupyter is None else force_jupyter\\n if self.is_jupyter:\\n width = width or 93\\n height = height or 100\\n self._width = width\\n self._height = height\\n self.tab_size = tab_size\\n self.record = record\\n self._markup = markup\\n self._emoji = emoji\\n self._highlight = highlight\\n self.legacy_windows: bool = (\\n (detect_legacy_windows() and not self.is_jupyter)\\n if legacy_windows is None\\n else legacy_windows\\n )\\n\\n self._color_system: Optional[ColorSystem]\\n self._force_terminal = force_terminal\\n self.file = file or sys.stdout\\n\\n if color_system is None:\\n self._color_system = None\\n elif color_system == \\\"auto\\\":\\n self._color_system = self._detect_color_system()\\n else:\\n self._color_system = COLOR_SYSTEMS[color_system]\\n\\n self._lock = threading.RLock()\\n self._log_render = LogRender(\\n show_time=log_time,\\n show_path=log_path,\\n time_format=log_time_format,\\n )\\n self.highlighter: HighlighterType = highlighter or _null_highlighter\\n self.safe_box = safe_box\\n\\n self._record_buffer_lock = threading.RLock()\\n self._thread_locals = ConsoleThreadLocals(\\n theme_stack=ThemeStack(themes.DEFAULT if theme is None else theme)\\n )\\n self._record_buffer: List[Segment] = []\\n self._render_hooks: List[RenderHook] = []\\n\\n def __repr__(self) -> str:\\n return f\\\"\\\"\\n\\n @property\\n def _buffer(self) -> List[Segment]:\\n \\\"\\\"\\\"Get a thread local buffer.\\\"\\\"\\\"\\n return self._thread_locals.buffer\\n\\n @property\\n def _buffer_index(self) -> int:\\n \\\"\\\"\\\"Get a thread local buffer.\\\"\\\"\\\"\\n return self._thread_locals.buffer_index\\n\\n @_buffer_index.setter\\n def _buffer_index(self, value: int) -> None:\\n self._thread_locals.buffer_index = value\\n\\n @property\\n def _theme_stack(self) -> ThemeStack:\\n \\\"\\\"\\\"Get the thread local theme stack.\\\"\\\"\\\"\\n return self._thread_locals.theme_stack\\n\\n def _detect_color_system(self) -> Optional[ColorSystem]:\\n \\\"\\\"\\\"Detect color system from env vars.\\\"\\\"\\\"\\n if self.is_jupyter:\\n return ColorSystem.TRUECOLOR\\n if not self.is_terminal or \\\"NO_COLOR\\\" in self._environ or self.is_dumb_terminal:\\n return None\\n if WINDOWS: # pragma: no cover\\n if self.legacy_windows: # pragma: no cover\\n return ColorSystem.WINDOWS\\n windows_console_features = get_windows_console_features()\\n return (\\n ColorSystem.TRUECOLOR\\n if windows_console_features.truecolor\\n else ColorSystem.EIGHT_BIT\\n )\\n else:\\n color_term = self._environ.get(\\\"COLORTERM\\\", \\\"\\\").strip().lower()\\n if color_term in (\\\"truecolor\\\", \\\"24bit\\\"):\\n return ColorSystem.TRUECOLOR\\n term = self._environ.get(\\\"TERM\\\", \\\"\\\").strip().lower()\\n _term_name, _hyphen, colors = term.partition(\\\"-\\\")\\n color_system = _TERM_COLORS.get(colors, ColorSystem.STANDARD)\\n return color_system\\n\\n def _enter_buffer(self) -> None:\\n \\\"\\\"\\\"Enter in to a buffer context, and buffer all output.\\\"\\\"\\\"\\n self._buffer_index += 1\\n\\n def _exit_buffer(self) -> None:\\n \\\"\\\"\\\"Leave buffer context, and render content if required.\\\"\\\"\\\"\\n self._buffer_index -= 1\\n self._check_buffer()\\n\\n def push_render_hook(self, hook: RenderHook) -> None:\\n \\\"\\\"\\\"Add a new render hook to the stack.\\n\\n Args:\\n hook (RenderHook): Render hook instance.\\n \\\"\\\"\\\"\\n\\n self._render_hooks.append(hook)\\n\\n def pop_render_hook(self) -> None:\\n \\\"\\\"\\\"Pop the last renderhook from the stack.\\\"\\\"\\\"\\n self._render_hooks.pop()\\n\\n def __enter__(self) -> \\\"Console\\\":\\n \\\"\\\"\\\"Own context manager to enter buffer context.\\\"\\\"\\\"\\n self._enter_buffer()\\n return self\\n\\n def __exit__(self, exc_type, exc_value, traceback) -> None:\\n \\\"\\\"\\\"Exit buffer context.\\\"\\\"\\\"\\n self._exit_buffer()\\n\\n def begin_capture(self) -> None:\\n \\\"\\\"\\\"Begin capturing console output. Call :meth:`end_capture` to exit capture mode and return output.\\\"\\\"\\\"\\n self._enter_buffer()\\n\\n def end_capture(self) -> str:\\n \\\"\\\"\\\"End capture mode and return captured string.\\n\\n Returns:\\n str: Console output.\\n \\\"\\\"\\\"\\n render_result = self._render_buffer(self._buffer)\\n del self._buffer[:]\\n self._exit_buffer()\\n return render_result\\n\\n def push_theme(self, theme: Theme, *, inherit: bool = True) -> None:\\n \\\"\\\"\\\"Push a new theme on to the top of the stack, replacing the styles from the previous theme.\\n Generally speaking, you should call :meth:`~rich.console.Console.use_theme` to get a context manager, rather\\n than calling this method directly.\\n\\n Args:\\n theme (Theme): A theme instance.\\n inherit (bool, optional): Inherit existing styles. Defaults to True.\\n \\\"\\\"\\\"\\n self._theme_stack.push_theme(theme, inherit=inherit)\\n\\n def pop_theme(self) -> None:\\n \\\"\\\"\\\"Remove theme from top of stack, restoring previous theme.\\\"\\\"\\\"\\n self._theme_stack.pop_theme()\\n\\n def use_theme(self, theme: Theme, *, inherit: bool = True) -> ThemeContext:\\n \\\"\\\"\\\"Use a different theme for the duration of the context manager.\\n\\n Args:\\n theme (Theme): Theme instance to user.\\n inherit (bool, optional): Inherit existing console styles. Defaults to True.\\n\\n Returns:\\n ThemeContext: [description]\\n \\\"\\\"\\\"\\n return ThemeContext(self, theme, inherit)\\n\\n @property\\n def color_system(self) -> Optional[str]:\\n \\\"\\\"\\\"Get color system string.\\n\\n Returns:\\n Optional[str]: \\\"standard\\\", \\\"256\\\" or \\\"truecolor\\\".\\n \\\"\\\"\\\"\\n\\n if self._color_system is not None:\\n return _COLOR_SYSTEMS_NAMES[self._color_system]\\n else:\\n return None\\n\\n @property\\n def encoding(self) -> str:\\n \\\"\\\"\\\"Get the encoding of the console file, e.g. ``\\\"utf-8\\\"``.\\n\\n Returns:\\n str: A standard encoding string.\\n \\\"\\\"\\\"\\n return (getattr(self.file, \\\"encoding\\\", \\\"utf-8\\\") or \\\"utf-8\\\").lower()\\n\\n @property\\n def is_terminal(self) -> bool:\\n \\\"\\\"\\\"Check if the console is writing to a terminal.\\n\\n Returns:\\n bool: True if the console writing to a device capable of\\n understanding terminal codes, otherwise False.\\n \\\"\\\"\\\"\\n if self._force_terminal is not None:\\n return self._force_terminal\\n isatty = getattr(self.file, \\\"isatty\\\", None)\\n return False if isatty is None else isatty()\\n\\n @property\\n def is_dumb_terminal(self) -> bool:\\n \\\"\\\"\\\"Detect dumb terminal.\\n\\n Returns:\\n bool: True if writing to a dumb terminal, otherwise False.\\n\\n \\\"\\\"\\\"\\n _term = self._environ.get(\\\"TERM\\\", \\\"\\\")\\n is_dumb = _term.lower() in (\\\"dumb\\\", \\\"unknown\\\")\\n return self.is_terminal and is_dumb\\n\\n @property\\n def options(self) -> ConsoleOptions:\\n \\\"\\\"\\\"Get default console options.\\\"\\\"\\\"\\n return ConsoleOptions(\\n legacy_windows=self.legacy_windows,\\n min_width=1,\\n max_width=self.width,\\n encoding=self.encoding,\\n is_terminal=self.is_terminal,\\n )\\n\\n @property\\n def size(self) -> ConsoleDimensions:\\n \\\"\\\"\\\"Get the size of the console.\\n\\n Returns:\\n ConsoleDimensions: A named tuple containing the dimensions.\\n \\\"\\\"\\\"\\n\\n if self._width is not None and self._height is not None:\\n return ConsoleDimensions(self._width, self._height)\\n\\n if self.is_dumb_terminal:\\n return ConsoleDimensions(80, 25)\\n\\n width, height = shutil.get_terminal_size()\\n # get_terminal_size can report 0, 0 if run from pseudo-terminal\\n width = width or 80\\n height = height or 25\\n return ConsoleDimensions(\\n (width - self.legacy_windows) if self._width is None else self._width,\\n height if self._height is None else self._height,\\n )\\n\\n @property\\n def width(self) -> int:\\n \\\"\\\"\\\"Get the width of the console.\\n\\n Returns:\\n int: The width (in characters) of the console.\\n \\\"\\\"\\\"\\n width, _ = self.size\\n return width\\n\\n def bell(self) -> None:\\n \\\"\\\"\\\"Play a 'bell' sound (if supported by the terminal).\\\"\\\"\\\"\\n self.control(\\\"\\\\x07\\\")\\n\\n def capture(self) -> Capture:\\n \\\"\\\"\\\"A context manager to *capture* the result of print() or log() in a string,\\n rather than writing it to the console.\\n\\n Example:\\n >>> from rich.console import Console\\n >>> console = Console()\\n >>> with console.capture() as capture:\\n ... console.print(\\\"[bold magenta]Hello World[/]\\\")\\n >>> print(capture.get())\\n\\n Returns:\\n Capture: Context manager with disables writing to the terminal.\\n \\\"\\\"\\\"\\n capture = Capture(self)\\n return capture\\n\\n def pager(\\n self, pager: Pager = None, styles: bool = False, links: bool = False\\n ) -> PagerContext:\\n \\\"\\\"\\\"A context manager to display anything printed within a \\\"pager\\\". The pager used\\n is defined by the system and will typically support at less pressing a key to scroll.\\n\\n Args:\\n pager (Pager, optional): A pager object, or None to use :class:~rich.pager.SystemPager`. Defaults to None.\\n styles (bool, optional): Show styles in pager. Defaults to False.\\n links (bool, optional): Show links in pager. Defaults to False.\\n\\n Example:\\n >>> from rich.console import Console\\n >>> from rich.__main__ import make_test_card\\n >>> console = Console()\\n >>> with console.pager():\\n console.print(make_test_card())\\n\\n Returns:\\n PagerContext: A context manager.\\n \\\"\\\"\\\"\\n return PagerContext(self, pager=pager, styles=styles, links=links)\\n\\n def line(self, count: int = 1) -> None:\\n \\\"\\\"\\\"Write new line(s).\\n\\n Args:\\n count (int, optional): Number of new lines. Defaults to 1.\\n \\\"\\\"\\\"\\n\\n assert count >= 0, \\\"count must be >= 0\\\"\\n if count:\\n self._buffer.append(Segment(\\\"\\\\n\\\" * count))\\n self._check_buffer()\\n\\n def clear(self, home: bool = True) -> None:\\n \\\"\\\"\\\"Clear the screen.\\n\\n Args:\\n home (bool, optional): Also move the cursor to 'home' position. Defaults to True.\\n \\\"\\\"\\\"\\n self.control(\\\"\\\\033[2J\\\\033[H\\\" if home else \\\"\\\\033[2J\\\")\\n\\n def show_cursor(self, show: bool = True) -> None:\\n \\\"\\\"\\\"Show or hide the cursor.\\n\\n Args:\\n show (bool, optional): Set visibility of the cursor.\\n \\\"\\\"\\\"\\n if self.is_terminal and not self.legacy_windows:\\n self.control(\\\"\\\\033[?25h\\\" if show else \\\"\\\\033[?25l\\\")\\n\\n def render(\\n self, renderable: RenderableType, options: ConsoleOptions = None\\n ) -> Iterable[Segment]:\\n \\\"\\\"\\\"Render an object in to an iterable of `Segment` instances.\\n\\n This method contains the logic for rendering objects with the console protocol.\\n You are unlikely to need to use it directly, unless you are extending the library.\\n\\n Args:\\n renderable (RenderableType): An object supporting the console protocol, or\\n an object that may be converted to a string.\\n options (ConsoleOptions, optional): An options object, or None to use self.options. Defaults to None.\\n\\n Returns:\\n Iterable[Segment]: An iterable of segments that may be rendered.\\n \\\"\\\"\\\"\\n\\n _options = options or self.options\\n if _options.max_width < 1:\\n # No space to render anything. This prevents potential recursion errors.\\n return\\n render_iterable: RenderResult\\n if isinstance(renderable, RichCast):\\n renderable = renderable.__rich__()\\n if isinstance(renderable, ConsoleRenderable):\\n render_iterable = renderable.__rich_console__(self, _options)\\n elif isinstance(renderable, str):\\n yield from self.render(self.render_str(renderable), _options)\\n return\\n else:\\n raise errors.NotRenderableError(\\n f\\\"Unable to render {renderable!r}; \\\"\\n \\\"A str, Segment or object with __rich_console__ method is required\\\"\\n )\\n\\n try:\\n iter_render = iter(render_iterable)\\n except TypeError:\\n raise errors.NotRenderableError(\\n f\\\"object {render_iterable!r} is not renderable\\\"\\n )\\n for render_output in iter_render:\\n if isinstance(render_output, Segment):\\n yield render_output\\n else:\\n yield from self.render(render_output, _options)\\n\\n def render_lines(\\n self,\\n renderable: RenderableType,\\n options: Optional[ConsoleOptions] = None,\\n *,\\n style: Optional[Style] = None,\\n pad: bool = True,\\n ) -> List[List[Segment]]:\\n \\\"\\\"\\\"Render objects in to a list of lines.\\n\\n The output of render_lines is useful when further formatting of rendered console text\\n is required, such as the Panel class which draws a border around any renderable object.\\n\\n Args:\\n renderable (RenderableType): Any object renderable in the console.\\n options (Optional[ConsoleOptions], optional): Console options, or None to use self.options. Default to ``None``.\\n style (Style, optional): Optional style to apply to renderables. Defaults to ``None``.\\n pad (bool, optional): Pad lines shorter than render width. Defaults to ``True``.\\n\\n Returns:\\n List[List[Segment]]: A list of lines, where a line is a list of Segment objects.\\n \\\"\\\"\\\"\\n render_options = options or self.options\\n _rendered = self.render(renderable, render_options)\\n if style is not None:\\n _rendered = Segment.apply_style(_rendered, style)\\n lines = list(\\n Segment.split_and_crop_lines(\\n _rendered, render_options.max_width, include_new_lines=False, pad=pad\\n )\\n )\\n return lines\\n\\n def render_str(\\n self,\\n text: str,\\n *,\\n style: Union[str, Style] = \\\"\\\",\\n justify: JustifyMethod = None,\\n overflow: OverflowMethod = None,\\n emoji: bool = None,\\n markup: bool = None,\\n highlighter: HighlighterType = None,\\n ) -> \\\"Text\\\":\\n \\\"\\\"\\\"Convert a string to a Text instance. This is is called automatically if\\n you print or log a string.\\n\\n Args:\\n text (str): Text to render.\\n style (Union[str, Style], optional): Style to apply to rendered text.\\n justify (str, optional): Justify method: \\\"default\\\", \\\"left\\\", \\\"center\\\", \\\"full\\\", or \\\"right\\\". Defaults to ``None``.\\n overflow (str, optional): Overflow method: \\\"crop\\\", \\\"fold\\\", or \\\"ellipsis\\\". Defaults to ``None``.\\n emoji (Optional[bool], optional): Enable emoji, or ``None`` to use Console default.\\n markup (Optional[bool], optional): Enable markup, or ``None`` to use Console default.\\n highlighter (HighlighterType, optional): Optional highlighter to apply.\\n Returns:\\n ConsoleRenderable: Renderable object.\\n\\n \\\"\\\"\\\"\\n emoji_enabled = emoji or (emoji is None and self._emoji)\\n markup_enabled = markup or (markup is None and self._markup)\\n\\n if markup_enabled:\\n rich_text = render_markup(text, style=style, emoji=emoji_enabled)\\n rich_text.justify = justify\\n rich_text.overflow = overflow\\n else:\\n rich_text = Text(\\n _emoji_replace(text) if emoji_enabled else text,\\n justify=justify,\\n overflow=overflow,\\n style=style,\\n )\\n\\n if highlighter is not None:\\n highlight_text = highlighter(str(rich_text))\\n highlight_text.copy_styles(rich_text)\\n return highlight_text\\n\\n return rich_text\\n\\n def get_style(\\n self, name: Union[str, Style], *, default: Union[Style, str] = None\\n ) -> Style:\\n \\\"\\\"\\\"Get a Style instance by it's theme name or parse a definition.\\n\\n Args:\\n name (str): The name of a style or a style definition.\\n\\n Returns:\\n Style: A Style object.\\n\\n Raises:\\n MissingStyle: If no style could be parsed from name.\\n\\n \\\"\\\"\\\"\\n if isinstance(name, Style):\\n return name\\n\\n try:\\n style = self._theme_stack.get(name)\\n if style is None:\\n style = Style.parse(name)\\n return style.copy() if style.link else style\\n except errors.StyleSyntaxError as error:\\n if default is not None:\\n return self.get_style(default)\\n raise errors.MissingStyle(f\\\"Failed to get style {name!r}; {error}\\\")\\n\\n def _collect_renderables(\\n self,\\n objects: Iterable[Any],\\n sep: str,\\n end: str,\\n *,\\n justify: JustifyMethod = None,\\n emoji: bool = None,\\n markup: bool = None,\\n highlight: bool = None,\\n ) -> List[ConsoleRenderable]:\\n \\\"\\\"\\\"Combined a number of renderables and text in to one renderable.\\n\\n Args:\\n objects (Iterable[Any]): Anything that Rich can render.\\n sep (str, optional): String to write between print data. Defaults to \\\" \\\".\\n end (str, optional): String to write at end of print data. Defaults to \\\"\\\\\\\\n\\\".\\n justify (str, optional): One of \\\"left\\\", \\\"right\\\", \\\"center\\\", or \\\"full\\\". Defaults to ``None``.\\n emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default.\\n markup (Optional[bool], optional): Enable markup, or ``None`` to use console default.\\n highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default.\\n\\n Returns:\\n List[ConsoleRenderable]: A list of things to render.\\n \\\"\\\"\\\"\\n renderables: List[ConsoleRenderable] = []\\n _append = renderables.append\\n text: List[Text] = []\\n append_text = text.append\\n\\n append = _append\\n if justify in (\\\"left\\\", \\\"center\\\", \\\"right\\\"):\\n\\n def align_append(renderable: RenderableType) -> None:\\n _append(Align(renderable, cast(AlignValues, justify)))\\n\\n append = align_append\\n\\n _highlighter: HighlighterType = _null_highlighter\\n if highlight or (highlight is None and self._highlight):\\n _highlighter = self.highlighter\\n\\n def check_text() -> None:\\n if text:\\n sep_text = Text(sep, end=end)\\n append(sep_text.join(text))\\n del text[:]\\n\\n for renderable in objects:\\n rich_cast = getattr(renderable, \\\"__rich__\\\", None)\\n if rich_cast:\\n renderable = rich_cast()\\n if isinstance(renderable, str):\\n append_text(\\n self.render_str(\\n renderable,\\n emoji=emoji,\\n markup=markup,\\n highlighter=_highlighter,\\n )\\n )\\n elif isinstance(renderable, ConsoleRenderable):\\n check_text()\\n append(renderable)\\n elif isinstance(renderable, (abc.Mapping, abc.Sequence, abc.Set)):\\n check_text()\\n append(Pretty(renderable, highlighter=_highlighter))\\n else:\\n append_text(_highlighter(str(renderable)))\\n\\n check_text()\\n\\n return renderables\\n\\n def rule(\\n self,\\n title: str = \\\"\\\",\\n *,\\n characters: str = \\\"─\\\",\\n style: Union[str, Style] = \\\"rule.line\\\",\\n ) -> None:\\n \\\"\\\"\\\"Draw a line with optional centered title.\\n\\n Args:\\n title (str, optional): Text to render over the rule. Defaults to \\\"\\\".\\n characters (str, optional): Character(s) to form the line. Defaults to \\\"─\\\".\\n \\\"\\\"\\\"\\n from .rule import Rule\\n\\n rule = Rule(title=title, characters=characters, style=style)\\n self.print(rule)\\n\\n def control(self, control_codes: Union[\\\"Control\\\", str]) -> None:\\n \\\"\\\"\\\"Insert non-printing control codes.\\n\\n Args:\\n control_codes (str): Control codes, such as those that may move the cursor.\\n \\\"\\\"\\\"\\n if not self.is_dumb_terminal:\\n self._buffer.append(Segment.control(str(control_codes)))\\n self._check_buffer()\\n\\n def print(\\n self,\\n *objects: Any,\\n sep=\\\" \\\",\\n end=\\\"\\\\n\\\",\\n style: Union[str, Style] = None,\\n justify: JustifyMethod = None,\\n overflow: OverflowMethod = None,\\n no_wrap: bool = None,\\n emoji: bool = None,\\n markup: bool = None,\\n highlight: bool = None,\\n width: int = None,\\n crop: bool = True,\\n soft_wrap: bool = False,\\n ) -> None:\\n \\\"\\\"\\\"Print to the console.\\n\\n Args:\\n objects (positional args): Objects to log to the terminal.\\n sep (str, optional): String to write between print data. Defaults to \\\" \\\".\\n end (str, optional): String to write at end of print data. Defaults to \\\"\\\\\\\\n\\\".\\n style (Union[str, Style], optional): A style to apply to output. Defaults to None.\\n justify (str, optional): Justify method: \\\"default\\\", \\\"left\\\", \\\"right\\\", \\\"center\\\", or \\\"full\\\". Defaults to ``None``.\\n overflow (str, optional): Overflow method: \\\"ignore\\\", \\\"crop\\\", \\\"fold\\\", or \\\"ellipsis\\\". Defaults to None.\\n no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.\\n emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``.\\n markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``.\\n highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``.\\n width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``.\\n crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True.\\n soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping. Defaults to False.\\n \\\"\\\"\\\"\\n if not objects:\\n self.line()\\n return\\n\\n if soft_wrap:\\n if no_wrap is None:\\n no_wrap = True\\n if overflow is None:\\n overflow = \\\"ignore\\\"\\n crop = False\\n\\n with self:\\n renderables = self._collect_renderables(\\n objects,\\n sep,\\n end,\\n justify=justify,\\n emoji=emoji,\\n markup=markup,\\n highlight=highlight,\\n )\\n for hook in self._render_hooks:\\n renderables = hook.process_renderables(renderables)\\n render_options = self.options.update(\\n justify=justify, overflow=overflow, width=width, no_wrap=no_wrap\\n )\\n new_segments: List[Segment] = []\\n extend = new_segments.extend\\n render = self.render\\n if style is None:\\n for renderable in renderables:\\n extend(render(renderable, render_options))\\n else:\\n for renderable in renderables:\\n extend(\\n Segment.apply_style(\\n render(renderable, render_options), self.get_style(style)\\n )\\n )\\n if crop:\\n buffer_extend = self._buffer.extend\\n for line in Segment.split_and_crop_lines(\\n new_segments, self.width, pad=False\\n ):\\n buffer_extend(line)\\n else:\\n self._buffer.extend(new_segments)\\n\\n def print_exception(\\n self,\\n *,\\n width: Optional[int] = 100,\\n extra_lines: int = 3,\\n theme: Optional[str] = None,\\n word_wrap: bool = False,\\n show_locals: bool = False,\\n ) -> None:\\n \\\"\\\"\\\"Prints a rich render of the last exception and traceback.\\n\\n Args:\\n width (Optional[int], optional): Number of characters used to render code. Defaults to 88.\\n extra_lines (int, optional): Additional lines of code to render. Defaults to 3.\\n theme (str, optional): Override pygments theme used in traceback\\n word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.\\n show_locals (bool, optional): Enable display of local variables. Defaults to False.\\n \\\"\\\"\\\"\\n from .traceback import Traceback\\n\\n traceback = Traceback(\\n width=width,\\n extra_lines=extra_lines,\\n theme=theme,\\n word_wrap=word_wrap,\\n show_locals=show_locals,\\n )\\n self.print(traceback)\\n\\n def log(\\n self,\\n *objects: Any,\\n sep=\\\" \\\",\\n end=\\\"\\\\n\\\",\\n justify: JustifyMethod = None,\\n emoji: bool = None,\\n markup: bool = None,\\n highlight: bool = None,\\n log_locals: bool = False,\\n _stack_offset=1,\\n ) -> None:\\n \\\"\\\"\\\"Log rich content to the terminal.\\n\\n Args:\\n objects (positional args): Objects to log to the terminal.\\n sep (str, optional): String to write between print data. Defaults to \\\" \\\".\\n end (str, optional): String to write at end of print data. Defaults to \\\"\\\\\\\\n\\\".\\n justify (str, optional): One of \\\"left\\\", \\\"right\\\", \\\"center\\\", or \\\"full\\\". Defaults to ``None``.\\n overflow (str, optional): Overflow method: \\\"crop\\\", \\\"fold\\\", or \\\"ellipsis\\\". Defaults to None.\\n emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to None.\\n markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to None.\\n highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to None.\\n log_locals (bool, optional): Boolean to enable logging of locals where ``log()``\\n was called. Defaults to False.\\n _stack_offset (int, optional): Offset of caller from end of call stack. Defaults to 1.\\n \\\"\\\"\\\"\\n if not objects:\\n self.line()\\n return\\n with self:\\n renderables = self._collect_renderables(\\n objects,\\n sep,\\n end,\\n justify=justify,\\n emoji=emoji,\\n markup=markup,\\n highlight=highlight,\\n )\\n\\n caller = inspect.stack()[_stack_offset]\\n link_path = (\\n None\\n if caller.filename.startswith(\\\"<\\\")\\n else os.path.abspath(caller.filename)\\n )\\n path = caller.filename.rpartition(os.sep)[-1]\\n line_no = caller.lineno\\n if log_locals:\\n locals_map = {\\n key: value\\n for key, value in caller.frame.f_locals.items()\\n if not key.startswith(\\\"__\\\")\\n }\\n renderables.append(render_scope(locals_map, title=\\\"[i]locals\\\"))\\n\\n renderables = [\\n self._log_render(\\n self,\\n renderables,\\n path=path,\\n line_no=line_no,\\n link_path=link_path,\\n )\\n ]\\n for hook in self._render_hooks:\\n renderables = hook.process_renderables(renderables)\\n new_segments: List[Segment] = []\\n extend = new_segments.extend\\n render = self.render\\n render_options = self.options\\n for renderable in renderables:\\n extend(render(renderable, render_options))\\n buffer_extend = self._buffer.extend\\n for line in Segment.split_and_crop_lines(\\n new_segments, self.width, pad=False\\n ):\\n buffer_extend(line)\\n\\n def _check_buffer(self) -> None:\\n \\\"\\\"\\\"Check if the buffer may be rendered.\\\"\\\"\\\"\\n with self._lock:\\n if self._buffer_index == 0:\\n if self.is_jupyter: # pragma: no cover\\n from .jupyter import display\\n\\n display(self._buffer)\\n del self._buffer[:]\\n else:\\n text = self._render_buffer(self._buffer[:])\\n del self._buffer[:]\\n if text:\\n try:\\n if WINDOWS: # pragma: no cover\\n # https://bugs.python.org/issue37871\\n write = self.file.write\\n for line in text.splitlines(True):\\n write(line)\\n else:\\n self.file.write(text)\\n self.file.flush()\\n except UnicodeEncodeError as error:\\n error.reason = f\\\"{error.reason}\\\\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***\\\"\\n raise\\n\\n def _render_buffer(self, buffer: Iterable[Segment]) -> str:\\n \\\"\\\"\\\"Render buffered output, and clear buffer.\\\"\\\"\\\"\\n output: List[str] = []\\n append = output.append\\n color_system = self._color_system\\n legacy_windows = self.legacy_windows\\n if self.record:\\n with self._record_buffer_lock:\\n self._record_buffer.extend(buffer)\\n not_terminal = not self.is_terminal\\n for text, style, is_control in buffer:\\n if style and not is_control:\\n append(\\n style.render(\\n text,\\n color_system=color_system,\\n legacy_windows=legacy_windows,\\n )\\n )\\n elif not (not_terminal and is_control):\\n append(text)\\n\\n rendered = \\\"\\\".join(output)\\n return rendered\\n\\n def input(\\n self,\\n prompt: TextType = \\\"\\\",\\n *,\\n markup: bool = True,\\n emoji: bool = True,\\n password: bool = False,\\n stream: TextIO = None,\\n ) -> str:\\n \\\"\\\"\\\"Displays a prompt and waits for input from the user. The prompt may contain color / style.\\n\\n Args:\\n prompt (Union[str, Text]): Text to render in the prompt.\\n markup (bool, optional): Enable console markup (requires a str prompt). Defaults to True.\\n emoji (bool, optional): Enable emoji (requires a str prompt). Defaults to True.\\n password: (bool, optional): Hide typed text. Defaults to False.\\n stream: (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None.\\n\\n Returns:\\n str: Text read from stdin.\\n \\\"\\\"\\\"\\n prompt_str = \\\"\\\"\\n if prompt:\\n with self.capture() as capture:\\n self.print(prompt, markup=markup, emoji=emoji, end=\\\"\\\")\\n prompt_str = capture.get()\\n if password:\\n result = getpass(prompt_str, stream=stream)\\n else:\\n if stream:\\n self.file.write(prompt_str)\\n result = stream.readline()\\n else:\\n result = input(prompt_str)\\n return result\\n\\n def export_text(self, *, clear: bool = True, styles: bool = False) -> str:\\n \\\"\\\"\\\"Generate text from console contents (requires record=True argument in constructor).\\n\\n Args:\\n clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\\n styles (bool, optional): If ``True``, ansi escape codes will be included. ``False`` for plain text.\\n Defaults to ``False``.\\n\\n Returns:\\n str: String containing console contents.\\n\\n \\\"\\\"\\\"\\n assert (\\n self.record\\n ), \\\"To export console contents set record=True in the constructor or instance\\\"\\n\\n with self._record_buffer_lock:\\n if styles:\\n text = \\\"\\\".join(\\n (style.render(text) if style else text)\\n for text, style, _ in self._record_buffer\\n )\\n else:\\n text = \\\"\\\".join(\\n segment.text\\n for segment in self._record_buffer\\n if not segment.is_control\\n )\\n if clear:\\n del self._record_buffer[:]\\n return text\\n\\n def save_text(self, path: str, *, clear: bool = True, styles: bool = False) -> None:\\n \\\"\\\"\\\"Generate text from console and save to a given location (requires record=True argument in constructor).\\n\\n Args:\\n path (str): Path to write text files.\\n clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\\n styles (bool, optional): If ``True``, ansi style codes will be included. ``False`` for plain text.\\n Defaults to ``False``.\\n\\n \\\"\\\"\\\"\\n text = self.export_text(clear=clear, styles=styles)\\n with open(path, \\\"wt\\\", encoding=\\\"utf-8\\\") as write_file:\\n write_file.write(text)\\n\\n def export_html(\\n self,\\n *,\\n theme: TerminalTheme = None,\\n clear: bool = True,\\n code_format: str = None,\\n inline_styles: bool = False,\\n ) -> str:\\n \\\"\\\"\\\"Generate HTML from console contents (requires record=True argument in constructor).\\n\\n Args:\\n theme (TerminalTheme, optional): TerminalTheme object containing console colors.\\n clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\\n code_format (str, optional): Format string to render HTML, should contain {foreground}\\n {background} and {code}.\\n inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files\\n larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.\\n Defaults to False.\\n\\n Returns:\\n str: String containing console contents as HTML.\\n \\\"\\\"\\\"\\n assert (\\n self.record\\n ), \\\"To export console contents set record=True in the constructor or instance\\\"\\n fragments: List[str] = []\\n append = fragments.append\\n _theme = theme or DEFAULT_TERMINAL_THEME\\n stylesheet = \\\"\\\"\\n\\n def escape(text: str) -> str:\\n \\\"\\\"\\\"Escape html.\\\"\\\"\\\"\\n return text.replace(\\\"&\\\", \\\"&amp;\\\").replace(\\\"<\\\", \\\"&lt;\\\").replace(\\\">\\\", \\\"&gt;\\\")\\n\\n render_code_format = CONSOLE_HTML_FORMAT if code_format is None else code_format\\n\\n with self._record_buffer_lock:\\n if inline_styles:\\n for text, style, _ in Segment.filter_control(\\n Segment.simplify(self._record_buffer)\\n ):\\n text = escape(text)\\n if style:\\n rule = style.get_html_style(_theme)\\n text = f'{text}' if rule else text\\n if style.link:\\n text = f'{text}'\\n append(text)\\n else:\\n styles: Dict[str, int] = {}\\n for text, style, _ in Segment.filter_control(\\n Segment.simplify(self._record_buffer)\\n ):\\n text = escape(text)\\n if style:\\n rule = style.get_html_style(_theme)\\n if rule:\\n style_number = styles.setdefault(rule, len(styles) + 1)\\n text = f'{text}'\\n if style.link:\\n text = f'{text}'\\n append(text)\\n stylesheet_rules: List[str] = []\\n stylesheet_append = stylesheet_rules.append\\n for style_rule, style_number in styles.items():\\n if style_rule:\\n stylesheet_append(f\\\".r{style_number} {{{style_rule}}}\\\")\\n stylesheet = \\\"\\\\n\\\".join(stylesheet_rules)\\n\\n rendered_code = render_code_format.format(\\n code=\\\"\\\".join(fragments),\\n stylesheet=stylesheet,\\n foreground=_theme.foreground_color.hex,\\n background=_theme.background_color.hex,\\n )\\n if clear:\\n del self._record_buffer[:]\\n return rendered_code\\n\\n def save_html(\\n self,\\n path: str,\\n *,\\n theme: TerminalTheme = None,\\n clear: bool = True,\\n code_format=CONSOLE_HTML_FORMAT,\\n inline_styles: bool = False,\\n ) -> None:\\n \\\"\\\"\\\"Generate HTML from console contents and write to a file (requires record=True argument in constructor).\\n\\n Args:\\n path (str): Path to write html file.\\n theme (TerminalTheme, optional): TerminalTheme object containing console colors.\\n clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\\n code_format (str, optional): Format string to render HTML, should contain {foreground}\\n {background} and {code}.\\n inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files\\n larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.\\n Defaults to False.\\n\\n \\\"\\\"\\\"\\n html = self.export_html(\\n theme=theme,\\n clear=clear,\\n code_format=code_format,\\n inline_styles=inline_styles,\\n )\\n with open(path, \\\"wt\\\", encoding=\\\"utf-8\\\") as write_file:\\n write_file.write(html)\\n\\n\\nif __name__ == \\\"__main__\\\": # pragma: no cover\\n console = Console()\\n\\n console.log(\\n \\\"JSONRPC [i]request[/i]\\\",\\n 5,\\n 1.3,\\n True,\\n False,\\n None,\\n {\\n \\\"jsonrpc\\\": \\\"2.0\\\",\\n \\\"method\\\": \\\"subtract\\\",\\n \\\"params\\\": {\\\"minuend\\\": 42, \\\"subtrahend\\\": 23},\\n \\\"id\\\": 3,\\n },\\n )\\n\\n console.log(\\\"Hello, World!\\\", \\\"{'a': 1}\\\", repr(console))\\n\\n console.print(\\n {\\n \\\"name\\\": None,\\n \\\"empty\\\": [],\\n \\\"quiz\\\": {\\n \\\"sport\\\": {\\n \\\"answered\\\": True,\\n \\\"q1\\\": {\\n \\\"question\\\": \\\"Which one is correct team name in NBA?\\\",\\n \\\"options\\\": [\\n \\\"New York Bulls\\\",\\n \\\"Los Angeles Kings\\\",\\n \\\"Golden State Warriors\\\",\\n \\\"Huston Rocket\\\",\\n ],\\n \\\"answer\\\": \\\"Huston Rocket\\\",\\n },\\n },\\n \\\"maths\\\": {\\n \\\"answered\\\": False,\\n \\\"q1\\\": {\\n \\\"question\\\": \\\"5 + 7 = ?\\\",\\n \\\"options\\\": [10, 11, 12, 13],\\n \\\"answer\\\": 12,\\n },\\n \\\"q2\\\": {\\n \\\"question\\\": \\\"12 - 8 = ?\\\",\\n \\\"options\\\": [1, 2, 3, 4],\\n \\\"answer\\\": 4,\\n },\\n },\\n },\\n }\\n )\\n console.log(\\\"foo\\\")\\n\"}"},"non_py_patch":{"kind":"string","value":"diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex f813ffeb0a..132fafbbc2 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -18,6 +18,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n - Addded box.SQUARE_DOUBLE_HEAD\n - Added highlighting of EUI-48 and EUI-64 (MAC addresses)\n - Added Console.pager\n+- Added Console.out\n \n ### Changed\n \ndiff --git a/docs/source/console.rst b/docs/source/console.rst\nindex a3c690c794..f5565ee6b3 100644\n--- a/docs/source/console.rst\n+++ b/docs/source/console.rst\n@@ -69,6 +69,15 @@ The :meth:`~rich.console.Console.log` methods offers the same capabilities as pr\n \n To help with debugging, the log() method has a ``log_locals`` parameter. If you set this to ``True``, Rich will display a table of local variables where the method was called.\n \n+Low level output\n+----------------\n+\n+In additional to :meth:`~rich.console.Console.print` and :meth:`~rich.console.Console.log`, Rich has a :meth:`~rich.console.Console.out` method which provides a lower-level way of writing to the terminal. The out() method converts all the positional arguments to strings and won't pretty print, word wrap, or apply markup to the output, but can apply a basic style and will optionally do highlighting.\n+\n+Here's an example::\n+\n+ >>> console.out(\"Locals\", locals())\n+\n \n Justify / Alignment\n -------------------\n"},"new_components":{"kind":"string","value":"{\"rich/console.py\": [{\"type\": \"function\", \"name\": \"Console.out\", \"lines\": [1015, 1043], \"signature\": \"def out( self, *objects: Any, sep=\\\" \\\", end=\\\"\\\\n\\\", style: Union[str, Style] = None, highlight: bool = True, ) -> None:\", \"doc\": \"Output to the terminal. This is a low-level way of writing to the terminal which unlike\\n:meth:`~rich.console.Console.print` doesn't pretty print, wrap text, nor markup, but will highlighting\\nand apply basic style.\\n\\nArgs:\\n sep (str, optional): String to write between print data. Defaults to \\\" \\\".\\n end (str, optional): String to write at end of print data. Defaults to \\\"\\\\n\\\".\\n style (Union[str, Style], optional): A style to apply to output. Defaults to None.\\n highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``.\"}]}"},"version":{"kind":"null"},"FAIL_TO_PASS":{"kind":"string","value":"[\"tests/test_console.py::test_out\"]"},"PASS_TO_PASS":{"kind":"string","value":"[\"tests/test_console.py::test_dumb_terminal\", \"tests/test_console.py::test_16color_terminal\", \"tests/test_console.py::test_truecolor_terminal\", \"tests/test_console.py::test_console_options_update\", \"tests/test_console.py::test_init\", \"tests/test_console.py::test_size\", \"tests/test_console.py::test_repr\", \"tests/test_console.py::test_print\", \"tests/test_console.py::test_print_empty\", \"tests/test_console.py::test_markup_highlight\", \"tests/test_console.py::test_print_style\", \"tests/test_console.py::test_show_cursor\", \"tests/test_console.py::test_clear\", \"tests/test_console.py::test_clear_no_terminal\", \"tests/test_console.py::test_get_style\", \"tests/test_console.py::test_get_style_default\", \"tests/test_console.py::test_get_style_error\", \"tests/test_console.py::test_render_error\", \"tests/test_console.py::test_control\", \"tests/test_console.py::test_capture\", \"tests/test_console.py::test_input\", \"tests/test_console.py::test_input_password\", \"tests/test_console.py::test_justify_none\", \"tests/test_console.py::test_justify_left\", \"tests/test_console.py::test_justify_center\", \"tests/test_console.py::test_justify_right\", \"tests/test_console.py::test_justify_renderable_none\", \"tests/test_console.py::test_justify_renderable_left\", \"tests/test_console.py::test_justify_renderable_center\", \"tests/test_console.py::test_justify_renderable_right\", \"tests/test_console.py::test_render_broken_renderable\", \"tests/test_console.py::test_export_text\", \"tests/test_console.py::test_export_html\", \"tests/test_console.py::test_export_html_inline\", \"tests/test_console.py::test_save_text\", \"tests/test_console.py::test_save_html\", \"tests/test_console.py::test_no_wrap\", \"tests/test_console.py::test_soft_wrap\", \"tests/test_console.py::test_unicode_error\", \"tests/test_console.py::test_bell\", \"tests/test_console.py::test_pager\", \"tests/test_padding.py::test_repr\", \"tests/test_padding.py::test_indent\", \"tests/test_padding.py::test_unpack\", \"tests/test_padding.py::test_rich_console\"]"},"environment_setup_commit":{"kind":"string","value":"b0661de34bab35af9b4b1d3ba8e28b186b225e84"},"problem_statement":{"kind":"string","value":"{\"first_commit_time\": 1602433996.0, \"pr_title\": \"console out\", \"pr_body\": \"Adds a Console.out method which is like a low-level print does simple styling only.\\r\\n\\r\\n## Type of changes\\r\\n\\r\\n- [ ] Bug fix\\r\\n- [x] New feature\\r\\n- [x] Documentation / docstrings\\r\\n- [ ] Tests\\r\\n- [ ] Other\\r\\n\\r\\n## Checklist\\r\\n\\r\\n- [x] I've run the latest [black](https://github.com/psf/black) with default args on new code.\\r\\n- [x] I've updated CHANGELOG.md and CONTRIBUTORS.md where appropriate.\\r\\n- [x] I've added tests for new code.\\r\\n- [x] I accept that @willmcgugan may be pedantic in the code review.\\r\\n\\r\\n## Description\\r\\n\\r\\nPlease describe your changes here. If this fixes a bug, please link to the issue, if possible.\\r\\n\", \"pr_timeline\": [{\"time\": 1602434572.0, \"comment\": \"# [Codecov](https://codecov.io/gh/willmcgugan/rich/pull/376?src=pr&el=h1) Report\\n> Merging [#376](https://codecov.io/gh/willmcgugan/rich/pull/376?src=pr&el=desc) into [master](https://codecov.io/gh/willmcgugan/rich/commit/e11800a2889fa35228bd22b0121f42cd6e856976?el=desc) will **increase** coverage by `0.06%`.\\n> The diff coverage is `100.00%`.\\n\\n[![Impacted file tree graph](https://codecov.io/gh/willmcgugan/rich/pull/376/graphs/tree.svg?width=650&height=150&src=pr&token=gpwvEeKjff)](https://codecov.io/gh/willmcgugan/rich/pull/376?src=pr&el=tree)\\n\\n```diff\\n@@ Coverage Diff @@\\n## master #376 +/- ##\\n==========================================\\n+ Coverage 99.35% 99.42% +0.06% \\n==========================================\\n Files 51 51 \\n Lines 4374 4373 -1 \\n==========================================\\n+ Hits 4346 4348 +2 \\n+ Misses 28 25 -3 \\n```\\n\\n| Flag | Coverage \\u0394 | |\\n|---|---|---|\\n| #unittests | `99.42% <100.00%> (+0.06%)` | :arrow_up: |\\n\\nFlags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags#carryforward-flags-in-the-pull-request-comment) to find out more.\\n\\n| [Impacted Files](https://codecov.io/gh/willmcgugan/rich/pull/376?src=pr&el=tree) | Coverage \\u0394 | |\\n|---|---|---|\\n| [rich/console.py](https://codecov.io/gh/willmcgugan/rich/pull/376/diff?src=pr&el=tree#diff-cmljaC9jb25zb2xlLnB5) | `100.00% <100.00%> (\\u00f8)` | |\\n| [rich/containers.py](https://codecov.io/gh/willmcgugan/rich/pull/376/diff?src=pr&el=tree#diff-cmljaC9jb250YWluZXJzLnB5) | `100.00% <100.00%> (+1.17%)` | :arrow_up: |\\n| [rich/measure.py](https://codecov.io/gh/willmcgugan/rich/pull/376/diff?src=pr&el=tree#diff-cmljaC9tZWFzdXJlLnB5) | `100.00% <0.00%> (+4.65%)` | :arrow_up: |\\n\\n------\\n\\n[Continue to review full report at Codecov](https://codecov.io/gh/willmcgugan/rich/pull/376?src=pr&el=continue).\\n> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)\\n> `\\u0394 = absolute (impact)`, `\\u00f8 = not affected`, `? = missing data`\\n> Powered by [Codecov](https://codecov.io/gh/willmcgugan/rich/pull/376?src=pr&el=footer). Last update [a83ee86...ba78d0e](https://codecov.io/gh/willmcgugan/rich/pull/376?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).\\n\"}], \"issues\": {}}"}}},{"rowIdx":8,"cells":{"repo":{"kind":"string","value":"Textualize/rich"},"pull_number":{"kind":"number","value":901,"string":"901"},"url":{"kind":"string","value":"https://github.com/Textualize/rich/pull/901"},"instance_id":{"kind":"string","value":"Textualize__rich-901"},"issue_numbers":{"kind":"string","value":"[]"},"base_commit":{"kind":"string","value":"a9c0f917aed8d0bba232b7584742962f03a9a293"},"patch":{"kind":"string","value":"diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex d8378b729a..acb53b1308 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n ### Added\n \n - Added rich.tree\n+- Added no_color argument to Console\n \n ## [9.6.2] - 2021-01-07\n \ndiff --git a/rich/console.py b/rich/console.py\nindex 2ef5b3d75b..d955ecd1f4 100644\n--- a/rich/console.py\n+++ b/rich/console.py\n@@ -402,6 +402,7 @@ class Console:\n width (int, optional): The width of the terminal. Leave as default to auto-detect width.\n height (int, optional): The height of the terminal. Leave as default to auto-detect height.\n style (StyleType, optional): Style to apply to all output, or None for no style. Defaults to None.\n+ no_color (Optional[bool], optional): Enabled no color mode, or None to auto detect. Defaults to None.\n record (bool, optional): Boolean to enable recording of terminal output,\n required to call :meth:`export_html` and :meth:`export_text`. Defaults to False.\n markup (bool, optional): Boolean to enable :ref:`console_markup`. Defaults to True.\n@@ -433,6 +434,7 @@ def __init__(\n width: int = None,\n height: int = None,\n style: StyleType = None,\n+ no_color: bool = None,\n tab_size: int = 8,\n record: bool = False,\n markup: bool = True,\n@@ -492,6 +494,9 @@ def __init__(\n self.get_datetime = get_datetime or datetime.now\n self.get_time = get_time or monotonic\n self.style = style\n+ self.no_color = (\n+ no_color if no_color is not None else \"NO_COLOR\" in self._environ\n+ )\n \n self._record_buffer_lock = threading.RLock()\n self._thread_locals = ConsoleThreadLocals(\n@@ -538,7 +543,7 @@ def _detect_color_system(self) -> Optional[ColorSystem]:\n \"\"\"Detect color system from env vars.\"\"\"\n if self.is_jupyter:\n return ColorSystem.TRUECOLOR\n- if not self.is_terminal or \"NO_COLOR\" in self._environ or self.is_dumb_terminal:\n+ if not self.is_terminal or self.is_dumb_terminal:\n return None\n if WINDOWS: # pragma: no cover\n if self.legacy_windows: # pragma: no cover\n@@ -1374,6 +1379,8 @@ def _render_buffer(self, buffer: Iterable[Segment]) -> str:\n with self._record_buffer_lock:\n self._record_buffer.extend(buffer)\n not_terminal = not self.is_terminal\n+ if self.no_color and color_system:\n+ buffer = Segment.remove_color(buffer)\n for text, style, is_control in buffer:\n if style:\n append(\ndiff --git a/rich/segment.py b/rich/segment.py\nindex db17b0fbb6..34ae7ab0d0 100644\n--- a/rich/segment.py\n+++ b/rich/segment.py\n@@ -1,4 +1,4 @@\n-from typing import NamedTuple, Optional\n+from typing import Dict, NamedTuple, Optional\n \n from .cells import cell_len, set_cell_size\n from .style import Style\n@@ -331,12 +331,37 @@ def strip_links(cls, segments: Iterable[\"Segment\"]) -> Iterable[\"Segment\"]:\n def strip_styles(cls, segments: Iterable[\"Segment\"]) -> Iterable[\"Segment\"]:\n \"\"\"Remove all styles from an iterable of segments.\n \n+ Args:\n+ segments (Iterable[Segment]): An iterable segments.\n+\n Yields:\n Segment: Segments with styles replace with None\n \"\"\"\n for text, _style, is_control in segments:\n yield cls(text, None, is_control)\n \n+ @classmethod\n+ def remove_color(cls, segments: Iterable[\"Segment\"]) -> Iterable[\"Segment\"]:\n+ \"\"\"Remove all color from an iterable of segments.\n+\n+ Args:\n+ segments (Iterable[Segment]): An iterable segments.\n+\n+ Yields:\n+ Segment: Segments with colorless style.\n+ \"\"\"\n+\n+ cache: Dict[Style, Style] = {}\n+ for text, style, is_control in segments:\n+ if style:\n+ colorless_style = cache.get(style)\n+ if colorless_style is None:\n+ colorless_style = style.without_color\n+ cache[style] = colorless_style\n+ yield cls(text, colorless_style, is_control)\n+ else:\n+ yield cls(text, None, is_control)\n+\n \n if __name__ == \"__main__\": # pragma: no cover\n lines = [[Segment(\"Hello\")]]\ndiff --git a/rich/style.py b/rich/style.py\nindex 5a802d0762..cda8380638 100644\n--- a/rich/style.py\n+++ b/rich/style.py\n@@ -383,6 +383,24 @@ def background_style(self) -> \"Style\":\n \"\"\"A Style with background only.\"\"\"\n return Style(bgcolor=self.bgcolor)\n \n+ @property\n+ def without_color(self) -> \"Style\":\n+ \"\"\"Get a copy of the style with color removed.\"\"\"\n+ if self._null:\n+ return NULL_STYLE\n+ style = self.__new__(Style)\n+ style._ansi = None\n+ style._style_definition = None\n+ style._color = None\n+ style._bgcolor = None\n+ style._attributes = self._attributes\n+ style._set_attributes = self._set_attributes\n+ style._link = self._link\n+ style._link_id = f\"{time()}-{randint(0, 999999)}\" if self._link else \"\"\n+ style._hash = self._hash\n+ style._null = False\n+ return style\n+\n @classmethod\n @lru_cache(maxsize=4096)\n def parse(cls, style_definition: str) -> \"Style\":\n"},"test_patch":{"kind":"string","value":"diff --git a/tests/test_console.py b/tests/test_console.py\nindex b82c765911..82bc5b48d4 100644\n--- a/tests/test_console.py\n+++ b/tests/test_console.py\n@@ -467,3 +467,14 @@ def test_console_style() -> None:\n expected = \"\\x1b[31mfoo\\x1b[0m\\n\"\n result = console.file.getvalue()\n assert result == expected\n+\n+\n+def test_no_color():\n+ console = Console(\n+ file=io.StringIO(), color_system=\"truecolor\", force_terminal=True, no_color=True\n+ )\n+ console.print(\"[bold magenta on red]FOO\")\n+ expected = \"\\x1b[1mFOO\\x1b[0m\\n\"\n+ result = console.file.getvalue()\n+ print(repr(result))\n+ assert result == expected\ndiff --git a/tests/test_segment.py b/tests/test_segment.py\nindex 2c3344dd1b..42abdcbacf 100644\n--- a/tests/test_segment.py\n+++ b/tests/test_segment.py\n@@ -96,3 +96,14 @@ def test_strip_styles():\n def test_strip_links():\n segments = [Segment(\"foo\", Style(bold=True, link=\"https://www.example.org\"))]\n assert list(Segment.strip_links(segments)) == [Segment(\"foo\", Style(bold=True))]\n+\n+\n+def test_remove_color():\n+ segments = [\n+ Segment(\"foo\", Style(bold=True, color=\"red\")),\n+ Segment(\"bar\", None),\n+ ]\n+ assert list(Segment.remove_color(segments)) == [\n+ Segment(\"foo\", Style(bold=True)),\n+ Segment(\"bar\", None),\n+ ]\ndiff --git a/tests/test_style.py b/tests/test_style.py\nindex a5075e80fb..8282331f30 100644\n--- a/tests/test_style.py\n+++ b/tests/test_style.py\n@@ -196,3 +196,13 @@ def test_background_style():\n assert Style(bold=True, color=\"yellow\", bgcolor=\"red\").background_style == Style(\n bgcolor=\"red\"\n )\n+\n+\n+def test_without_color():\n+ style = Style(bold=True, color=\"red\", bgcolor=\"blue\")\n+ colorless_style = style.without_color\n+ assert colorless_style.color == None\n+ assert colorless_style.bgcolor == None\n+ assert colorless_style.bold == True\n+ null_style = Style.null()\n+ assert null_style.without_color == null_style\n"},"created_at":{"kind":"timestamp","value":"2021-01-09T16:12:28","string":"2021-01-09T16:12:28"},"readmes":{"kind":"string","value":"{\"README.md\": \"

\\n \\n \\\"fea-bench\\\"\\n \\n

\\n\\n

\\n A benchmark that aims to evaluate the capability of implementing new features in the code repositories.\\n

\\n\\n

\\n \\n \\\"paper\\\"\\n \\n \\n \\\"License\\\"\\n \\n \\n \\\"Leaderboard\\\"\\n \\n \\n \\\"dataset\\\"\\n \\n

\\n\\n---\\n\\n# Evaluation\\n\\nThis repository is the official implementation of the paper \\\"FEA-Bench: A Benchmark for Evaluating Repository-Level Code Generation for Feature Implementation.\\\" It can be used for baseline evaluation using the prompts mentioned in the paper.\\n\\nThe repository includes several functionalities, primarily for obtaining the full dataset, running model inference aligned with the paper, and evaluating the results. The complete pipeline is as follows:\\n\\n## 1. Environment Setup\\n\\nYou can create a new Python environment and install all dependencies using:\\n```bash\\npip install -e .\\n```\\nIf you plan to use VLLM inference, ensure that the installed libraries match your hardware.\\n\\n## 2. Building the Full Evaluation Dataset\\n\\nDue to licensing and company policies, we cannot release the full dataset. Our published version ([https://huggingface.co/datasets/microsoft/FEA-Bench](https://huggingface.co/datasets/microsoft/FEA-Bench)) only includes essential attributes, and the remaining content needs to be scraped from GitHub.\\n\\nTo construct the full FEA-Bench dataset and save it in the `feabench-data` folder, run the following command. Note that you need to replace `GITHUB_TOKEN` with your own GitHub token, which should have read-only access to public repositories:\\n```bash\\nexport GITHUB_TOKEN=\\\"xxx\\\"\\n\\npython -m feabench.get_dataset \\\\\\n --dataset microsoft/FEA-Bench \\\\\\n --testbed feabench-data/testbed \\\\\\n --lite_ids instances_lite.json \\\\\\n --medium_file feabench-data/FEA-Bench-v1.0-medium.jsonl \\\\\\n --standard_dataset_path feabench-data/FEA-Bench-v1.0-Standard \\\\\\n --oracle_dataset_path feabench-data/FEA-Bench-v1.0-Oracle \\\\\\n --lite_standard_dataset_path feabench-data/FEA-Bench-v1.0-Lite-Standard \\\\\\n --lite_oracle_dataset_path feabench-data/FEA-Bench-v1.0-Lite-Oracle\\n```\\n\\n## 3. Running Model Inference\\n\\nOur repository only provides inference methods consistent with those in the paper. Agentless and other agent-based inferences can use the `FEA-Bench-v1.0-Lite-Standard` dataset constructed in the previous step, which is aligned with the format of SWE-Bench.\\n\\n### Example of VLLM Inference:\\n```bash\\nexport MAX_SEQ_LEN=128000\\nexport MAX_GEN_LEN=4096\\n\\nDATASET_PATH=feabench-data/FEA-Bench-v1.0-Oracle\\nMODEL_NAME=Qwen/Qwen2.5-Coder-3B-Instruct\\nRESULTS_ROOT_DIR=scripts/experiments/results_full\\n\\nPROMPT_MODE=natural-detailed\\npython -m feabench.run_prediction \\\\\\n --dataset_name_or_path $DATASET_PATH \\\\\\n --model_type vllm \\\\\\n --model_name_or_path $MODEL_NAME \\\\\\n --input_text $PROMPT_MODE \\\\\\n --output_dir $RESULTS_ROOT_DIR/$PROMPT_MODE\\n```\\n\\n### Example of OpenAI API-style Inference:\\n(DEEPSEEK_TOKENIZER is only required when using DeepSeek model inference)\\n```bash\\nexport DEEPSEEK_TOKENIZER_PATH=\\\"xxx\\\"\\nexport OPENAI_API_KEY=\\\"xxx\\\"\\nexport OPENAI_BASE_URL=\\\"https://api.deepseek.com\\\"\\n\\nDATASET_PATH=feabench-data/FEA-Bench-v1.0-Oracle\\nMODEL_NAME=deepseek-chat\\nRESULTS_ROOT_DIR=scripts/experiments/results_full\\n\\nPROMPT_MODE=natural-detailed\\npython -m feabench.run_prediction \\\\\\n --dataset_name_or_path $DATASET_PATH \\\\\\n --model_type openai \\\\\\n --model_name_or_path $MODEL_NAME \\\\\\n --input_text $PROMPT_MODE \\\\\\n --output_dir $RESULTS_ROOT_DIR/$PROMPT_MODE \\\\\\n --num_proc 1\\n```\\n\\nAfter running the inference, you should see the output `.jsonl` result files in the specified `output_dir`.\\n\\n## 4. Running Model Evaluation\\n\\nOur evaluation process is based on the code provided by SWE-Bench. We have provided a patch file `swe-bench.diff` to include the environment configurations for the task instances we are involved in.\\n\\nClone the SWE-Bench repository and apply the patch:\\n```bash\\nmkdir -p evaluator\\ncd evaluator\\ngit clone https://github.com/SWE-bench/SWE-bench.git\\ncd SWE-bench\\ngit checkout a0536ee6f9fd5ff88acf17a36a384bf3da3d93d6\\ngit apply ../../swe-bench.diff\\nconda create --name fea-eval python=3.11\\nconda activate fea-eval\\npip install -e .\\n```\\n\\nTo verify that the FEA-Bench task instances can run correctly on your machine, you can build a gold result based on the dataset:\\n```bash\\npython -m feabench.get_gold_results \\\\\\n --dataset_name_or_path feabench-data/FEA-Bench-v1.0-Standard \\\\\\n --save_dir feabench-data/experiments/gold \\\\\\n --file_name Gold__FEABench_v1.0__test.jsonl\\n```\\n\\nThe command to run the evaluation script is as follows (using the gold result constructed above as an example):\\n```bash\\npython -m swebench.harness.run_evaluation \\\\\\n --dataset_name ../../feabench-data/FEA-Bench-v1.0-Standard \\\\\\n --predictions_path ../../feabench-data/experiments/gold/Gold__FEABench_v1.0__test.jsonl \\\\\\n --max_workers 10 \\\\\\n --cache_level instance \\\\\\n --timeout 900 \\\\\\n --run_id FEABench_v1_Gold\\n```\\nThe usage is identical to SWE-Bench. You can set the cache level `cache_level` based on your disk size. You should then obtain a result file similar to the following `.json` format:\\n```json\\n{\\n \\\"total_instances\\\": 1401,\\n \\\"submitted_instances\\\": 1401,\\n \\\"completed_instances\\\": 1401,\\n \\\"resolved_instances\\\": 1401,\\n \\\"unresolved_instances\\\": 0,\\n \\\"empty_patch_instances\\\": 0,\\n \\\"error_instances\\\": 0,\\n ...\\n}\\n```\\n\\nCongratulations! You have completed the usage of FEA-Bench. If you have any questions, please raise them in the issues.\\n\\n---\\n\\nFor more details, please refer to the [FEA-Bench Paper](https://arxiv.org/abs/2503.06680).\\nIf you find our work helpful, we would be grateful if you could cite our work.\\n```\\n@misc{li2025feabenchbenchmarkevaluatingrepositorylevel,\\n title={FEA-Bench: A Benchmark for Evaluating Repository-Level Code Generation for Feature Implementation}, \\n author={Wei Li and Xin Zhang and Zhongxin Guo and Shaoguang Mao and Wen Luo and Guangyue Peng and Yangyu Huang and Houfeng Wang and Scarlett Li},\\n year={2025},\\n eprint={2503.06680},\\n archivePrefix={arXiv},\\n primaryClass={cs.SE},\\n url={https://arxiv.org/abs/2503.06680}, \\n}\\n```\\n\\n\\n\\n## Contributing\\n\\nThis project welcomes contributions and suggestions. Most contributions require you to agree to a\\nContributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us\\nthe rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.\\n\\nWhen you submit a pull request, a CLA bot will automatically determine whether you need to provide\\na CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions\\nprovided by the bot. You will only need to do this once across all repos using our CLA.\\n\\nThis project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).\\nFor more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or\\ncontact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.\\n\\n## Trademarks\\n\\nThis project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft \\ntrademarks or logos is subject to and must follow \\n[Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general).\\nUse of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship.\\nAny use of third-party trademarks or logos are subject to those third-party's policies.\\n\"}"},"files":{"kind":"string","value":"{\"CHANGELOG.md\": \"# Changelog\\n\\nAll notable changes to this project will be documented in this file.\\n\\nThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),\\nand this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\\n\\n## [9.7.0] - Unreleased\\n\\n### Added\\n\\n- Added rich.tree\\n\\n## [9.6.2] - 2021-01-07\\n\\n### Fixed\\n\\n- Fixed markup escaping edge case https://github.com/willmcgugan/rich/issues/878\\n- Double tag escape, i.e. `\\\"\\\\\\\\[foo]\\\"` results in a backslash plus `[foo]` tag\\n\\n## [9.6.1] - 2020-12-31\\n\\n### Fixed\\n\\n- Fixed encoding error on Windows when loading code for Tracebacks\\n\\n## [9.6.0] - 2020-12-30\\n\\n### Changed\\n\\n- MarkupError exception raise from None to omit internal exception\\n- Factored out RichHandler.render and RichHandler.render_message for easier extending\\n- Display pretty printed value in rich.inspect\\n\\n### Added\\n\\n- Added Progress.TimeElapsedColumn\\n- Added IPython support to pretty.install\\n\\n### Fixed\\n\\n- Fixed display of locals in Traceback for stdin\\n\\n## [9.5.1] - 2020-12-19\\n\\n### Fixed\\n\\n- Fixed terminal size detection on Windows https://github.com/willmcgugan/rich/issues/836\\n- Fixed hex number highlighting\\n\\n## [9.5.0] - 2020-12-18\\n\\n### Changed\\n\\n- If file is not specified on Console then the Console.file will return the current sys.stdout. Prior to 9.5.0 sys.stdout was cached on the Console, which could break code that wrapped sys.stdout after the Console was constructed.\\n- Changed `Color.__str__` to not include ansi codes\\n- Changed Console.size to get the terminal dimensions via sys.stdin. This means that if you set file to be an io.StringIO file then the width will be set to the current terminal dimensions and not a default of 80.\\n\\n### Added\\n\\n- Added stderr parameter to Console\\n- Added rich.reconfigure\\n- Added `Color.__rich__`\\n- Added Console.soft_wrap\\n- Added Console.style parameter\\n- Added Table.highlight parameter to enable highlighting of cells\\n- Added Panel.highlight parameter to enable highlighting of panel title\\n- Added highlight to ConsoleOptions\\n\\n### Fixed\\n\\n- Fixed double output in rich.live https://github.com/willmcgugan/rich/issues/485\\n- Fixed Console.out highlighting not reflecting defaults https://github.com/willmcgugan/rich/issues/827\\n- FileProxy now raises TypeError for empty non-str arguments https://github.com/willmcgugan/rich/issues/828\\n\\n## [9.4.0] - 2020-12-12\\n\\n### Added\\n\\n- Added rich.live https://github.com/willmcgugan/rich/pull/382\\n- Added algin parameter to Rule and Console.rule\\n- Added rich.Status class and Console.status\\n- Added getitem to Text\\n- Added style parameter to Console.log\\n- Added rich.diagnose command\\n\\n### Changed\\n\\n- Table.add_row style argument now applies to entire line and not just cells\\n- Added end_section parameter to Table.add_row to force a line underneath row\\n\\n## Fixed\\n\\n- Fixed suppressed traceback context https://github.com/willmcgugan/rich/issues/468\\n\\n## [9.3.0] - 2020-12-1\\n\\n### Added\\n\\n- Added get_datetime parameter to Console, to allow for repeatable tests\\n- Added get_time parameter to Console\\n- Added rich.abc.RichRenderable\\n- Added expand_all to rich.pretty.install()\\n- Added locals_max_length, and locals_max_string to Traceback and logging.RichHandler\\n- Set defaults of max_length and max_string for Traceback to 10 and 80\\n- Added disable argument to Progress\\n\\n### Changed\\n\\n- Reformatted test card (python -m rich)\\n\\n### Fixed\\n\\n- Fixed redirecting of stderr in Progress\\n- Fixed broken expanded tuple of one https://github.com/willmcgugan/rich/issues/445\\n- Fixed traceback message with `from` exceptions\\n- Fixed justify argument not working in console.log https://github.com/willmcgugan/rich/issues/460\\n\\n## [9.2.0] - 2020-11-08\\n\\n### Added\\n\\n- Added tracebacks_show_locals parameter to RichHandler\\n- Added max_string to Pretty\\n- Added rich.ansi.AnsiDecoder\\n- Added decoding of ansi codes to captured stdout in Progress\\n- Added expand_all to rich.pretty.pprint\\n\\n### Changed\\n\\n- Applied dim=True to indent guide styles\\n- Factored out RichHandler.get_style_and_level to allow for overriding in subclasses\\n- Hid progress bars from html export\\n- rich.pretty.pprint now soft wraps\\n\\n## [9.1.0] - 2020-10-23\\n\\n### Added\\n\\n- Added Text.with_indentation_guide\\n- Added Text.detect_indentation\\n- Added Pretty.indent_guides\\n- Added Syntax.indent_guides\\n- Added indent_guides parameter on pretty.install\\n- Added rich.pretty.pprint\\n- Added max_length to Pretty\\n\\n### Changed\\n\\n- Enabled indent guides on Tracebacks\\n\\n### Fixed\\n\\n- Fixed negative time remaining in Progress bars https://github.com/willmcgugan/rich/issues/378\\n\\n## [9.0.1] - 2020-10-19\\n\\n### Fixed\\n\\n- Fixed broken ANSI codes in input on windows legacy https://github.com/willmcgugan/rich/issues/393\\n\\n## [9.0.0] - 2020-10-18\\n\\n### Fixed\\n\\n- Progress download column now displays decimal units\\n\\n### Added\\n\\n- Support for Python 3.9\\n- Added legacy_windows to ConsoleOptions\\n- Added ascii_only to ConsoleOptions\\n- Added box.SQUARE_DOUBLE_HEAD\\n- Added highlighting of EUI-48 and EUI-64 (MAC addresses)\\n- Added Console.pager\\n- Added Console.out\\n- Added binary_units in progress download column\\n- Added Progress.reset\\n- Added Style.background_style property\\n- Added Bar renderable https://github.com/willmcgugan/rich/pull/361\\n- Added Table.min_width\\n- Added table.Column.min_width and table.Column.max_width, and same to Table.add_column\\n\\n### Changed\\n\\n- Dropped box.get_safe_box function in favor of Box.substitute\\n- Changed default padding in Panel from 0 to (0, 1) https://github.com/willmcgugan/rich/issues/385\\n- Table with row_styles will extend background color between cells if the box has no vertical dividerhttps://github.com/willmcgugan/rich/issues/383\\n- Changed default of fit kwarg in render_group() from False to True\\n- Renamed rich.bar to rich.progress_bar, and Bar class to ProgressBar, rich.bar is now the new solid bar class\\n\\n### Fixed\\n\\n- Fixed typo in `Style.transparent_background` method name.\\n\\n## [8.0.0] - 2020-10-03\\n\\n### Added\\n\\n- Added Console.bell method\\n- Added Set to types that Console.print will automatically pretty print\\n- Added show_locals to Traceback\\n- Added theme stack mechanism, see Console.push_theme and Console.pop_theme\\n\\n### Changed\\n\\n- Changed Style.empty to Style.null to better reflect what it does\\n- Optimized combining styles involving a null style\\n- Change error messages in Style.parse to read better\\n\\n### Fixed\\n\\n- Fixed Table.\\\\_\\\\_rich_measure\\\\_\\\\_\\n- Fixed incorrect calculation of fixed width columns\\n\\n## [7.1.0] - 2020-09-26\\n\\n### Added\\n\\n- Added Console.begin_capture, Console.end_capture and Console.capture\\n- Added Table.title_justify and Table.caption_justify https://github.com/willmcgugan/rich/issues/301\\n\\n### Changed\\n\\n- Improved formatting of exceptions\\n- Enabled Rich exceptions in logging https://github.com/taliraj\\n- UTF-8 encoding is now mentioned in HTML head section\\n\\n### Removed\\n\\n- Removed line_numbers argument from traceback.install, which was undocumented and did nothing\\n\\n## [7.0.0] - 2020-09-18\\n\\n### Added\\n\\n- New ansi_dark and ansi_light themes\\n- Added Text.append_tokens for fast appending of string + Style pairs\\n- Added Text.remove_suffix\\n- Added Text.append_tokens\\n\\n### Changed\\n\\n- Text.tabs_to_spaces was renamed to Text.expand_tabs, which works in place rather than returning a new instance\\n- Renamed Column.index to Column.\\\\_index\\n- Optimized Style.combine and Style.chain\\n- Optimized text rendering by fixing internal cache mechanism\\n- Optimized hash generation for Styles\\n\\n## [6.2.0] - 2020-09-13\\n\\n### Added\\n\\n- Added inline code highlighting to Markdown\\n\\n## [6.1.2] - 2020-09-11\\n\\n### Added\\n\\n- Added ipv4 and ipv6 to ReprHighlighter\\n\\n### Changed\\n\\n- The `#` sign is included in url highlighting\\n\\n### Fixed\\n\\n- Fixed force-color switch in rich.syntax and rich.markdown commands\\n\\n## [6.1.1] - 2020-09-07\\n\\n### Changed\\n\\n- Restored \\\"def\\\" in inspect signature\\n\\n## [6.1.0] - 2020-09-07\\n\\n### Added\\n\\n- New inspect module\\n- Added os.\\\\_Environ to pretty print\\n\\n### Fixed\\n\\n- Prevented recursive renderables from getting stuck\\n\\n## Changed\\n\\n- force_terminal and force_jupyter can now be used to force the disabled state, or left as None to auto-detect.\\n- Panel now expands to fit title if supplied\\n\\n## [6.0.0] - 2020-08-25\\n\\n### Fixed\\n\\n- Fixed use of `__rich__` cast\\n\\n### Changed\\n\\n- New algorithm to pretty print which fits more on a line if possible\\n- Deprecated `character` parameter in Rule and Console.rule, in favor of `characters`\\n- Optimized Syntax.from_path to avoid searching all lexers, which also speeds up tracebacks\\n\\n### Added\\n\\n- Added soft_wrap flag to Console.print\\n\\n## [5.2.1] - 2020-08-19\\n\\n### Fixed\\n\\n- Fixed underscore with display hook https://github.com/willmcgugan/rich/issues/235\\n\\n## [5.2.0] - 2020-08-14\\n\\n### Changed\\n\\n- Added crop argument to Console.print\\n- Added \\\"ignore\\\" overflow method\\n- Added multiple characters per rule @hedythedev https://github.com/willmcgugan/rich/pull/207\\n\\n## [5.1.2] - 2020-08-10\\n\\n### Fixed\\n\\n- Further optimized pretty printing ~5X.\\n\\n## [5.1.1] - 2020-08-09\\n\\n### Fixed\\n\\n- Optimized pretty printing ~3X faster\\n\\n## [5.1.0] - 2020-08-08\\n\\n### Added\\n\\n- Added Text.cell_len\\n- Added helpful message regarding unicode decoding errors https://github.com/willmcgugan/rich/issues/212\\n- Added display hook with pretty.install()\\n\\n### Fixed\\n\\n- Fixed deprecation warnings re backslash https://github.com/willmcgugan/rich/issues/210\\n- Fixed repr highlighting of scientific notation, e.g. 1e100\\n\\n### Changed\\n\\n- Implemented pretty printing, and removed pprintpp from dependencies\\n- Optimized Text.join\\n\\n## [5.0.0] - 2020-08-02\\n\\n### Changed\\n\\n- Change to console markup syntax to not parse Python structures as markup, i.e. `[1,2,3]` is treated as a literal, not a tag.\\n- Standard color numbers syntax has changed to `\\\"color()\\\"` so that `[5]` (for example) is considered a literal.\\n- Markup escape method has changed from double brackets to preceding with a backslash, so `foo[[]]` would be `foo\\\\[bar]`\\n\\n## [4.2.2] - 2020-07-30\\n\\n### Changed\\n\\n- Added thread to automatically call update() in progress.track(). Replacing previous adaptive algorithm.\\n- Second attempt at working around https://bugs.python.org/issue37871\\n\\n## [4.2.1] - 2020-07-29\\n\\n### Added\\n\\n- Added show_time and show_level parameters to RichHandler https://github.com/willmcgugan/rich/pull/182\\n\\n### Fixed\\n\\n- Fixed progress.track iterator exiting early https://github.com/willmcgugan/rich/issues/189\\n- Added workaround for Python bug https://bugs.python.org/issue37871, fixing https://github.com/willmcgugan/rich/issues/186\\n\\n### Changed\\n\\n- Set overflow=fold for log messages https://github.com/willmcgugan/rich/issues/190\\n\\n## [4.2.0] - 2020-07-27\\n\\n### Fixed\\n\\n- Fixed missing new lines https://github.com/willmcgugan/rich/issues/178\\n- Fixed Progress.track https://github.com/willmcgugan/rich/issues/184\\n- Remove control codes from exported text https://github.com/willmcgugan/rich/issues/181\\n- Implemented auto-detection and color rendition of 16-color mode\\n\\n## [4.1.0] - 2020-07-26\\n\\n### Changed\\n\\n- Optimized progress.track for very quick iterations\\n- Force default size of 80x25 if get_terminal_size reports size of 0,0\\n\\n## [4.0.0] - 2020-07-23\\n\\nMajor version bump for a breaking change to `Text.stylize signature`, which corrects a minor but irritating API wart. The style now comes first and the `start` and `end` offsets default to the entire text. This allows for `text.stylize_all(style)` to be replaced with `text.stylize(style)`. The `start` and `end` offsets now support negative indexing, so `text.stylize(\\\"bold\\\", -1)` makes the last character bold.\\n\\n### Added\\n\\n- Added markup switch to RichHandler https://github.com/willmcgugan/rich/issues/171\\n\\n### Changed\\n\\n- Change signature of Text.stylize to accept style first\\n- Remove Text.stylize_all which is no longer necessary\\n\\n### Fixed\\n\\n- Fixed rendering of Confirm prompt https://github.com/willmcgugan/rich/issues/170\\n\\n## [3.4.1] - 2020-07-22\\n\\n### Fixed\\n\\n- Fixed incorrect default of expand in Table.grid\\n\\n## [3.4.0] - 2020-07-22\\n\\n### Added\\n\\n- Added stream parameter to Console.input\\n- Added password parameter to Console.input\\n- Added description parameter to Progress.update\\n- Added rich.prompt\\n- Added detecting 'dumb' terminals\\n- Added Text.styled alternative constructor\\n\\n### Fixes\\n\\n- Fixed progress bars so that they are readable when color is disabled\\n\\n## [3.3.2] - 2020-07-14\\n\\n### Changed\\n\\n- Optimized Text.pad\\n\\n### Added\\n\\n- Added rich.scope\\n- Change log_locals to use scope.render_scope\\n- Added title parameter to Columns\\n\\n## [3.3.1] - 2020-07-13\\n\\n### Added\\n\\n- box.ASCII_DOUBLE_HEAD\\n\\n### Changed\\n\\n- Removed replace of -- --- ... from Markdown, as it made it impossible to include CLI info\\n\\n## [3.3.0] - 2020-07-12\\n\\n### Added\\n\\n- Added title and title_align options to Panel\\n- Added pad and width parameters to Align\\n- Added end parameter to Rule\\n- Added Text.pad and Text.align methods\\n- Added leading parameter to Table\\n\\n## [3.2.0] - 2020-07-10\\n\\n### Added\\n\\n- Added Align.left Align.center Align.right shortcuts\\n- Added Panel.fit shortcut\\n- Added align parameter to Columns\\n\\n### Fixed\\n\\n- Align class now pads to the right, like Text\\n- ipywidgets added as an optional dependency\\n- Issue with Panel and background color\\n- Fixed missing `__bool__` on Segment\\n\\n### Changed\\n\\n- Added `border_style` argument to Panel (note, `style` now applies to interior of the panel)\\n\\n## [3.1.0] - 2020-07-09\\n\\n### Changed\\n\\n- Progress bars now work in Jupyter\\n\\n## Added\\n\\n- Added refresh_per_second to progress.track\\n- Added styles to BarColumn and progress.track\\n\\n## [3.0.5] - 2020-07-07\\n\\n### Fixed\\n\\n- Fixed Windows version number require for truecolor\\n\\n## [3.0.4] - 2020-07-07\\n\\n### Changed\\n\\n- More precise detection of Windows console https://github.com/willmcgugan/rich/issues/140\\n\\n## [3.0.3] - 2020-07-03\\n\\n### Fixed\\n\\n- Fixed edge case with wrapped and overflowed text\\n\\n### Changed\\n\\n- New algorithm for compressing table that priorities smaller columns\\n\\n### Added\\n\\n- Added safe_box parameter to Console constructor\\n\\n## [3.0.2] - 2020-07-02\\n\\n### Added\\n\\n- Added rich.styled.Styled class to apply styles to renderable\\n- Table.add_row now has an optional style parameter\\n- Added table_movie.py to examples\\n\\n### Changed\\n\\n- Modified box options to use half line characters at edges\\n- Non no_wrap columns will now shrink below minimum width if table is compressed\\n\\n## [3.0.1] - 2020-06-30\\n\\n### Added\\n\\n- Added box.ASCII2\\n- Added markup argument to logging extra\\n\\n### Changed\\n\\n- Setting a non-None width now implies expand=True\\n\\n## [3.0.0] - 2020-06-28\\n\\n### Changed\\n\\n- Enabled supported box chars for legacy Windows, and introduce `safe_box` flag\\n- Disable hyperlinks on legacy Windows\\n- Constructors for Rule and Panel now have keyword only arguments (reason for major version bump)\\n- Table.add_colum added keyword only arguments\\n\\n### Fixed\\n\\n- Fixed Table measure\\n\\n## [2.3.1] - 2020-06-26\\n\\n### Fixed\\n\\n- Disabled legacy_windows if jupyter is detected https://github.com/willmcgugan/rich/issues/125\\n\\n## [2.3.0] - 2020-06-26\\n\\n### Fixed\\n\\n- Fixed highlighting of paths / filenames\\n- Corrected docs for RichHandler which erroneously said default console writes to stderr\\n\\n### Changed\\n\\n- Allowed `style` parameter for `highlight_regex` to be a callable that returns a style\\n\\n### Added\\n\\n- Added optional highlighter parameter to RichHandler\\n\\n## [2.2.6] - 2020-06-24\\n\\n### Changed\\n\\n- Store a \\\"link id\\\" on Style instance, so links containing different styles are highlighted together. (https://github.com/willmcgugan/rich/pull/123)\\n\\n## [2.2.5] - 2020-06-23\\n\\n### Fixed\\n\\n- Fixed justify of tables (https://github.com/willmcgugan/rich/issues/117)\\n\\n## [2.2.4] - 2020-06-21\\n\\n### Added\\n\\n- Added enable_link_path to RichHandler\\n- Added legacy_windows switch to Console constructor\\n\\n## [2.2.3] - 2020-06-15\\n\\n### Fixed\\n\\n- Fixed console.log hyperlink not containing full path\\n\\n### Changed\\n\\n- Used random number for hyperlink id\\n\\n## [2.2.2] - 2020-06-14\\n\\n### Changed\\n\\n- Exposed RichHandler highlighter as a class var\\n\\n## [2.2.1] - 2020-06-14\\n\\n### Changed\\n\\n- Linked path in log render to file\\n\\n## [2.2.0] - 2020-06-14\\n\\n### Added\\n\\n- Added redirect_stdout and redirect_stderr to Progress\\n\\n### Changed\\n\\n- printing to console with an active Progress doesn't break visuals\\n\\n## [2.1.0] - 2020-06-11\\n\\n### Added\\n\\n- Added 'transient' option to Progress\\n\\n### Changed\\n\\n- Truncated overly long text in Rule with ellipsis overflow\\n\\n## [2.0.1] - 2020-06-10\\n\\n### Added\\n\\n- Added expand option to Padding\\n\\n### Changed\\n\\n- Some minor optimizations in Text\\n\\n### Fixed\\n\\n- Fixed broken rule with CJK text\\n\\n## [2.0.0] - 2020-06-06\\n\\n### Added\\n\\n- Added overflow methods\\n- Added no_wrap option to print()\\n- Added width option to print\\n- Improved handling of compressed tables\\n\\n### Fixed\\n\\n- Fixed erroneous space at end of log\\n- Fixed erroneous space at end of progress bar\\n\\n### Changed\\n\\n- Renamed \\\\_ratio.ratio_divide to \\\\_ratio.ratio_distribute\\n- Renamed JustifyValues to JustifyMethod (backwards incompatible)\\n- Optimized \\\\_trim_spans\\n- Enforced keyword args in Console / Text interfaces (backwards incompatible)\\n- Return self from text.append\\n\\n## [1.3.1] - 2020-06-01\\n\\n### Changed\\n\\n- Changed defaults of Table.grid\\n- Polished listdir.py example\\n\\n### Added\\n\\n- Added width argument to Columns\\n\\n### Fixed\\n\\n- Fixed for `columns_first` argument in Columns\\n- Fixed incorrect padding in columns with fixed width\\n\\n## [1.3.0] - 2020-05-31\\n\\n### Added\\n\\n- Added rich.get_console() function to get global console instance.\\n- Added Columns class\\n\\n### Changed\\n\\n- Updated `markdown.Heading.create()` to work with subclassing.\\n- Console now transparently works with Jupyter\\n\\n### Fixed\\n\\n- Fixed issue with broken table with show_edge=False and a non-None box arg\\n\\n## [1.2.3] - 2020-05-24\\n\\n### Added\\n\\n- Added `padding` parameter to Panel\\n- Added 'indeterminate' state when progress bars aren't started\\n\\n### Fixed\\n\\n- Fixed Progress deadlock https://github.com/willmcgugan/rich/issues/90\\n\\n### Changed\\n\\n- Auto-detect \\\"truecolor\\\" color system when in Windows Terminal\\n\\n## [1.2.2] - 2020-05-22\\n\\n### Fixed\\n\\n- Issue with right aligned wrapped text adding extra spaces\\n\\n## [1.2.1] - 2020-05-22\\n\\n### Fixed\\n\\n- Issue with sum and Style\\n\\n## [1.2.0] - 2020-05-22\\n\\n### Added\\n\\n- Support for double underline, framed, encircled, and overlined attributes\\n\\n### Changed\\n\\n- Optimized Style\\n- Changed methods `__console__` to `__rich_console__`, and `__measure__` to `__rich_measure__`\\n\\n## [1.1.9] - 2020-05-20\\n\\n### Fixed\\n\\n- Exception when BarColumn.bar_width == None\\n\\n## [1.1.8] - 2020-05-20\\n\\n### Changed\\n\\n- Optimizations for Segment, Console and Table\\n\\n### Added\\n\\n- Added Console.clear method\\n- Added exporting of links to HTML\\n\\n## [1.1.7] - 2020-05-19\\n\\n### Added\\n\\n- Added collapse_padding option to Table.\\n\\n### Changed\\n\\n- Some style attributes may be abbreviated (b for bold, i for italic etc). Previously abbreviations worked in console markup but only one at a time, i.e. \\\"[b]Hello[/]\\\" but not \\\"[b i]Hello[/]\\\" -- now they work everywhere.\\n- Renamed 'text' property on Text to 'plain'. i.e. text.plain returns a string version of the Text instance.\\n\\n### Fixed\\n\\n- Fixed zero division if total is 0 in progress bar\\n\\n## [1.1.6] - 2020-05-17\\n\\n### Added\\n\\n- Added rich.align.Align class\\n- Added justify argument to Console.print and console.log\\n\\n## [1.1.5] - 2020-05-15\\n\\n### Changed\\n\\n- Changed progress bars to write to stdout on terminal and hide on non-terminal\\n\\n## [1.1.4] - 2020-05-15\\n\\n### Fixed\\n\\n- Fixed incorrect file and link in progress.log\\n- Fixes for legacy windows: Bar, Panel, and Rule now use ASCII characters\\n- show_cursor is now a no-op on legacy windows\\n\\n### Added\\n\\n- Added Console.input\\n\\n### Changed\\n\\n- Disable progress bars when not writing to a terminal\\n\\n## [1.1.3] - 2020-05-14\\n\\n### Fixed\\n\\n- Issue with progress of one line`\\n\\n## [1.1.2] - 2020-05-14\\n\\n### Added\\n\\n- Added -p switch to python -m rich.markdown to page output\\n- Added Console.control to output control codes\\n\\n### Changed\\n\\n- Changed Console log_time_format to no longer require a space at the end\\n- Added print and log to Progress to render terminal output when progress is active\\n\\n## [1.1.1] - 2020-05-12\\n\\n### Changed\\n\\n- Stripped cursor moving control codes from text\\n\\n## [1.1.0] - 2020-05-10\\n\\n### Added\\n\\n- Added hyperlinks to Style and markup\\n- Added justify and code theme switches to markdown command\\n\\n## [1.0.3] - 2020-05-08\\n\\n### Added\\n\\n- Added `python -m rich.syntax` command\\n\\n## [1.0.2] - 2020-05-08\\n\\n### Fixed\\n\\n- Issue with Windows legacy support https://github.com/willmcgugan/rich/issues/59\\n\\n## [1.0.1] - 2020-05-08\\n\\n### Changed\\n\\n- Applied console markup after highlighting\\n- Documented highlighting\\n- Changed Markup parser to handle overlapping styles\\n- Relaxed dependency on colorama\\n- Allowed Theme to accept values as style definitions (str) as well as Style instances\\n- Added a panel to emphasize code in Markdown\\n\\n### Added\\n\\n- Added markup.escape\\n- Added `python -m rich.theme` command\\n- Added `python -m rich.markdown` command\\n- Added rendering of images in Readme (links only)\\n\\n### Fixed\\n\\n- Fixed Text.assemble not working with strings https://github.com/willmcgugan/rich/issues/57\\n- Fixed table when column widths must be compressed to fit\\n\\n## [1.0.0] - 2020-05-03\\n\\n### Changed\\n\\n- Improvements to repr highlighter to highlight URLs\\n\\n## [0.8.13] - 2020-04-28\\n\\n### Fixed\\n\\n- Fixed incorrect markdown rendering for quotes and changed style\\n\\n## [0.8.12] - 2020-04-21\\n\\n### Fixed\\n\\n- Removed debug print from rich.progress\\n\\n## [0.8.11] - 2020-04-14\\n\\n### Added\\n\\n- Added Table.show_lines to render lines between rows\\n\\n### Changed\\n\\n- Added markup escape with double square brackets\\n\\n## [0.8.10] - 2020-04-12\\n\\n### Fixed\\n\\n- Fix row_styles applying to header\\n\\n## [0.8.9] - 2020-04-12\\n\\n### Changed\\n\\n- Added force_terminal option to `Console.__init__`\\n\\n### Added\\n\\n- Added Table.row_styles to enable zebra striping.\\n\\n## [0.8.8] - 2020-03-31\\n\\n### Fixed\\n\\n- Fixed background in Syntax\\n\\n## [0.8.7] - 2020-03-31\\n\\n### Fixed\\n\\n- Broken wrapping of long lines\\n- Fixed wrapping in Syntax\\n\\n### Changed\\n\\n- Added word_wrap option to Syntax, which defaults to False.\\n- Added word_wrap option to Traceback.\\n\\n## [0.8.6] - 2020-03-29\\n\\n### Added\\n\\n- Experimental Jupyter notebook support: from rich.jupyter import print\\n\\n## [0.8.5] - 2020-03-29\\n\\n### Changed\\n\\n- Smarter number parsing regex for repr highlighter\\n\\n### Added\\n\\n- uuid highlighter for repr\\n\\n## [0.8.4] - 2020-03-28\\n\\n### Added\\n\\n- Added 'test card', run python -m rich\\n\\n### Changed\\n\\n- Detected windows terminal, defaulting to colorama support\\n\\n### Fixed\\n\\n- Fixed table scaling issue\\n\\n## [0.8.3] - 2020-03-27\\n\\n### Fixed\\n\\n- CJK right align\\n\\n## [0.8.2] - 2020-03-27\\n\\n### Changed\\n\\n- Fixed issue with 0 speed resulting in zero division error\\n- Changed signature of Progress.update\\n- Made calling start() a second time a no-op\\n\\n## [0.8.1] - 2020-03-22\\n\\n### Added\\n\\n- Added progress.DownloadColumn\\n\\n## [0.8.0] - 2020-03-17\\n\\n### Added\\n\\n- CJK support\\n- Console level highlight flag\\n- Added encoding argument to Syntax.from_path\\n\\n### Changed\\n\\n- Dropped support for Windows command prompt (try https://www.microsoft.com/en-gb/p/windows-terminal-preview/)\\n- Added task_id to Progress.track\\n\\n## [0.7.2] - 2020-03-15\\n\\n### Fixed\\n\\n- KeyError for missing pygments style\\n\\n## [0.7.1] - 2020-03-13\\n\\n### Fixed\\n\\n- Issue with control codes being used in length calculation\\n\\n### Changed\\n\\n- Remove current_style concept, which wasn't really used and was problematic for concurrency\\n\\n## [0.7.0] - 2020-03-12\\n\\n### Changed\\n\\n- Added width option to Panel\\n- Change special method `__render_width__` to `__measure__`\\n- Dropped the \\\"markdown style\\\" syntax in console markup\\n- Optimized style rendering\\n\\n### Added\\n\\n- Added Console.show_cursor method\\n- Added Progress bars\\n\\n### Fixed\\n\\n- Fixed wrapping when a single word was too large to fit in a line\\n\\n## [0.6.0] - 2020-03-03\\n\\n### Added\\n\\n- Added tab_size to Console and Text\\n- Added protocol.is_renderable for runtime check\\n- Added emoji switch to Console\\n- Added inherit boolean to Theme\\n- Made Console thread safe, with a thread local buffer\\n\\n### Changed\\n\\n- Console.markup attribute now effects Table\\n- SeparatedConsoleRenderable and RichCast types\\n\\n### Fixed\\n\\n- Fixed tabs breaking rendering by converting to spaces\\n\\n## [0.5.0] - 2020-02-23\\n\\n### Changed\\n\\n- Replaced `__console_str__` with `__rich__`\\n\\n## [0.4.1] - 2020-02-22\\n\\n### Fixed\\n\\n- Readme links in Pypi\\n\\n## [0.4.0] - 2020-02-22\\n\\n### Added\\n\\n- Added Traceback rendering and handler\\n- Added rich.constrain\\n- Added rich.rule\\n\\n### Fixed\\n\\n- Fixed unnecessary padding\\n\\n## [0.3.3] - 2020-02-04\\n\\n### Fixed\\n\\n- Fixed Windows color support\\n- Fixed line width on windows issue (https://github.com/willmcgugan/rich/issues/7)\\n- Fixed Pretty print on Windows\\n\\n## [0.3.2] - 2020-01-26\\n\\n### Added\\n\\n- Added rich.logging\\n\\n## [0.3.1] - 2020-01-22\\n\\n### Added\\n\\n- Added colorama for Windows support\\n\\n## [0.3.0] - 2020-01-19\\n\\n### Added\\n\\n- First official release, API still to be stabilized\\n\", \"rich/console.py\": \"import inspect\\nimport os\\nimport platform\\nimport shutil\\nimport sys\\nimport threading\\nfrom abc import ABC, abstractmethod\\nfrom collections import abc\\nfrom dataclasses import dataclass, field, replace\\nfrom datetime import datetime\\nfrom functools import wraps\\nfrom getpass import getpass\\nfrom time import monotonic\\nfrom typing import (\\n IO,\\n TYPE_CHECKING,\\n Any,\\n Callable,\\n Dict,\\n Iterable,\\n List,\\n NamedTuple,\\n Optional,\\n TextIO,\\n Union,\\n cast,\\n)\\n\\nfrom typing_extensions import Literal, Protocol, runtime_checkable\\n\\nfrom . import errors, themes\\nfrom ._emoji_replace import _emoji_replace\\nfrom ._log_render import LogRender\\nfrom .align import Align, AlignMethod\\nfrom .color import ColorSystem\\nfrom .control import Control\\nfrom .highlighter import NullHighlighter, ReprHighlighter\\nfrom .markup import render as render_markup\\nfrom .measure import Measurement, measure_renderables\\nfrom .pager import Pager, SystemPager\\nfrom .pretty import Pretty\\nfrom .scope import render_scope\\nfrom .segment import Segment\\nfrom .style import Style, StyleType\\nfrom .styled import Styled\\nfrom .terminal_theme import DEFAULT_TERMINAL_THEME, TerminalTheme\\nfrom .text import Text, TextType\\nfrom .theme import Theme, ThemeStack\\n\\nif TYPE_CHECKING:\\n from ._windows import WindowsConsoleFeatures\\n from .status import Status\\n\\nWINDOWS = platform.system() == \\\"Windows\\\"\\n\\nHighlighterType = Callable[[Union[str, \\\"Text\\\"]], \\\"Text\\\"]\\nJustifyMethod = Literal[\\\"default\\\", \\\"left\\\", \\\"center\\\", \\\"right\\\", \\\"full\\\"]\\nOverflowMethod = Literal[\\\"fold\\\", \\\"crop\\\", \\\"ellipsis\\\", \\\"ignore\\\"]\\n\\n\\nCONSOLE_HTML_FORMAT = \\\"\\\"\\\"\\\\\\n\\n\\n\\n\\n\\n\\n\\n \\n
{code}
\\n
\\n\\n\\n\\\"\\\"\\\"\\n\\n_TERM_COLORS = {\\\"256color\\\": ColorSystem.EIGHT_BIT, \\\"16color\\\": ColorSystem.STANDARD}\\n\\n\\n@dataclass\\nclass ConsoleOptions:\\n \\\"\\\"\\\"Options for __rich_console__ method.\\\"\\\"\\\"\\n\\n legacy_windows: bool\\n \\\"\\\"\\\"legacy_windows: flag for legacy windows.\\\"\\\"\\\"\\n min_width: int\\n \\\"\\\"\\\"Minimum width of renderable.\\\"\\\"\\\"\\n max_width: int\\n \\\"\\\"\\\"Maximum width of renderable.\\\"\\\"\\\"\\n is_terminal: bool\\n \\\"\\\"\\\"True if the target is a terminal, otherwise False.\\\"\\\"\\\"\\n encoding: str\\n \\\"\\\"\\\"Encoding of terminal.\\\"\\\"\\\"\\n justify: Optional[JustifyMethod] = None\\n \\\"\\\"\\\"Justify value override for renderable.\\\"\\\"\\\"\\n overflow: Optional[OverflowMethod] = None\\n \\\"\\\"\\\"Overflow value override for renderable.\\\"\\\"\\\"\\n no_wrap: Optional[bool] = False\\n \\\"\\\"\\\"Disable wrapping for text.\\\"\\\"\\\"\\n highlight: Optional[bool] = None\\n \\\"\\\"\\\"Highlight override for render_str.\\\"\\\"\\\"\\n\\n @property\\n def ascii_only(self) -> bool:\\n \\\"\\\"\\\"Check if renderables should use ascii only.\\\"\\\"\\\"\\n return not self.encoding.startswith(\\\"utf\\\")\\n\\n def update(\\n self,\\n width: int = None,\\n min_width: int = None,\\n max_width: int = None,\\n justify: JustifyMethod = None,\\n overflow: OverflowMethod = None,\\n no_wrap: bool = None,\\n highlight: bool = None,\\n ) -> \\\"ConsoleOptions\\\":\\n \\\"\\\"\\\"Update values, return a copy.\\\"\\\"\\\"\\n options = replace(self)\\n if width is not None:\\n options.min_width = options.max_width = width\\n if min_width is not None:\\n options.min_width = min_width\\n if max_width is not None:\\n options.max_width = max_width\\n if justify is not None:\\n options.justify = justify\\n if overflow is not None:\\n options.overflow = overflow\\n if no_wrap is not None:\\n options.no_wrap = no_wrap\\n if highlight is not None:\\n options.highlight = highlight\\n return options\\n\\n\\n@runtime_checkable\\nclass RichCast(Protocol):\\n \\\"\\\"\\\"An object that may be 'cast' to a console renderable.\\\"\\\"\\\"\\n\\n def __rich__(self) -> Union[\\\"ConsoleRenderable\\\", str]: # pragma: no cover\\n ...\\n\\n\\n@runtime_checkable\\nclass ConsoleRenderable(Protocol):\\n \\\"\\\"\\\"An object that supports the console protocol.\\\"\\\"\\\"\\n\\n def __rich_console__(\\n self, console: \\\"Console\\\", options: \\\"ConsoleOptions\\\"\\n ) -> \\\"RenderResult\\\": # pragma: no cover\\n ...\\n\\n\\nRenderableType = Union[ConsoleRenderable, RichCast, str]\\n\\\"\\\"\\\"A type that may be rendered by Console.\\\"\\\"\\\"\\n\\nRenderResult = Iterable[Union[RenderableType, Segment]]\\n\\\"\\\"\\\"The result of calling a __rich_console__ method.\\\"\\\"\\\"\\n\\n\\n_null_highlighter = NullHighlighter()\\n\\n\\nclass CaptureError(Exception):\\n \\\"\\\"\\\"An error in the Capture context manager.\\\"\\\"\\\"\\n\\n\\nclass Capture:\\n \\\"\\\"\\\"Context manager to capture the result of printing to the console.\\n See :meth:`~rich.console.Console.capture` for how to use.\\n\\n Args:\\n console (Console): A console instance to capture output.\\n \\\"\\\"\\\"\\n\\n def __init__(self, console: \\\"Console\\\") -> None:\\n self._console = console\\n self._result: Optional[str] = None\\n\\n def __enter__(self) -> \\\"Capture\\\":\\n self._console.begin_capture()\\n return self\\n\\n def __exit__(self, exc_type, exc_val, exc_tb) -> None:\\n self._result = self._console.end_capture()\\n\\n def get(self) -> str:\\n \\\"\\\"\\\"Get the result of the capture.\\\"\\\"\\\"\\n if self._result is None:\\n raise CaptureError(\\n \\\"Capture result is not available until context manager exits.\\\"\\n )\\n return self._result\\n\\n\\nclass ThemeContext:\\n \\\"\\\"\\\"A context manager to use a temporary theme. See :meth:`~rich.console.Console.theme` for usage.\\\"\\\"\\\"\\n\\n def __init__(self, console: \\\"Console\\\", theme: Theme, inherit: bool = True) -> None:\\n self.console = console\\n self.theme = theme\\n self.inherit = inherit\\n\\n def __enter__(self) -> \\\"ThemeContext\\\":\\n self.console.push_theme(self.theme)\\n return self\\n\\n def __exit__(self, exc_type, exc_val, exc_tb) -> None:\\n self.console.pop_theme()\\n\\n\\nclass PagerContext:\\n \\\"\\\"\\\"A context manager that 'pages' content. See :meth:`~rich.console.Console.pager` for usage.\\\"\\\"\\\"\\n\\n def __init__(\\n self,\\n console: \\\"Console\\\",\\n pager: Pager = None,\\n styles: bool = False,\\n links: bool = False,\\n ) -> None:\\n self._console = console\\n self.pager = SystemPager() if pager is None else pager\\n self.styles = styles\\n self.links = links\\n\\n def __enter__(self) -> \\\"PagerContext\\\":\\n self._console._enter_buffer()\\n return self\\n\\n def __exit__(self, exc_type, exc_val, exc_tb) -> None:\\n if exc_type is None:\\n with self._console._lock:\\n buffer: List[Segment] = self._console._buffer[:]\\n del self._console._buffer[:]\\n segments: Iterable[Segment] = buffer\\n if not self.styles:\\n segments = Segment.strip_styles(segments)\\n elif not self.links:\\n segments = Segment.strip_links(segments)\\n content = self._console._render_buffer(segments)\\n self.pager.show(content)\\n self._console._exit_buffer()\\n\\n\\nclass RenderGroup:\\n \\\"\\\"\\\"Takes a group of renderables and returns a renderable object that renders the group.\\n\\n Args:\\n renderables (Iterable[RenderableType]): An iterable of renderable objects.\\n fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.\\n \\\"\\\"\\\"\\n\\n def __init__(self, *renderables: \\\"RenderableType\\\", fit: bool = True) -> None:\\n self._renderables = renderables\\n self.fit = fit\\n self._render: Optional[List[RenderableType]] = None\\n\\n @property\\n def renderables(self) -> List[\\\"RenderableType\\\"]:\\n if self._render is None:\\n self._render = list(self._renderables)\\n return self._render\\n\\n def __rich_measure__(self, console: \\\"Console\\\", max_width: int) -> \\\"Measurement\\\":\\n if self.fit:\\n return measure_renderables(console, self.renderables, max_width)\\n else:\\n return Measurement(max_width, max_width)\\n\\n def __rich_console__(\\n self, console: \\\"Console\\\", options: \\\"ConsoleOptions\\\"\\n ) -> RenderResult:\\n yield from self.renderables\\n\\n\\ndef render_group(fit: bool = True) -> Callable:\\n \\\"\\\"\\\"A decorator that turns an iterable of renderables in to a group.\\n\\n Args:\\n fit (bool, optional): Fit dimension of group to contents, or fill available space. Defaults to True.\\n \\\"\\\"\\\"\\n\\n def decorator(method):\\n \\\"\\\"\\\"Convert a method that returns an iterable of renderables in to a RenderGroup.\\\"\\\"\\\"\\n\\n @wraps(method)\\n def _replace(*args, **kwargs):\\n renderables = method(*args, **kwargs)\\n return RenderGroup(*renderables, fit=fit)\\n\\n return _replace\\n\\n return decorator\\n\\n\\nclass ConsoleDimensions(NamedTuple):\\n \\\"\\\"\\\"Size of the terminal.\\\"\\\"\\\"\\n\\n width: int\\n \\\"\\\"\\\"The width of the console in 'cells'.\\\"\\\"\\\"\\n height: int\\n \\\"\\\"\\\"The height of the console in lines.\\\"\\\"\\\"\\n\\n\\ndef _is_jupyter() -> bool: # pragma: no cover\\n \\\"\\\"\\\"Check if we're running in a Jupyter notebook.\\\"\\\"\\\"\\n try:\\n get_ipython # type: ignore\\n except NameError:\\n return False\\n shell = get_ipython().__class__.__name__ # type: ignore\\n if shell == \\\"ZMQInteractiveShell\\\":\\n return True # Jupyter notebook or qtconsole\\n elif shell == \\\"TerminalInteractiveShell\\\":\\n return False # Terminal running IPython\\n else:\\n return False # Other type (?)\\n\\n\\nCOLOR_SYSTEMS = {\\n \\\"standard\\\": ColorSystem.STANDARD,\\n \\\"256\\\": ColorSystem.EIGHT_BIT,\\n \\\"truecolor\\\": ColorSystem.TRUECOLOR,\\n \\\"windows\\\": ColorSystem.WINDOWS,\\n}\\n\\n\\n_COLOR_SYSTEMS_NAMES = {system: name for name, system in COLOR_SYSTEMS.items()}\\n\\n\\n@dataclass\\nclass ConsoleThreadLocals(threading.local):\\n \\\"\\\"\\\"Thread local values for Console context.\\\"\\\"\\\"\\n\\n theme_stack: ThemeStack\\n buffer: List[Segment] = field(default_factory=list)\\n buffer_index: int = 0\\n\\n\\nclass RenderHook(ABC):\\n \\\"\\\"\\\"Provides hooks in to the render process.\\\"\\\"\\\"\\n\\n @abstractmethod\\n def process_renderables(\\n self, renderables: List[ConsoleRenderable]\\n ) -> List[ConsoleRenderable]:\\n \\\"\\\"\\\"Called with a list of objects to render.\\n\\n This method can return a new list of renderables, or modify and return the same list.\\n\\n Args:\\n renderables (List[ConsoleRenderable]): A number of renderable objects.\\n\\n Returns:\\n List[ConsoleRenderable]: A replacement list of renderables.\\n \\\"\\\"\\\"\\n\\n\\n_windows_console_features: Optional[\\\"WindowsConsoleFeatures\\\"] = None\\n\\n\\ndef get_windows_console_features() -> \\\"WindowsConsoleFeatures\\\": # pragma: no cover\\n global _windows_console_features\\n if _windows_console_features is not None:\\n return _windows_console_features\\n from ._windows import get_windows_console_features\\n\\n _windows_console_features = get_windows_console_features()\\n return _windows_console_features\\n\\n\\ndef detect_legacy_windows() -> bool:\\n \\\"\\\"\\\"Detect legacy Windows.\\\"\\\"\\\"\\n return WINDOWS and not get_windows_console_features().vt\\n\\n\\nif detect_legacy_windows(): # pragma: no cover\\n from colorama import init\\n\\n init()\\n\\n\\nclass Console:\\n \\\"\\\"\\\"A high level console interface.\\n\\n Args:\\n color_system (str, optional): The color system supported by your terminal,\\n either ``\\\"standard\\\"``, ``\\\"256\\\"`` or ``\\\"truecolor\\\"``. Leave as ``\\\"auto\\\"`` to autodetect.\\n force_terminal (Optional[bool], optional): Enable/disable terminal control codes, or None to auto-detect terminal. Defaults to None.\\n force_jupyter (Optional[bool], optional): Enable/disable Jupyter rendering, or None to auto-detect Jupyter. Defaults to None.\\n soft_wrap (Optional[bool], optional): Set soft wrap default on print method. Defaults to False.\\n theme (Theme, optional): An optional style theme object, or ``None`` for default theme.\\n stderr (bool, optional): Use stderr rather than stdout if ``file `` is not specified. Defaults to False.\\n file (IO, optional): A file object where the console should write to. Defaults to stdout.\\n width (int, optional): The width of the terminal. Leave as default to auto-detect width.\\n height (int, optional): The height of the terminal. Leave as default to auto-detect height.\\n style (StyleType, optional): Style to apply to all output, or None for no style. Defaults to None.\\n record (bool, optional): Boolean to enable recording of terminal output,\\n required to call :meth:`export_html` and :meth:`export_text`. Defaults to False.\\n markup (bool, optional): Boolean to enable :ref:`console_markup`. Defaults to True.\\n emoji (bool, optional): Enable emoji code. Defaults to True.\\n highlight (bool, optional): Enable automatic highlighting. Defaults to True.\\n log_time (bool, optional): Boolean to enable logging of time by :meth:`log` methods. Defaults to True.\\n log_path (bool, optional): Boolean to enable the logging of the caller by :meth:`log`. Defaults to True.\\n log_time_format (str, optional): Log time format if ``log_time`` is enabled. Defaults to \\\"[%X] \\\".\\n highlighter (HighlighterType, optional): Default highlighter.\\n legacy_windows (bool, optional): Enable legacy Windows mode, or ``None`` to auto detect. Defaults to ``None``.\\n safe_box (bool, optional): Restrict box options that don't render on legacy Windows.\\n get_datetime (Callable[[], datetime], optional): Callable that gets the current time as a datetime.datetime object (used by Console.log),\\n or None for datetime.now.\\n get_time (Callable[[], time], optional): Callable that gets the current time in seconds, default uses time.monotonic.\\n \\\"\\\"\\\"\\n\\n def __init__(\\n self,\\n *,\\n color_system: Optional[\\n Literal[\\\"auto\\\", \\\"standard\\\", \\\"256\\\", \\\"truecolor\\\", \\\"windows\\\"]\\n ] = \\\"auto\\\",\\n force_terminal: bool = None,\\n force_jupyter: bool = None,\\n soft_wrap: bool = False,\\n theme: Theme = None,\\n stderr: bool = False,\\n file: IO[str] = None,\\n width: int = None,\\n height: int = None,\\n style: StyleType = None,\\n tab_size: int = 8,\\n record: bool = False,\\n markup: bool = True,\\n emoji: bool = True,\\n highlight: bool = True,\\n log_time: bool = True,\\n log_path: bool = True,\\n log_time_format: str = \\\"[%X]\\\",\\n highlighter: Optional[\\\"HighlighterType\\\"] = ReprHighlighter(),\\n legacy_windows: bool = None,\\n safe_box: bool = True,\\n get_datetime: Callable[[], datetime] = None,\\n get_time: Callable[[], float] = None,\\n _environ: Dict[str, str] = None,\\n ):\\n # Copy of os.environ allows us to replace it for testing\\n self._environ = os.environ if _environ is None else _environ\\n\\n self.is_jupyter = _is_jupyter() if force_jupyter is None else force_jupyter\\n if self.is_jupyter:\\n width = width or 93\\n height = height or 100\\n self.soft_wrap = soft_wrap\\n self._width = width\\n self._height = height\\n self.tab_size = tab_size\\n self.record = record\\n self._markup = markup\\n self._emoji = emoji\\n self._highlight = highlight\\n self.legacy_windows: bool = (\\n (detect_legacy_windows() and not self.is_jupyter)\\n if legacy_windows is None\\n else legacy_windows\\n )\\n\\n self._color_system: Optional[ColorSystem]\\n self._force_terminal = force_terminal\\n self._file = file\\n self.stderr = stderr\\n\\n if color_system is None:\\n self._color_system = None\\n elif color_system == \\\"auto\\\":\\n self._color_system = self._detect_color_system()\\n else:\\n self._color_system = COLOR_SYSTEMS[color_system]\\n\\n self._lock = threading.RLock()\\n self._log_render = LogRender(\\n show_time=log_time,\\n show_path=log_path,\\n time_format=log_time_format,\\n )\\n self.highlighter: HighlighterType = highlighter or _null_highlighter\\n self.safe_box = safe_box\\n self.get_datetime = get_datetime or datetime.now\\n self.get_time = get_time or monotonic\\n self.style = style\\n\\n self._record_buffer_lock = threading.RLock()\\n self._thread_locals = ConsoleThreadLocals(\\n theme_stack=ThemeStack(themes.DEFAULT if theme is None else theme)\\n )\\n self._record_buffer: List[Segment] = []\\n self._render_hooks: List[RenderHook] = []\\n\\n def __repr__(self) -> str:\\n return f\\\"\\\"\\n\\n @property\\n def file(self) -> IO[str]:\\n \\\"\\\"\\\"Get the file object to write to.\\\"\\\"\\\"\\n file = self._file or (sys.stderr if self.stderr else sys.stdout)\\n file = getattr(file, \\\"rich_proxied_file\\\", file)\\n return file\\n\\n @file.setter\\n def file(self, new_file: IO[str]) -> None:\\n \\\"\\\"\\\"Set a new file object.\\\"\\\"\\\"\\n self._file = new_file\\n\\n @property\\n def _buffer(self) -> List[Segment]:\\n \\\"\\\"\\\"Get a thread local buffer.\\\"\\\"\\\"\\n return self._thread_locals.buffer\\n\\n @property\\n def _buffer_index(self) -> int:\\n \\\"\\\"\\\"Get a thread local buffer.\\\"\\\"\\\"\\n return self._thread_locals.buffer_index\\n\\n @_buffer_index.setter\\n def _buffer_index(self, value: int) -> None:\\n self._thread_locals.buffer_index = value\\n\\n @property\\n def _theme_stack(self) -> ThemeStack:\\n \\\"\\\"\\\"Get the thread local theme stack.\\\"\\\"\\\"\\n return self._thread_locals.theme_stack\\n\\n def _detect_color_system(self) -> Optional[ColorSystem]:\\n \\\"\\\"\\\"Detect color system from env vars.\\\"\\\"\\\"\\n if self.is_jupyter:\\n return ColorSystem.TRUECOLOR\\n if not self.is_terminal or \\\"NO_COLOR\\\" in self._environ or self.is_dumb_terminal:\\n return None\\n if WINDOWS: # pragma: no cover\\n if self.legacy_windows: # pragma: no cover\\n return ColorSystem.WINDOWS\\n windows_console_features = get_windows_console_features()\\n return (\\n ColorSystem.TRUECOLOR\\n if windows_console_features.truecolor\\n else ColorSystem.EIGHT_BIT\\n )\\n else:\\n color_term = self._environ.get(\\\"COLORTERM\\\", \\\"\\\").strip().lower()\\n if color_term in (\\\"truecolor\\\", \\\"24bit\\\"):\\n return ColorSystem.TRUECOLOR\\n term = self._environ.get(\\\"TERM\\\", \\\"\\\").strip().lower()\\n _term_name, _hyphen, colors = term.partition(\\\"-\\\")\\n color_system = _TERM_COLORS.get(colors, ColorSystem.STANDARD)\\n return color_system\\n\\n def _enter_buffer(self) -> None:\\n \\\"\\\"\\\"Enter in to a buffer context, and buffer all output.\\\"\\\"\\\"\\n self._buffer_index += 1\\n\\n def _exit_buffer(self) -> None:\\n \\\"\\\"\\\"Leave buffer context, and render content if required.\\\"\\\"\\\"\\n self._buffer_index -= 1\\n self._check_buffer()\\n\\n def push_render_hook(self, hook: RenderHook) -> None:\\n \\\"\\\"\\\"Add a new render hook to the stack.\\n\\n Args:\\n hook (RenderHook): Render hook instance.\\n \\\"\\\"\\\"\\n\\n self._render_hooks.append(hook)\\n\\n def pop_render_hook(self) -> None:\\n \\\"\\\"\\\"Pop the last renderhook from the stack.\\\"\\\"\\\"\\n self._render_hooks.pop()\\n\\n def __enter__(self) -> \\\"Console\\\":\\n \\\"\\\"\\\"Own context manager to enter buffer context.\\\"\\\"\\\"\\n self._enter_buffer()\\n return self\\n\\n def __exit__(self, exc_type, exc_value, traceback) -> None:\\n \\\"\\\"\\\"Exit buffer context.\\\"\\\"\\\"\\n self._exit_buffer()\\n\\n def begin_capture(self) -> None:\\n \\\"\\\"\\\"Begin capturing console output. Call :meth:`end_capture` to exit capture mode and return output.\\\"\\\"\\\"\\n self._enter_buffer()\\n\\n def end_capture(self) -> str:\\n \\\"\\\"\\\"End capture mode and return captured string.\\n\\n Returns:\\n str: Console output.\\n \\\"\\\"\\\"\\n render_result = self._render_buffer(self._buffer)\\n del self._buffer[:]\\n self._exit_buffer()\\n return render_result\\n\\n def push_theme(self, theme: Theme, *, inherit: bool = True) -> None:\\n \\\"\\\"\\\"Push a new theme on to the top of the stack, replacing the styles from the previous theme.\\n Generally speaking, you should call :meth:`~rich.console.Console.use_theme` to get a context manager, rather\\n than calling this method directly.\\n\\n Args:\\n theme (Theme): A theme instance.\\n inherit (bool, optional): Inherit existing styles. Defaults to True.\\n \\\"\\\"\\\"\\n self._theme_stack.push_theme(theme, inherit=inherit)\\n\\n def pop_theme(self) -> None:\\n \\\"\\\"\\\"Remove theme from top of stack, restoring previous theme.\\\"\\\"\\\"\\n self._theme_stack.pop_theme()\\n\\n def use_theme(self, theme: Theme, *, inherit: bool = True) -> ThemeContext:\\n \\\"\\\"\\\"Use a different theme for the duration of the context manager.\\n\\n Args:\\n theme (Theme): Theme instance to user.\\n inherit (bool, optional): Inherit existing console styles. Defaults to True.\\n\\n Returns:\\n ThemeContext: [description]\\n \\\"\\\"\\\"\\n return ThemeContext(self, theme, inherit)\\n\\n @property\\n def color_system(self) -> Optional[str]:\\n \\\"\\\"\\\"Get color system string.\\n\\n Returns:\\n Optional[str]: \\\"standard\\\", \\\"256\\\" or \\\"truecolor\\\".\\n \\\"\\\"\\\"\\n\\n if self._color_system is not None:\\n return _COLOR_SYSTEMS_NAMES[self._color_system]\\n else:\\n return None\\n\\n @property\\n def encoding(self) -> str:\\n \\\"\\\"\\\"Get the encoding of the console file, e.g. ``\\\"utf-8\\\"``.\\n\\n Returns:\\n str: A standard encoding string.\\n \\\"\\\"\\\"\\n return (getattr(self.file, \\\"encoding\\\", \\\"utf-8\\\") or \\\"utf-8\\\").lower()\\n\\n @property\\n def is_terminal(self) -> bool:\\n \\\"\\\"\\\"Check if the console is writing to a terminal.\\n\\n Returns:\\n bool: True if the console writing to a device capable of\\n understanding terminal codes, otherwise False.\\n \\\"\\\"\\\"\\n if self._force_terminal is not None:\\n return self._force_terminal\\n isatty = getattr(self.file, \\\"isatty\\\", None)\\n return False if isatty is None else isatty()\\n\\n @property\\n def is_dumb_terminal(self) -> bool:\\n \\\"\\\"\\\"Detect dumb terminal.\\n\\n Returns:\\n bool: True if writing to a dumb terminal, otherwise False.\\n\\n \\\"\\\"\\\"\\n _term = self._environ.get(\\\"TERM\\\", \\\"\\\")\\n is_dumb = _term.lower() in (\\\"dumb\\\", \\\"unknown\\\")\\n return self.is_terminal and is_dumb\\n\\n @property\\n def options(self) -> ConsoleOptions:\\n \\\"\\\"\\\"Get default console options.\\\"\\\"\\\"\\n return ConsoleOptions(\\n legacy_windows=self.legacy_windows,\\n min_width=1,\\n max_width=self.width,\\n encoding=self.encoding,\\n is_terminal=self.is_terminal,\\n )\\n\\n @property\\n def size(self) -> ConsoleDimensions:\\n \\\"\\\"\\\"Get the size of the console.\\n\\n Returns:\\n ConsoleDimensions: A named tuple containing the dimensions.\\n \\\"\\\"\\\"\\n\\n if self._width is not None and self._height is not None:\\n return ConsoleDimensions(self._width, self._height)\\n\\n if self.is_dumb_terminal:\\n return ConsoleDimensions(80, 25)\\n\\n width: Optional[int] = None\\n height: Optional[int] = None\\n if WINDOWS: # pragma: no cover\\n width, height = shutil.get_terminal_size()\\n else:\\n try:\\n width, height = os.get_terminal_size(sys.stdin.fileno())\\n except (AttributeError, ValueError, OSError):\\n pass\\n\\n # get_terminal_size can report 0, 0 if run from pseudo-terminal\\n width = width or 80\\n height = height or 25\\n return ConsoleDimensions(\\n (width - self.legacy_windows) if self._width is None else self._width,\\n height if self._height is None else self._height,\\n )\\n\\n @property\\n def width(self) -> int:\\n \\\"\\\"\\\"Get the width of the console.\\n\\n Returns:\\n int: The width (in characters) of the console.\\n \\\"\\\"\\\"\\n width, _ = self.size\\n return width\\n\\n def bell(self) -> None:\\n \\\"\\\"\\\"Play a 'bell' sound (if supported by the terminal).\\\"\\\"\\\"\\n self.control(\\\"\\\\x07\\\")\\n\\n def capture(self) -> Capture:\\n \\\"\\\"\\\"A context manager to *capture* the result of print() or log() in a string,\\n rather than writing it to the console.\\n\\n Example:\\n >>> from rich.console import Console\\n >>> console = Console()\\n >>> with console.capture() as capture:\\n ... console.print(\\\"[bold magenta]Hello World[/]\\\")\\n >>> print(capture.get())\\n\\n Returns:\\n Capture: Context manager with disables writing to the terminal.\\n \\\"\\\"\\\"\\n capture = Capture(self)\\n return capture\\n\\n def pager(\\n self, pager: Pager = None, styles: bool = False, links: bool = False\\n ) -> PagerContext:\\n \\\"\\\"\\\"A context manager to display anything printed within a \\\"pager\\\". The pager application\\n is defined by the system and will typically support at least pressing a key to scroll.\\n\\n Args:\\n pager (Pager, optional): A pager object, or None to use :class:~rich.pager.SystemPager`. Defaults to None.\\n styles (bool, optional): Show styles in pager. Defaults to False.\\n links (bool, optional): Show links in pager. Defaults to False.\\n\\n Example:\\n >>> from rich.console import Console\\n >>> from rich.__main__ import make_test_card\\n >>> console = Console()\\n >>> with console.pager():\\n console.print(make_test_card())\\n\\n Returns:\\n PagerContext: A context manager.\\n \\\"\\\"\\\"\\n return PagerContext(self, pager=pager, styles=styles, links=links)\\n\\n def line(self, count: int = 1) -> None:\\n \\\"\\\"\\\"Write new line(s).\\n\\n Args:\\n count (int, optional): Number of new lines. Defaults to 1.\\n \\\"\\\"\\\"\\n\\n assert count >= 0, \\\"count must be >= 0\\\"\\n if count:\\n self._buffer.append(Segment(\\\"\\\\n\\\" * count))\\n self._check_buffer()\\n\\n def clear(self, home: bool = True) -> None:\\n \\\"\\\"\\\"Clear the screen.\\n\\n Args:\\n home (bool, optional): Also move the cursor to 'home' position. Defaults to True.\\n \\\"\\\"\\\"\\n self.control(\\\"\\\\033[2J\\\\033[H\\\" if home else \\\"\\\\033[2J\\\")\\n\\n def status(\\n self,\\n status: RenderableType,\\n spinner: str = \\\"dots\\\",\\n spinner_style: str = \\\"status.spinner\\\",\\n speed: float = 1.0,\\n refresh_per_second: float = 12.5,\\n ) -> \\\"Status\\\":\\n \\\"\\\"\\\"Display a status and spinner.\\n\\n Args:\\n status (RenderableType): A status renderable (str or Text typically).\\n console (Console, optional): Console instance to use, or None for global console. Defaults to None.\\n spinner (str, optional): Name of spinner animation (see python -m rich.spinner). Defaults to \\\"dots\\\".\\n spinner_style (StyleType, optional): Style of spinner. Defaults to \\\"status.spinner\\\".\\n speed (float, optional): Speed factor for spinner animation. Defaults to 1.0.\\n refresh_per_second (float, optional): Number of refreshes per second. Defaults to 12.5.\\n\\n Returns:\\n Status: A Status object that may be used as a context manager.\\n \\\"\\\"\\\"\\n from .status import Status\\n\\n status_renderable = Status(\\n status,\\n console=self,\\n spinner=spinner,\\n spinner_style=spinner_style,\\n speed=speed,\\n refresh_per_second=refresh_per_second,\\n )\\n return status_renderable\\n\\n def show_cursor(self, show: bool = True) -> None:\\n \\\"\\\"\\\"Show or hide the cursor.\\n\\n Args:\\n show (bool, optional): Set visibility of the cursor.\\n \\\"\\\"\\\"\\n if self.is_terminal and not self.legacy_windows:\\n self.control(\\\"\\\\033[?25h\\\" if show else \\\"\\\\033[?25l\\\")\\n\\n def render(\\n self, renderable: RenderableType, options: ConsoleOptions = None\\n ) -> Iterable[Segment]:\\n \\\"\\\"\\\"Render an object in to an iterable of `Segment` instances.\\n\\n This method contains the logic for rendering objects with the console protocol.\\n You are unlikely to need to use it directly, unless you are extending the library.\\n\\n Args:\\n renderable (RenderableType): An object supporting the console protocol, or\\n an object that may be converted to a string.\\n options (ConsoleOptions, optional): An options object, or None to use self.options. Defaults to None.\\n\\n Returns:\\n Iterable[Segment]: An iterable of segments that may be rendered.\\n \\\"\\\"\\\"\\n\\n _options = options or self.options\\n if _options.max_width < 1:\\n # No space to render anything. This prevents potential recursion errors.\\n return\\n render_iterable: RenderResult\\n if isinstance(renderable, RichCast):\\n renderable = renderable.__rich__()\\n if isinstance(renderable, ConsoleRenderable):\\n render_iterable = renderable.__rich_console__(self, _options)\\n elif isinstance(renderable, str):\\n yield from self.render(\\n self.render_str(renderable, highlight=_options.highlight), _options\\n )\\n return\\n else:\\n raise errors.NotRenderableError(\\n f\\\"Unable to render {renderable!r}; \\\"\\n \\\"A str, Segment or object with __rich_console__ method is required\\\"\\n )\\n\\n try:\\n iter_render = iter(render_iterable)\\n except TypeError:\\n raise errors.NotRenderableError(\\n f\\\"object {render_iterable!r} is not renderable\\\"\\n )\\n for render_output in iter_render:\\n if isinstance(render_output, Segment):\\n yield render_output\\n else:\\n yield from self.render(render_output, _options)\\n\\n def render_lines(\\n self,\\n renderable: RenderableType,\\n options: Optional[ConsoleOptions] = None,\\n *,\\n style: Optional[Style] = None,\\n pad: bool = True,\\n ) -> List[List[Segment]]:\\n \\\"\\\"\\\"Render objects in to a list of lines.\\n\\n The output of render_lines is useful when further formatting of rendered console text\\n is required, such as the Panel class which draws a border around any renderable object.\\n\\n Args:\\n renderable (RenderableType): Any object renderable in the console.\\n options (Optional[ConsoleOptions], optional): Console options, or None to use self.options. Default to ``None``.\\n style (Style, optional): Optional style to apply to renderables. Defaults to ``None``.\\n pad (bool, optional): Pad lines shorter than render width. Defaults to ``True``.\\n\\n Returns:\\n List[List[Segment]]: A list of lines, where a line is a list of Segment objects.\\n \\\"\\\"\\\"\\n render_options = options or self.options\\n _rendered = self.render(renderable, render_options)\\n if style is not None:\\n _rendered = Segment.apply_style(_rendered, style)\\n lines = list(\\n Segment.split_and_crop_lines(\\n _rendered, render_options.max_width, include_new_lines=False, pad=pad\\n )\\n )\\n return lines\\n\\n def render_str(\\n self,\\n text: str,\\n *,\\n style: Union[str, Style] = \\\"\\\",\\n justify: JustifyMethod = None,\\n overflow: OverflowMethod = None,\\n emoji: bool = None,\\n markup: bool = None,\\n highlight: bool = None,\\n highlighter: HighlighterType = None,\\n ) -> \\\"Text\\\":\\n \\\"\\\"\\\"Convert a string to a Text instance. This is is called automatically if\\n you print or log a string.\\n\\n Args:\\n text (str): Text to render.\\n style (Union[str, Style], optional): Style to apply to rendered text.\\n justify (str, optional): Justify method: \\\"default\\\", \\\"left\\\", \\\"center\\\", \\\"full\\\", or \\\"right\\\". Defaults to ``None``.\\n overflow (str, optional): Overflow method: \\\"crop\\\", \\\"fold\\\", or \\\"ellipsis\\\". Defaults to ``None``.\\n emoji (Optional[bool], optional): Enable emoji, or ``None`` to use Console default.\\n markup (Optional[bool], optional): Enable markup, or ``None`` to use Console default.\\n highlight (Optional[bool], optional): Enable highlighting, or ``None`` to use Console default.\\n highlighter (HighlighterType, optional): Optional highlighter to apply.\\n Returns:\\n ConsoleRenderable: Renderable object.\\n\\n \\\"\\\"\\\"\\n emoji_enabled = emoji or (emoji is None and self._emoji)\\n markup_enabled = markup or (markup is None and self._markup)\\n highlight_enabled = highlight or (highlight is None and self._highlight)\\n\\n if markup_enabled:\\n rich_text = render_markup(text, style=style, emoji=emoji_enabled)\\n rich_text.justify = justify\\n rich_text.overflow = overflow\\n else:\\n rich_text = Text(\\n _emoji_replace(text) if emoji_enabled else text,\\n justify=justify,\\n overflow=overflow,\\n style=style,\\n )\\n\\n _highlighter = (highlighter or self.highlighter) if highlight_enabled else None\\n if _highlighter is not None:\\n highlight_text = _highlighter(str(rich_text))\\n highlight_text.copy_styles(rich_text)\\n return highlight_text\\n\\n return rich_text\\n\\n def get_style(\\n self, name: Union[str, Style], *, default: Union[Style, str] = None\\n ) -> Style:\\n \\\"\\\"\\\"Get a Style instance by it's theme name or parse a definition.\\n\\n Args:\\n name (str): The name of a style or a style definition.\\n\\n Returns:\\n Style: A Style object.\\n\\n Raises:\\n MissingStyle: If no style could be parsed from name.\\n\\n \\\"\\\"\\\"\\n if isinstance(name, Style):\\n return name\\n\\n try:\\n style = self._theme_stack.get(name)\\n if style is None:\\n style = Style.parse(name)\\n return style.copy() if style.link else style\\n except errors.StyleSyntaxError as error:\\n if default is not None:\\n return self.get_style(default)\\n raise errors.MissingStyle(f\\\"Failed to get style {name!r}; {error}\\\")\\n\\n def _collect_renderables(\\n self,\\n objects: Iterable[Any],\\n sep: str,\\n end: str,\\n *,\\n justify: JustifyMethod = None,\\n emoji: bool = None,\\n markup: bool = None,\\n highlight: bool = None,\\n ) -> List[ConsoleRenderable]:\\n \\\"\\\"\\\"Combined a number of renderables and text in to one renderable.\\n\\n Args:\\n objects (Iterable[Any]): Anything that Rich can render.\\n sep (str, optional): String to write between print data. Defaults to \\\" \\\".\\n end (str, optional): String to write at end of print data. Defaults to \\\"\\\\\\\\n\\\".\\n justify (str, optional): One of \\\"left\\\", \\\"right\\\", \\\"center\\\", or \\\"full\\\". Defaults to ``None``.\\n emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default.\\n markup (Optional[bool], optional): Enable markup, or ``None`` to use console default.\\n highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default.\\n\\n Returns:\\n List[ConsoleRenderable]: A list oxf things to render.\\n \\\"\\\"\\\"\\n renderables: List[ConsoleRenderable] = []\\n _append = renderables.append\\n text: List[Text] = []\\n append_text = text.append\\n\\n append = _append\\n if justify in (\\\"left\\\", \\\"center\\\", \\\"right\\\"):\\n\\n def align_append(renderable: RenderableType) -> None:\\n _append(Align(renderable, cast(AlignMethod, justify)))\\n\\n append = align_append\\n\\n _highlighter: HighlighterType = _null_highlighter\\n if highlight or (highlight is None and self._highlight):\\n _highlighter = self.highlighter\\n\\n def check_text() -> None:\\n if text:\\n sep_text = Text(sep, justify=justify, end=end)\\n append(sep_text.join(text))\\n del text[:]\\n\\n for renderable in objects:\\n rich_cast = getattr(renderable, \\\"__rich__\\\", None)\\n if rich_cast:\\n renderable = rich_cast()\\n if isinstance(renderable, str):\\n append_text(\\n self.render_str(\\n renderable, emoji=emoji, markup=markup, highlighter=_highlighter\\n )\\n )\\n elif isinstance(renderable, ConsoleRenderable):\\n check_text()\\n append(renderable)\\n elif isinstance(renderable, (abc.Mapping, abc.Sequence, abc.Set)):\\n check_text()\\n append(Pretty(renderable, highlighter=_highlighter))\\n else:\\n append_text(_highlighter(str(renderable)))\\n\\n check_text()\\n\\n if self.style is not None:\\n style = self.get_style(self.style)\\n renderables = [Styled(renderable, style) for renderable in renderables]\\n\\n return renderables\\n\\n def rule(\\n self,\\n title: TextType = \\\"\\\",\\n *,\\n characters: str = \\\"─\\\",\\n style: Union[str, Style] = \\\"rule.line\\\",\\n align: AlignMethod = \\\"center\\\",\\n ) -> None:\\n \\\"\\\"\\\"Draw a line with optional centered title.\\n\\n Args:\\n title (str, optional): Text to render over the rule. Defaults to \\\"\\\".\\n characters (str, optional): Character(s) to form the line. Defaults to \\\"─\\\".\\n style (str, optional): Style of line. Defaults to \\\"rule.line\\\".\\n align (str, optional): How to align the title, one of \\\"left\\\", \\\"center\\\", or \\\"right\\\". Defaults to \\\"center\\\".\\n \\\"\\\"\\\"\\n from .rule import Rule\\n\\n rule = Rule(title=title, characters=characters, style=style, align=align)\\n self.print(rule)\\n\\n def control(self, control_codes: Union[\\\"Control\\\", str]) -> None:\\n \\\"\\\"\\\"Insert non-printing control codes.\\n\\n Args:\\n control_codes (str): Control codes, such as those that may move the cursor.\\n \\\"\\\"\\\"\\n if not self.is_dumb_terminal:\\n self._buffer.append(Segment.control(str(control_codes)))\\n self._check_buffer()\\n\\n def out(\\n self,\\n *objects: Any,\\n sep=\\\" \\\",\\n end=\\\"\\\\n\\\",\\n style: Union[str, Style] = None,\\n highlight: bool = None,\\n ) -> None:\\n \\\"\\\"\\\"Output to the terminal. This is a low-level way of writing to the terminal which unlike\\n :meth:`~rich.console.Console.print` won't pretty print, wrap text, or apply markup, but will\\n optionally apply highlighting and a basic style.\\n\\n Args:\\n sep (str, optional): String to write between print data. Defaults to \\\" \\\".\\n end (str, optional): String to write at end of print data. Defaults to \\\"\\\\\\\\n\\\".\\n style (Union[str, Style], optional): A style to apply to output. Defaults to None.\\n highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use\\n console default. Defaults to ``None``.\\n \\\"\\\"\\\"\\n raw_output: str = sep.join(str(_object) for _object in objects)\\n self.print(\\n raw_output,\\n style=style,\\n highlight=highlight,\\n emoji=False,\\n markup=False,\\n no_wrap=True,\\n overflow=\\\"ignore\\\",\\n crop=False,\\n end=end,\\n )\\n\\n def print(\\n self,\\n *objects: Any,\\n sep=\\\" \\\",\\n end=\\\"\\\\n\\\",\\n style: Union[str, Style] = None,\\n justify: JustifyMethod = None,\\n overflow: OverflowMethod = None,\\n no_wrap: bool = None,\\n emoji: bool = None,\\n markup: bool = None,\\n highlight: bool = None,\\n width: int = None,\\n crop: bool = True,\\n soft_wrap: bool = None,\\n ) -> None:\\n \\\"\\\"\\\"Print to the console.\\n\\n Args:\\n objects (positional args): Objects to log to the terminal.\\n sep (str, optional): String to write between print data. Defaults to \\\" \\\".\\n end (str, optional): String to write at end of print data. Defaults to \\\"\\\\\\\\n\\\".\\n style (Union[str, Style], optional): A style to apply to output. Defaults to None.\\n justify (str, optional): Justify method: \\\"default\\\", \\\"left\\\", \\\"right\\\", \\\"center\\\", or \\\"full\\\". Defaults to ``None``.\\n overflow (str, optional): Overflow method: \\\"ignore\\\", \\\"crop\\\", \\\"fold\\\", or \\\"ellipsis\\\". Defaults to None.\\n no_wrap (Optional[bool], optional): Disable word wrapping. Defaults to None.\\n emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to ``None``.\\n markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to ``None``.\\n highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to ``None``.\\n width (Optional[int], optional): Width of output, or ``None`` to auto-detect. Defaults to ``None``.\\n crop (Optional[bool], optional): Crop output to width of terminal. Defaults to True.\\n soft_wrap (bool, optional): Enable soft wrap mode which disables word wrapping and cropping of text or None for\\n Console default. Defaults to ``None``.\\n \\\"\\\"\\\"\\n if not objects:\\n self.line()\\n return\\n\\n if soft_wrap is None:\\n soft_wrap = self.soft_wrap\\n if soft_wrap:\\n if no_wrap is None:\\n no_wrap = True\\n if overflow is None:\\n overflow = \\\"ignore\\\"\\n crop = False\\n\\n with self:\\n renderables = self._collect_renderables(\\n objects,\\n sep,\\n end,\\n justify=justify,\\n emoji=emoji,\\n markup=markup,\\n highlight=highlight,\\n )\\n for hook in self._render_hooks:\\n renderables = hook.process_renderables(renderables)\\n render_options = self.options.update(\\n justify=justify,\\n overflow=overflow,\\n width=min(width, self.width) if width else None,\\n no_wrap=no_wrap,\\n )\\n new_segments: List[Segment] = []\\n extend = new_segments.extend\\n render = self.render\\n if style is None:\\n for renderable in renderables:\\n extend(render(renderable, render_options))\\n else:\\n for renderable in renderables:\\n extend(\\n Segment.apply_style(\\n render(renderable, render_options), self.get_style(style)\\n )\\n )\\n if crop:\\n buffer_extend = self._buffer.extend\\n for line in Segment.split_and_crop_lines(\\n new_segments, self.width, pad=False\\n ):\\n buffer_extend(line)\\n else:\\n self._buffer.extend(new_segments)\\n\\n def print_exception(\\n self,\\n *,\\n width: Optional[int] = 100,\\n extra_lines: int = 3,\\n theme: Optional[str] = None,\\n word_wrap: bool = False,\\n show_locals: bool = False,\\n ) -> None:\\n \\\"\\\"\\\"Prints a rich render of the last exception and traceback.\\n\\n Args:\\n width (Optional[int], optional): Number of characters used to render code. Defaults to 88.\\n extra_lines (int, optional): Additional lines of code to render. Defaults to 3.\\n theme (str, optional): Override pygments theme used in traceback\\n word_wrap (bool, optional): Enable word wrapping of long lines. Defaults to False.\\n show_locals (bool, optional): Enable display of local variables. Defaults to False.\\n \\\"\\\"\\\"\\n from .traceback import Traceback\\n\\n traceback = Traceback(\\n width=width,\\n extra_lines=extra_lines,\\n theme=theme,\\n word_wrap=word_wrap,\\n show_locals=show_locals,\\n )\\n self.print(traceback)\\n\\n def log(\\n self,\\n *objects: Any,\\n sep=\\\" \\\",\\n end=\\\"\\\\n\\\",\\n style: Union[str, Style] = None,\\n justify: JustifyMethod = None,\\n emoji: bool = None,\\n markup: bool = None,\\n highlight: bool = None,\\n log_locals: bool = False,\\n _stack_offset=1,\\n ) -> None:\\n \\\"\\\"\\\"Log rich content to the terminal.\\n\\n Args:\\n objects (positional args): Objects to log to the terminal.\\n sep (str, optional): String to write between print data. Defaults to \\\" \\\".\\n end (str, optional): String to write at end of print data. Defaults to \\\"\\\\\\\\n\\\".\\n style (Union[str, Style], optional): A style to apply to output. Defaults to None.\\n justify (str, optional): One of \\\"left\\\", \\\"right\\\", \\\"center\\\", or \\\"full\\\". Defaults to ``None``.\\n overflow (str, optional): Overflow method: \\\"crop\\\", \\\"fold\\\", or \\\"ellipsis\\\". Defaults to None.\\n emoji (Optional[bool], optional): Enable emoji code, or ``None`` to use console default. Defaults to None.\\n markup (Optional[bool], optional): Enable markup, or ``None`` to use console default. Defaults to None.\\n highlight (Optional[bool], optional): Enable automatic highlighting, or ``None`` to use console default. Defaults to None.\\n log_locals (bool, optional): Boolean to enable logging of locals where ``log()``\\n was called. Defaults to False.\\n _stack_offset (int, optional): Offset of caller from end of call stack. Defaults to 1.\\n \\\"\\\"\\\"\\n if not objects:\\n self.line()\\n return\\n with self:\\n renderables = self._collect_renderables(\\n objects,\\n sep,\\n end,\\n justify=justify,\\n emoji=emoji,\\n markup=markup,\\n highlight=highlight,\\n )\\n if style is not None:\\n renderables = [Styled(renderable, style) for renderable in renderables]\\n\\n caller = inspect.stack()[_stack_offset]\\n link_path = (\\n None\\n if caller.filename.startswith(\\\"<\\\")\\n else os.path.abspath(caller.filename)\\n )\\n path = caller.filename.rpartition(os.sep)[-1]\\n line_no = caller.lineno\\n if log_locals:\\n locals_map = {\\n key: value\\n for key, value in caller.frame.f_locals.items()\\n if not key.startswith(\\\"__\\\")\\n }\\n renderables.append(render_scope(locals_map, title=\\\"[i]locals\\\"))\\n\\n renderables = [\\n self._log_render(\\n self,\\n renderables,\\n log_time=self.get_datetime(),\\n path=path,\\n line_no=line_no,\\n link_path=link_path,\\n )\\n ]\\n for hook in self._render_hooks:\\n renderables = hook.process_renderables(renderables)\\n new_segments: List[Segment] = []\\n extend = new_segments.extend\\n render = self.render\\n render_options = self.options\\n for renderable in renderables:\\n extend(render(renderable, render_options))\\n buffer_extend = self._buffer.extend\\n for line in Segment.split_and_crop_lines(\\n new_segments, self.width, pad=False\\n ):\\n buffer_extend(line)\\n\\n def _check_buffer(self) -> None:\\n \\\"\\\"\\\"Check if the buffer may be rendered.\\\"\\\"\\\"\\n with self._lock:\\n if self._buffer_index == 0:\\n if self.is_jupyter: # pragma: no cover\\n from .jupyter import display\\n\\n display(self._buffer)\\n del self._buffer[:]\\n else:\\n text = self._render_buffer(self._buffer[:])\\n del self._buffer[:]\\n if text:\\n try:\\n if WINDOWS: # pragma: no cover\\n # https://bugs.python.org/issue37871\\n write = self.file.write\\n for line in text.splitlines(True):\\n write(line)\\n else:\\n self.file.write(text)\\n self.file.flush()\\n except UnicodeEncodeError as error:\\n error.reason = f\\\"{error.reason}\\\\n*** You may need to add PYTHONIOENCODING=utf-8 to your environment ***\\\"\\n raise\\n\\n def _render_buffer(self, buffer: Iterable[Segment]) -> str:\\n \\\"\\\"\\\"Render buffered output, and clear buffer.\\\"\\\"\\\"\\n output: List[str] = []\\n append = output.append\\n color_system = self._color_system\\n legacy_windows = self.legacy_windows\\n if self.record:\\n with self._record_buffer_lock:\\n self._record_buffer.extend(buffer)\\n not_terminal = not self.is_terminal\\n for text, style, is_control in buffer:\\n if style:\\n append(\\n style.render(\\n text,\\n color_system=color_system,\\n legacy_windows=legacy_windows,\\n )\\n )\\n elif not (not_terminal and is_control):\\n append(text)\\n\\n rendered = \\\"\\\".join(output)\\n return rendered\\n\\n def input(\\n self,\\n prompt: TextType = \\\"\\\",\\n *,\\n markup: bool = True,\\n emoji: bool = True,\\n password: bool = False,\\n stream: TextIO = None,\\n ) -> str:\\n \\\"\\\"\\\"Displays a prompt and waits for input from the user. The prompt may contain color / style.\\n\\n Args:\\n prompt (Union[str, Text]): Text to render in the prompt.\\n markup (bool, optional): Enable console markup (requires a str prompt). Defaults to True.\\n emoji (bool, optional): Enable emoji (requires a str prompt). Defaults to True.\\n password: (bool, optional): Hide typed text. Defaults to False.\\n stream: (TextIO, optional): Optional file to read input from (rather than stdin). Defaults to None.\\n\\n Returns:\\n str: Text read from stdin.\\n \\\"\\\"\\\"\\n prompt_str = \\\"\\\"\\n if prompt:\\n with self.capture() as capture:\\n self.print(prompt, markup=markup, emoji=emoji, end=\\\"\\\")\\n prompt_str = capture.get()\\n if self.legacy_windows:\\n # Legacy windows doesn't like ANSI codes in getpass or input (colorama bug)?\\n self.file.write(prompt_str)\\n prompt_str = \\\"\\\"\\n if password:\\n result = getpass(prompt_str, stream=stream)\\n else:\\n if stream:\\n self.file.write(prompt_str)\\n result = stream.readline()\\n else:\\n result = input(prompt_str)\\n return result\\n\\n def export_text(self, *, clear: bool = True, styles: bool = False) -> str:\\n \\\"\\\"\\\"Generate text from console contents (requires record=True argument in constructor).\\n\\n Args:\\n clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\\n styles (bool, optional): If ``True``, ansi escape codes will be included. ``False`` for plain text.\\n Defaults to ``False``.\\n\\n Returns:\\n str: String containing console contents.\\n\\n \\\"\\\"\\\"\\n assert (\\n self.record\\n ), \\\"To export console contents set record=True in the constructor or instance\\\"\\n\\n with self._record_buffer_lock:\\n if styles:\\n text = \\\"\\\".join(\\n (style.render(text) if style else text)\\n for text, style, _ in self._record_buffer\\n )\\n else:\\n text = \\\"\\\".join(\\n segment.text\\n for segment in self._record_buffer\\n if not segment.is_control\\n )\\n if clear:\\n del self._record_buffer[:]\\n return text\\n\\n def save_text(self, path: str, *, clear: bool = True, styles: bool = False) -> None:\\n \\\"\\\"\\\"Generate text from console and save to a given location (requires record=True argument in constructor).\\n\\n Args:\\n path (str): Path to write text files.\\n clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\\n styles (bool, optional): If ``True``, ansi style codes will be included. ``False`` for plain text.\\n Defaults to ``False``.\\n\\n \\\"\\\"\\\"\\n text = self.export_text(clear=clear, styles=styles)\\n with open(path, \\\"wt\\\", encoding=\\\"utf-8\\\") as write_file:\\n write_file.write(text)\\n\\n def export_html(\\n self,\\n *,\\n theme: TerminalTheme = None,\\n clear: bool = True,\\n code_format: str = None,\\n inline_styles: bool = False,\\n ) -> str:\\n \\\"\\\"\\\"Generate HTML from console contents (requires record=True argument in constructor).\\n\\n Args:\\n theme (TerminalTheme, optional): TerminalTheme object containing console colors.\\n clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\\n code_format (str, optional): Format string to render HTML, should contain {foreground}\\n {background} and {code}.\\n inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files\\n larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.\\n Defaults to False.\\n\\n Returns:\\n str: String containing console contents as HTML.\\n \\\"\\\"\\\"\\n assert (\\n self.record\\n ), \\\"To export console contents set record=True in the constructor or instance\\\"\\n fragments: List[str] = []\\n append = fragments.append\\n _theme = theme or DEFAULT_TERMINAL_THEME\\n stylesheet = \\\"\\\"\\n\\n def escape(text: str) -> str:\\n \\\"\\\"\\\"Escape html.\\\"\\\"\\\"\\n return text.replace(\\\"&\\\", \\\"&amp;\\\").replace(\\\"<\\\", \\\"&lt;\\\").replace(\\\">\\\", \\\"&gt;\\\")\\n\\n render_code_format = CONSOLE_HTML_FORMAT if code_format is None else code_format\\n\\n with self._record_buffer_lock:\\n if inline_styles:\\n for text, style, _ in Segment.filter_control(\\n Segment.simplify(self._record_buffer)\\n ):\\n text = escape(text)\\n if style:\\n rule = style.get_html_style(_theme)\\n text = f'{text}' if rule else text\\n if style.link:\\n text = f'{text}'\\n append(text)\\n else:\\n styles: Dict[str, int] = {}\\n for text, style, _ in Segment.filter_control(\\n Segment.simplify(self._record_buffer)\\n ):\\n text = escape(text)\\n if style:\\n rule = style.get_html_style(_theme)\\n if rule:\\n style_number = styles.setdefault(rule, len(styles) + 1)\\n text = f'{text}'\\n if style.link:\\n text = f'{text}'\\n append(text)\\n stylesheet_rules: List[str] = []\\n stylesheet_append = stylesheet_rules.append\\n for style_rule, style_number in styles.items():\\n if style_rule:\\n stylesheet_append(f\\\".r{style_number} {{{style_rule}}}\\\")\\n stylesheet = \\\"\\\\n\\\".join(stylesheet_rules)\\n\\n rendered_code = render_code_format.format(\\n code=\\\"\\\".join(fragments),\\n stylesheet=stylesheet,\\n foreground=_theme.foreground_color.hex,\\n background=_theme.background_color.hex,\\n )\\n if clear:\\n del self._record_buffer[:]\\n return rendered_code\\n\\n def save_html(\\n self,\\n path: str,\\n *,\\n theme: TerminalTheme = None,\\n clear: bool = True,\\n code_format=CONSOLE_HTML_FORMAT,\\n inline_styles: bool = False,\\n ) -> None:\\n \\\"\\\"\\\"Generate HTML from console contents and write to a file (requires record=True argument in constructor).\\n\\n Args:\\n path (str): Path to write html file.\\n theme (TerminalTheme, optional): TerminalTheme object containing console colors.\\n clear (bool, optional): Clear record buffer after exporting. Defaults to ``True``.\\n code_format (str, optional): Format string to render HTML, should contain {foreground}\\n {background} and {code}.\\n inline_styles (bool, optional): If ``True`` styles will be inlined in to spans, which makes files\\n larger but easier to cut and paste markup. If ``False``, styles will be embedded in a style tag.\\n Defaults to False.\\n\\n \\\"\\\"\\\"\\n html = self.export_html(\\n theme=theme,\\n clear=clear,\\n code_format=code_format,\\n inline_styles=inline_styles,\\n )\\n with open(path, \\\"wt\\\", encoding=\\\"utf-8\\\") as write_file:\\n write_file.write(html)\\n\\n\\nif __name__ == \\\"__main__\\\": # pragma: no cover\\n console = Console()\\n\\n console.log(\\n \\\"JSONRPC [i]request[/i]\\\",\\n 5,\\n 1.3,\\n True,\\n False,\\n None,\\n {\\n \\\"jsonrpc\\\": \\\"2.0\\\",\\n \\\"method\\\": \\\"subtract\\\",\\n \\\"params\\\": {\\\"minuend\\\": 42, \\\"subtrahend\\\": 23},\\n \\\"id\\\": 3,\\n },\\n )\\n\\n console.log(\\\"Hello, World!\\\", \\\"{'a': 1}\\\", repr(console))\\n\\n console.print(\\n {\\n \\\"name\\\": None,\\n \\\"empty\\\": [],\\n \\\"quiz\\\": {\\n \\\"sport\\\": {\\n \\\"answered\\\": True,\\n \\\"q1\\\": {\\n \\\"question\\\": \\\"Which one is correct team name in NBA?\\\",\\n \\\"options\\\": [\\n \\\"New York Bulls\\\",\\n \\\"Los Angeles Kings\\\",\\n \\\"Golden State Warriors\\\",\\n \\\"Huston Rocket\\\",\\n ],\\n \\\"answer\\\": \\\"Huston Rocket\\\",\\n },\\n },\\n \\\"maths\\\": {\\n \\\"answered\\\": False,\\n \\\"q1\\\": {\\n \\\"question\\\": \\\"5 + 7 = ?\\\",\\n \\\"options\\\": [10, 11, 12, 13],\\n \\\"answer\\\": 12,\\n },\\n \\\"q2\\\": {\\n \\\"question\\\": \\\"12 - 8 = ?\\\",\\n \\\"options\\\": [1, 2, 3, 4],\\n \\\"answer\\\": 4,\\n },\\n },\\n },\\n }\\n )\\n console.log(\\\"foo\\\")\\n\", \"rich/segment.py\": \"from typing import NamedTuple, Optional\\n\\nfrom .cells import cell_len, set_cell_size\\nfrom .style import Style\\n\\nfrom itertools import filterfalse, zip_longest\\nfrom operator import attrgetter\\nfrom typing import Iterable, List, Tuple\\n\\n\\nclass Segment(NamedTuple):\\n \\\"\\\"\\\"A piece of text with associated style.\\n\\n Args:\\n text (str): A piece of text.\\n style (:class:`~rich.style.Style`, optional): An optional style to apply to the text.\\n is_control (bool, optional): Boolean that marks segment as containing non-printable control codes.\\n \\\"\\\"\\\"\\n\\n text: str = \\\"\\\"\\n \\\"\\\"\\\"Raw text.\\\"\\\"\\\"\\n style: Optional[Style] = None\\n \\\"\\\"\\\"An optional style.\\\"\\\"\\\"\\n is_control: bool = False\\n \\\"\\\"\\\"True if the segment contains control codes, otherwise False.\\\"\\\"\\\"\\n\\n def __repr__(self) -> str:\\n \\\"\\\"\\\"Simplified repr.\\\"\\\"\\\"\\n if self.is_control:\\n return f\\\"Segment.control({self.text!r}, {self.style!r})\\\"\\n else:\\n return f\\\"Segment({self.text!r}, {self.style!r})\\\"\\n\\n def __bool__(self) -> bool:\\n \\\"\\\"\\\"Check if the segment contains text.\\\"\\\"\\\"\\n return bool(self.text)\\n\\n @property\\n def cell_length(self) -> int:\\n \\\"\\\"\\\"Get cell length of segment.\\\"\\\"\\\"\\n return 0 if self.is_control else cell_len(self.text)\\n\\n @classmethod\\n def control(cls, text: str, style: Optional[Style] = None) -> \\\"Segment\\\":\\n \\\"\\\"\\\"Create a Segment with control codes.\\n\\n Args:\\n text (str): Text containing non-printable control codes.\\n style (Optional[style]): Optional style.\\n\\n Returns:\\n Segment: A Segment instance with ``is_control=True``.\\n \\\"\\\"\\\"\\n return cls(text, style, is_control=True)\\n\\n @classmethod\\n def make_control(cls, segments: Iterable[\\\"Segment\\\"]) -> Iterable[\\\"Segment\\\"]:\\n \\\"\\\"\\\"Convert all segments in to control segments.\\n\\n Returns:\\n Iterable[Segments]: Segments with is_control=True\\n \\\"\\\"\\\"\\n return [cls(text, style, True) for text, style, _ in segments]\\n\\n @classmethod\\n def line(cls, is_control: bool = False) -> \\\"Segment\\\":\\n \\\"\\\"\\\"Make a new line segment.\\\"\\\"\\\"\\n return cls(\\\"\\\\n\\\", is_control=is_control)\\n\\n @classmethod\\n def apply_style(\\n cls, segments: Iterable[\\\"Segment\\\"], style: Style = None\\n ) -> Iterable[\\\"Segment\\\"]:\\n \\\"\\\"\\\"Apply a style to an iterable of segments.\\n\\n Args:\\n segments (Iterable[Segment]): Segments to process.\\n style (Style, optional): A style to apply. Defaults to None.\\n\\n Returns:\\n Iterable[Segments]: A new iterable of segments (possibly the same iterable).\\n \\\"\\\"\\\"\\n if style is None:\\n return segments\\n apply = style.__add__\\n return (\\n cls(text, None if is_control else apply(style), is_control)\\n for text, style, is_control in segments\\n )\\n\\n @classmethod\\n def filter_control(\\n cls, segments: Iterable[\\\"Segment\\\"], is_control=False\\n ) -> Iterable[\\\"Segment\\\"]:\\n \\\"\\\"\\\"Filter segments by ``is_control`` attribute.\\n\\n Args:\\n segments (Iterable[Segment]): An iterable of Segment instances.\\n is_control (bool, optional): is_control flag to match in search.\\n\\n Returns:\\n Iterable[Segment]: And iterable of Segment instances.\\n\\n \\\"\\\"\\\"\\n if is_control:\\n return filter(attrgetter(\\\"is_control\\\"), segments)\\n else:\\n return filterfalse(attrgetter(\\\"is_control\\\"), segments)\\n\\n @classmethod\\n def split_lines(cls, segments: Iterable[\\\"Segment\\\"]) -> Iterable[List[\\\"Segment\\\"]]:\\n \\\"\\\"\\\"Split a sequence of segments in to a list of lines.\\n\\n Args:\\n segments (Iterable[Segment]): Segments potentially containing line feeds.\\n\\n Yields:\\n Iterable[List[Segment]]: Iterable of segment lists, one per line.\\n \\\"\\\"\\\"\\n line: List[Segment] = []\\n append = line.append\\n\\n for segment in segments:\\n if \\\"\\\\n\\\" in segment.text and not segment.is_control:\\n text, style, _ = segment\\n while text:\\n _text, new_line, text = text.partition(\\\"\\\\n\\\")\\n if _text:\\n append(cls(_text, style))\\n if new_line:\\n yield line\\n line = []\\n append = line.append\\n else:\\n append(segment)\\n if line:\\n yield line\\n\\n @classmethod\\n def split_and_crop_lines(\\n cls,\\n segments: Iterable[\\\"Segment\\\"],\\n length: int,\\n style: Style = None,\\n pad: bool = True,\\n include_new_lines: bool = True,\\n ) -> Iterable[List[\\\"Segment\\\"]]:\\n \\\"\\\"\\\"Split segments in to lines, and crop lines greater than a given length.\\n\\n Args:\\n segments (Iterable[Segment]): An iterable of segments, probably\\n generated from console.render.\\n length (int): Desired line length.\\n style (Style, optional): Style to use for any padding.\\n pad (bool): Enable padding of lines that are less than `length`.\\n\\n Returns:\\n Iterable[List[Segment]]: An iterable of lines of segments.\\n \\\"\\\"\\\"\\n line: List[Segment] = []\\n append = line.append\\n\\n adjust_line_length = cls.adjust_line_length\\n new_line_segment = cls(\\\"\\\\n\\\")\\n\\n for segment in segments:\\n if \\\"\\\\n\\\" in segment.text and not segment.is_control:\\n text, style, _ = segment\\n while text:\\n _text, new_line, text = text.partition(\\\"\\\\n\\\")\\n if _text:\\n append(cls(_text, style))\\n if new_line:\\n cropped_line = adjust_line_length(\\n line, length, style=style, pad=pad\\n )\\n if include_new_lines:\\n cropped_line.append(new_line_segment)\\n yield cropped_line\\n del line[:]\\n else:\\n append(segment)\\n if line:\\n yield adjust_line_length(line, length, style=style, pad=pad)\\n\\n @classmethod\\n def adjust_line_length(\\n cls, line: List[\\\"Segment\\\"], length: int, style: Style = None, pad: bool = True\\n ) -> List[\\\"Segment\\\"]:\\n \\\"\\\"\\\"Adjust a line to a given width (cropping or padding as required).\\n\\n Args:\\n segments (Iterable[Segment]): A list of segments in a single line.\\n length (int): The desired width of the line.\\n style (Style, optional): The style of padding if used (space on the end). Defaults to None.\\n pad (bool, optional): Pad lines with spaces if they are shorter than `length`. Defaults to True.\\n\\n Returns:\\n List[Segment]: A line of segments with the desired length.\\n \\\"\\\"\\\"\\n line_length = sum(segment.cell_length for segment in line)\\n new_line: List[Segment]\\n\\n if line_length < length:\\n if pad:\\n new_line = line + [cls(\\\" \\\" * (length - line_length), style)]\\n else:\\n new_line = line[:]\\n elif line_length > length:\\n new_line = []\\n append = new_line.append\\n line_length = 0\\n for segment in line:\\n segment_length = segment.cell_length\\n if line_length + segment_length < length or segment.is_control:\\n append(segment)\\n line_length += segment_length\\n else:\\n text, segment_style, _ = segment\\n text = set_cell_size(text, length - line_length)\\n append(cls(text, segment_style))\\n break\\n else:\\n new_line = line[:]\\n return new_line\\n\\n @classmethod\\n def get_line_length(cls, line: List[\\\"Segment\\\"]) -> int:\\n \\\"\\\"\\\"Get the length of list of segments.\\n\\n Args:\\n line (List[Segment]): A line encoded as a list of Segments (assumes no '\\\\\\\\n' characters),\\n\\n Returns:\\n int: The length of the line.\\n \\\"\\\"\\\"\\n return sum(segment.cell_length for segment in line)\\n\\n @classmethod\\n def get_shape(cls, lines: List[List[\\\"Segment\\\"]]) -> Tuple[int, int]:\\n \\\"\\\"\\\"Get the shape (enclosing rectangle) of a list of lines.\\n\\n Args:\\n lines (List[List[Segment]]): A list of lines (no '\\\\\\\\n' characters).\\n\\n Returns:\\n Tuple[int, int]: Width and height in characters.\\n \\\"\\\"\\\"\\n get_line_length = cls.get_line_length\\n max_width = max(get_line_length(line) for line in lines) if lines else 0\\n return (max_width, len(lines))\\n\\n @classmethod\\n def set_shape(\\n cls,\\n lines: List[List[\\\"Segment\\\"]],\\n width: int,\\n height: int = None,\\n style: Style = None,\\n ) -> List[List[\\\"Segment\\\"]]:\\n \\\"\\\"\\\"Set the shape of a list of lines (enclosing rectangle).\\n\\n Args:\\n lines (List[List[Segment]]): A list of lines.\\n width (int): Desired width.\\n height (int, optional): Desired height or None for no change.\\n style (Style, optional): Style of any padding added. Defaults to None.\\n\\n Returns:\\n List[List[Segment]]: New list of lines that fits width x height.\\n \\\"\\\"\\\"\\n if height is None:\\n height = len(lines)\\n new_lines: List[List[Segment]] = []\\n pad_line = [Segment(\\\" \\\" * width, style)]\\n append = new_lines.append\\n adjust_line_length = cls.adjust_line_length\\n line: Optional[List[Segment]]\\n for line, _ in zip_longest(lines, range(height)):\\n if line is None:\\n append(pad_line)\\n else:\\n append(adjust_line_length(line, width, style=style))\\n return new_lines\\n\\n @classmethod\\n def simplify(cls, segments: Iterable[\\\"Segment\\\"]) -> Iterable[\\\"Segment\\\"]:\\n \\\"\\\"\\\"Simplify an iterable of segments by combining contiguous segments with the same style.\\n\\n Args:\\n segments (Iterable[Segment]): An iterable of segments.\\n\\n Returns:\\n Iterable[Segment]: A possibly smaller iterable of segments that will render the same way.\\n \\\"\\\"\\\"\\n iter_segments = iter(segments)\\n try:\\n last_segment = next(iter_segments)\\n except StopIteration:\\n return\\n\\n _Segment = Segment\\n for segment in iter_segments:\\n if last_segment.style == segment.style and not segment.is_control:\\n last_segment = _Segment(\\n last_segment.text + segment.text, last_segment.style\\n )\\n else:\\n yield last_segment\\n last_segment = segment\\n yield last_segment\\n\\n @classmethod\\n def strip_links(cls, segments: Iterable[\\\"Segment\\\"]) -> Iterable[\\\"Segment\\\"]:\\n \\\"\\\"\\\"Remove all links from an iterable of styles.\\n\\n Args:\\n segments (Iterable[Segment]): An iterable segments.\\n\\n Yields:\\n Segment: Segments with link removed.\\n \\\"\\\"\\\"\\n for segment in segments:\\n if segment.is_control or segment.style is None:\\n yield segment\\n else:\\n text, style, _is_control = segment\\n yield cls(text, style.update_link(None) if style else None)\\n\\n @classmethod\\n def strip_styles(cls, segments: Iterable[\\\"Segment\\\"]) -> Iterable[\\\"Segment\\\"]:\\n \\\"\\\"\\\"Remove all styles from an iterable of segments.\\n\\n Yields:\\n Segment: Segments with styles replace with None\\n \\\"\\\"\\\"\\n for text, _style, is_control in segments:\\n yield cls(text, None, is_control)\\n\\n\\nif __name__ == \\\"__main__\\\": # pragma: no cover\\n lines = [[Segment(\\\"Hello\\\")]]\\n lines = Segment.set_shape(lines, 50, 4, style=Style.parse(\\\"on blue\\\"))\\n for line in lines:\\n print(line)\\n\\n print(Style.parse(\\\"on blue\\\") + Style.parse(\\\"on red\\\"))\\n\", \"rich/style.py\": \"import sys\\nfrom functools import lru_cache\\nfrom random import randint\\nfrom time import time\\nfrom typing import Any, Dict, Iterable, List, Optional, Type, Union\\n\\nfrom . import errors\\nfrom .color import Color, ColorParseError, ColorSystem, blend_rgb\\nfrom .terminal_theme import DEFAULT_TERMINAL_THEME, TerminalTheme\\n\\n# Style instances and style definitions are often interchangeable\\nStyleType = Union[str, \\\"Style\\\"]\\n\\n\\nclass _Bit:\\n \\\"\\\"\\\"A descriptor to get/set a style attribute bit.\\\"\\\"\\\"\\n\\n __slots__ = [\\\"bit\\\"]\\n\\n def __init__(self, bit_no: int) -> None:\\n self.bit = 1 << bit_no\\n\\n def __get__(self, obj: \\\"Style\\\", objtype: Type[\\\"Style\\\"]) -> Optional[bool]:\\n if obj._set_attributes & self.bit:\\n return obj._attributes & self.bit != 0\\n return None\\n\\n\\nclass Style:\\n \\\"\\\"\\\"A terminal style.\\n\\n A terminal style consists of a color (`color`), a background color (`bgcolor`), and a number of attributes, such\\n as bold, italic etc. The attributes have 3 states: they can either be on\\n (``True``), off (``False``), or not set (``None``).\\n\\n Args:\\n color (Union[Color, str], optional): Color of terminal text. Defaults to None.\\n bgcolor (Union[Color, str], optional): Color of terminal background. Defaults to None.\\n bold (bool, optional): Enable bold text. Defaults to None.\\n dim (bool, optional): Enable dim text. Defaults to None.\\n italic (bool, optional): Enable italic text. Defaults to None.\\n underline (bool, optional): Enable underlined text. Defaults to None.\\n blink (bool, optional): Enabled blinking text. Defaults to None.\\n blink2 (bool, optional): Enable fast blinking text. Defaults to None.\\n reverse (bool, optional): Enabled reverse text. Defaults to None.\\n conceal (bool, optional): Enable concealed text. Defaults to None.\\n strike (bool, optional): Enable strikethrough text. Defaults to None.\\n underline2 (bool, optional): Enable doubly underlined text. Defaults to None.\\n frame (bool, optional): Enable framed text. Defaults to None.\\n encircle (bool, optional): Enable encircled text. Defaults to None.\\n overline (bool, optional): Enable overlined text. Defaults to None.\\n link (str, link): Link URL. Defaults to None.\\n\\n \\\"\\\"\\\"\\n\\n _color: Optional[Color]\\n _bgcolor: Optional[Color]\\n _attributes: int\\n _set_attributes: int\\n _hash: int\\n _null: bool\\n\\n __slots__ = [\\n \\\"_color\\\",\\n \\\"_bgcolor\\\",\\n \\\"_attributes\\\",\\n \\\"_set_attributes\\\",\\n \\\"_link\\\",\\n \\\"_link_id\\\",\\n \\\"_ansi\\\",\\n \\\"_style_definition\\\",\\n \\\"_hash\\\",\\n \\\"_null\\\",\\n ]\\n\\n # maps bits on to SGR parameter\\n _style_map = {\\n 0: \\\"1\\\",\\n 1: \\\"2\\\",\\n 2: \\\"3\\\",\\n 3: \\\"4\\\",\\n 4: \\\"5\\\",\\n 5: \\\"6\\\",\\n 6: \\\"7\\\",\\n 7: \\\"8\\\",\\n 8: \\\"9\\\",\\n 9: \\\"21\\\",\\n 10: \\\"51\\\",\\n 11: \\\"52\\\",\\n 12: \\\"53\\\",\\n }\\n\\n def __init__(\\n self,\\n *,\\n color: Union[Color, str] = None,\\n bgcolor: Union[Color, str] = None,\\n bold: bool = None,\\n dim: bool = None,\\n italic: bool = None,\\n underline: bool = None,\\n blink: bool = None,\\n blink2: bool = None,\\n reverse: bool = None,\\n conceal: bool = None,\\n strike: bool = None,\\n underline2: bool = None,\\n frame: bool = None,\\n encircle: bool = None,\\n overline: bool = None,\\n link: str = None,\\n ):\\n self._ansi: Optional[str] = None\\n self._style_definition: Optional[str] = None\\n\\n def _make_color(color: Union[Color, str]) -> Color:\\n return color if isinstance(color, Color) else Color.parse(color)\\n\\n self._color = None if color is None else _make_color(color)\\n self._bgcolor = None if bgcolor is None else _make_color(bgcolor)\\n self._set_attributes = sum(\\n (\\n bold is not None,\\n dim is not None and 2,\\n italic is not None and 4,\\n underline is not None and 8,\\n blink is not None and 16,\\n blink2 is not None and 32,\\n reverse is not None and 64,\\n conceal is not None and 128,\\n strike is not None and 256,\\n underline2 is not None and 512,\\n frame is not None and 1024,\\n encircle is not None and 2048,\\n overline is not None and 4096,\\n )\\n )\\n self._attributes = (\\n sum(\\n (\\n bold and 1 or 0,\\n dim and 2 or 0,\\n italic and 4 or 0,\\n underline and 8 or 0,\\n blink and 16 or 0,\\n blink2 and 32 or 0,\\n reverse and 64 or 0,\\n conceal and 128 or 0,\\n strike and 256 or 0,\\n underline2 and 512 or 0,\\n frame and 1024 or 0,\\n encircle and 2048 or 0,\\n overline and 4096 or 0,\\n )\\n )\\n if self._set_attributes\\n else 0\\n )\\n\\n self._link = link\\n self._link_id = f\\\"{time()}-{randint(0, 999999)}\\\" if link else \\\"\\\"\\n self._hash = hash(\\n (\\n self._color,\\n self._bgcolor,\\n self._attributes,\\n self._set_attributes,\\n link,\\n )\\n )\\n self._null = not (self._set_attributes or color or bgcolor or link)\\n\\n @classmethod\\n def null(cls) -> \\\"Style\\\":\\n \\\"\\\"\\\"Create an 'null' style, equivalent to Style(), but more performant.\\\"\\\"\\\"\\n return NULL_STYLE\\n\\n @classmethod\\n def from_color(cls, color: Color = None, bgcolor: Color = None) -> \\\"Style\\\":\\n \\\"\\\"\\\"Create a new style with colors and no attributes.\\n\\n Returns:\\n color (Optional[Color]): A (foreground) color, or None for no color. Defaults to None.\\n bgcolor (Optional[Color]): A (background) color, or None for no color. Defaults to None.\\n \\\"\\\"\\\"\\n style = cls.__new__(Style)\\n style._ansi = None\\n style._style_definition = None\\n style._color = color\\n style._bgcolor = bgcolor\\n style._set_attributes = 0\\n style._attributes = 0\\n style._link = None\\n style._link_id = \\\"\\\"\\n style._hash = hash(\\n (\\n color,\\n bgcolor,\\n None,\\n None,\\n None,\\n )\\n )\\n style._null = not (color or bgcolor)\\n return style\\n\\n bold = _Bit(0)\\n dim = _Bit(1)\\n italic = _Bit(2)\\n underline = _Bit(3)\\n blink = _Bit(4)\\n blink2 = _Bit(5)\\n reverse = _Bit(6)\\n conceal = _Bit(7)\\n strike = _Bit(8)\\n underline2 = _Bit(9)\\n frame = _Bit(10)\\n encircle = _Bit(11)\\n overline = _Bit(12)\\n\\n @property\\n def link_id(self) -> str:\\n \\\"\\\"\\\"Get a link id, used in ansi code for links.\\\"\\\"\\\"\\n return self._link_id\\n\\n def __str__(self) -> str:\\n \\\"\\\"\\\"Re-generate style definition from attributes.\\\"\\\"\\\"\\n if self._style_definition is None:\\n attributes: List[str] = []\\n append = attributes.append\\n bits = self._set_attributes\\n if bits & 0b0000000001111:\\n if bits & 1:\\n append(\\\"bold\\\" if self.bold else \\\"not bold\\\")\\n if bits & (1 << 1):\\n append(\\\"dim\\\" if self.dim else \\\"not dim\\\")\\n if bits & (1 << 2):\\n append(\\\"italic\\\" if self.italic else \\\"not italic\\\")\\n if bits & (1 << 3):\\n append(\\\"underline\\\" if self.underline else \\\"not underline\\\")\\n if bits & 0b0000111110000:\\n if bits & (1 << 4):\\n append(\\\"blink\\\" if self.blink else \\\"not blink\\\")\\n if bits & (1 << 5):\\n append(\\\"blink2\\\" if self.blink2 else \\\"not blink2\\\")\\n if bits & (1 << 6):\\n append(\\\"reverse\\\" if self.reverse else \\\"not reverse\\\")\\n if bits & (1 << 7):\\n append(\\\"conceal\\\" if self.conceal else \\\"not conceal\\\")\\n if bits & (1 << 8):\\n append(\\\"strike\\\" if self.strike else \\\"not strike\\\")\\n if bits & 0b1111000000000:\\n if bits & (1 << 9):\\n append(\\\"underline2\\\" if self.underline2 else \\\"not underline2\\\")\\n if bits & (1 << 10):\\n append(\\\"frame\\\" if self.frame else \\\"not frame\\\")\\n if bits & (1 << 11):\\n append(\\\"encircle\\\" if self.encircle else \\\"not encircle\\\")\\n if bits & (1 << 12):\\n append(\\\"overline\\\" if self.overline else \\\"not overline\\\")\\n if self._color is not None:\\n append(self._color.name)\\n if self._bgcolor is not None:\\n append(\\\"on\\\")\\n append(self._bgcolor.name)\\n if self._link:\\n append(\\\"link\\\")\\n append(self._link)\\n self._style_definition = \\\" \\\".join(attributes) or \\\"none\\\"\\n return self._style_definition\\n\\n def __bool__(self) -> bool:\\n \\\"\\\"\\\"A Style is false if it has no attributes, colors, or links.\\\"\\\"\\\"\\n return not self._null\\n\\n def _make_ansi_codes(self, color_system: ColorSystem) -> str:\\n \\\"\\\"\\\"Generate ANSI codes for this style.\\n\\n Args:\\n color_system (ColorSystem): Color system.\\n\\n Returns:\\n str: String containing codes.\\n \\\"\\\"\\\"\\n if self._ansi is None:\\n sgr: List[str] = []\\n append = sgr.append\\n _style_map = self._style_map\\n attributes = self._attributes & self._set_attributes\\n if attributes:\\n if attributes & 1:\\n append(_style_map[0])\\n if attributes & 2:\\n append(_style_map[1])\\n if attributes & 4:\\n append(_style_map[2])\\n if attributes & 8:\\n append(_style_map[3])\\n if attributes & 0b0000111110000:\\n for bit in range(4, 9):\\n if attributes & (1 << bit):\\n append(_style_map[bit])\\n if attributes & 0b1111000000000:\\n for bit in range(9, 13):\\n if attributes & (1 << bit):\\n append(_style_map[bit])\\n if self._color is not None:\\n sgr.extend(self._color.downgrade(color_system).get_ansi_codes())\\n if self._bgcolor is not None:\\n sgr.extend(\\n self._bgcolor.downgrade(color_system).get_ansi_codes(\\n foreground=False\\n )\\n )\\n self._ansi = \\\";\\\".join(sgr)\\n return self._ansi\\n\\n @classmethod\\n @lru_cache(maxsize=1024)\\n def normalize(cls, style: str) -> str:\\n \\\"\\\"\\\"Normalize a style definition so that styles with the same effect have the same string\\n representation.\\n\\n Args:\\n style (str): A style definition.\\n\\n Returns:\\n str: Normal form of style definition.\\n \\\"\\\"\\\"\\n try:\\n return str(cls.parse(style))\\n except errors.StyleSyntaxError:\\n return style.strip().lower()\\n\\n @classmethod\\n def pick_first(cls, *values: Optional[StyleType]) -> StyleType:\\n \\\"\\\"\\\"Pick first non-None style.\\\"\\\"\\\"\\n for value in values:\\n if value is not None:\\n return value\\n raise ValueError(\\\"expected at least one non-None style\\\")\\n\\n def __repr__(self) -> str:\\n \\\"\\\"\\\"Render a named style differently from an anonymous style.\\\"\\\"\\\"\\n return f'Style.parse(\\\"{self}\\\")'\\n\\n def __eq__(self, other: Any) -> bool:\\n if not isinstance(other, Style):\\n return NotImplemented\\n return (\\n self._color == other._color\\n and self._bgcolor == other._bgcolor\\n and self._set_attributes == other._set_attributes\\n and self._attributes == other._attributes\\n and self._link == other._link\\n )\\n\\n def __hash__(self) -> int:\\n return self._hash\\n\\n @property\\n def color(self) -> Optional[Color]:\\n \\\"\\\"\\\"The foreground color or None if it is not set.\\\"\\\"\\\"\\n return self._color\\n\\n @property\\n def bgcolor(self) -> Optional[Color]:\\n \\\"\\\"\\\"The background color or None if it is not set.\\\"\\\"\\\"\\n return self._bgcolor\\n\\n @property\\n def link(self) -> Optional[str]:\\n \\\"\\\"\\\"Link text, if set.\\\"\\\"\\\"\\n return self._link\\n\\n @property\\n def transparent_background(self) -> bool:\\n \\\"\\\"\\\"Check if the style specified a transparent background.\\\"\\\"\\\"\\n return self.bgcolor is None or self.bgcolor.is_default\\n\\n @property\\n def background_style(self) -> \\\"Style\\\":\\n \\\"\\\"\\\"A Style with background only.\\\"\\\"\\\"\\n return Style(bgcolor=self.bgcolor)\\n\\n @classmethod\\n @lru_cache(maxsize=4096)\\n def parse(cls, style_definition: str) -> \\\"Style\\\":\\n \\\"\\\"\\\"Parse a style definition.\\n\\n Args:\\n style_definition (str): A string containing a style.\\n\\n Raises:\\n errors.StyleSyntaxError: If the style definition syntax is invalid.\\n\\n Returns:\\n `Style`: A Style instance.\\n \\\"\\\"\\\"\\n if style_definition.strip() == \\\"none\\\":\\n return cls.null()\\n\\n style_attributes = {\\n \\\"dim\\\": \\\"dim\\\",\\n \\\"d\\\": \\\"dim\\\",\\n \\\"bold\\\": \\\"bold\\\",\\n \\\"b\\\": \\\"bold\\\",\\n \\\"italic\\\": \\\"italic\\\",\\n \\\"i\\\": \\\"italic\\\",\\n \\\"underline\\\": \\\"underline\\\",\\n \\\"u\\\": \\\"underline\\\",\\n \\\"blink\\\": \\\"blink\\\",\\n \\\"blink2\\\": \\\"blink2\\\",\\n \\\"reverse\\\": \\\"reverse\\\",\\n \\\"r\\\": \\\"reverse\\\",\\n \\\"conceal\\\": \\\"conceal\\\",\\n \\\"c\\\": \\\"conceal\\\",\\n \\\"strike\\\": \\\"strike\\\",\\n \\\"s\\\": \\\"strike\\\",\\n \\\"underline2\\\": \\\"underline2\\\",\\n \\\"uu\\\": \\\"underline2\\\",\\n \\\"frame\\\": \\\"frame\\\",\\n \\\"encircle\\\": \\\"encircle\\\",\\n \\\"overline\\\": \\\"overline\\\",\\n \\\"o\\\": \\\"overline\\\",\\n }\\n color: Optional[str] = None\\n bgcolor: Optional[str] = None\\n attributes: Dict[str, Optional[bool]] = {}\\n link: Optional[str] = None\\n\\n words = iter(style_definition.split())\\n for original_word in words:\\n word = original_word.lower()\\n if word == \\\"on\\\":\\n word = next(words, \\\"\\\")\\n if not word:\\n raise errors.StyleSyntaxError(\\\"color expected after 'on'\\\")\\n try:\\n Color.parse(word) is None\\n except ColorParseError as error:\\n raise errors.StyleSyntaxError(\\n f\\\"unable to parse {word!r} as background color; {error}\\\"\\n ) from None\\n bgcolor = word\\n\\n elif word == \\\"not\\\":\\n word = next(words, \\\"\\\")\\n attribute = style_attributes.get(word)\\n if attribute is None:\\n raise errors.StyleSyntaxError(\\n f\\\"expected style attribute after 'not', found {word!r}\\\"\\n )\\n attributes[attribute] = False\\n\\n elif word == \\\"link\\\":\\n word = next(words, \\\"\\\")\\n if not word:\\n raise errors.StyleSyntaxError(\\\"URL expected after 'link'\\\")\\n link = word\\n\\n elif word in style_attributes:\\n attributes[style_attributes[word]] = True\\n\\n else:\\n try:\\n Color.parse(word)\\n except ColorParseError as error:\\n raise errors.StyleSyntaxError(\\n f\\\"unable to parse {word!r} as color; {error}\\\"\\n ) from None\\n color = word\\n style = Style(color=color, bgcolor=bgcolor, link=link, **attributes)\\n return style\\n\\n @lru_cache(maxsize=1024)\\n def get_html_style(self, theme: TerminalTheme = None) -> str:\\n \\\"\\\"\\\"Get a CSS style rule.\\\"\\\"\\\"\\n theme = theme or DEFAULT_TERMINAL_THEME\\n css: List[str] = []\\n append = css.append\\n\\n color = self.color\\n bgcolor = self.bgcolor\\n if self.reverse:\\n color, bgcolor = bgcolor, color\\n if self.dim:\\n foreground_color = (\\n theme.foreground_color if color is None else color.get_truecolor(theme)\\n )\\n color = Color.from_triplet(\\n blend_rgb(foreground_color, theme.background_color, 0.5)\\n )\\n if color is not None:\\n theme_color = color.get_truecolor(theme)\\n append(f\\\"color: {theme_color.hex}\\\")\\n if bgcolor is not None:\\n theme_color = bgcolor.get_truecolor(theme, foreground=False)\\n append(f\\\"background-color: {theme_color.hex}\\\")\\n if self.bold:\\n append(\\\"font-weight: bold\\\")\\n if self.italic:\\n append(\\\"font-style: italic\\\")\\n if self.underline:\\n append(\\\"text-decoration: underline\\\")\\n if self.strike:\\n append(\\\"text-decoration: line-through\\\")\\n if self.overline:\\n append(\\\"text-decoration: overline\\\")\\n return \\\"; \\\".join(css)\\n\\n @classmethod\\n def combine(cls, styles: Iterable[\\\"Style\\\"]) -> \\\"Style\\\":\\n \\\"\\\"\\\"Combine styles and get result.\\n\\n Args:\\n styles (Iterable[Style]): Styles to combine.\\n\\n Returns:\\n Style: A new style instance.\\n \\\"\\\"\\\"\\n iter_styles = iter(styles)\\n return sum(iter_styles, next(iter_styles))\\n\\n @classmethod\\n def chain(cls, *styles: \\\"Style\\\") -> \\\"Style\\\":\\n \\\"\\\"\\\"Combine styles from positional argument in to a single style.\\n\\n Args:\\n *styles (Iterable[Style]): Styles to combine.\\n\\n Returns:\\n Style: A new style instance.\\n \\\"\\\"\\\"\\n iter_styles = iter(styles)\\n return sum(iter_styles, next(iter_styles))\\n\\n def copy(self) -> \\\"Style\\\":\\n \\\"\\\"\\\"Get a copy of this style.\\n\\n Returns:\\n Style: A new Style instance with identical attributes.\\n \\\"\\\"\\\"\\n if self._null:\\n return NULL_STYLE\\n style = self.__new__(Style)\\n style._ansi = self._ansi\\n style._style_definition = self._style_definition\\n style._color = self._color\\n style._bgcolor = self._bgcolor\\n style._attributes = self._attributes\\n style._set_attributes = self._set_attributes\\n style._link = self._link\\n style._link_id = f\\\"{time()}-{randint(0, 999999)}\\\" if self._link else \\\"\\\"\\n style._hash = self._hash\\n style._null = False\\n return style\\n\\n def update_link(self, link: str = None) -> \\\"Style\\\":\\n \\\"\\\"\\\"Get a copy with a different value for link.\\n\\n Args:\\n link (str, optional): New value for link. Defaults to None.\\n\\n Returns:\\n Style: A new Style instance.\\n \\\"\\\"\\\"\\n style = self.__new__(Style)\\n style._ansi = self._ansi\\n style._style_definition = self._style_definition\\n style._color = self._color\\n style._bgcolor = self._bgcolor\\n style._attributes = self._attributes\\n style._set_attributes = self._set_attributes\\n style._link = link\\n style._link_id = f\\\"{time()}-{randint(0, 999999)}\\\" if link else \\\"\\\"\\n style._hash = self._hash\\n style._null = False\\n return style\\n\\n def render(\\n self,\\n text: str = \\\"\\\",\\n *,\\n color_system: Optional[ColorSystem] = ColorSystem.TRUECOLOR,\\n legacy_windows: bool = False,\\n ) -> str:\\n \\\"\\\"\\\"Render the ANSI codes for the style.\\n\\n Args:\\n text (str, optional): A string to style. Defaults to \\\"\\\".\\n color_system (Optional[ColorSystem], optional): Color system to render to. Defaults to ColorSystem.TRUECOLOR.\\n\\n Returns:\\n str: A string containing ANSI style codes.\\n \\\"\\\"\\\"\\n if not text or color_system is None:\\n return text\\n attrs = self._make_ansi_codes(color_system)\\n rendered = f\\\"\\\\x1b[{attrs}m{text}\\\\x1b[0m\\\" if attrs else text\\n if self._link and not legacy_windows:\\n rendered = (\\n f\\\"\\\\x1b]8;id={self._link_id};{self._link}\\\\x1b\\\\\\\\{rendered}\\\\x1b]8;;\\\\x1b\\\\\\\\\\\"\\n )\\n return rendered\\n\\n def test(self, text: Optional[str] = None) -> None:\\n \\\"\\\"\\\"Write text with style directly to terminal.\\n\\n This method is for testing purposes only.\\n\\n Args:\\n text (Optional[str], optional): Text to style or None for style name.\\n\\n \\\"\\\"\\\"\\n text = text or str(self)\\n sys.stdout.write(f\\\"{self.render(text)}\\\\n\\\")\\n\\n def __add__(self, style: Optional[\\\"Style\\\"]) -> \\\"Style\\\":\\n if not (isinstance(style, Style) or style is None):\\n return NotImplemented # type: ignore\\n if style is None or style._null:\\n return self\\n if self._null:\\n return style\\n new_style = self.__new__(Style)\\n new_style._ansi = None\\n new_style._style_definition = None\\n new_style._color = style._color or self._color\\n new_style._bgcolor = style._bgcolor or self._bgcolor\\n new_style._attributes = (self._attributes & ~style._set_attributes) | (\\n style._attributes & style._set_attributes\\n )\\n new_style._set_attributes = self._set_attributes | style._set_attributes\\n new_style._link = style._link or self._link\\n new_style._link_id = style._link_id or self._link_id\\n new_style._hash = style._hash\\n new_style._null = self._null or style._null\\n return new_style\\n\\n\\nNULL_STYLE = Style()\\n\\n\\nclass StyleStack:\\n \\\"\\\"\\\"A stack of styles.\\\"\\\"\\\"\\n\\n __slots__ = [\\\"_stack\\\"]\\n\\n def __init__(self, default_style: \\\"Style\\\") -> None:\\n self._stack: List[Style] = [default_style]\\n\\n def __repr__(self) -> str:\\n return f\\\"\\\"\\n\\n @property\\n def current(self) -> Style:\\n \\\"\\\"\\\"Get the Style at the top of the stack.\\\"\\\"\\\"\\n return self._stack[-1]\\n\\n def push(self, style: Style) -> None:\\n \\\"\\\"\\\"Push a new style on to the stack.\\n\\n Args:\\n style (Style): New style to combine with current style.\\n \\\"\\\"\\\"\\n self._stack.append(self._stack[-1] + style)\\n\\n def pop(self) -> Style:\\n \\\"\\\"\\\"Pop last style and discard.\\n\\n Returns:\\n Style: New current style (also available as stack.current)\\n \\\"\\\"\\\"\\n self._stack.pop()\\n return self._stack[-1]\\n\"}"},"non_py_patch":{"kind":"string","value":"diff --git a/CHANGELOG.md b/CHANGELOG.md\nindex d8378b729a..acb53b1308 100644\n--- a/CHANGELOG.md\n+++ b/CHANGELOG.md\n@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0\n ### Added\n \n - Added rich.tree\n+- Added no_color argument to Console\n \n ## [9.6.2] - 2021-01-07\n \n"},"new_components":{"kind":"string","value":"{\"rich/segment.py\": [{\"type\": \"function\", \"name\": \"Segment.remove_color\", \"lines\": [344, 363], \"signature\": \"def remove_color(cls, segments: Iterable[\\\"Segment\\\"]) -> Iterable[\\\"Segment\\\"]:\", \"doc\": \"Remove all color from an iterable of segments.\\n\\nArgs:\\n segments (Iterable[Segment]): An iterable segments.\\n\\nYields:\\n Segment: Segments with colorless style.\"}], \"rich/style.py\": [{\"type\": \"function\", \"name\": \"Style.without_color\", \"lines\": [387, 402], \"signature\": \"def without_color(self) -> \\\"Style\\\":\", \"doc\": \"Get a copy of the style with color removed.\"}]}"},"version":{"kind":"null"},"FAIL_TO_PASS":{"kind":"string","value":"[\"tests/test_console.py::test_no_color\", \"tests/test_segment.py::test_remove_color\", \"tests/test_style.py::test_without_color\"]"},"PASS_TO_PASS":{"kind":"string","value":"[\"tests/test_console.py::test_dumb_terminal\", \"tests/test_console.py::test_soft_wrap\", \"tests/test_console.py::test_16color_terminal\", \"tests/test_console.py::test_truecolor_terminal\", \"tests/test_console.py::test_console_options_update\", \"tests/test_console.py::test_init\", \"tests/test_console.py::test_size\", \"tests/test_console.py::test_repr\", \"tests/test_console.py::test_print\", \"tests/test_console.py::test_log\", \"tests/test_console.py::test_print_empty\", \"tests/test_console.py::test_markup_highlight\", \"tests/test_console.py::test_print_style\", \"tests/test_console.py::test_show_cursor\", \"tests/test_console.py::test_clear\", \"tests/test_console.py::test_clear_no_terminal\", \"tests/test_console.py::test_get_style\", \"tests/test_console.py::test_get_style_default\", \"tests/test_console.py::test_get_style_error\", \"tests/test_console.py::test_render_error\", \"tests/test_console.py::test_control\", \"tests/test_console.py::test_capture\", \"tests/test_console.py::test_input\", \"tests/test_console.py::test_input_legacy_windows\", \"tests/test_console.py::test_input_password\", \"tests/test_console.py::test_status\", \"tests/test_console.py::test_justify_none\", \"tests/test_console.py::test_justify_left\", \"tests/test_console.py::test_justify_center\", \"tests/test_console.py::test_justify_right\", \"tests/test_console.py::test_justify_renderable_none\", \"tests/test_console.py::test_justify_renderable_left\", \"tests/test_console.py::test_justify_renderable_center\", \"tests/test_console.py::test_justify_renderable_right\", \"tests/test_console.py::test_render_broken_renderable\", \"tests/test_console.py::test_export_text\", \"tests/test_console.py::test_export_html\", \"tests/test_console.py::test_export_html_inline\", \"tests/test_console.py::test_save_text\", \"tests/test_console.py::test_save_html\", \"tests/test_console.py::test_no_wrap\", \"tests/test_console.py::test_unicode_error\", \"tests/test_console.py::test_bell\", \"tests/test_console.py::test_pager\", \"tests/test_console.py::test_out\", \"tests/test_console.py::test_render_group\", \"tests/test_console.py::test_render_group_fit\", \"tests/test_console.py::test_get_time\", \"tests/test_console.py::test_console_style\", \"tests/test_segment.py::test_repr\", \"tests/test_segment.py::test_line\", \"tests/test_segment.py::test_apply_style\", \"tests/test_segment.py::test_split_lines\", \"tests/test_segment.py::test_split_and_crop_lines\", \"tests/test_segment.py::test_adjust_line_length\", \"tests/test_segment.py::test_get_line_length\", \"tests/test_segment.py::test_get_shape\", \"tests/test_segment.py::test_set_shape\", \"tests/test_segment.py::test_simplify\", \"tests/test_segment.py::test_filter_control\", \"tests/test_segment.py::test_strip_styles\", \"tests/test_segment.py::test_strip_links\", \"tests/test_style.py::test_str\", \"tests/test_style.py::test_ansi_codes\", \"tests/test_style.py::test_repr\", \"tests/test_style.py::test_eq\", \"tests/test_style.py::test_hash\", \"tests/test_style.py::test_empty\", \"tests/test_style.py::test_bool\", \"tests/test_style.py::test_color_property\", \"tests/test_style.py::test_bgcolor_property\", \"tests/test_style.py::test_parse\", \"tests/test_style.py::test_link_id\", \"tests/test_style.py::test_get_html_style\", \"tests/test_style.py::test_chain\", \"tests/test_style.py::test_copy\", \"tests/test_style.py::test_render\", \"tests/test_style.py::test_test\", \"tests/test_style.py::test_add\", \"tests/test_style.py::test_iadd\", \"tests/test_style.py::test_style_stack\", \"tests/test_style.py::test_pick_first\", \"tests/test_style.py::test_background_style\"]"},"environment_setup_commit":{"kind":"string","value":"b0661de34bab35af9b4b1d3ba8e28b186b225e84"},"problem_statement":{"kind":"string","value":"{\"first_commit_time\": 1610208516.0, \"pr_title\": \"No color\", \"pr_body\": \"Fixes https://github.com/willmcgugan/rich/issues/882\\r\\n\\r\\nAdds a no_color mode which strips color before render.\\r\\n\\r\\n## Type of changes\\r\\n\\r\\n- [ ] Bug fix\\r\\n- [ ] New feature\\r\\n- [ ] Documentation / docstrings\\r\\n- [ ] Tests\\r\\n- [ ] Other\\r\\n\\r\\n## Checklist\\r\\n\\r\\n- [ ] I've run the latest [black](https://github.com/psf/black) with default args on new code.\\r\\n- [ ] I've updated CHANGELOG.md and CONTRIBUTORS.md where appropriate.\\r\\n- [ ] I've added tests for new code.\\r\\n- [ ] I accept that @willmcgugan may be pedantic in the code review.\\r\\n\\r\\n## Description\\r\\n\\r\\nPlease describe your changes here. If this fixes a bug, please link to the issue, if possible.\\r\\n\", \"pr_timeline\": [{\"time\": 1610209402.0, \"comment\": \"# [Codecov](https://codecov.io/gh/willmcgugan/rich/pull/901?src=pr&el=h1) Report\\n> Merging [#901](https://codecov.io/gh/willmcgugan/rich/pull/901?src=pr&el=desc) (6bac7ff) into [master](https://codecov.io/gh/willmcgugan/rich/commit/6853210b5ea1886b7380589239b9b055eaaa0687?el=desc) (6853210) will **increase** coverage by `0.00%`.\\n> The diff coverage is `100.00%`.\\n\\n[![Impacted file tree graph](https://codecov.io/gh/willmcgugan/rich/pull/901/graphs/tree.svg?width=650&height=150&src=pr&token=gpwvEeKjff)](https://codecov.io/gh/willmcgugan/rich/pull/901?src=pr&el=tree)\\n\\n```diff\\n@@ Coverage Diff @@\\n## master #901 +/- ##\\n=======================================\\n Coverage 99.53% 99.54% \\n=======================================\\n Files 58 58 \\n Lines 4992 5022 +30 \\n=======================================\\n+ Hits 4969 4999 +30 \\n Misses 23 23 \\n```\\n\\n| Flag | Coverage \\u0394 | |\\n|---|---|---|\\n| unittests | `99.54% <100.00%> (+<0.01%)` | :arrow_up: |\\n\\nFlags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags#carryforward-flags-in-the-pull-request-comment) to find out more.\\n\\n| [Impacted Files](https://codecov.io/gh/willmcgugan/rich/pull/901?src=pr&el=tree) | Coverage \\u0394 | |\\n|---|---|---|\\n| [rich/console.py](https://codecov.io/gh/willmcgugan/rich/pull/901/diff?src=pr&el=tree#diff-cmljaC9jb25zb2xlLnB5) | `100.00% <100.00%> (\\u00f8)` | |\\n| [rich/segment.py](https://codecov.io/gh/willmcgugan/rich/pull/901/diff?src=pr&el=tree#diff-cmljaC9zZWdtZW50LnB5) | `100.00% <100.00%> (\\u00f8)` | |\\n| [rich/style.py](https://codecov.io/gh/willmcgugan/rich/pull/901/diff?src=pr&el=tree#diff-cmljaC9zdHlsZS5weQ==) | `100.00% <100.00%> (\\u00f8)` | |\\n\\n------\\n\\n[Continue to review full report at Codecov](https://codecov.io/gh/willmcgugan/rich/pull/901?src=pr&el=continue).\\n> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)\\n> `\\u0394 = absolute (impact)`, `\\u00f8 = not affected`, `? = missing data`\\n> Powered by [Codecov](https://codecov.io/gh/willmcgugan/rich/pull/901?src=pr&el=footer). Last update [a9c0f91...6bac7ff](https://codecov.io/gh/willmcgugan/rich/pull/901?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).\\n\"}], \"issues\": {}}"}}},{"rowIdx":9,"cells":{"repo":{"kind":"string","value":"Textualize/textual"},"pull_number":{"kind":"number","value":1517,"string":"1,517"},"url":{"kind":"string","value":"https://github.com/Textualize/textual/pull/1517"},"instance_id":{"kind":"string","value":"Textualize__textual-1517"},"issue_numbers":{"kind":"string","value":"[]"},"base_commit":{"kind":"string","value":"779b10a0e8b8581fab512eb684a06eb90381705d"},"patch":{"kind":"string","value":"diff --git a/src/textual/app.py b/src/textual/app.py\nindex b207bbd025..89da6aaf60 100644\n--- a/src/textual/app.py\n+++ b/src/textual/app.py\n@@ -1,6 +1,8 @@\n from __future__ import annotations\n \n import asyncio\n+from concurrent.futures import Future\n+from functools import partial\n import inspect\n import io\n import os\n@@ -18,6 +20,7 @@\n from typing import (\n TYPE_CHECKING,\n Any,\n+ Awaitable,\n Callable,\n Generic,\n Iterable,\n@@ -206,6 +209,8 @@ def stop(self) -> None:\n \n CSSPathType = Union[str, PurePath, List[Union[str, PurePath]], None]\n \n+CallThreadReturnType = TypeVar(\"CallThreadReturnType\")\n+\n \n @rich.repr.auto\n class App(Generic[ReturnType], DOMNode):\n@@ -353,6 +358,8 @@ def __init__(\n else:\n self.devtools = DevtoolsClient()\n \n+ self._loop: asyncio.AbstractEventLoop | None = None\n+ self._thread_id: int = 0\n self._return_value: ReturnType | None = None\n self._exit = False\n \n@@ -604,6 +611,51 @@ def _log(\n except Exception as error:\n self._handle_exception(error)\n \n+ def call_from_thread(\n+ self,\n+ callback: Callable[..., CallThreadReturnType | Awaitable[CallThreadReturnType]],\n+ *args,\n+ **kwargs,\n+ ) -> CallThreadReturnType:\n+ \"\"\"Run a callback from another thread.\n+\n+ Like asyncio apps in general, Textual apps are not thread-safe. If you call methods\n+ or set attributes on Textual objects from a thread, you may get unpredictable results.\n+\n+ This method will ensure that your code is ran within the correct context.\n+\n+ Args:\n+ callback (Callable): A callable to run.\n+ *args: Arguments to the callback.\n+ **kwargs: Keyword arguments for the callback.\n+\n+ Raises:\n+ RuntimeError: If the app isn't running or if this method is called from the same\n+ thread where the app is running.\n+ \"\"\"\n+\n+ if self._loop is None:\n+ raise RuntimeError(\"App is not running\")\n+\n+ if self._thread_id == threading.get_ident():\n+ raise RuntimeError(\n+ \"The `call_from_thread` method must run in a different thread from the app\"\n+ )\n+\n+ callback_with_args = partial(callback, *args, **kwargs)\n+\n+ async def run_callback() -> CallThreadReturnType:\n+ \"\"\"Run the callback, set the result or error on the future.\"\"\"\n+ self._set_active()\n+ return await invoke(callback_with_args)\n+\n+ # Post the message to the main loop\n+ future: Future[CallThreadReturnType] = asyncio.run_coroutine_threadsafe(\n+ run_callback(), loop=self._loop\n+ )\n+ result = future.result()\n+ return result\n+\n def action_toggle_dark(self) -> None:\n \"\"\"Action to toggle dark mode.\"\"\"\n self.dark = not self.dark\n@@ -874,11 +926,17 @@ def run(\n \n async def run_app() -> None:\n \"\"\"Run the app.\"\"\"\n- await self.run_async(\n- headless=headless,\n- size=size,\n- auto_pilot=auto_pilot,\n- )\n+ self._loop = asyncio.get_running_loop()\n+ self._thread_id = threading.get_ident()\n+ try:\n+ await self.run_async(\n+ headless=headless,\n+ size=size,\n+ auto_pilot=auto_pilot,\n+ )\n+ finally:\n+ self._loop = None\n+ self._thread_id = 0\n \n if _ASYNCIO_GET_EVENT_LOOP_IS_DEPRECATED:\n # N.B. This doesn't work with Python<3.10, as we end up with 2 event loops:\n"},"test_patch":{"kind":"string","value":"diff --git a/tests/test_concurrency.py b/tests/test_concurrency.py\nnew file mode 100644\nindex 0000000000..c73418f2f2\n--- /dev/null\n+++ b/tests/test_concurrency.py\n@@ -0,0 +1,53 @@\n+import pytest\n+\n+from threading import Thread\n+from textual.app import App, ComposeResult\n+from textual.widgets import TextLog\n+\n+\n+def test_call_from_thread_app_not_running():\n+ app = App()\n+\n+ # Should fail if app is not running\n+ with pytest.raises(RuntimeError):\n+ app.call_from_thread(print)\n+\n+\n+def test_call_from_thread():\n+ \"\"\"Test the call_from_thread method.\"\"\"\n+\n+ class BackgroundThread(Thread):\n+ \"\"\"A background thread which will modify app in some way.\"\"\"\n+\n+ def __init__(self, app: App) -> None:\n+ self.app = app\n+ super().__init__()\n+\n+ def run(self) -> None:\n+ def write_stuff(text: str) -> None:\n+ \"\"\"Write stuff to a widget.\"\"\"\n+ self.app.query_one(TextLog).write(text)\n+\n+ self.app.call_from_thread(write_stuff, \"Hello\")\n+ # Exit the app with a code we can assert\n+ self.app.call_from_thread(self.app.exit, 123)\n+\n+ class ThreadTestApp(App):\n+ \"\"\"Trivial app with a single widget.\"\"\"\n+\n+ def compose(self) -> ComposeResult:\n+ yield TextLog()\n+\n+ def on_ready(self) -> None:\n+ \"\"\"Launch a thread which will modify the app.\"\"\"\n+ try:\n+ self.call_from_thread(print)\n+ except RuntimeError as error:\n+ # Calling this from the same thread as the app is an error\n+ self._runtime_error = error\n+ BackgroundThread(self).start()\n+\n+ app = ThreadTestApp()\n+ result = app.run(headless=True, size=(80, 24))\n+ assert isinstance(app._runtime_error, RuntimeError)\n+ assert result == 123\n"},"created_at":{"kind":"timestamp","value":"2023-01-07T14:10:40","string":"2023-01-07T14:10:40"},"readmes":{"kind":"string","value":"{\"README.md\": \"

\\n \\n \\\"fea-bench\\\"\\n \\n

\\n\\n

\\n A benchmark that aims to evaluate the capability of implementing new features in the code repositories.\\n

\\n\\n

\\n \\n \\\"paper\\\"\\n \\n \\n \\\"License\\\"\\n \\n \\n \\\"Leaderboard\\\"\\n \\n \\n \\\"dataset\\\"\\n \\n

\\n\\n---\\n\\n# Evaluation\\n\\nThis repository is the official implementation of the paper \\\"FEA-Bench: A Benchmark for Evaluating Repository-Level Code Generation for Feature Implementation.\\\" It can be used for baseline evaluation using the prompts mentioned in the paper.\\n\\nThe repository includes several functionalities, primarily for obtaining the full dataset, running model inference aligned with the paper, and evaluating the results. The complete pipeline is as follows:\\n\\n## 1. Environment Setup\\n\\nYou can create a new Python environment and install all dependencies using:\\n```bash\\npip install -e .\\n```\\nIf you plan to use VLLM inference, ensure that the installed libraries match your hardware.\\n\\n## 2. Building the Full Evaluation Dataset\\n\\nDue to licensing and company policies, we cannot release the full dataset. Our published version ([https://huggingface.co/datasets/microsoft/FEA-Bench](https://huggingface.co/datasets/microsoft/FEA-Bench)) only includes essential attributes, and the remaining content needs to be scraped from GitHub.\\n\\nTo construct the full FEA-Bench dataset and save it in the `feabench-data` folder, run the following command. Note that you need to replace `GITHUB_TOKEN` with your own GitHub token, which should have read-only access to public repositories:\\n```bash\\nexport GITHUB_TOKEN=\\\"xxx\\\"\\n\\npython -m feabench.get_dataset \\\\\\n --dataset microsoft/FEA-Bench \\\\\\n --testbed feabench-data/testbed \\\\\\n --lite_ids instances_lite.json \\\\\\n --medium_file feabench-data/FEA-Bench-v1.0-medium.jsonl \\\\\\n --standard_dataset_path feabench-data/FEA-Bench-v1.0-Standard \\\\\\n --oracle_dataset_path feabench-data/FEA-Bench-v1.0-Oracle \\\\\\n --lite_standard_dataset_path feabench-data/FEA-Bench-v1.0-Lite-Standard \\\\\\n --lite_oracle_dataset_path feabench-data/FEA-Bench-v1.0-Lite-Oracle\\n```\\n\\n## 3. Running Model Inference\\n\\nOur repository only provides inference methods consistent with those in the paper. Agentless and other agent-based inferences can use the `FEA-Bench-v1.0-Lite-Standard` dataset constructed in the previous step, which is aligned with the format of SWE-Bench.\\n\\n### Example of VLLM Inference:\\n```bash\\nexport MAX_SEQ_LEN=128000\\nexport MAX_GEN_LEN=4096\\n\\nDATASET_PATH=feabench-data/FEA-Bench-v1.0-Oracle\\nMODEL_NAME=Qwen/Qwen2.5-Coder-3B-Instruct\\nRESULTS_ROOT_DIR=scripts/experiments/results_full\\n\\nPROMPT_MODE=natural-detailed\\npython -m feabench.run_prediction \\\\\\n --dataset_name_or_path $DATASET_PATH \\\\\\n --model_type vllm \\\\\\n --model_name_or_path $MODEL_NAME \\\\\\n --input_text $PROMPT_MODE \\\\\\n --output_dir $RESULTS_ROOT_DIR/$PROMPT_MODE\\n```\\n\\n### Example of OpenAI API-style Inference:\\n(DEEPSEEK_TOKENIZER is only required when using DeepSeek model inference)\\n```bash\\nexport DEEPSEEK_TOKENIZER_PATH=\\\"xxx\\\"\\nexport OPENAI_API_KEY=\\\"xxx\\\"\\nexport OPENAI_BASE_URL=\\\"https://api.deepseek.com\\\"\\n\\nDATASET_PATH=feabench-data/FEA-Bench-v1.0-Oracle\\nMODEL_NAME=deepseek-chat\\nRESULTS_ROOT_DIR=scripts/experiments/results_full\\n\\nPROMPT_MODE=natural-detailed\\npython -m feabench.run_prediction \\\\\\n --dataset_name_or_path $DATASET_PATH \\\\\\n --model_type openai \\\\\\n --model_name_or_path $MODEL_NAME \\\\\\n --input_text $PROMPT_MODE \\\\\\n --output_dir $RESULTS_ROOT_DIR/$PROMPT_MODE \\\\\\n --num_proc 1\\n```\\n\\nAfter running the inference, you should see the output `.jsonl` result files in the specified `output_dir`.\\n\\n## 4. Running Model Evaluation\\n\\nOur evaluation process is based on the code provided by SWE-Bench. We have provided a patch file `swe-bench.diff` to include the environment configurations for the task instances we are involved in.\\n\\nClone the SWE-Bench repository and apply the patch:\\n```bash\\nmkdir -p evaluator\\ncd evaluator\\ngit clone https://github.com/SWE-bench/SWE-bench.git\\ncd SWE-bench\\ngit checkout a0536ee6f9fd5ff88acf17a36a384bf3da3d93d6\\ngit apply ../../swe-bench.diff\\nconda create --name fea-eval python=3.11\\nconda activate fea-eval\\npip install -e .\\n```\\n\\nTo verify that the FEA-Bench task instances can run correctly on your machine, you can build a gold result based on the dataset:\\n```bash\\npython -m feabench.get_gold_results \\\\\\n --dataset_name_or_path feabench-data/FEA-Bench-v1.0-Standard \\\\\\n --save_dir feabench-data/experiments/gold \\\\\\n --file_name Gold__FEABench_v1.0__test.jsonl\\n```\\n\\nThe command to run the evaluation script is as follows (using the gold result constructed above as an example):\\n```bash\\npython -m swebench.harness.run_evaluation \\\\\\n --dataset_name ../../feabench-data/FEA-Bench-v1.0-Standard \\\\\\n --predictions_path ../../feabench-data/experiments/gold/Gold__FEABench_v1.0__test.jsonl \\\\\\n --max_workers 10 \\\\\\n --cache_level instance \\\\\\n --timeout 900 \\\\\\n --run_id FEABench_v1_Gold\\n```\\nThe usage is identical to SWE-Bench. You can set the cache level `cache_level` based on your disk size. You should then obtain a result file similar to the following `.json` format:\\n```json\\n{\\n \\\"total_instances\\\": 1401,\\n \\\"submitted_instances\\\": 1401,\\n \\\"completed_instances\\\": 1401,\\n \\\"resolved_instances\\\": 1401,\\n \\\"unresolved_instances\\\": 0,\\n \\\"empty_patch_instances\\\": 0,\\n \\\"error_instances\\\": 0,\\n ...\\n}\\n```\\n\\nCongratulations! You have completed the usage of FEA-Bench. If you have any questions, please raise them in the issues.\\n\\n---\\n\\nFor more details, please refer to the [FEA-Bench Paper](https://arxiv.org/abs/2503.06680).\\nIf you find our work helpful, we would be grateful if you could cite our work.\\n```\\n@misc{li2025feabenchbenchmarkevaluatingrepositorylevel,\\n title={FEA-Bench: A Benchmark for Evaluating Repository-Level Code Generation for Feature Implementation}, \\n author={Wei Li and Xin Zhang and Zhongxin Guo and Shaoguang Mao and Wen Luo and Guangyue Peng and Yangyu Huang and Houfeng Wang and Scarlett Li},\\n year={2025},\\n eprint={2503.06680},\\n archivePrefix={arXiv},\\n primaryClass={cs.SE},\\n url={https://arxiv.org/abs/2503.06680}, \\n}\\n```\\n\\n\\n\\n## Contributing\\n\\nThis project welcomes contributions and suggestions. Most contributions require you to agree to a\\nContributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us\\nthe rights to use your contribution. For details, visit https://cla.opensource.microsoft.com.\\n\\nWhen you submit a pull request, a CLA bot will automatically determine whether you need to provide\\na CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions\\nprovided by the bot. You will only need to do this once across all repos using our CLA.\\n\\nThis project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).\\nFor more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or\\ncontact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.\\n\\n## Trademarks\\n\\nThis project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft \\ntrademarks or logos is subject to and must follow \\n[Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general).\\nUse of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship.\\nAny use of third-party trademarks or logos are subject to those third-party's policies.\\n\"}"},"files":{"kind":"string","value":"{\"src/textual/app.py\": \"from __future__ import annotations\\n\\nimport asyncio\\nimport inspect\\nimport io\\nimport os\\nimport platform\\nimport sys\\nimport threading\\nimport unicodedata\\nimport warnings\\nfrom asyncio import Task\\nfrom contextlib import asynccontextmanager, redirect_stderr, redirect_stdout\\nfrom datetime import datetime\\nfrom pathlib import Path, PurePath\\nfrom queue import Queue\\nfrom time import perf_counter\\nfrom typing import (\\n TYPE_CHECKING,\\n Any,\\n Callable,\\n Generic,\\n Iterable,\\n List,\\n Type,\\n TypeVar,\\n Union,\\n cast,\\n overload,\\n)\\nfrom weakref import WeakSet, WeakValueDictionary\\n\\nimport nanoid\\nimport rich\\nimport rich.repr\\nfrom rich.console import Console, RenderableType\\nfrom rich.protocol import is_renderable\\nfrom rich.segment import Segment, Segments\\nfrom rich.traceback import Traceback\\n\\nfrom . import actions, Logger, LogGroup, LogVerbosity, events, log, messages\\nfrom ._animator import DEFAULT_EASING, Animatable, Animator, EasingFunction\\nfrom ._ansi_sequences import SYNC_END, SYNC_START\\nfrom ._callback import invoke\\nfrom ._context import active_app\\nfrom ._event_broker import NoHandler, extract_handler_actions\\nfrom ._filter import LineFilter, Monochrome\\nfrom ._path import _make_path_object_relative\\nfrom ._typing import Final, TypeAlias\\nfrom .actions import SkipAction\\nfrom .await_remove import AwaitRemove\\nfrom .binding import Binding, Bindings\\nfrom .css.query import NoMatches\\nfrom .css.stylesheet import Stylesheet\\nfrom .design import ColorSystem\\nfrom .dom import DOMNode\\nfrom .driver import Driver\\nfrom .drivers.headless_driver import HeadlessDriver\\nfrom .features import FeatureFlag, parse_features\\nfrom .file_monitor import FileMonitor\\nfrom .geometry import Offset, Region, Size\\nfrom .keys import REPLACED_KEYS, _get_key_display\\nfrom .messages import CallbackType\\nfrom .reactive import Reactive\\nfrom .renderables.blank import Blank\\nfrom .screen import Screen\\nfrom .widget import AwaitMount, Widget\\n\\n\\nif TYPE_CHECKING:\\n from .devtools.client import DevtoolsClient\\n from .pilot import Pilot\\n\\nPLATFORM = platform.system()\\nWINDOWS = PLATFORM == \\\"Windows\\\"\\n\\n# asyncio will warn against resources not being cleared\\nwarnings.simplefilter(\\\"always\\\", ResourceWarning)\\n\\n# `asyncio.get_event_loop()` is deprecated since Python 3.10:\\n_ASYNCIO_GET_EVENT_LOOP_IS_DEPRECATED = sys.version_info >= (3, 10, 0)\\n\\nLayoutDefinition = \\\"dict[str, Any]\\\"\\n\\nDEFAULT_COLORS = {\\n \\\"dark\\\": ColorSystem(\\n primary=\\\"#004578\\\",\\n secondary=\\\"#ffa62b\\\",\\n warning=\\\"#ffa62b\\\",\\n error=\\\"#ba3c5b\\\",\\n success=\\\"#4EBF71\\\",\\n accent=\\\"#0178D4\\\",\\n dark=True,\\n ),\\n \\\"light\\\": ColorSystem(\\n primary=\\\"#004578\\\",\\n secondary=\\\"#ffa62b\\\",\\n warning=\\\"#ffa62b\\\",\\n error=\\\"#ba3c5b\\\",\\n success=\\\"#4EBF71\\\",\\n accent=\\\"#0178D4\\\",\\n dark=False,\\n ),\\n}\\n\\nComposeResult = Iterable[Widget]\\nRenderResult = RenderableType\\n\\nAutopilotCallbackType: TypeAlias = \\\"Callable[[Pilot], Coroutine[Any, Any, None]]\\\"\\n\\n\\nclass AppError(Exception):\\n pass\\n\\n\\nclass ActionError(Exception):\\n pass\\n\\n\\nclass ScreenError(Exception):\\n pass\\n\\n\\nclass ScreenStackError(ScreenError):\\n \\\"\\\"\\\"Raised when attempting to pop the last screen from the stack.\\\"\\\"\\\"\\n\\n\\nclass CssPathError(Exception):\\n \\\"\\\"\\\"Raised when supplied CSS path(s) are invalid.\\\"\\\"\\\"\\n\\n\\nReturnType = TypeVar(\\\"ReturnType\\\")\\n\\n\\nclass _NullFile:\\n \\\"\\\"\\\"A file-like where writes go nowhere.\\\"\\\"\\\"\\n\\n def write(self, text: str) -> None:\\n pass\\n\\n def flush(self) -> None:\\n pass\\n\\n\\nMAX_QUEUED_WRITES: Final[int] = 30\\n\\n\\nclass _WriterThread(threading.Thread):\\n \\\"\\\"\\\"A thread / file-like to do writes to stdout in the background.\\\"\\\"\\\"\\n\\n def __init__(self) -> None:\\n super().__init__(daemon=True)\\n self._queue: Queue[str | None] = Queue(MAX_QUEUED_WRITES)\\n self._file = sys.__stdout__\\n\\n def write(self, text: str) -> None:\\n \\\"\\\"\\\"Write text. Text will be enqueued for writing.\\n\\n Args:\\n text (str): Text to write to the file.\\n \\\"\\\"\\\"\\n self._queue.put(text)\\n\\n def isatty(self) -> bool:\\n \\\"\\\"\\\"Pretend to be a terminal.\\n\\n Returns:\\n bool: True if this is a tty.\\n \\\"\\\"\\\"\\n return True\\n\\n def fileno(self) -> int:\\n \\\"\\\"\\\"Get file handle number.\\n\\n Returns:\\n int: File number of proxied file.\\n \\\"\\\"\\\"\\n return self._file.fileno()\\n\\n def flush(self) -> None:\\n \\\"\\\"\\\"Flush the file (a no-op, because flush is done in the thread).\\\"\\\"\\\"\\n return\\n\\n def run(self) -> None:\\n \\\"\\\"\\\"Run the thread.\\\"\\\"\\\"\\n write = self._file.write\\n flush = self._file.flush\\n get = self._queue.get\\n qsize = self._queue.qsize\\n # Read from the queue, write to the file.\\n # Flush when there is a break.\\n while True:\\n text: str | None = get()\\n empty = qsize() == 0\\n if text is None:\\n break\\n write(text)\\n if empty:\\n flush()\\n\\n def stop(self) -> None:\\n \\\"\\\"\\\"Stop the thread, and block until it finished.\\\"\\\"\\\"\\n self._queue.put(None)\\n self.join()\\n\\n\\nCSSPathType = Union[str, PurePath, List[Union[str, PurePath]], None]\\n\\n\\n@rich.repr.auto\\nclass App(Generic[ReturnType], DOMNode):\\n \\\"\\\"\\\"The base class for Textual Applications.\\n Args:\\n driver_class (Type[Driver] | None, optional): Driver class or ``None`` to auto-detect. Defaults to None.\\n css_path (str | PurePath | list[str | PurePath] | None, optional): Path to CSS or ``None`` for no CSS file.\\n Defaults to None. To load multiple CSS files, pass a list of strings or paths which will be loaded in order.\\n watch_css (bool, optional): Watch CSS for changes. Defaults to False.\\n\\n Raises:\\n CssPathError: When the supplied CSS path(s) are an unexpected type.\\n \\\"\\\"\\\"\\n\\n CSS = \\\"\\\"\\n \\\"\\\"\\\"Inline CSS, useful for quick scripts. This is loaded after CSS_PATH,\\n and therefore takes priority in the event of a specificity clash.\\\"\\\"\\\"\\n\\n # Default (the lowest priority) CSS\\n DEFAULT_CSS = \\\"\\\"\\\"\\n App {\\n background: $background;\\n color: $text;\\n }\\n \\\"\\\"\\\"\\n\\n SCREENS: dict[str, Screen | Callable[[], Screen]] = {}\\n _BASE_PATH: str | None = None\\n CSS_PATH: CSSPathType = None\\n TITLE: str | None = None\\n SUB_TITLE: str | None = None\\n\\n BINDINGS = [\\n Binding(\\\"ctrl+c\\\", \\\"quit\\\", \\\"Quit\\\", show=False, priority=True),\\n Binding(\\\"tab\\\", \\\"focus_next\\\", \\\"Focus Next\\\", show=False),\\n Binding(\\\"shift+tab\\\", \\\"focus_previous\\\", \\\"Focus Previous\\\", show=False),\\n ]\\n\\n title: Reactive[str] = Reactive(\\\"\\\")\\n sub_title: Reactive[str] = Reactive(\\\"\\\")\\n dark: Reactive[bool] = Reactive(True)\\n\\n def __init__(\\n self,\\n driver_class: Type[Driver] | None = None,\\n css_path: CSSPathType = None,\\n watch_css: bool = False,\\n ):\\n # N.B. This must be done *before* we call the parent constructor, because MessagePump's\\n # constructor instantiates a `asyncio.PriorityQueue` and in Python versions older than 3.10\\n # this will create some first references to an asyncio loop.\\n _init_uvloop()\\n\\n super().__init__()\\n self.features: frozenset[FeatureFlag] = parse_features(os.getenv(\\\"TEXTUAL\\\", \\\"\\\"))\\n\\n self._filter: LineFilter | None = None\\n environ = dict(os.environ)\\n no_color = environ.pop(\\\"NO_COLOR\\\", None)\\n if no_color is not None:\\n self._filter = Monochrome()\\n\\n self._writer_thread: _WriterThread | None = None\\n if sys.__stdout__ is None:\\n file = _NullFile()\\n else:\\n self._writer_thread = _WriterThread()\\n self._writer_thread.start()\\n file = self._writer_thread\\n\\n self.console = Console(\\n file=file,\\n markup=False,\\n highlight=False,\\n emoji=False,\\n legacy_windows=False,\\n _environ=environ,\\n )\\n self.error_console = Console(markup=False, stderr=True)\\n self.driver_class = driver_class or self.get_driver_class()\\n self._screen_stack: list[Screen] = []\\n self._sync_available = False\\n\\n self.mouse_over: Widget | None = None\\n self.mouse_captured: Widget | None = None\\n self._driver: Driver | None = None\\n self._exit_renderables: list[RenderableType] = []\\n\\n self._action_targets = {\\\"app\\\", \\\"screen\\\"}\\n self._animator = Animator(self)\\n self._animate = self._animator.bind(self)\\n self.mouse_position = Offset(0, 0)\\n self.title = (\\n self.TITLE if self.TITLE is not None else f\\\"{self.__class__.__name__}\\\"\\n )\\n self.sub_title = self.SUB_TITLE if self.SUB_TITLE is not None else \\\"\\\"\\n\\n self._logger = Logger(self._log)\\n\\n self._refresh_required = False\\n\\n self.design = DEFAULT_COLORS\\n\\n self.stylesheet = Stylesheet(variables=self.get_css_variables())\\n self._require_stylesheet_update: set[DOMNode] = set()\\n\\n css_path = css_path or self.CSS_PATH\\n if css_path is not None:\\n # When value(s) are supplied for CSS_PATH, we normalise them to a list of Paths.\\n if isinstance(css_path, str):\\n css_paths = [Path(css_path)]\\n elif isinstance(css_path, PurePath):\\n css_paths = [css_path]\\n elif isinstance(css_path, list):\\n css_paths = []\\n for path in css_path:\\n css_paths.append(Path(path) if isinstance(path, str) else path)\\n else:\\n raise CssPathError(\\n \\\"Expected a str, Path or list[str | Path] for the CSS_PATH.\\\"\\n )\\n\\n # We want the CSS path to be resolved from the location of the App subclass\\n css_paths = [\\n _make_path_object_relative(css_path, self) for css_path in css_paths\\n ]\\n else:\\n css_paths = []\\n\\n self.css_path = css_paths\\n self._registry: WeakSet[DOMNode] = WeakSet()\\n\\n self._installed_screens: WeakValueDictionary[\\n str, Screen | Callable[[], Screen]\\n ] = WeakValueDictionary()\\n self._installed_screens.update(**self.SCREENS)\\n\\n self.devtools: DevtoolsClient | None = None\\n if \\\"devtools\\\" in self.features:\\n try:\\n from .devtools.client import DevtoolsClient\\n except ImportError:\\n # Dev dependencies not installed\\n pass\\n else:\\n self.devtools = DevtoolsClient()\\n\\n self._return_value: ReturnType | None = None\\n self._exit = False\\n\\n self.css_monitor = (\\n FileMonitor(self.css_path, self._on_css_change)\\n if ((watch_css or self.debug) and self.css_path)\\n else None\\n )\\n self._screenshot: str | None = None\\n self._dom_lock = asyncio.Lock()\\n self._dom_ready = False\\n self.set_class(self.dark, \\\"-dark-mode\\\")\\n\\n @property\\n def return_value(self) -> ReturnType | None:\\n \\\"\\\"\\\"ReturnType | None: The return type of the app.\\\"\\\"\\\"\\n return self._return_value\\n\\n def animate(\\n self,\\n attribute: str,\\n value: float | Animatable,\\n *,\\n final_value: object = ...,\\n duration: float | None = None,\\n speed: float | None = None,\\n delay: float = 0.0,\\n easing: EasingFunction | str = DEFAULT_EASING,\\n on_complete: CallbackType | None = None,\\n ) -> None:\\n \\\"\\\"\\\"Animate an attribute.\\n\\n Args:\\n attribute (str): Name of the attribute to animate.\\n value (float | Animatable): The value to animate to.\\n final_value (object, optional): The final value of the animation. Defaults to `value` if not set.\\n duration (float | None, optional): The duration of the animate. Defaults to None.\\n speed (float | None, optional): The speed of the animation. Defaults to None.\\n delay (float, optional): A delay (in seconds) before the animation starts. Defaults to 0.0.\\n easing (EasingFunction | str, optional): An easing method. Defaults to \\\"in_out_cubic\\\".\\n on_complete (CallbackType | None, optional): A callable to invoke when the animation is finished. Defaults to None.\\n\\n \\\"\\\"\\\"\\n self._animate(\\n attribute,\\n value,\\n final_value=final_value,\\n duration=duration,\\n speed=speed,\\n delay=delay,\\n easing=easing,\\n on_complete=on_complete,\\n )\\n\\n @property\\n def debug(self) -> bool:\\n \\\"\\\"\\\"bool: Is debug mode is enabled?\\\"\\\"\\\"\\n return \\\"debug\\\" in self.features\\n\\n @property\\n def is_headless(self) -> bool:\\n \\\"\\\"\\\"bool: Is the app running in 'headless' mode?\\\"\\\"\\\"\\n return False if self._driver is None else self._driver.is_headless\\n\\n @property\\n def screen_stack(self) -> list[Screen]:\\n \\\"\\\"\\\"list[Screen]: A *copy* of the screen stack.\\\"\\\"\\\"\\n return self._screen_stack.copy()\\n\\n def exit(\\n self, result: ReturnType | None = None, message: RenderableType | None = None\\n ) -> None:\\n \\\"\\\"\\\"Exit the app, and return the supplied result.\\n\\n Args:\\n result (ReturnType | None, optional): Return value. Defaults to None.\\n message (RenderableType | None): Optional message to display on exit.\\n \\\"\\\"\\\"\\n self._exit = True\\n self._return_value = result\\n self.post_message_no_wait(messages.ExitApp(sender=self))\\n if message:\\n self._exit_renderables.append(message)\\n\\n @property\\n def focused(self) -> Widget | None:\\n \\\"\\\"\\\"Widget | None: the widget that is focused on the currently active screen.\\\"\\\"\\\"\\n return self.screen.focused\\n\\n @property\\n def namespace_bindings(self) -> dict[str, tuple[DOMNode, Binding]]:\\n \\\"\\\"\\\"Get current bindings. If no widget is focused, then the app-level bindings\\n are returned. If a widget is focused, then any bindings present in the active\\n screen and app are merged and returned.\\\"\\\"\\\"\\n\\n namespace_binding_map: dict[str, tuple[DOMNode, Binding]] = {}\\n for namespace, bindings in reversed(self._binding_chain):\\n for key, binding in bindings.keys.items():\\n namespace_binding_map[key] = (namespace, binding)\\n\\n return namespace_binding_map\\n\\n def _set_active(self) -> None:\\n \\\"\\\"\\\"Set this app to be the currently active app.\\\"\\\"\\\"\\n active_app.set(self)\\n\\n def compose(self) -> ComposeResult:\\n \\\"\\\"\\\"Yield child widgets for a container.\\\"\\\"\\\"\\n yield from ()\\n\\n def get_css_variables(self) -> dict[str, str]:\\n \\\"\\\"\\\"Get a mapping of variables used to pre-populate CSS.\\n\\n Returns:\\n dict[str, str]: A mapping of variable name to value.\\n \\\"\\\"\\\"\\n variables = self.design[\\\"dark\\\" if self.dark else \\\"light\\\"].generate()\\n return variables\\n\\n def watch_dark(self, dark: bool) -> None:\\n \\\"\\\"\\\"Watches the dark bool.\\\"\\\"\\\"\\n self.set_class(dark, \\\"-dark-mode\\\")\\n self.set_class(not dark, \\\"-light-mode\\\")\\n try:\\n self.refresh_css()\\n except ScreenStackError:\\n # It's possible that `dark` can be set before we have a default\\n # screen, in an app's `on_load`, for example. So let's eat the\\n # ScreenStackError -- the above styles will be handled once the\\n # screen is spun up anyway.\\n pass\\n\\n def get_driver_class(self) -> Type[Driver]:\\n \\\"\\\"\\\"Get a driver class for this platform.\\n\\n Called by the constructor.\\n\\n Returns:\\n Driver: A Driver class which manages input and display.\\n \\\"\\\"\\\"\\n driver_class: Type[Driver]\\n if WINDOWS:\\n from .drivers.windows_driver import WindowsDriver\\n\\n driver_class = WindowsDriver\\n else:\\n from .drivers.linux_driver import LinuxDriver\\n\\n driver_class = LinuxDriver\\n return driver_class\\n\\n def __rich_repr__(self) -> rich.repr.Result:\\n yield \\\"title\\\", self.title\\n yield \\\"id\\\", self.id, None\\n if self.name:\\n yield \\\"name\\\", self.name\\n if self.classes:\\n yield \\\"classes\\\", set(self.classes)\\n pseudo_classes = self.pseudo_classes\\n if pseudo_classes:\\n yield \\\"pseudo_classes\\\", set(pseudo_classes)\\n\\n @property\\n def is_transparent(self) -> bool:\\n return True\\n\\n @property\\n def animator(self) -> Animator:\\n return self._animator\\n\\n @property\\n def screen(self) -> Screen:\\n \\\"\\\"\\\"Screen: The current screen.\\n\\n Raises:\\n ScreenStackError: If there are no screens on the stack.\\n \\\"\\\"\\\"\\n try:\\n return self._screen_stack[-1]\\n except IndexError:\\n raise ScreenStackError(\\\"No screens on stack\\\") from None\\n\\n @property\\n def size(self) -> Size:\\n \\\"\\\"\\\"Size: The size of the terminal.\\\"\\\"\\\"\\n if self._driver is not None and self._driver._size is not None:\\n width, height = self._driver._size\\n else:\\n width, height = self.console.size\\n return Size(width, height)\\n\\n @property\\n def log(self) -> Logger:\\n \\\"\\\"\\\"Logger: The logger object.\\\"\\\"\\\"\\n return self._logger\\n\\n def _log(\\n self,\\n group: LogGroup,\\n verbosity: LogVerbosity,\\n _textual_calling_frame: inspect.FrameInfo,\\n *objects: Any,\\n **kwargs,\\n ) -> None:\\n \\\"\\\"\\\"Write to logs or devtools.\\n\\n Positional args will logged. Keyword args will be prefixed with the key.\\n\\n Example:\\n ```python\\n data = [1,2,3]\\n self.log(\\\"Hello, World\\\", state=data)\\n self.log(self.tree)\\n self.log(locals())\\n ```\\n\\n Args:\\n verbosity (int, optional): Verbosity level 0-3. Defaults to 1.\\n \\\"\\\"\\\"\\n\\n devtools = self.devtools\\n if devtools is None or not devtools.is_connected:\\n return\\n\\n if verbosity.value > LogVerbosity.NORMAL.value and not devtools.verbose:\\n return\\n\\n try:\\n from .devtools.client import DevtoolsLog\\n\\n if len(objects) == 1 and not kwargs:\\n devtools.log(\\n DevtoolsLog(objects, caller=_textual_calling_frame),\\n group,\\n verbosity,\\n )\\n else:\\n output = \\\" \\\".join(str(arg) for arg in objects)\\n if kwargs:\\n key_values = \\\" \\\".join(\\n f\\\"{key}={value!r}\\\" for key, value in kwargs.items()\\n )\\n output = f\\\"{output} {key_values}\\\" if output else key_values\\n devtools.log(\\n DevtoolsLog(output, caller=_textual_calling_frame),\\n group,\\n verbosity,\\n )\\n except Exception as error:\\n self._handle_exception(error)\\n\\n def action_toggle_dark(self) -> None:\\n \\\"\\\"\\\"Action to toggle dark mode.\\\"\\\"\\\"\\n self.dark = not self.dark\\n\\n def action_screenshot(self, filename: str | None = None, path: str = \\\"./\\\") -> None:\\n \\\"\\\"\\\"Save an SVG \\\"screenshot\\\". This action will save an SVG file containing the current contents of the screen.\\n\\n Args:\\n filename (str | None, optional): Filename of screenshot, or None to auto-generate. Defaults to None.\\n path (str, optional): Path to directory. Defaults to current working directory.\\n \\\"\\\"\\\"\\n self.save_screenshot(filename, path)\\n\\n def export_screenshot(self, *, title: str | None = None) -> str:\\n \\\"\\\"\\\"Export an SVG screenshot of the current screen.\\n\\n Args:\\n title (str | None, optional): The title of the exported screenshot or None\\n to use app title. Defaults to None.\\n\\n \\\"\\\"\\\"\\n assert self._driver is not None, \\\"App must be running\\\"\\n width, height = self.size\\n console = Console(\\n width=width,\\n height=height,\\n file=io.StringIO(),\\n force_terminal=True,\\n color_system=\\\"truecolor\\\",\\n record=True,\\n legacy_windows=False,\\n )\\n screen_render = self.screen._compositor.render(full=True)\\n console.print(screen_render)\\n return console.export_svg(title=title or self.title)\\n\\n def save_screenshot(\\n self,\\n filename: str | None = None,\\n path: str = \\\"./\\\",\\n time_format: str = \\\"%Y%m%d %H%M%S %f\\\",\\n ) -> str:\\n \\\"\\\"\\\"Save an SVG screenshot of the current screen.\\n\\n Args:\\n filename (str | None, optional): Filename of SVG screenshot, or None to auto-generate\\n a filename with the date and time. Defaults to None.\\n path (str, optional): Path to directory for output. Defaults to current working directory.\\n time_format (str, optional): Time format to use if filename is None. Defaults to \\\"%Y-%m-%d %X %f\\\".\\n\\n Returns:\\n str: Filename of screenshot.\\n \\\"\\\"\\\"\\n if filename is None:\\n svg_filename = (\\n f\\\"{self.title.lower()} {datetime.now().strftime(time_format)}.svg\\\"\\n )\\n for reserved in '<>:\\\"/\\\\\\\\|?*':\\n svg_filename = svg_filename.replace(reserved, \\\"_\\\")\\n else:\\n svg_filename = filename\\n svg_path = os.path.expanduser(os.path.join(path, svg_filename))\\n screenshot_svg = self.export_screenshot()\\n with open(svg_path, \\\"w\\\", encoding=\\\"utf-8\\\") as svg_file:\\n svg_file.write(screenshot_svg)\\n return svg_path\\n\\n def bind(\\n self,\\n keys: str,\\n action: str,\\n *,\\n description: str = \\\"\\\",\\n show: bool = True,\\n key_display: str | None = None,\\n ) -> None:\\n \\\"\\\"\\\"Bind a key to an action.\\n\\n Args:\\n keys (str): A comma separated list of keys, i.e.\\n action (str): Action to bind to.\\n description (str, optional): Short description of action. Defaults to \\\"\\\".\\n show (bool, optional): Show key in UI. Defaults to True.\\n key_display (str, optional): Replacement text for key, or None to use default. Defaults to None.\\n \\\"\\\"\\\"\\n self._bindings.bind(\\n keys, action, description, show=show, key_display=key_display\\n )\\n\\n def get_key_display(self, key: str) -> str:\\n \\\"\\\"\\\"For a given key, return how it should be displayed in an app\\n (e.g. in the Footer widget).\\n By key, we refer to the string used in the \\\"key\\\" argument for\\n a Binding instance. By overriding this method, you can ensure that\\n keys are displayed consistently throughout your app, without\\n needing to add a key_display to every binding.\\n\\n Args:\\n key (str): The binding key string.\\n\\n Returns:\\n str: The display string for the input key.\\n \\\"\\\"\\\"\\n return _get_key_display(key)\\n\\n async def _press_keys(self, keys: Iterable[str]) -> None:\\n \\\"\\\"\\\"A task to send key events.\\\"\\\"\\\"\\n app = self\\n driver = app._driver\\n assert driver is not None\\n await asyncio.sleep(0.02)\\n for key in keys:\\n if key == \\\"_\\\":\\n print(\\\"(pause 50ms)\\\")\\n await asyncio.sleep(0.05)\\n elif key.startswith(\\\"wait:\\\"):\\n _, wait_ms = key.split(\\\":\\\")\\n print(f\\\"(pause {wait_ms}ms)\\\")\\n await asyncio.sleep(float(wait_ms) / 1000)\\n else:\\n if len(key) == 1 and not key.isalnum():\\n key = (\\n unicodedata.name(key)\\n .lower()\\n .replace(\\\"-\\\", \\\"_\\\")\\n .replace(\\\" \\\", \\\"_\\\")\\n )\\n original_key = REPLACED_KEYS.get(key, key)\\n char: str | None\\n try:\\n char = unicodedata.lookup(original_key.upper().replace(\\\"_\\\", \\\" \\\"))\\n except KeyError:\\n char = key if len(key) == 1 else None\\n print(f\\\"press {key!r} (char={char!r})\\\")\\n key_event = events.Key(app, key, char)\\n driver.send_event(key_event)\\n # TODO: A bit of a fudge - extra sleep after tabbing to help guard against race\\n # condition between widget-level key handling and app/screen level handling.\\n # More information here: https://github.com/Textualize/textual/issues/1009\\n # This conditional sleep can be removed after that issue is closed.\\n if key == \\\"tab\\\":\\n await asyncio.sleep(0.05)\\n await asyncio.sleep(0.025)\\n await app._animator.wait_for_idle()\\n\\n @asynccontextmanager\\n async def run_test(\\n self,\\n *,\\n headless: bool = True,\\n size: tuple[int, int] | None = (80, 24),\\n ):\\n \\\"\\\"\\\"An asynchronous context manager for testing app.\\n\\n Args:\\n headless (bool, optional): Run in headless mode (no output or input). Defaults to True.\\n size (tuple[int, int] | None, optional): Force terminal size to `(WIDTH, HEIGHT)`,\\n or None to auto-detect. Defaults to None.\\n\\n \\\"\\\"\\\"\\n from .pilot import Pilot\\n\\n app = self\\n app_ready_event = asyncio.Event()\\n\\n def on_app_ready() -> None:\\n \\\"\\\"\\\"Called when app is ready to process events.\\\"\\\"\\\"\\n app_ready_event.set()\\n\\n async def run_app(app) -> None:\\n await app._process_messages(\\n ready_callback=on_app_ready,\\n headless=headless,\\n terminal_size=size,\\n )\\n\\n # Launch the app in the \\\"background\\\"\\n app_task = asyncio.create_task(run_app(app))\\n\\n # Wait until the app has performed all startup routines.\\n await app_ready_event.wait()\\n\\n # Get the app in an active state.\\n app._set_active()\\n\\n # Context manager returns pilot object to manipulate the app\\n try:\\n yield Pilot(app)\\n finally:\\n # Shutdown the app cleanly\\n await app._shutdown()\\n await app_task\\n\\n async def run_async(\\n self,\\n *,\\n headless: bool = False,\\n size: tuple[int, int] | None = None,\\n auto_pilot: AutopilotCallbackType | None = None,\\n ) -> ReturnType | None:\\n \\\"\\\"\\\"Run the app asynchronously.\\n\\n Args:\\n headless (bool, optional): Run in headless mode (no output). Defaults to False.\\n size (tuple[int, int] | None, optional): Force terminal size to `(WIDTH, HEIGHT)`,\\n or None to auto-detect. Defaults to None.\\n auto_pilot (AutopilotCallbackType): An auto pilot coroutine.\\n\\n Returns:\\n ReturnType | None: App return value.\\n \\\"\\\"\\\"\\n from .pilot import Pilot\\n\\n app = self\\n\\n auto_pilot_task: Task | None = None\\n\\n async def app_ready() -> None:\\n \\\"\\\"\\\"Called by the message loop when the app is ready.\\\"\\\"\\\"\\n nonlocal auto_pilot_task\\n if auto_pilot is not None:\\n\\n async def run_auto_pilot(\\n auto_pilot: AutopilotCallbackType, pilot: Pilot\\n ) -> None:\\n try:\\n await auto_pilot(pilot)\\n except Exception:\\n app.exit()\\n raise\\n\\n pilot = Pilot(app)\\n auto_pilot_task = asyncio.create_task(run_auto_pilot(auto_pilot, pilot))\\n\\n try:\\n await app._process_messages(\\n ready_callback=None if auto_pilot is None else app_ready,\\n headless=headless,\\n terminal_size=size,\\n )\\n finally:\\n try:\\n if auto_pilot_task is not None:\\n await auto_pilot_task\\n finally:\\n await app._shutdown()\\n\\n return app.return_value\\n\\n def run(\\n self,\\n *,\\n headless: bool = False,\\n size: tuple[int, int] | None = None,\\n auto_pilot: AutopilotCallbackType | None = None,\\n ) -> ReturnType | None:\\n \\\"\\\"\\\"Run the app.\\n\\n Args:\\n headless (bool, optional): Run in headless mode (no output). Defaults to False.\\n size (tuple[int, int] | None, optional): Force terminal size to `(WIDTH, HEIGHT)`,\\n or None to auto-detect. Defaults to None.\\n auto_pilot (AutopilotCallbackType): An auto pilot coroutine.\\n\\n Returns:\\n ReturnType | None: App return value.\\n \\\"\\\"\\\"\\n\\n async def run_app() -> None:\\n \\\"\\\"\\\"Run the app.\\\"\\\"\\\"\\n await self.run_async(\\n headless=headless,\\n size=size,\\n auto_pilot=auto_pilot,\\n )\\n\\n if _ASYNCIO_GET_EVENT_LOOP_IS_DEPRECATED:\\n # N.B. This doesn't work with Python<3.10, as we end up with 2 event loops:\\n asyncio.run(run_app())\\n else:\\n # However, this works with Python<3.10:\\n event_loop = asyncio.get_event_loop()\\n event_loop.run_until_complete(run_app())\\n return self.return_value\\n\\n async def _on_css_change(self) -> None:\\n \\\"\\\"\\\"Called when the CSS changes (if watch_css is True).\\\"\\\"\\\"\\n css_paths = self.css_path\\n if css_paths:\\n try:\\n time = perf_counter()\\n stylesheet = self.stylesheet.copy()\\n stylesheet.read_all(css_paths)\\n stylesheet.parse()\\n elapsed = (perf_counter() - time) * 1000\\n self.log.system(\\n f\\\" loaded {len(css_paths)} CSS files in {elapsed:.0f} ms\\\"\\n )\\n except Exception as error:\\n # TODO: Catch specific exceptions\\n self.log.error(error)\\n self.bell()\\n else:\\n self.stylesheet = stylesheet\\n self.reset_styles()\\n self.stylesheet.update(self)\\n self.screen.refresh(layout=True)\\n\\n def render(self) -> RenderableType:\\n return Blank(self.styles.background)\\n\\n ExpectType = TypeVar(\\\"ExpectType\\\", bound=Widget)\\n\\n @overload\\n def get_child_by_id(self, id: str) -> Widget:\\n ...\\n\\n @overload\\n def get_child_by_id(self, id: str, expect_type: type[ExpectType]) -> ExpectType:\\n ...\\n\\n def get_child_by_id(\\n self, id: str, expect_type: type[ExpectType] | None = None\\n ) -> ExpectType | Widget:\\n \\\"\\\"\\\"Shorthand for self.screen.get_child(id: str)\\n Returns the first child (immediate descendent) of this DOMNode\\n with the given ID.\\n\\n Args:\\n id (str): The ID of the node to search for.\\n expect_type (type | None, optional): Require the object be of the supplied type, or None for any type.\\n Defaults to None.\\n\\n Returns:\\n ExpectType | Widget: The first child of this node with the specified ID.\\n\\n Raises:\\n NoMatches: if no children could be found for this ID\\n WrongType: if the wrong type was found.\\n \\\"\\\"\\\"\\n return (\\n self.screen.get_child_by_id(id)\\n if expect_type is None\\n else self.screen.get_child_by_id(id, expect_type)\\n )\\n\\n @overload\\n def get_widget_by_id(self, id: str) -> Widget:\\n ...\\n\\n @overload\\n def get_widget_by_id(self, id: str, expect_type: type[ExpectType]) -> ExpectType:\\n ...\\n\\n def get_widget_by_id(\\n self, id: str, expect_type: type[ExpectType] | None = None\\n ) -> ExpectType | Widget:\\n \\\"\\\"\\\"Shorthand for self.screen.get_widget_by_id(id)\\n Return the first descendant widget with the given ID.\\n\\n Performs a breadth-first search rooted at the current screen.\\n It will not return the Screen if that matches the ID.\\n To get the screen, use `self.screen`.\\n\\n Args:\\n id (str): The ID to search for in the subtree\\n expect_type (type | None, optional): Require the object be of the supplied type, or None for any type.\\n Defaults to None.\\n\\n Returns:\\n ExpectType | Widget: The first descendant encountered with this ID.\\n\\n Raises:\\n NoMatches: if no children could be found for this ID\\n WrongType: if the wrong type was found.\\n \\\"\\\"\\\"\\n return (\\n self.screen.get_widget_by_id(id)\\n if expect_type is None\\n else self.screen.get_widget_by_id(id, expect_type)\\n )\\n\\n def update_styles(self, node: DOMNode | None = None) -> None:\\n \\\"\\\"\\\"Request update of styles.\\n\\n Should be called whenever CSS classes / pseudo classes change.\\n\\n \\\"\\\"\\\"\\n self._require_stylesheet_update.add(self.screen if node is None else node)\\n self.check_idle()\\n\\n def mount(\\n self,\\n *widgets: Widget,\\n before: int | str | Widget | None = None,\\n after: int | str | Widget | None = None,\\n ) -> AwaitMount:\\n \\\"\\\"\\\"Mount the given widgets relative to the app's screen.\\n\\n Args:\\n *widgets (Widget): The widget(s) to mount.\\n before (int | str | Widget, optional): Optional location to mount before.\\n after (int | str | Widget, optional): Optional location to mount after.\\n\\n Returns:\\n AwaitMount: An awaitable object that waits for widgets to be mounted.\\n\\n Raises:\\n MountError: If there is a problem with the mount request.\\n\\n Note:\\n Only one of ``before`` or ``after`` can be provided. If both are\\n provided a ``MountError`` will be raised.\\n \\\"\\\"\\\"\\n return self.screen.mount(*widgets, before=before, after=after)\\n\\n def mount_all(\\n self,\\n widgets: Iterable[Widget],\\n before: int | str | Widget | None = None,\\n after: int | str | Widget | None = None,\\n ) -> AwaitMount:\\n \\\"\\\"\\\"Mount widgets from an iterable.\\n\\n Args:\\n widgets (Iterable[Widget]): An iterable of widgets.\\n before (int | str | Widget, optional): Optional location to mount before.\\n after (int | str | Widget, optional): Optional location to mount after.\\n\\n Returns:\\n AwaitMount: An awaitable object that waits for widgets to be mounted.\\n\\n Raises:\\n MountError: If there is a problem with the mount request.\\n\\n Note:\\n Only one of ``before`` or ``after`` can be provided. If both are\\n provided a ``MountError`` will be raised.\\n \\\"\\\"\\\"\\n return self.mount(*widgets, before=before, after=after)\\n\\n def is_screen_installed(self, screen: Screen | str) -> bool:\\n \\\"\\\"\\\"Check if a given screen has been installed.\\n\\n Args:\\n screen (Screen | str): Either a Screen object or screen name (the `name` argument when installed).\\n\\n Returns:\\n bool: True if the screen is currently installed,\\n \\\"\\\"\\\"\\n if isinstance(screen, str):\\n return screen in self._installed_screens\\n else:\\n return screen in self._installed_screens.values()\\n\\n def get_screen(self, screen: Screen | str) -> Screen:\\n \\\"\\\"\\\"Get an installed screen.\\n\\n Args:\\n screen (Screen | str): Either a Screen object or screen name (the `name` argument when installed).\\n\\n Raises:\\n KeyError: If the named screen doesn't exist.\\n\\n Returns:\\n Screen: A screen instance.\\n \\\"\\\"\\\"\\n if isinstance(screen, str):\\n try:\\n next_screen = self._installed_screens[screen]\\n except KeyError:\\n raise KeyError(f\\\"No screen called {screen!r} installed\\\") from None\\n if callable(next_screen):\\n next_screen = next_screen()\\n self._installed_screens[screen] = next_screen\\n else:\\n next_screen = screen\\n return next_screen\\n\\n def _get_screen(self, screen: Screen | str) -> tuple[Screen, AwaitMount]:\\n \\\"\\\"\\\"Get an installed screen and an AwaitMount object.\\n\\n If the screen isn't running, it will be registered before it is run.\\n\\n Args:\\n screen (Screen | str): Either a Screen object or screen name (the `name` argument when installed).\\n\\n Raises:\\n KeyError: If the named screen doesn't exist.\\n\\n Returns:\\n tuple[Screen, AwaitMount]: A screen instance and an awaitable that awaits the children mounting.\\n\\n \\\"\\\"\\\"\\n _screen = self.get_screen(screen)\\n if not _screen.is_running:\\n widgets = self._register(self, _screen)\\n return (_screen, AwaitMount(_screen, widgets))\\n else:\\n return (_screen, AwaitMount(_screen, []))\\n\\n def _replace_screen(self, screen: Screen) -> Screen:\\n \\\"\\\"\\\"Handle the replaced screen.\\n\\n Args:\\n screen (Screen): A screen object.\\n\\n Returns:\\n Screen: The screen that was replaced.\\n\\n \\\"\\\"\\\"\\n screen.post_message_no_wait(events.ScreenSuspend(self))\\n self.log.system(f\\\"{screen} SUSPENDED\\\")\\n if not self.is_screen_installed(screen) and screen not in self._screen_stack:\\n screen.remove()\\n self.log.system(f\\\"{screen} REMOVED\\\")\\n return screen\\n\\n def push_screen(self, screen: Screen | str) -> AwaitMount:\\n \\\"\\\"\\\"Push a new screen on the screen stack.\\n\\n Args:\\n screen (Screen | str): A Screen instance or the name of an installed screen.\\n\\n \\\"\\\"\\\"\\n next_screen, await_mount = self._get_screen(screen)\\n self._screen_stack.append(next_screen)\\n self.screen.post_message_no_wait(events.ScreenResume(self))\\n self.log.system(f\\\"{self.screen} is current (PUSHED)\\\")\\n return await_mount\\n\\n def switch_screen(self, screen: Screen | str) -> AwaitMount:\\n \\\"\\\"\\\"Switch to another screen by replacing the top of the screen stack with a new screen.\\n\\n Args:\\n screen (Screen | str): Either a Screen object or screen name (the `name` argument when installed).\\n\\n \\\"\\\"\\\"\\n if self.screen is not screen:\\n self._replace_screen(self._screen_stack.pop())\\n next_screen, await_mount = self._get_screen(screen)\\n self._screen_stack.append(next_screen)\\n self.screen.post_message_no_wait(events.ScreenResume(self))\\n self.log.system(f\\\"{self.screen} is current (SWITCHED)\\\")\\n return await_mount\\n return AwaitMount(self.screen, [])\\n\\n def install_screen(self, screen: Screen, name: str | None = None) -> AwaitMount:\\n \\\"\\\"\\\"Install a screen.\\n\\n Args:\\n screen (Screen): Screen to install.\\n name (str | None, optional): Unique name of screen or None to auto-generate.\\n Defaults to None.\\n\\n Raises:\\n ScreenError: If the screen can't be installed.\\n\\n Returns:\\n AwaitMount: An awaitable that awaits the mounting of the screen and its children.\\n \\\"\\\"\\\"\\n if name is None:\\n name = nanoid.generate()\\n if name in self._installed_screens:\\n raise ScreenError(f\\\"Can't install screen; {name!r} is already installed\\\")\\n if screen in self._installed_screens.values():\\n raise ScreenError(\\n \\\"Can't install screen; {screen!r} has already been installed\\\"\\n )\\n self._installed_screens[name] = screen\\n _screen, await_mount = self._get_screen(name) # Ensures screen is running\\n self.log.system(f\\\"{screen} INSTALLED name={name!r}\\\")\\n return await_mount\\n\\n def uninstall_screen(self, screen: Screen | str) -> str | None:\\n \\\"\\\"\\\"Uninstall a screen. If the screen was not previously installed then this\\n method is a null-op.\\n\\n Args:\\n screen (Screen | str): The screen to uninstall or the name of a installed screen.\\n\\n Returns:\\n str | None: The name of the screen that was uninstalled, or None if no screen was uninstalled.\\n \\\"\\\"\\\"\\n if isinstance(screen, str):\\n if screen not in self._installed_screens:\\n return None\\n uninstall_screen = self._installed_screens[screen]\\n if uninstall_screen in self._screen_stack:\\n raise ScreenStackError(\\\"Can't uninstall screen in screen stack\\\")\\n del self._installed_screens[screen]\\n self.log.system(f\\\"{uninstall_screen} UNINSTALLED name={screen!r}\\\")\\n return screen\\n else:\\n if screen in self._screen_stack:\\n raise ScreenStackError(\\\"Can't uninstall screen in screen stack\\\")\\n for name, installed_screen in self._installed_screens.items():\\n if installed_screen is screen:\\n self._installed_screens.pop(name)\\n self.log.system(f\\\"{screen} UNINSTALLED name={name!r}\\\")\\n return name\\n return None\\n\\n def pop_screen(self) -> Screen:\\n \\\"\\\"\\\"Pop the current screen from the stack, and switch to the previous screen.\\n\\n Returns:\\n Screen: The screen that was replaced.\\n \\\"\\\"\\\"\\n screen_stack = self._screen_stack\\n if len(screen_stack) <= 1:\\n raise ScreenStackError(\\n \\\"Can't pop screen; there must be at least one screen on the stack\\\"\\n )\\n previous_screen = self._replace_screen(screen_stack.pop())\\n self.screen._screen_resized(self.size)\\n self.screen.post_message_no_wait(events.ScreenResume(self))\\n self.log.system(f\\\"{self.screen} is active\\\")\\n return previous_screen\\n\\n def set_focus(self, widget: Widget | None, scroll_visible: bool = True) -> None:\\n \\\"\\\"\\\"Focus (or unfocus) a widget. A focused widget will receive key events first.\\n\\n Args:\\n widget (Widget): Widget to focus.\\n scroll_visible (bool, optional): Scroll widget in to view.\\n \\\"\\\"\\\"\\n self.screen.set_focus(widget, scroll_visible)\\n\\n async def _set_mouse_over(self, widget: Widget | None) -> None:\\n \\\"\\\"\\\"Called when the mouse is over another widget.\\n\\n Args:\\n widget (Widget | None): Widget under mouse, or None for no widgets.\\n \\\"\\\"\\\"\\n if widget is None:\\n if self.mouse_over is not None:\\n try:\\n await self.mouse_over.post_message(events.Leave(self))\\n finally:\\n self.mouse_over = None\\n else:\\n if self.mouse_over is not widget:\\n try:\\n if self.mouse_over is not None:\\n await self.mouse_over._forward_event(events.Leave(self))\\n if widget is not None:\\n await widget._forward_event(events.Enter(self))\\n finally:\\n self.mouse_over = widget\\n\\n def capture_mouse(self, widget: Widget | None) -> None:\\n \\\"\\\"\\\"Send all mouse events to the given widget, disable mouse capture.\\n\\n Args:\\n widget (Widget | None): If a widget, capture mouse event, or None to end mouse capture.\\n \\\"\\\"\\\"\\n if widget == self.mouse_captured:\\n return\\n if self.mouse_captured is not None:\\n self.mouse_captured.post_message_no_wait(\\n events.MouseRelease(self, self.mouse_position)\\n )\\n self.mouse_captured = widget\\n if widget is not None:\\n widget.post_message_no_wait(events.MouseCapture(self, self.mouse_position))\\n\\n def panic(self, *renderables: RenderableType) -> None:\\n \\\"\\\"\\\"Exits the app then displays a message.\\n\\n Args:\\n *renderables (RenderableType, optional): Rich renderables to display on exit.\\n \\\"\\\"\\\"\\n\\n assert all(\\n is_renderable(renderable) for renderable in renderables\\n ), \\\"Can only call panic with strings or Rich renderables\\\"\\n\\n def render(renderable: RenderableType) -> list[Segment]:\\n \\\"\\\"\\\"Render a panic renderables.\\\"\\\"\\\"\\n segments = list(self.console.render(renderable, self.console.options))\\n return segments\\n\\n pre_rendered = [Segments(render(renderable)) for renderable in renderables]\\n self._exit_renderables.extend(pre_rendered)\\n self._close_messages_no_wait()\\n\\n def _handle_exception(self, error: Exception) -> None:\\n \\\"\\\"\\\"Called with an unhandled exception.\\n\\n Args:\\n error (Exception): An exception instance.\\n \\\"\\\"\\\"\\n\\n if hasattr(error, \\\"__rich__\\\"):\\n # Exception has a rich method, so we can defer to that for the rendering\\n self.panic(error)\\n else:\\n # Use default exception rendering\\n self.fatal_error()\\n\\n def fatal_error(self) -> None:\\n \\\"\\\"\\\"Exits the app after an unhandled exception.\\\"\\\"\\\"\\n self.bell()\\n traceback = Traceback(\\n show_locals=True, width=None, locals_max_length=5, suppress=[rich]\\n )\\n self._exit_renderables.append(\\n Segments(self.console.render(traceback, self.console.options))\\n )\\n self._close_messages_no_wait()\\n\\n def _print_error_renderables(self) -> None:\\n for renderable in self._exit_renderables:\\n self.error_console.print(renderable)\\n self._exit_renderables.clear()\\n\\n async def _process_messages(\\n self,\\n ready_callback: CallbackType | None = None,\\n headless: bool = False,\\n terminal_size: tuple[int, int] | None = None,\\n ) -> None:\\n self._set_active()\\n\\n if self.devtools is not None:\\n from .devtools.client import DevtoolsConnectionError\\n\\n try:\\n await self.devtools.connect()\\n self.log.system(f\\\"Connected to devtools ( {self.devtools.url} )\\\")\\n except DevtoolsConnectionError:\\n self.log.system(f\\\"Couldn't connect to devtools ( {self.devtools.url} )\\\")\\n\\n self.log.system(\\\"---\\\")\\n\\n self.log.system(driver=self.driver_class)\\n self.log.system(loop=asyncio.get_running_loop())\\n self.log.system(features=self.features)\\n\\n try:\\n if self.css_path:\\n self.stylesheet.read_all(self.css_path)\\n for path, css, tie_breaker in self.get_default_css():\\n self.stylesheet.add_source(\\n css, path=path, is_default_css=True, tie_breaker=tie_breaker\\n )\\n if self.CSS:\\n try:\\n app_css_path = (\\n f\\\"{inspect.getfile(self.__class__)}:{self.__class__.__name__}\\\"\\n )\\n except TypeError:\\n app_css_path = f\\\"{self.__class__.__name__}\\\"\\n self.stylesheet.add_source(\\n self.CSS, path=app_css_path, is_default_css=False\\n )\\n except Exception as error:\\n self._handle_exception(error)\\n self._print_error_renderables()\\n return\\n\\n if self.css_monitor:\\n self.set_interval(0.25, self.css_monitor, name=\\\"css monitor\\\")\\n self.log.system(\\\"[b green]STARTED[/]\\\", self.css_monitor)\\n\\n async def run_process_messages():\\n \\\"\\\"\\\"The main message loop, invoke below.\\\"\\\"\\\"\\n\\n async def invoke_ready_callback() -> None:\\n if ready_callback is not None:\\n ready_result = ready_callback()\\n if inspect.isawaitable(ready_result):\\n await ready_result\\n\\n try:\\n try:\\n await self._dispatch_message(events.Compose(sender=self))\\n await self._dispatch_message(events.Mount(sender=self))\\n finally:\\n self._mounted_event.set()\\n\\n Reactive._initialize_object(self)\\n\\n self.stylesheet.update(self)\\n self.refresh()\\n\\n await self.animator.start()\\n\\n except Exception:\\n await self.animator.stop()\\n raise\\n\\n finally:\\n self._running = True\\n await self._ready()\\n await invoke_ready_callback()\\n\\n try:\\n await self._process_messages_loop()\\n except asyncio.CancelledError:\\n pass\\n finally:\\n self._running = False\\n try:\\n await self.animator.stop()\\n finally:\\n for timer in list(self._timers):\\n await timer.stop()\\n\\n self._running = True\\n try:\\n load_event = events.Load(sender=self)\\n await self._dispatch_message(load_event)\\n\\n driver: Driver\\n driver_class = cast(\\n \\\"type[Driver]\\\",\\n HeadlessDriver if headless else self.driver_class,\\n )\\n driver = self._driver = driver_class(self.console, self, size=terminal_size)\\n\\n if not self._exit:\\n driver.start_application_mode()\\n try:\\n if headless:\\n await run_process_messages()\\n else:\\n if self.devtools is not None:\\n devtools = self.devtools\\n assert devtools is not None\\n from .devtools.redirect_output import StdoutRedirector\\n\\n redirector = StdoutRedirector(devtools)\\n with redirect_stderr(redirector):\\n with redirect_stdout(redirector): # type: ignore\\n await run_process_messages()\\n else:\\n null_file = _NullFile()\\n with redirect_stderr(null_file):\\n with redirect_stdout(null_file):\\n await run_process_messages()\\n\\n finally:\\n driver.stop_application_mode()\\n except Exception as error:\\n self._handle_exception(error)\\n\\n async def _pre_process(self) -> None:\\n pass\\n\\n async def _ready(self) -> None:\\n \\\"\\\"\\\"Called immediately prior to processing messages.\\n\\n May be used as a hook for any operations that should run first.\\n\\n \\\"\\\"\\\"\\n try:\\n screenshot_timer = float(os.environ.get(\\\"TEXTUAL_SCREENSHOT\\\", \\\"0\\\"))\\n except ValueError:\\n return\\n\\n screenshot_title = os.environ.get(\\\"TEXTUAL_SCREENSHOT_TITLE\\\")\\n\\n if not screenshot_timer:\\n return\\n\\n async def on_screenshot():\\n \\\"\\\"\\\"Used by docs plugin.\\\"\\\"\\\"\\n svg = self.export_screenshot(title=screenshot_title)\\n self._screenshot = svg # type: ignore\\n self.exit()\\n\\n self.set_timer(screenshot_timer, on_screenshot, name=\\\"screenshot timer\\\")\\n\\n async def _on_compose(self) -> None:\\n try:\\n widgets = list(self.compose())\\n except TypeError as error:\\n raise TypeError(\\n f\\\"{self!r} compose() returned an invalid response; {error}\\\"\\n ) from None\\n await self.mount_all(widgets)\\n\\n def _on_idle(self) -> None:\\n \\\"\\\"\\\"Perform actions when there are no messages in the queue.\\\"\\\"\\\"\\n if self._require_stylesheet_update:\\n nodes: set[DOMNode] = {\\n child\\n for node in self._require_stylesheet_update\\n for child in node.walk_children(with_self=True)\\n }\\n self._require_stylesheet_update.clear()\\n self.stylesheet.update_nodes(nodes, animate=True)\\n\\n def _register_child(\\n self, parent: DOMNode, child: Widget, before: int | None, after: int | None\\n ) -> None:\\n \\\"\\\"\\\"Register a widget as a child of another.\\n\\n Args:\\n parent (DOMNode): Parent node.\\n child (Widget): The child widget to register.\\n widgets: The widget to register.\\n before (int, optional): A location to mount before.\\n after (int, option): A location to mount after.\\n \\\"\\\"\\\"\\n\\n # Let's be 100% sure that we've not been asked to do a before and an\\n # after at the same time. It's possible that we can remove this\\n # check later on, but for the purposes of development right now,\\n # it's likely a good idea to keep it here to check assumptions in\\n # the rest of the code.\\n if before is not None and after is not None:\\n raise AppError(\\\"Only one of 'before' and 'after' may be specified.\\\")\\n\\n # If we don't already know about this widget...\\n if child not in self._registry:\\n # Now to figure out where to place it. If we've got a `before`...\\n if before is not None:\\n # ...it's safe to NodeList._insert before that location.\\n parent.children._insert(before, child)\\n elif after is not None and after != -1:\\n # In this case we've got an after. -1 holds the special\\n # position (for now) of meaning \\\"okay really what I mean is\\n # do an append, like if I'd asked to add with no before or\\n # after\\\". So... we insert before the next item in the node\\n # list, iff after isn't -1.\\n parent.children._insert(after + 1, child)\\n else:\\n # At this point we appear to not be adding before or after,\\n # or we've got a before/after value that really means\\n # \\\"please append\\\". So...\\n parent.children._append(child)\\n\\n # Now that the widget is in the NodeList of its parent, sort out\\n # the rest of the admin.\\n self._registry.add(child)\\n child._attach(parent)\\n child._post_register(self)\\n child._start_messages()\\n\\n def _register(\\n self,\\n parent: DOMNode,\\n *widgets: Widget,\\n before: int | None = None,\\n after: int | None = None,\\n ) -> list[Widget]:\\n \\\"\\\"\\\"Register widget(s) so they may receive events.\\n\\n Args:\\n parent (DOMNode): Parent node.\\n *widgets: The widget(s) to register.\\n before (int, optional): A location to mount before.\\n after (int, option): A location to mount after.\\n Returns:\\n list[Widget]: List of modified widgets.\\n\\n \\\"\\\"\\\"\\n\\n if not widgets:\\n return []\\n\\n new_widgets = list(widgets)\\n if before is not None or after is not None:\\n # There's a before or after, which means there's going to be an\\n # insertion, so make it easier to get the new things in the\\n # correct order.\\n new_widgets = reversed(new_widgets)\\n\\n apply_stylesheet = self.stylesheet.apply\\n for widget in new_widgets:\\n if not isinstance(widget, Widget):\\n raise AppError(f\\\"Can't register {widget!r}; expected a Widget instance\\\")\\n if widget not in self._registry:\\n self._register_child(parent, widget, before, after)\\n if widget.children:\\n self._register(widget, *widget.children)\\n apply_stylesheet(widget)\\n return list(widgets)\\n\\n def _unregister(self, widget: Widget) -> None:\\n \\\"\\\"\\\"Unregister a widget.\\n\\n Args:\\n widget (Widget): A Widget to unregister\\n \\\"\\\"\\\"\\n widget.reset_focus()\\n if isinstance(widget._parent, Widget):\\n widget._parent.children._remove(widget)\\n widget._detach()\\n self._registry.discard(widget)\\n\\n async def _disconnect_devtools(self):\\n if self.devtools is not None:\\n await self.devtools.disconnect()\\n\\n def _start_widget(self, parent: Widget, widget: Widget) -> None:\\n \\\"\\\"\\\"Start a widget (run it's task) so that it can receive messages.\\n\\n Args:\\n parent (Widget): The parent of the Widget.\\n widget (Widget): The Widget to start.\\n \\\"\\\"\\\"\\n\\n widget._attach(parent)\\n widget._start_messages()\\n self.app._registry.add(widget)\\n\\n def is_mounted(self, widget: Widget) -> bool:\\n \\\"\\\"\\\"Check if a widget is mounted.\\n\\n Args:\\n widget (Widget): A widget.\\n\\n Returns:\\n bool: True of the widget is mounted.\\n \\\"\\\"\\\"\\n return widget in self._registry\\n\\n async def _close_all(self) -> None:\\n \\\"\\\"\\\"Close all message pumps.\\\"\\\"\\\"\\n\\n # Close all screens on the stack\\n for screen in self._screen_stack:\\n if screen._running:\\n await self._prune_node(screen)\\n\\n self._screen_stack.clear()\\n\\n # Close pre-defined screens\\n for screen in self.SCREENS.values():\\n if isinstance(screen, Screen) and screen._running:\\n await self._prune_node(screen)\\n\\n # Close any remaining nodes\\n # Should be empty by now\\n remaining_nodes = list(self._registry)\\n for child in remaining_nodes:\\n await child._close_messages()\\n\\n async def _shutdown(self) -> None:\\n driver = self._driver\\n self._running = False\\n if driver is not None:\\n driver.disable_input()\\n await self._close_all()\\n await self._close_messages()\\n\\n await self._dispatch_message(events.Unmount(sender=self))\\n\\n self._print_error_renderables()\\n if self.devtools is not None and self.devtools.is_connected:\\n await self._disconnect_devtools()\\n\\n if self._writer_thread is not None:\\n self._writer_thread.stop()\\n\\n async def _on_exit_app(self) -> None:\\n await self._message_queue.put(None)\\n\\n def refresh(self, *, repaint: bool = True, layout: bool = False) -> None:\\n if self._screen_stack:\\n self.screen.refresh(repaint=repaint, layout=layout)\\n self.check_idle()\\n\\n def refresh_css(self, animate: bool = True) -> None:\\n \\\"\\\"\\\"Refresh CSS.\\n\\n Args:\\n animate (bool, optional): Also execute CSS animations. Defaults to True.\\n \\\"\\\"\\\"\\n stylesheet = self.app.stylesheet\\n stylesheet.set_variables(self.get_css_variables())\\n stylesheet.reparse()\\n stylesheet.update(self.app, animate=animate)\\n self.screen._refresh_layout(self.size, full=True)\\n\\n def _display(self, screen: Screen, renderable: RenderableType | None) -> None:\\n \\\"\\\"\\\"Display a renderable within a sync.\\n\\n Args:\\n screen (Screen): Screen instance\\n renderable (RenderableType): A Rich renderable.\\n \\\"\\\"\\\"\\n\\n try:\\n if screen is not self.screen or renderable is None:\\n return\\n\\n if self._running and not self._closed and not self.is_headless:\\n console = self.console\\n self._begin_update()\\n try:\\n try:\\n console.print(renderable)\\n except Exception as error:\\n self._handle_exception(error)\\n finally:\\n self._end_update()\\n console.file.flush()\\n finally:\\n self.post_display_hook()\\n\\n def post_display_hook(self) -> None:\\n \\\"\\\"\\\"Called immediately after a display is done. Used in tests.\\\"\\\"\\\"\\n\\n def get_widget_at(self, x: int, y: int) -> tuple[Widget, Region]:\\n \\\"\\\"\\\"Get the widget under the given coordinates.\\n\\n Args:\\n x (int): X Coord.\\n y (int): Y Coord.\\n\\n Returns:\\n tuple[Widget, Region]: The widget and the widget's screen region.\\n \\\"\\\"\\\"\\n return self.screen.get_widget_at(x, y)\\n\\n def bell(self) -> None:\\n \\\"\\\"\\\"Play the console 'bell'.\\\"\\\"\\\"\\n if not self.is_headless:\\n self.console.bell()\\n\\n @property\\n def _binding_chain(self) -> list[tuple[DOMNode, Bindings]]:\\n \\\"\\\"\\\"Get a chain of nodes and bindings to consider. If no widget is focused, returns the bindings from both the screen and the app level bindings. Otherwise, combines all the bindings from the currently focused node up the DOM to the root App.\\n\\n Returns:\\n list[tuple[DOMNode, Bindings]]: List of DOM nodes and their bindings.\\n \\\"\\\"\\\"\\n focused = self.focused\\n namespace_bindings: list[tuple[DOMNode, Bindings]]\\n if focused is None:\\n namespace_bindings = [\\n (self.screen, self.screen._bindings),\\n (self, self._bindings),\\n ]\\n else:\\n namespace_bindings = [\\n (node, node._bindings) for node in focused.ancestors_with_self\\n ]\\n return namespace_bindings\\n\\n async def check_bindings(self, key: str, priority: bool = False) -> bool:\\n \\\"\\\"\\\"Handle a key press.\\n\\n Args:\\n key (str): A key.\\n priority (bool): If `True` check from `App` down, otherwise from focused up.\\n\\n Returns:\\n bool: True if the key was handled by a binding, otherwise False\\n \\\"\\\"\\\"\\n for namespace, bindings in (\\n reversed(self._binding_chain) if priority else self._binding_chain\\n ):\\n binding = bindings.keys.get(key)\\n if binding is not None and binding.priority == priority:\\n if await self.action(binding.action, namespace):\\n return True\\n return False\\n\\n async def on_event(self, event: events.Event) -> None:\\n # Handle input events that haven't been forwarded\\n # If the event has been forwarded it may have bubbled up back to the App\\n if isinstance(event, events.Compose):\\n screen = Screen(id=\\\"_default\\\")\\n self._register(self, screen)\\n self._screen_stack.append(screen)\\n await super().on_event(event)\\n\\n elif isinstance(event, events.InputEvent) and not event.is_forwarded:\\n if isinstance(event, events.MouseEvent):\\n # Record current mouse position on App\\n self.mouse_position = Offset(event.x, event.y)\\n await self.screen._forward_event(event)\\n elif isinstance(event, events.Key):\\n if not await self.check_bindings(event.key, priority=True):\\n forward_target = self.focused or self.screen\\n await forward_target._forward_event(event)\\n else:\\n await self.screen._forward_event(event)\\n\\n elif isinstance(event, events.Paste):\\n if self.focused is not None:\\n await self.focused._forward_event(event)\\n else:\\n await super().on_event(event)\\n\\n async def action(\\n self,\\n action: str | tuple[str, tuple[str, ...]],\\n default_namespace: object | None = None,\\n ) -> bool:\\n \\\"\\\"\\\"Perform an action.\\n\\n Args:\\n action (str): Action encoded in a string.\\n default_namespace (object | None): Namespace to use if not provided in the action,\\n or None to use app. Defaults to None.\\n\\n Returns:\\n bool: True if the event has handled.\\n \\\"\\\"\\\"\\n print(\\\"ACTION\\\", action, default_namespace)\\n if isinstance(action, str):\\n target, params = actions.parse(action)\\n else:\\n target, params = action\\n implicit_destination = True\\n if \\\".\\\" in target:\\n destination, action_name = target.split(\\\".\\\", 1)\\n if destination not in self._action_targets:\\n raise ActionError(f\\\"Action namespace {destination} is not known\\\")\\n action_target = getattr(self, destination)\\n implicit_destination = True\\n else:\\n action_target = default_namespace or self\\n action_name = target\\n\\n handled = await self._dispatch_action(action_target, action_name, params)\\n if not handled and implicit_destination and not isinstance(action_target, App):\\n handled = await self.app._dispatch_action(self.app, action_name, params)\\n return handled\\n\\n async def _dispatch_action(\\n self, namespace: object, action_name: str, params: Any\\n ) -> bool:\\n \\\"\\\"\\\"Dispatch an action to an action method.\\n\\n Args:\\n namespace (object): Namespace (object) of action.\\n action_name (str): Name of the action.\\n params (Any): Action parameters.\\n\\n Returns:\\n bool: True if handled, otherwise False.\\n \\\"\\\"\\\"\\n _rich_traceback_guard = True\\n\\n log(\\n \\\"\\\",\\n namespace=namespace,\\n action_name=action_name,\\n params=params,\\n )\\n\\n try:\\n private_method = getattr(namespace, f\\\"_action_{action_name}\\\", None)\\n if callable(private_method):\\n await invoke(private_method, *params)\\n return True\\n public_method = getattr(namespace, f\\\"action_{action_name}\\\", None)\\n if callable(public_method):\\n await invoke(public_method, *params)\\n return True\\n log(\\n f\\\" {action_name!r} has no target.\\\"\\n f\\\" Could not find methods '_action_{action_name}' or 'action_{action_name}'\\\"\\n )\\n except SkipAction:\\n # The action method raised this to explicitly not handle the action\\n log(\\\" {action_name!r} skipped.\\\")\\n return False\\n\\n async def _broker_event(\\n self, event_name: str, event: events.Event, default_namespace: object | None\\n ) -> bool:\\n \\\"\\\"\\\"Allow the app an opportunity to dispatch events to action system.\\n\\n Args:\\n event_name (str): _description_\\n event (events.Event): An event object.\\n default_namespace (object | None): The default namespace, where one isn't supplied.\\n\\n Returns:\\n bool: True if an action was processed.\\n \\\"\\\"\\\"\\n try:\\n style = getattr(event, \\\"style\\\")\\n except AttributeError:\\n return False\\n try:\\n _modifiers, action = extract_handler_actions(event_name, style.meta)\\n except NoHandler:\\n return False\\n else:\\n event.stop()\\n if isinstance(action, (str, tuple)):\\n await self.action(action, default_namespace=default_namespace)\\n elif callable(action):\\n await action()\\n else:\\n return False\\n return True\\n\\n async def _on_update(self, message: messages.Update) -> None:\\n message.stop()\\n\\n async def _on_layout(self, message: messages.Layout) -> None:\\n message.stop()\\n\\n async def _on_key(self, event: events.Key) -> None:\\n if not (await self.check_bindings(event.key)):\\n await self.dispatch_key(event)\\n\\n async def _on_shutdown_request(self, event: events.ShutdownRequest) -> None:\\n log(\\\"shutdown request\\\")\\n await self._close_messages()\\n\\n async def _on_resize(self, event: events.Resize) -> None:\\n event.stop()\\n await self.screen.post_message(event)\\n\\n def _detach_from_dom(self, widgets: list[Widget]) -> list[Widget]:\\n \\\"\\\"\\\"Detach a list of widgets from the DOM.\\n\\n Args:\\n widgets (list[Widget]): The list of widgets to detach from the DOM.\\n\\n Returns:\\n list[Widget]: The list of widgets that should be pruned.\\n\\n Note:\\n A side-effect of calling this function is that each parent of\\n each affected widget will be made to forget about the affected\\n child.\\n \\\"\\\"\\\"\\n\\n # We've been given a list of widgets to remove, but removing those\\n # will also result in other (descendent) widgets being removed. So\\n # to start with let's get a list of everything that's not going to\\n # be in the DOM by the time we've finished. Note that, at this\\n # point, it's entirely possible that there will be duplicates.\\n everything_to_remove: list[Widget] = []\\n for widget in widgets:\\n everything_to_remove.extend(\\n widget.walk_children(\\n Widget, with_self=True, method=\\\"depth\\\", reverse=True\\n )\\n )\\n\\n # Next up, let's quickly create a deduped collection of things to\\n # remove and ensure that, if one of them is the focused widget,\\n # focus gets moved to somewhere else.\\n dedupe_to_remove = set(everything_to_remove)\\n if self.screen.focused in dedupe_to_remove:\\n self.screen._reset_focus(\\n self.screen.focused,\\n [to_remove for to_remove in dedupe_to_remove if to_remove.can_focus],\\n )\\n\\n # Next, we go through the set of widgets we've been asked to remove\\n # and try and find the minimal collection of widgets that will\\n # result in everything else that should be removed, being removed.\\n # In other words: find the smallest set of ancestors in the DOM that\\n # will remove the widgets requested for removal, and also ensure\\n # that all knock-on effects happen too.\\n request_remove = set(widgets)\\n pruned_remove = [\\n widget for widget in widgets if request_remove.isdisjoint(widget.ancestors)\\n ]\\n\\n # Now that we know that minimal set of widgets, we go through them\\n # and get their parents to forget about them. This has the effect of\\n # snipping each affected branch from the DOM.\\n for widget in pruned_remove:\\n if widget.parent is not None:\\n widget.parent.children._remove(widget)\\n\\n # Return the list of widgets that should end up being sent off in a\\n # prune event.\\n return pruned_remove\\n\\n def _walk_children(self, root: Widget) -> Iterable[list[Widget]]:\\n \\\"\\\"\\\"Walk children depth first, generating widgets and a list of their siblings.\\n\\n Returns:\\n Iterable[list[Widget]]: The child widgets of root.\\n\\n \\\"\\\"\\\"\\n stack: list[Widget] = [root]\\n pop = stack.pop\\n push = stack.append\\n\\n while stack:\\n widget = pop()\\n if widget.children:\\n yield [*widget.children, *widget._get_virtual_dom()]\\n for child in widget.children:\\n push(child)\\n\\n def _remove_nodes(self, widgets: list[Widget]) -> AwaitRemove:\\n \\\"\\\"\\\"Remove nodes from DOM, and return an awaitable that awaits cleanup.\\n\\n Args:\\n widgets (list[Widget]): List of nodes to remvoe.\\n\\n Returns:\\n AwaitRemove: Awaitable that returns when the nodes have been fully removed.\\n \\\"\\\"\\\"\\n\\n async def prune_widgets_task(\\n widgets: list[Widget], finished_event: asyncio.Event\\n ) -> None:\\n \\\"\\\"\\\"Prune widgets as a background task.\\n\\n Args:\\n widgets (list[Widget]): Widgets to prune.\\n finished_event (asyncio.Event): Event to set when complete.\\n \\\"\\\"\\\"\\n try:\\n await self._prune_nodes(widgets)\\n finally:\\n finished_event.set()\\n self.refresh(layout=True)\\n\\n removed_widgets = self._detach_from_dom(widgets)\\n\\n finished_event = asyncio.Event()\\n asyncio.create_task(prune_widgets_task(removed_widgets, finished_event))\\n\\n return AwaitRemove(finished_event)\\n\\n async def _prune_nodes(self, widgets: list[Widget]) -> None:\\n \\\"\\\"\\\"Remove nodes and children.\\n\\n Args:\\n widgets (Widget): _description_\\n \\\"\\\"\\\"\\n async with self._dom_lock:\\n for widget in widgets:\\n await self._prune_node(widget)\\n\\n async def _prune_node(self, root: Widget) -> None:\\n \\\"\\\"\\\"Remove a node and its children. Children are removed before parents.\\n\\n Args:\\n root (Widget): Node to remove.\\n \\\"\\\"\\\"\\n # Pruning a node that has been removed is a no-op\\n if root not in self._registry:\\n return\\n\\n node_children = list(self._walk_children(root))\\n\\n for children in reversed(node_children):\\n # Closing children can be done asynchronously.\\n close_messages = [\\n child._close_messages(wait=True) for child in children if child._running\\n ]\\n # TODO: What if a message pump refuses to exit?\\n if close_messages:\\n await asyncio.gather(*close_messages)\\n for child in children:\\n self._unregister(child)\\n\\n await root._close_messages(wait=False)\\n self._unregister(root)\\n\\n async def action_check_bindings(self, key: str) -> None:\\n if not await self.check_bindings(key, priority=True):\\n await self.check_bindings(key, priority=False)\\n\\n async def action_quit(self) -> None:\\n \\\"\\\"\\\"Quit the app as soon as possible.\\\"\\\"\\\"\\n self.exit()\\n\\n async def action_bang(self) -> None:\\n 1 / 0\\n\\n async def action_bell(self) -> None:\\n \\\"\\\"\\\"Play the terminal 'bell'.\\\"\\\"\\\"\\n self.bell()\\n\\n async def action_focus(self, widget_id: str) -> None:\\n \\\"\\\"\\\"Focus the given widget.\\n\\n Args:\\n widget_id (str): ID of widget to focus.\\n \\\"\\\"\\\"\\n try:\\n node = self.query(f\\\"#{widget_id}\\\").first()\\n except NoMatches:\\n pass\\n else:\\n if isinstance(node, Widget):\\n self.set_focus(node)\\n\\n async def action_switch_screen(self, screen: str) -> None:\\n \\\"\\\"\\\"Switches to another screen.\\n\\n Args:\\n screen (str): Name of the screen.\\n \\\"\\\"\\\"\\n self.switch_screen(screen)\\n\\n async def action_push_screen(self, screen: str) -> None:\\n \\\"\\\"\\\"Pushes a screen on to the screen stack and makes it active.\\n\\n Args:\\n screen (str): Name of the screen.\\n \\\"\\\"\\\"\\n self.push_screen(screen)\\n\\n async def action_pop_screen(self) -> None:\\n \\\"\\\"\\\"Removes the topmost screen and makes the new topmost screen active.\\\"\\\"\\\"\\n self.pop_screen()\\n\\n async def action_back(self) -> None:\\n try:\\n self.pop_screen()\\n except ScreenStackError:\\n pass\\n\\n async def action_add_class_(self, selector: str, class_name: str) -> None:\\n self.screen.query(selector).add_class(class_name)\\n\\n async def action_remove_class_(self, selector: str, class_name: str) -> None:\\n self.screen.query(selector).remove_class(class_name)\\n\\n async def action_toggle_class(self, selector: str, class_name: str) -> None:\\n self.screen.query(selector).toggle_class(class_name)\\n\\n def action_focus_next(self) -> None:\\n \\\"\\\"\\\"Focus the next widget.\\\"\\\"\\\"\\n self.screen.focus_next()\\n\\n def action_focus_previous(self) -> None:\\n \\\"\\\"\\\"Focus the previous widget.\\\"\\\"\\\"\\n self.screen.focus_previous()\\n\\n def _on_terminal_supports_synchronized_output(\\n self, message: messages.TerminalSupportsSynchronizedOutput\\n ) -> None:\\n log.system(\\\"[b green]SynchronizedOutput mode is supported\\\")\\n self._sync_available = True\\n\\n def _begin_update(self) -> None:\\n if self._sync_available:\\n self.console.file.write(SYNC_START)\\n\\n def _end_update(self) -> None:\\n if self._sync_available:\\n self.console.file.write(SYNC_END)\\n\\n\\n_uvloop_init_done: bool = False\\n\\n\\ndef _init_uvloop() -> None:\\n \\\"\\\"\\\"\\n Import and install the `uvloop` asyncio policy, if available.\\n This is done only once, even if the function is called multiple times.\\n \\\"\\\"\\\"\\n global _uvloop_init_done\\n\\n if _uvloop_init_done:\\n return\\n\\n try:\\n import uvloop\\n except ImportError:\\n pass\\n else:\\n uvloop.install()\\n\\n _uvloop_init_done = True\\n\"}"},"non_py_patch":{"kind":"string","value":""},"new_components":{"kind":"string","value":"{\"src/textual/app.py\": [{\"type\": \"function\", \"name\": \"App.call_from_thread\", \"lines\": [614, 657], \"signature\": \"def call_from_thread( self, callback: Callable[..., CallThreadReturnType | Awaitable[CallThreadReturnType]], *args, **kwargs, ) -> CallThreadReturnType:\", \"doc\": \"Run a callback from another thread.\\n\\nLike asyncio apps in general, Textual apps are not thread-safe. If you call methods\\nor set attributes on Textual objects from a thread, you may get unpredictable results.\\n\\nThis method will ensure that your code is ran within the correct context.\\n\\nArgs:\\n callback (Callable): A callable to run.\\n *args: Arguments to the callback.\\n **kwargs: Keyword arguments for the callback.\\n\\nRaises:\\n RuntimeError: If the app isn't running or if this method is called from the same\\n thread where the app is running.\"}]}"},"version":{"kind":"null"},"FAIL_TO_PASS":{"kind":"string","value":"[\"tests/test_concurrency.py::test_call_from_thread_app_not_running\", \"tests/test_concurrency.py::test_call_from_thread\"]"},"PASS_TO_PASS":{"kind":"string","value":"[]"},"environment_setup_commit":{"kind":"string","value":"86e93536b991014e0ea4bf993068202b446bb698"},"problem_statement":{"kind":"string","value":"{\"first_commit_time\": 1673100292.0, \"pr_title\": \"Call from thread method\", \"pr_body\": \"This is a step towards having an answer to devs who want to integrate a third-party API with Textual.\\r\\n\\r\\nThe `call_from_thread` takes a callback that will be called in the app's loop from a thread. It will block until the callback returns. If integrating with a threaded API (many are under the hood), this will generally give the most predictable behaviour.\\r\\n\\r\\nThere are downsides: you call it from the same thread as the app. Otherwise it would deadlock.\\r\\n\\r\\nI'll leave this method undocumented for now. We will at least have an answer for the next version, and we can work on greater syntactical sugar in the meantime.\", \"pr_timeline\": [], \"issues\": {}}"}}},{"rowIdx":10,"cells":{"repo":{"kind":"string","value":"astronomer/astronomer-cosmos"},"pull_number":{"kind":"number","value":758,"string":"758"},"url":{"kind":"string","value":"https://github.com/astronomer/astronomer-cosmos/pull/758"},"instance_id":{"kind":"string","value":"astronomer__astronomer-cosmos-758"},"issue_numbers":{"kind":"string","value":"[]"},"base_commit":{"kind":"string","value":"9fcee8e785ea3bcb0d19e8d36f3f5b94bedafc98"},"patch":{"kind":"string","value":"diff --git a/cosmos/profiles/athena/access_key.py b/cosmos/profiles/athena/access_key.py\nindex a8f71c2b7..02de2be24 100644\n--- a/cosmos/profiles/athena/access_key.py\n+++ b/cosmos/profiles/athena/access_key.py\n@@ -3,20 +3,33 @@\n \n from typing import Any\n \n+from cosmos.exceptions import CosmosValueError\n+\n from ..base import BaseProfileMapping\n \n \n class AthenaAccessKeyProfileMapping(BaseProfileMapping):\n \"\"\"\n- Maps Airflow AWS connections to a dbt Athena profile using an access key id and secret access key.\n+ Uses the Airflow AWS Connection provided to get_credentials() to generate the profile for dbt.\n \n- https://docs.getdbt.com/docs/core/connect-data-platform/athena-setup\n https://airflow.apache.org/docs/apache-airflow-providers-amazon/stable/connections/aws.html\n+\n+\n+ This behaves similarly to other provider operators such as the AWS Athena Operator.\n+ Where you pass the aws_conn_id and the operator will generate the credentials for you.\n+\n+ https://registry.astronomer.io/providers/amazon/versions/latest/modules/athenaoperator\n+\n+ Information about the dbt Athena profile that is generated can be found here:\n+\n+ https://github.com/dbt-athena/dbt-athena?tab=readme-ov-file#configuring-your-profile\n+ https://docs.getdbt.com/docs/core/connect-data-platform/athena-setup\n \"\"\"\n \n airflow_connection_type: str = \"aws\"\n dbt_profile_type: str = \"athena\"\n is_community: bool = True\n+ temporary_credentials = None\n \n required_fields = [\n \"aws_access_key_id\",\n@@ -26,11 +39,7 @@ class AthenaAccessKeyProfileMapping(BaseProfileMapping):\n \"s3_staging_dir\",\n \"schema\",\n ]\n- secret_fields = [\"aws_secret_access_key\", \"aws_session_token\"]\n airflow_param_mapping = {\n- \"aws_access_key_id\": \"login\",\n- \"aws_secret_access_key\": \"password\",\n- \"aws_session_token\": \"extra.aws_session_token\",\n \"aws_profile_name\": \"extra.aws_profile_name\",\n \"database\": \"extra.database\",\n \"debug_query_state\": \"extra.debug_query_state\",\n@@ -49,11 +58,43 @@ class AthenaAccessKeyProfileMapping(BaseProfileMapping):\n @property\n def profile(self) -> dict[str, Any | None]:\n \"Gets profile. The password is stored in an environment variable.\"\n+\n+ self.temporary_credentials = self._get_temporary_credentials() # type: ignore\n+\n profile = {\n **self.mapped_params,\n **self.profile_args,\n- # aws_secret_access_key and aws_session_token should always get set as env var\n+ \"aws_access_key_id\": self.temporary_credentials.access_key,\n \"aws_secret_access_key\": self.get_env_var_format(\"aws_secret_access_key\"),\n \"aws_session_token\": self.get_env_var_format(\"aws_session_token\"),\n }\n+\n return self.filter_null(profile)\n+\n+ @property\n+ def env_vars(self) -> dict[str, str]:\n+ \"Overwrites the env_vars for athena, Returns a dictionary of environment variables that should be set based on the self.temporary_credentials.\"\n+\n+ if self.temporary_credentials is None:\n+ raise CosmosValueError(f\"Could not find the athena credentials.\")\n+\n+ env_vars = {}\n+\n+ env_secret_key_name = self.get_env_var_name(\"aws_secret_access_key\")\n+ env_session_token_name = self.get_env_var_name(\"aws_session_token\")\n+\n+ env_vars[env_secret_key_name] = str(self.temporary_credentials.secret_key)\n+ env_vars[env_session_token_name] = str(self.temporary_credentials.token)\n+\n+ return env_vars\n+\n+ def _get_temporary_credentials(self): # type: ignore\n+ \"\"\"\n+ Helper function to retrieve temporary short lived credentials\n+ Returns an object including access_key, secret_key and token\n+ \"\"\"\n+ from airflow.providers.amazon.aws.hooks.base_aws import AwsGenericHook\n+\n+ hook = AwsGenericHook(self.conn_id) # type: ignore\n+ credentials = hook.get_credentials()\n+ return credentials\ndiff --git a/pyproject.toml b/pyproject.toml\nindex c08de4ade..9d367c075 100644\n--- a/pyproject.toml\n+++ b/pyproject.toml\n@@ -57,6 +57,7 @@ dbt-all = [\n ]\n dbt-athena = [\n \"dbt-athena-community\",\n+ \"apache-airflow-providers-amazon>=8.0.0\",\n ]\n dbt-bigquery = [\n \"dbt-bigquery\",\n@@ -110,7 +111,6 @@ tests = [\n \"mypy\",\n \"sqlalchemy-stubs\", # Change when sqlalchemy is upgraded https://docs.sqlalchemy.org/en/14/orm/extensions/mypy.html\n ]\n-\n docker = [\n \"apache-airflow-providers-docker>=3.5.0\",\n ]\n@@ -121,7 +121,6 @@ pydantic = [\n \"pydantic>=1.10.0,<2.0.0\",\n ]\n \n-\n [project.entry-points.cosmos]\n provider_info = \"cosmos:get_provider_info\"\n \n"},"test_patch":{"kind":"string","value":"diff --git a/tests/profiles/athena/test_athena_access_key.py b/tests/profiles/athena/test_athena_access_key.py\nindex 22c8efa2c..c224a9d4b 100644\n--- a/tests/profiles/athena/test_athena_access_key.py\n+++ b/tests/profiles/athena/test_athena_access_key.py\n@@ -1,20 +1,49 @@\n \"Tests for the Athena profile.\"\n \n import json\n-from unittest.mock import patch\n-\n+from collections import namedtuple\n+import sys\n+from unittest.mock import MagicMock, patch\n import pytest\n from airflow.models.connection import Connection\n \n from cosmos.profiles import get_automatic_profile_mapping\n from cosmos.profiles.athena.access_key import AthenaAccessKeyProfileMapping\n \n+Credentials = namedtuple(\"Credentials\", [\"access_key\", \"secret_key\", \"token\"])\n+\n+mock_assumed_credentials = Credentials(\n+ secret_key=\"my_aws_assumed_secret_key\",\n+ access_key=\"my_aws_assumed_access_key\",\n+ token=\"my_aws_assumed_token\",\n+)\n+\n+mock_missing_credentials = Credentials(access_key=None, secret_key=None, token=None)\n+\n+\n+@pytest.fixture(autouse=True)\n+def mock_aws_module():\n+ mock_aws_hook = MagicMock()\n+\n+ class MockAwsGenericHook:\n+ def __init__(self, conn_id: str) -> None:\n+ pass\n+\n+ def get_credentials(self) -> Credentials:\n+ return mock_assumed_credentials\n+\n+ mock_aws_hook.AwsGenericHook = MockAwsGenericHook\n+\n+ with patch.dict(sys.modules, {\"airflow.providers.amazon.aws.hooks.base_aws\": mock_aws_hook}):\n+ yield mock_aws_hook\n+\n \n @pytest.fixture()\n def mock_athena_conn(): # type: ignore\n \"\"\"\n Sets the connection as an environment variable.\n \"\"\"\n+\n conn = Connection(\n conn_id=\"my_athena_connection\",\n conn_type=\"aws\",\n@@ -24,7 +53,7 @@ def mock_athena_conn(): # type: ignore\n {\n \"aws_session_token\": \"token123\",\n \"database\": \"my_database\",\n- \"region_name\": \"my_region\",\n+ \"region_name\": \"us-east-1\",\n \"s3_staging_dir\": \"s3://my_bucket/dbt/\",\n \"schema\": \"my_schema\",\n }\n@@ -48,6 +77,7 @@ def test_athena_connection_claiming() -> None:\n # - region_name\n # - s3_staging_dir\n # - schema\n+\n potential_values = {\n \"conn_type\": \"aws\",\n \"login\": \"my_aws_access_key_id\",\n@@ -55,7 +85,7 @@ def test_athena_connection_claiming() -> None:\n \"extra\": json.dumps(\n {\n \"database\": \"my_database\",\n- \"region_name\": \"my_region\",\n+ \"region_name\": \"us-east-1\",\n \"s3_staging_dir\": \"s3://my_bucket/dbt/\",\n \"schema\": \"my_schema\",\n }\n@@ -68,12 +98,14 @@ def test_athena_connection_claiming() -> None:\n del values[key]\n conn = Connection(**values) # type: ignore\n \n- print(\"testing with\", values)\n-\n- with patch(\"airflow.hooks.base.BaseHook.get_connection\", return_value=conn):\n- # should raise an InvalidMappingException\n- profile_mapping = AthenaAccessKeyProfileMapping(conn, {})\n- assert not profile_mapping.can_claim_connection()\n+ with patch(\n+ \"cosmos.profiles.athena.access_key.AthenaAccessKeyProfileMapping._get_temporary_credentials\",\n+ return_value=mock_missing_credentials,\n+ ):\n+ with patch(\"airflow.hooks.base.BaseHook.get_connection\", return_value=conn):\n+ # should raise an InvalidMappingException\n+ profile_mapping = AthenaAccessKeyProfileMapping(conn, {})\n+ assert not profile_mapping.can_claim_connection()\n \n # if we have them all, it should claim\n conn = Connection(**potential_values) # type: ignore\n@@ -88,6 +120,7 @@ def test_athena_profile_mapping_selected(\n \"\"\"\n Tests that the correct profile mapping is selected for Athena.\n \"\"\"\n+\n profile_mapping = get_automatic_profile_mapping(\n mock_athena_conn.conn_id,\n )\n@@ -100,13 +133,14 @@ def test_athena_profile_args(\n \"\"\"\n Tests that the profile values get set correctly for Athena.\n \"\"\"\n+\n profile_mapping = get_automatic_profile_mapping(\n mock_athena_conn.conn_id,\n )\n \n assert profile_mapping.profile == {\n \"type\": \"athena\",\n- \"aws_access_key_id\": mock_athena_conn.login,\n+ \"aws_access_key_id\": mock_assumed_credentials.access_key,\n \"aws_secret_access_key\": \"{{ env_var('COSMOS_CONN_AWS_AWS_SECRET_ACCESS_KEY') }}\",\n \"aws_session_token\": \"{{ env_var('COSMOS_CONN_AWS_AWS_SESSION_TOKEN') }}\",\n \"database\": mock_athena_conn.extra_dejson.get(\"database\"),\n@@ -122,9 +156,14 @@ def test_athena_profile_args_overrides(\n \"\"\"\n Tests that you can override the profile values for Athena.\n \"\"\"\n+\n profile_mapping = get_automatic_profile_mapping(\n mock_athena_conn.conn_id,\n- profile_args={\"schema\": \"my_custom_schema\", \"database\": \"my_custom_db\", \"aws_session_token\": \"override_token\"},\n+ profile_args={\n+ \"schema\": \"my_custom_schema\",\n+ \"database\": \"my_custom_db\",\n+ \"aws_session_token\": \"override_token\",\n+ },\n )\n \n assert profile_mapping.profile_args == {\n@@ -135,7 +174,7 @@ def test_athena_profile_args_overrides(\n \n assert profile_mapping.profile == {\n \"type\": \"athena\",\n- \"aws_access_key_id\": mock_athena_conn.login,\n+ \"aws_access_key_id\": mock_assumed_credentials.access_key,\n \"aws_secret_access_key\": \"{{ env_var('COSMOS_CONN_AWS_AWS_SECRET_ACCESS_KEY') }}\",\n \"aws_session_token\": \"{{ env_var('COSMOS_CONN_AWS_AWS_SESSION_TOKEN') }}\",\n \"database\": \"my_custom_db\",\n@@ -151,10 +190,12 @@ def test_athena_profile_env_vars(\n \"\"\"\n Tests that the environment variables get set correctly for Athena.\n \"\"\"\n+\n profile_mapping = get_automatic_profile_mapping(\n mock_athena_conn.conn_id,\n )\n+\n assert profile_mapping.env_vars == {\n- \"COSMOS_CONN_AWS_AWS_SECRET_ACCESS_KEY\": mock_athena_conn.password,\n- \"COSMOS_CONN_AWS_AWS_SESSION_TOKEN\": mock_athena_conn.extra_dejson.get(\"aws_session_token\"),\n+ \"COSMOS_CONN_AWS_AWS_SECRET_ACCESS_KEY\": mock_assumed_credentials.secret_key,\n+ \"COSMOS_CONN_AWS_AWS_SESSION_TOKEN\": mock_assumed_credentials.token,\n }\n"},"created_at":{"kind":"timestamp","value":"2023-12-11T01:54:27","string":"2023-12-11T01:54:27"},"readmes":{"kind":"string","value":"{}"},"files":{"kind":"string","value":"{\"cosmos/profiles/athena/access_key.py\": \"\\\"Maps Airflow AWS connections to a dbt Athena profile using an access key id and secret access key.\\\"\\nfrom __future__ import annotations\\n\\nfrom typing import Any\\n\\nfrom ..base import BaseProfileMapping\\n\\n\\nclass AthenaAccessKeyProfileMapping(BaseProfileMapping):\\n \\\"\\\"\\\"\\n Maps Airflow AWS connections to a dbt Athena profile using an access key id and secret access key.\\n\\n https://docs.getdbt.com/docs/core/connect-data-platform/athena-setup\\n https://airflow.apache.org/docs/apache-airflow-providers-amazon/stable/connections/aws.html\\n \\\"\\\"\\\"\\n\\n airflow_connection_type: str = \\\"aws\\\"\\n dbt_profile_type: str = \\\"athena\\\"\\n is_community: bool = True\\n\\n required_fields = [\\n \\\"aws_access_key_id\\\",\\n \\\"aws_secret_access_key\\\",\\n \\\"database\\\",\\n \\\"region_name\\\",\\n \\\"s3_staging_dir\\\",\\n \\\"schema\\\",\\n ]\\n secret_fields = [\\\"aws_secret_access_key\\\", \\\"aws_session_token\\\"]\\n airflow_param_mapping = {\\n \\\"aws_access_key_id\\\": \\\"login\\\",\\n \\\"aws_secret_access_key\\\": \\\"password\\\",\\n \\\"aws_session_token\\\": \\\"extra.aws_session_token\\\",\\n \\\"aws_profile_name\\\": \\\"extra.aws_profile_name\\\",\\n \\\"database\\\": \\\"extra.database\\\",\\n \\\"debug_query_state\\\": \\\"extra.debug_query_state\\\",\\n \\\"lf_tags_database\\\": \\\"extra.lf_tags_database\\\",\\n \\\"num_retries\\\": \\\"extra.num_retries\\\",\\n \\\"poll_interval\\\": \\\"extra.poll_interval\\\",\\n \\\"region_name\\\": \\\"extra.region_name\\\",\\n \\\"s3_data_dir\\\": \\\"extra.s3_data_dir\\\",\\n \\\"s3_data_naming\\\": \\\"extra.s3_data_naming\\\",\\n \\\"s3_staging_dir\\\": \\\"extra.s3_staging_dir\\\",\\n \\\"schema\\\": \\\"extra.schema\\\",\\n \\\"seed_s3_upload_args\\\": \\\"extra.seed_s3_upload_args\\\",\\n \\\"work_group\\\": \\\"extra.work_group\\\",\\n }\\n\\n @property\\n def profile(self) -> dict[str, Any | None]:\\n \\\"Gets profile. The password is stored in an environment variable.\\\"\\n profile = {\\n **self.mapped_params,\\n **self.profile_args,\\n # aws_secret_access_key and aws_session_token should always get set as env var\\n \\\"aws_secret_access_key\\\": self.get_env_var_format(\\\"aws_secret_access_key\\\"),\\n \\\"aws_session_token\\\": self.get_env_var_format(\\\"aws_session_token\\\"),\\n }\\n return self.filter_null(profile)\\n\", \"pyproject.toml\": \"[build-system]\\nrequires = [\\\"hatchling\\\"]\\nbuild-backend = \\\"hatchling.build\\\"\\n\\n[project]\\nname = \\\"astronomer-cosmos\\\"\\ndynamic = [\\\"version\\\"]\\ndescription = \\\"Render 3rd party workflows in Airflow\\\"\\nreadme = \\\"README.rst\\\"\\nlicense = \\\"Apache-2.0\\\"\\nrequires-python = \\\">=3.8\\\"\\nauthors = [\\n { name = \\\"Astronomer\\\", email = \\\"humans@astronomer.io\\\" },\\n]\\nkeywords = [\\n \\\"airflow\\\",\\n \\\"apache-airflow\\\",\\n \\\"astronomer\\\",\\n \\\"dags\\\",\\n \\\"dbt\\\",\\n]\\nclassifiers = [\\n \\\"Development Status :: 3 - Alpha\\\",\\n \\\"Environment :: Web Environment\\\",\\n \\\"Framework :: Apache Airflow\\\",\\n \\\"Framework :: Apache Airflow :: Provider\\\",\\n \\\"Intended Audience :: Developers\\\",\\n \\\"License :: OSI Approved :: Apache Software License\\\",\\n \\\"Operating System :: OS Independent\\\",\\n \\\"Programming Language :: Python\\\",\\n \\\"Programming Language :: Python :: 3\\\",\\n \\\"Programming Language :: Python :: 3.8\\\",\\n \\\"Programming Language :: Python :: 3.9\\\",\\n \\\"Programming Language :: Python :: 3.10\\\",\\n]\\ndependencies = [\\n \\\"aenum\\\",\\n \\\"attrs\\\",\\n \\\"apache-airflow>=2.3.0\\\",\\n \\\"importlib-metadata; python_version < '3.8'\\\",\\n \\\"Jinja2>=3.0.0\\\",\\n \\\"typing-extensions; python_version < '3.8'\\\",\\n \\\"virtualenv\\\",\\n]\\n\\n[project.optional-dependencies]\\ndbt-all = [\\n \\\"dbt-athena\\\",\\n \\\"dbt-bigquery\\\",\\n \\\"dbt-databricks\\\",\\n \\\"dbt-exasol\\\",\\n \\\"dbt-postgres\\\",\\n \\\"dbt-redshift\\\",\\n \\\"dbt-snowflake\\\",\\n \\\"dbt-spark\\\",\\n \\\"dbt-vertica\\\",\\n]\\ndbt-athena = [\\n \\\"dbt-athena-community\\\",\\n]\\ndbt-bigquery = [\\n \\\"dbt-bigquery\\\",\\n]\\ndbt-databricks = [\\n \\\"dbt-databricks\\\",\\n]\\ndbt-exasol = [\\n \\\"dbt-exasol\\\",\\n]\\ndbt-postgres = [\\n \\\"dbt-postgres\\\",\\n]\\ndbt-redshift = [\\n \\\"dbt-redshift\\\",\\n]\\ndbt-snowflake = [\\n \\\"dbt-snowflake\\\",\\n]\\ndbt-spark = [\\n \\\"dbt-spark\\\",\\n]\\ndbt-vertica = [\\n \\\"dbt-vertica<=1.5.4\\\",\\n]\\nopenlineage = [\\n \\\"openlineage-integration-common\\\",\\n \\\"openlineage-airflow\\\",\\n]\\nall = [\\n \\\"astronomer-cosmos[dbt-all]\\\",\\n \\\"astronomer-cosmos[openlineage]\\\"\\n]\\ndocs =[\\n \\\"sphinx\\\",\\n \\\"pydata-sphinx-theme\\\",\\n \\\"sphinx-autobuild\\\",\\n \\\"sphinx-autoapi\\\",\\n \\\"apache-airflow-providers-cncf-kubernetes>=5.1.1\\\"\\n]\\ntests = [\\n \\\"packaging\\\",\\n \\\"pytest>=6.0\\\",\\n \\\"pytest-split\\\",\\n \\\"pytest-dotenv\\\",\\n \\\"requests-mock\\\",\\n \\\"pytest-cov\\\",\\n \\\"pytest-describe\\\",\\n \\\"sqlalchemy-stubs\\\", # Change when sqlalchemy is upgraded https://docs.sqlalchemy.org/en/14/orm/extensions/mypy.html\\n \\\"types-requests\\\",\\n \\\"mypy\\\",\\n \\\"sqlalchemy-stubs\\\", # Change when sqlalchemy is upgraded https://docs.sqlalchemy.org/en/14/orm/extensions/mypy.html\\n]\\n\\ndocker = [\\n \\\"apache-airflow-providers-docker>=3.5.0\\\",\\n]\\nkubernetes = [\\n \\\"apache-airflow-providers-cncf-kubernetes>=5.1.1\\\",\\n]\\npydantic = [\\n \\\"pydantic>=1.10.0,<2.0.0\\\",\\n]\\n\\n\\n[project.entry-points.cosmos]\\nprovider_info = \\\"cosmos:get_provider_info\\\"\\n\\n[project.urls]\\nHomepage = \\\"https://github.com/astronomer/astronomer-cosmos\\\"\\nDocumentation = \\\"https://astronomer.github.io/astronomer-cosmos\\\"\\n\\\"Source code\\\" = \\\"https://github.com/astronomer/astronomer-cosmos\\\"\\n\\n[tool.hatch.version]\\npath = \\\"cosmos/__init__.py\\\"\\n\\n[tool.hatch.build.targets.sdist]\\ninclude = [\\n \\\"/cosmos\\\",\\n]\\n\\n[tool.hatch.build.targets.wheel]\\npackages = [\\\"cosmos\\\"]\\n\\n######################################\\n# TESTING\\n######################################\\n\\n[tool.hatch.envs.tests]\\ndependencies = [\\n \\\"astronomer-cosmos[tests]\\\",\\n \\\"apache-airflow-providers-docker>=3.5.0\\\",\\n \\\"apache-airflow-providers-cncf-kubernetes>=5.1.1\\\",\\n \\\"types-PyYAML\\\",\\n \\\"types-attrs\\\",\\n \\\"types-requests\\\",\\n \\\"types-python-dateutil\\\",\\n \\\"apache-airflow\\\",\\n \\\"Werkzeug<3.0.0\\\",\\n]\\n\\n[[tool.hatch.envs.tests.matrix]]\\npython = [\\\"3.8\\\", \\\"3.9\\\", \\\"3.10\\\"]\\nairflow = [\\\"2.3\\\", \\\"2.4\\\", \\\"2.5\\\", \\\"2.6\\\", \\\"2.7\\\"]\\n\\n[tool.hatch.envs.tests.overrides]\\nmatrix.airflow.dependencies = [\\n { value = \\\"apache-airflow==2.3\\\", if = [\\\"2.3\\\"] },\\n { value = \\\"apache-airflow==2.4\\\", if = [\\\"2.4\\\"] },\\n { value = \\\"apache-airflow==2.5\\\", if = [\\\"2.5\\\"] },\\n { value = \\\"apache-airflow==2.6\\\", if = [\\\"2.6\\\"] },\\n { value = \\\"pydantic>=1.10.0,<2.0.0\\\", if = [\\\"2.6\\\"]},\\n { value = \\\"apache-airflow==2.7\\\", if = [\\\"2.7\\\"] },\\n]\\n\\n[tool.hatch.envs.tests.scripts]\\nfreeze = \\\"pip freeze\\\"\\ntype-check = \\\"mypy cosmos\\\"\\ntest = 'pytest -vv --durations=0 . -m \\\"not integration\\\" --ignore=tests/test_example_dags.py --ignore=tests/test_example_dags_no_connections.py'\\ntest-cov = \\\"\\\"\\\"pytest -vv --cov=cosmos --cov-report=term-missing --cov-report=xml --durations=0 -m \\\"not integration\\\" --ignore=tests/test_example_dags.py --ignore=tests/test_example_dags_no_connections.py\\\"\\\"\\\"\\n# we install using the following workaround to overcome installation conflicts, such as:\\n# apache-airflow 2.3.0 and dbt-core [0.13.0 - 1.5.2] and jinja2>=3.0.0 because these package versions have conflicting dependencies\\ntest-integration-setup = \\\"\\\"\\\"pip uninstall dbt-postgres dbt-databricks dbt-vertica; \\\\\\nrm -rf airflow.*; \\\\\\nairflow db init; \\\\\\npip install 'dbt-core' 'dbt-databricks' 'dbt-postgres' 'dbt-vertica' 'openlineage-airflow'\\\"\\\"\\\"\\ntest-integration = \\\"\\\"\\\"rm -rf dbt/jaffle_shop/dbt_packages;\\npytest -vv \\\\\\n--cov=cosmos \\\\\\n--cov-report=term-missing \\\\\\n--cov-report=xml \\\\\\n--durations=0 \\\\\\n-m integration \\\\\\n-k 'not (sqlite or example_cosmos_sources or example_cosmos_python_models or example_virtualenv)'\\\"\\\"\\\"\\ntest-integration-expensive = \\\"\\\"\\\"pytest -vv \\\\\\n--cov=cosmos \\\\\\n--cov-report=term-missing \\\\\\n--cov-report=xml \\\\\\n--durations=0 \\\\\\n-m integration \\\\\\n-k 'example_cosmos_python_models or example_virtualenv'\\\"\\\"\\\"\\ntest-integration-sqlite-setup = \\\"\\\"\\\"pip uninstall -y dbt-core dbt-sqlite openlineage-airflow openlineage-integration-common; \\\\\\nrm -rf airflow.*; \\\\\\nairflow db init; \\\\\\npip install 'dbt-core==1.4' 'dbt-sqlite<=1.4' 'dbt-databricks<=1.4' 'dbt-postgres<=1.4' \\\"\\\"\\\"\\ntest-integration-sqlite = \\\"\\\"\\\"\\npytest -vv \\\\\\n--cov=cosmos \\\\\\n--cov-report=term-missing \\\\\\n--cov-report=xml \\\\\\n--durations=0 \\\\\\n-m integration \\\\\\n-k 'example_cosmos_sources or sqlite'\\\"\\\"\\\"\\n\\n[tool.pytest.ini_options]\\nfilterwarnings = [\\n \\\"ignore::DeprecationWarning\\\",\\n]\\nminversion = \\\"6.0\\\"\\nmarkers = [\\n \\\"integration\\\",\\n \\\"sqlite\\\"\\n]\\n\\n######################################\\n# DOCS\\n######################################\\n\\n[tool.hatch.envs.docs]\\ndependencies = [\\n \\\"aenum\\\",\\n \\\"sphinx\\\",\\n \\\"pydata-sphinx-theme\\\",\\n \\\"sphinx-autobuild\\\",\\n \\\"sphinx-autoapi\\\",\\n \\\"openlineage-airflow\\\",\\n \\\"apache-airflow-providers-cncf-kubernetes>=5.1.1\\\"\\n]\\n\\n[tool.hatch.envs.docs.scripts]\\nbuild = \\\"sphinx-build -b html docs docs/_build\\\"\\nserve = \\\"sphinx-autobuild docs docs/_build\\\"\\n\\n######################################\\n# THIRD PARTY TOOLS\\n######################################\\n[tool.black]\\nline-length = 120\\ntarget-version = ['py37', 'py38', 'py39', 'py310']\\n\\n[tool.isort]\\nprofile = \\\"black\\\"\\nknown_third_party = [\\\"airflow\\\", \\\"jinja2\\\"]\\n\\n[tool.mypy]\\nstrict = true\\nignore_missing_imports = true\\nno_warn_unused_ignores = true\\n\\n[tool.ruff]\\nline-length = 120\\n[tool.ruff.lint]\\nselect = [\\\"C901\\\"]\\n[tool.ruff.lint.mccabe]\\nmax-complexity = 8\\n\\n[tool.distutils.bdist_wheel]\\nuniversal = true\\n\"}"},"non_py_patch":{"kind":"string","value":"diff --git a/pyproject.toml b/pyproject.toml\nindex c08de4ade..9d367c075 100644\n--- a/pyproject.toml\n+++ b/pyproject.toml\n@@ -57,6 +57,7 @@ dbt-all = [\n ]\n dbt-athena = [\n \"dbt-athena-community\",\n+ \"apache-airflow-providers-amazon>=8.0.0\",\n ]\n dbt-bigquery = [\n \"dbt-bigquery\",\n@@ -110,7 +111,6 @@ tests = [\n \"mypy\",\n \"sqlalchemy-stubs\", # Change when sqlalchemy is upgraded https://docs.sqlalchemy.org/en/14/orm/extensions/mypy.html\n ]\n-\n docker = [\n \"apache-airflow-providers-docker>=3.5.0\",\n ]\n@@ -121,7 +121,6 @@ pydantic = [\n \"pydantic>=1.10.0,<2.0.0\",\n ]\n \n-\n [project.entry-points.cosmos]\n provider_info = \"cosmos:get_provider_info\"\n \n"},"new_components":{"kind":"string","value":"{\"cosmos/profiles/athena/access_key.py\": [{\"type\": \"function\", \"name\": \"AthenaAccessKeyProfileMapping.env_vars\", \"lines\": [75, 89], \"signature\": \"def env_vars(self) -> dict[str, str]:\", \"doc\": \"Overwrites the env_vars for athena, Returns a dictionary of environment variables that should be set based on the self.temporary_credentials.\"}, {\"type\": \"function\", \"name\": \"AthenaAccessKeyProfileMapping._get_temporary_credentials\", \"lines\": [91, 100], \"signature\": \"def _get_temporary_credentials(self):\", \"doc\": \"Helper function to retrieve temporary short lived credentials\\nReturns an object including access_key, secret_key and token\"}]}"},"version":{"kind":"null"},"FAIL_TO_PASS":{"kind":"string","value":"[\"tests/profiles/athena/test_athena_access_key.py::test_athena_connection_claiming\", \"tests/profiles/athena/test_athena_access_key.py::test_athena_profile_args\", \"tests/profiles/athena/test_athena_access_key.py::test_athena_profile_args_overrides\", \"tests/profiles/athena/test_athena_access_key.py::test_athena_profile_env_vars\"]"},"PASS_TO_PASS":{"kind":"string","value":"[\"tests/profiles/athena/test_athena_access_key.py::test_athena_profile_mapping_selected\"]"},"environment_setup_commit":{"kind":"string","value":"c5edba07d2265d5185eaba149a639e8a0740e498"},"problem_statement":{"kind":"string","value":"{\"first_commit_time\": 1702073118.0, \"pr_title\": \"Athena - Get temporary credentials from the conn_id\", \"pr_body\": \"## Description\\r\\n\\r\\n\\r\\n\\r\\nPasses the `conn_id` to the `AwsGenericHook` and uses `get_credentials()`, which handles the creation of a session, credentials, freezing of credentials & also masking. \\r\\n\\r\\n[See get_credentials() docs here](https://airflow.apache.org/docs/apache-airflow-providers-amazon/stable/_api/airflow/providers/amazon/aws/hooks/base_aws/index.html#airflow.providers.amazon.aws.hooks.base_aws.AwsGenericHook.get_credentials)\\r\\n\\r\\n## Related Issue(s)\\r\\n\\r\\n#691 \\r\\n\\r\\n\\r\\n\\r\\n## Breaking Change?\\r\\n\\r\\n\\r\\n\\r\\n## Checklist\\r\\n\\r\\n- [ ] I have made corresponding changes to the documentation (if required)\\r\\n- [X] I have added tests that prove my fix is effective or that my feature works\\r\\n\", \"pr_timeline\": [{\"time\": 1702516996.0, \"comment\": \"### \\ud83d\\udc77 Deploy Preview for *amazing-pothos-a3bca0* processing.\\n\\n\\n| Name | Link |\\n|:-:|------------------------|\\n|\\ud83d\\udd28 Latest commit | 67615488341c4fbba77dd631e7d8f43ff1fbda36 |\\n|\\ud83d\\udd0d Latest deploy log | https://app.netlify.com/sites/amazing-pothos-a3bca0/deploys/657a59029dc4d1000891bfde |\"}, {\"time\": 1702280483.0, \"comment\": \"Do you mean dbt-Athena or dbt-athena-community. Dbt-Athena is the original module but the community version is much improved and optimised. https://github.com/dbt-athena/dbt-athena\"}, {\"time\": 1702284012.0, \"comment\": \"@pixie79 the `dbt-athena` references the project optional dependency on line 58 \\r\\n\\r\\n```\\r\\ndbt-athena = [\\r\\n \\\"dbt-athena-community\\\",\\r\\n]\\r\\n```\"}, {\"time\": 1702338636.0, \"comment\": \"@jbandoro Thanks for the feedback. If the user has an Airflow connection with no `extra.role_arn` provided, their credentials (secret + key id) used in the DBT profile will be unchanged, except there will now always be a `aws_session_token`.\"}, {\"time\": 1702343774.0, \"comment\": \"Tests failing due to #761\"}, {\"time\": 1702457551.0, \"comment\": \"LGTM, I tried this out today and it seems to work for my use-case -- unfortunately I don't have time to look into the memory issue and verify that this works at scale, but that's hopefully going to be resolved with the use of the AWS hook. Ran a couple of models concurrently and didn't run into any issues.\"}, {\"time\": 1702518365.0, \"comment\": \"## [Codecov](https://app.codecov.io/gh/astronomer/astronomer-cosmos/pull/758?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=astronomer) Report\\nAttention: `1 lines` in your changes are missing coverage. Please review.\\n> Comparison is base [(`9fcee8e`)](https://app.codecov.io/gh/astronomer/astronomer-cosmos/commit/9fcee8e785ea3bcb0d19e8d36f3f5b94bedafc98?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=astronomer) 93.22% compared to head [(`6761548`)](https://app.codecov.io/gh/astronomer/astronomer-cosmos/pull/758?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=astronomer) 93.22%.\\n\\n| [Files](https://app.codecov.io/gh/astronomer/astronomer-cosmos/pull/758?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=astronomer) | Patch % | Lines |\\n|---|---|---|\\n| [cosmos/profiles/athena/access\\\\_key.py](https://app.codecov.io/gh/astronomer/astronomer-cosmos/pull/758?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=astronomer#diff-Y29zbW9zL3Byb2ZpbGVzL2F0aGVuYS9hY2Nlc3Nfa2V5LnB5) | 94.44% | [1 Missing :warning: ](https://app.codecov.io/gh/astronomer/astronomer-cosmos/pull/758?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=astronomer) |\\n\\n
Additional details and impacted files\\n\\n\\n```diff\\n@@ Coverage Diff @@\\n## main #758 +/- ##\\n=======================================\\n Coverage 93.22% 93.22% \\n=======================================\\n Files 55 55 \\n Lines 2464 2481 +17 \\n=======================================\\n+ Hits 2297 2313 +16 \\n- Misses 167 168 +1 \\n```\\n\\n\\n\\n
\\n\\n[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/astronomer/astronomer-cosmos/pull/758?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=astronomer). \\n:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=astronomer).\\n\"}, {\"time\": 1702509972.0, \"comment\": \"@tatiana I am unable to write a test for the `_get_temporary_credentials`method, as I am unable to import `airflow.providers.amazon` via the test dependencies as we get some dependency conflicts when using Python 3.8/3.9 + Airflow 2.3. \\r\\n\\r\\nThe amazon provider at 8.0.0 is compatible with 2.3 and python down to 3.7.\\r\\n\\r\\nhttps://pypi.org/project/apache-airflow-providers-amazon/8.0.0/\\r\\n\\r\\nI tried many ways to fix this on the weekend, but could not. I ended up resolving this by removing the dependency and mocking the class function. \\r\\n\\r\\nThis has the unfortunately side-affect of reducing our test coverage\"}, {\"time\": 1702512862.0, \"comment\": \"Thanks @octiva addressing all the feedback! For your question below on test coverage:\\r\\n\\r\\n> I tried many ways to fix this on the weekend, but could not. I ended up resolving this by removing the dependency and mocking the class function.\\r\\n> \\r\\n> This has the unfortunately side-affect of reducing our test coverage\\r\\n\\r\\nYou can get test coverage for the `_get_temporary_credential` method by instead patching the provider module that can't be imported, like in the examples [here](https://github.com/astronomer/astronomer-cosmos/blob/9fcee8e785ea3bcb0d19e8d36f3f5b94bedafc98/tests/operators/test_local.py#L439) and [here](https://github.com/astronomer/astronomer-cosmos/blob/9fcee8e785ea3bcb0d19e8d36f3f5b94bedafc98/tests/test_export.py#L76-L83).\\r\\n\\r\\nIt might be easier to do this patching in a fixture and reuse it in all of tests that require it.\"}, {\"time\": 1702515418.0, \"comment\": \"reposting from correct account @jbandoro Thanks for the hint. I had attempted this, but was doing it at the wrong level, and now ive got it working quite nicely. Let me know what you think \\ud83d\\ude80 \"}], \"issues\": {}}"}}},{"rowIdx":11,"cells":{"repo":{"kind":"string","value":"astropy/astropy"},"pull_number":{"kind":"number","value":13094,"string":"13,094"},"url":{"kind":"string","value":"https://github.com/astropy/astropy/pull/13094"},"instance_id":{"kind":"string","value":"astropy__astropy-13094"},"issue_numbers":{"kind":"string","value":"[]"},"base_commit":{"kind":"string","value":"583464d40b32313da6b864d2f260c06d1a0e67e6"},"patch":{"kind":"string","value":"diff --git a/astropy/wcs/wcs.py b/astropy/wcs/wcs.py\nindex 6d508279375d..3903ad49cc1c 100644\n--- a/astropy/wcs/wcs.py\n+++ b/astropy/wcs/wcs.py\n@@ -3226,6 +3226,21 @@ def has_spectral(self):\n except InconsistentAxisTypesError:\n return False\n \n+ @property\n+ def temporal(self):\n+ \"\"\"\n+ A copy of the current WCS with only the time axes included\n+ \"\"\"\n+ return self.sub([WCSSUB_TIME]) # Defined by C-ext # noqa: F821\n+\n+ @property\n+ def is_temporal(self):\n+ return self.has_temporal and self.naxis == 1\n+\n+ @property\n+ def has_temporal(self):\n+ return any(t // 1000 == 4 for t in self.wcs.axis_types)\n+\n @property\n def has_distortion(self):\n \"\"\"\ndiff --git a/docs/changes/wcs/13094.feature.rst b/docs/changes/wcs/13094.feature.rst\nnew file mode 100644\nindex 000000000000..e6b718e0a4e0\n--- /dev/null\n+++ b/docs/changes/wcs/13094.feature.rst\n@@ -0,0 +1,2 @@\n+Add ``temporal`` properties for convenient access of/selection of/testing for\n+the ``TIME`` axis introduced in WCSLIB version 7.8.\n"},"test_patch":{"kind":"string","value":"diff --git a/astropy/wcs/tests/test_wcs.py b/astropy/wcs/tests/test_wcs.py\nindex f51b50906e80..9aca3b34b1de 100644\n--- a/astropy/wcs/tests/test_wcs.py\n+++ b/astropy/wcs/tests/test_wcs.py\n@@ -1534,10 +1534,24 @@ def test_pixlist_wcs_colsel():\n _WCSLIB_VER < Version('7.8'),\n reason=\"TIME axis extraction only works with wcslib 7.8 or later\"\n )\n-def test_time_axis_selection(tab_wcs_2di_f):\n+def test_time_axis_selection():\n w = wcs.WCS(naxis=3)\n w.wcs.ctype = ['RA---TAN', 'DEC--TAN', 'TIME']\n w.wcs.set()\n assert list(w.sub([wcs.WCSSUB_TIME]).wcs.ctype) == ['TIME']\n assert (w.wcs_pix2world([[1, 2, 3]], 0)[0, 2] ==\n w.sub([wcs.WCSSUB_TIME]).wcs_pix2world([[3]], 0)[0, 0])\n+\n+\n+@pytest.mark.skipif(\n+ _WCSLIB_VER < Version('7.8'),\n+ reason=\"TIME axis extraction only works with wcslib 7.8 or later\"\n+)\n+def test_temporal():\n+ w = wcs.WCS(naxis=3)\n+ w.wcs.ctype = ['RA---TAN', 'DEC--TAN', 'TIME']\n+ w.wcs.set()\n+ assert w.has_temporal\n+ assert w.sub([wcs.WCSSUB_TIME]).is_temporal\n+ assert (w.wcs_pix2world([[1, 2, 3]], 0)[0, 2] ==\n+ w.temporal.wcs_pix2world([[3]], 0)[0, 0])\n"},"created_at":{"kind":"timestamp","value":"2022-04-10T18:52:18","string":"2022-04-10T18:52:18"},"readmes":{"kind":"string","value":"{}"},"files":{"kind":"string","value":"{\"astropy/wcs/wcs.py\": \"# Licensed under a 3-clause BSD style license - see LICENSE.rst\\n\\n# Under the hood, there are 3 separate classes that perform different\\n# parts of the transformation:\\n#\\n# - `~astropy.wcs.Wcsprm`: Is a direct wrapper of the core WCS\\n# functionality in `wcslib`_. (This includes TPV and TPD\\n# polynomial distortion, but not SIP distortion).\\n#\\n# - `~astropy.wcs.Sip`: Handles polynomial distortion as defined in the\\n# `SIP`_ convention.\\n#\\n# - `~astropy.wcs.DistortionLookupTable`: Handles `distortion paper`_\\n# lookup tables.\\n#\\n# Additionally, the class `WCS` aggregates all of these transformations\\n# together in a pipeline:\\n#\\n# - Detector to image plane correction (by a pair of\\n# `~astropy.wcs.DistortionLookupTable` objects).\\n#\\n# - `SIP`_ distortion correction (by an underlying `~astropy.wcs.Sip`\\n# object)\\n#\\n# - `distortion paper`_ table-lookup correction (by a pair of\\n# `~astropy.wcs.DistortionLookupTable` objects).\\n#\\n# - `wcslib`_ WCS transformation (by a `~astropy.wcs.Wcsprm` object)\\n\\n# STDLIB\\nimport copy\\nimport uuid\\nimport io\\nimport itertools\\nimport os\\nimport re\\nimport textwrap\\nimport warnings\\nimport builtins\\n\\n# THIRD-PARTY\\nimport numpy as np\\n\\n# LOCAL\\nfrom astropy import log\\nfrom astropy.io import fits\\nfrom . import docstrings\\nfrom . import _wcs\\n\\nfrom astropy import units as u\\nfrom astropy.utils.compat import possible_filename\\nfrom astropy.utils.exceptions import AstropyWarning, AstropyUserWarning, AstropyDeprecationWarning\\nfrom astropy.utils.decorators import deprecated_renamed_argument\\n\\n# Mix-in class that provides the APE 14 API\\nfrom .wcsapi.fitswcs import FITSWCSAPIMixin, SlicedFITSWCS\\n\\n__all__ = ['FITSFixedWarning', 'WCS', 'find_all_wcs',\\n 'DistortionLookupTable', 'Sip', 'Tabprm', 'Wcsprm', 'Auxprm',\\n 'Celprm', 'Prjprm', 'Wtbarr', 'WCSBase', 'validate', 'WcsError',\\n 'SingularMatrixError', 'InconsistentAxisTypesError',\\n 'InvalidTransformError', 'InvalidCoordinateError',\\n 'InvalidPrjParametersError', 'NoSolutionError',\\n 'InvalidSubimageSpecificationError', 'NoConvergence',\\n 'NonseparableSubimageCoordinateSystemError',\\n 'NoWcsKeywordsFoundError', 'InvalidTabularParametersError']\\n\\n\\n__doctest_skip__ = ['WCS.all_world2pix']\\n\\n\\nif _wcs is not None:\\n _parsed_version = _wcs.__version__.split('.')\\n if int(_parsed_version[0]) == 5 and int(_parsed_version[1]) < 8:\\n raise ImportError(\\n \\\"astropy.wcs is built with wcslib {0}, but only versions 5.8 and \\\"\\n \\\"later on the 5.x series are known to work. The version of wcslib \\\"\\n \\\"that ships with astropy may be used.\\\")\\n\\n if not _wcs._sanity_check():\\n raise RuntimeError(\\n \\\"astropy.wcs did not pass its sanity check for your build \\\"\\n \\\"on your platform.\\\")\\n\\n WCSBase = _wcs._Wcs\\n DistortionLookupTable = _wcs.DistortionLookupTable\\n Sip = _wcs.Sip\\n Wcsprm = _wcs.Wcsprm\\n Auxprm = _wcs.Auxprm\\n Celprm = _wcs.Celprm\\n Prjprm = _wcs.Prjprm\\n Tabprm = _wcs.Tabprm\\n Wtbarr = _wcs.Wtbarr\\n WcsError = _wcs.WcsError\\n SingularMatrixError = _wcs.SingularMatrixError\\n InconsistentAxisTypesError = _wcs.InconsistentAxisTypesError\\n InvalidTransformError = _wcs.InvalidTransformError\\n InvalidCoordinateError = _wcs.InvalidCoordinateError\\n NoSolutionError = _wcs.NoSolutionError\\n InvalidSubimageSpecificationError = _wcs.InvalidSubimageSpecificationError\\n NonseparableSubimageCoordinateSystemError = _wcs.NonseparableSubimageCoordinateSystemError\\n NoWcsKeywordsFoundError = _wcs.NoWcsKeywordsFoundError\\n InvalidTabularParametersError = _wcs.InvalidTabularParametersError\\n InvalidPrjParametersError = _wcs.InvalidPrjParametersError\\n\\n # Copy all the constants from the C extension into this module's namespace\\n for key, val in _wcs.__dict__.items():\\n if key.startswith(('WCSSUB_', 'WCSHDR_', 'WCSHDO_', 'WCSCOMPARE_', 'PRJ_')):\\n locals()[key] = val\\n __all__.append(key)\\n\\n # Set coordinate extraction callback for WCS -TAB:\\n def _load_tab_bintable(hdulist, extnam, extver, extlev, kind, ttype, row, ndim):\\n arr = hdulist[(extnam, extver)].data[ttype][row - 1]\\n\\n if arr.ndim != ndim:\\n if kind == 'c' and ndim == 2:\\n arr = arr.reshape((arr.size, 1))\\n else:\\n raise ValueError(\\\"Bad TDIM\\\")\\n\\n return np.ascontiguousarray(arr, dtype=np.double)\\n\\n _wcs.set_wtbarr_fitsio_callback(_load_tab_bintable)\\n\\nelse:\\n WCSBase = object\\n Wcsprm = object\\n DistortionLookupTable = object\\n Sip = object\\n Tabprm = object\\n Wtbarr = object\\n WcsError = None\\n SingularMatrixError = None\\n InconsistentAxisTypesError = None\\n InvalidTransformError = None\\n InvalidCoordinateError = None\\n NoSolutionError = None\\n InvalidSubimageSpecificationError = None\\n NonseparableSubimageCoordinateSystemError = None\\n NoWcsKeywordsFoundError = None\\n InvalidTabularParametersError = None\\n\\n\\n# Additional relax bit flags\\nWCSHDO_SIP = 0x80000\\n\\n# Regular expression defining SIP keyword It matches keyword that starts with A\\n# or B, optionally followed by P, followed by an underscore then a number in\\n# range of 0-19, followed by an underscore and another number in range of 0-19.\\n# Keyword optionally ends with a capital letter.\\nSIP_KW = re.compile('''^[AB]P?_1?[0-9]_1?[0-9][A-Z]?$''')\\n\\n\\ndef _parse_keysel(keysel):\\n keysel_flags = 0\\n if keysel is not None:\\n for element in keysel:\\n if element.lower() == 'image':\\n keysel_flags |= _wcs.WCSHDR_IMGHEAD\\n elif element.lower() == 'binary':\\n keysel_flags |= _wcs.WCSHDR_BIMGARR\\n elif element.lower() == 'pixel':\\n keysel_flags |= _wcs.WCSHDR_PIXLIST\\n else:\\n raise ValueError(\\n \\\"keysel must be a list of 'image', 'binary' \\\" +\\n \\\"and/or 'pixel'\\\")\\n else:\\n keysel_flags = -1\\n\\n return keysel_flags\\n\\n\\nclass NoConvergence(Exception):\\n \\\"\\\"\\\"\\n An error class used to report non-convergence and/or divergence\\n of numerical methods. It is used to report errors in the\\n iterative solution used by\\n the :py:meth:`~astropy.wcs.WCS.all_world2pix`.\\n\\n Attributes\\n ----------\\n\\n best_solution : `numpy.ndarray`\\n Best solution achieved by the numerical method.\\n\\n accuracy : `numpy.ndarray`\\n Accuracy of the ``best_solution``.\\n\\n niter : `int`\\n Number of iterations performed by the numerical method\\n to compute ``best_solution``.\\n\\n divergent : None, `numpy.ndarray`\\n Indices of the points in ``best_solution`` array\\n for which the solution appears to be divergent. If the\\n solution does not diverge, ``divergent`` will be set to `None`.\\n\\n slow_conv : None, `numpy.ndarray`\\n Indices of the solutions in ``best_solution`` array\\n for which the solution failed to converge within the\\n specified maximum number of iterations. If there are no\\n non-converging solutions (i.e., if the required accuracy\\n has been achieved for all input data points)\\n then ``slow_conv`` will be set to `None`.\\n\\n \\\"\\\"\\\"\\n\\n def __init__(self, *args, best_solution=None, accuracy=None, niter=None,\\n divergent=None, slow_conv=None, **kwargs):\\n super().__init__(*args)\\n\\n self.best_solution = best_solution\\n self.accuracy = accuracy\\n self.niter = niter\\n self.divergent = divergent\\n self.slow_conv = slow_conv\\n\\n if kwargs:\\n warnings.warn(\\\"Function received unexpected arguments ({}) these \\\"\\n \\\"are ignored but will raise an Exception in the \\\"\\n \\\"future.\\\".format(list(kwargs)),\\n AstropyDeprecationWarning)\\n\\n\\nclass FITSFixedWarning(AstropyWarning):\\n \\\"\\\"\\\"\\n The warning raised when the contents of the FITS header have been\\n modified to be standards compliant.\\n \\\"\\\"\\\"\\n pass\\n\\n\\nclass WCS(FITSWCSAPIMixin, WCSBase):\\n \\\"\\\"\\\"WCS objects perform standard WCS transformations, and correct for\\n `SIP`_ and `distortion paper`_ table-lookup transformations, based\\n on the WCS keywords and supplementary data read from a FITS file.\\n\\n See also: https://docs.astropy.org/en/stable/wcs/\\n\\n Parameters\\n ----------\\n header : `~astropy.io.fits.Header`, `~astropy.io.fits.hdu.image.PrimaryHDU`, `~astropy.io.fits.hdu.image.ImageHDU`, str, dict-like, or None, optional\\n If *header* is not provided or None, the object will be\\n initialized to default values.\\n\\n fobj : `~astropy.io.fits.HDUList`, optional\\n It is needed when header keywords point to a `distortion\\n paper`_ lookup table stored in a different extension.\\n\\n key : str, optional\\n The name of a particular WCS transform to use. This may be\\n either ``' '`` or ``'A'``-``'Z'`` and corresponds to the\\n ``\\\\\\\"a\\\\\\\"`` part of the ``CTYPEia`` cards. *key* may only be\\n provided if *header* is also provided.\\n\\n minerr : float, optional\\n The minimum value a distortion correction must have in order\\n to be applied. If the value of ``CQERRja`` is smaller than\\n *minerr*, the corresponding distortion is not applied.\\n\\n relax : bool or int, optional\\n Degree of permissiveness:\\n\\n - `True` (default): Admit all recognized informal extensions\\n of the WCS standard.\\n\\n - `False`: Recognize only FITS keywords defined by the\\n published WCS standard.\\n\\n - `int`: a bit field selecting specific extensions to accept.\\n See :ref:`astropy:relaxread` for details.\\n\\n naxis : int or sequence, optional\\n Extracts specific coordinate axes using\\n :meth:`~astropy.wcs.Wcsprm.sub`. If a header is provided, and\\n *naxis* is not ``None``, *naxis* will be passed to\\n :meth:`~astropy.wcs.Wcsprm.sub` in order to select specific\\n axes from the header. See :meth:`~astropy.wcs.Wcsprm.sub` for\\n more details about this parameter.\\n\\n keysel : sequence of str, optional\\n A sequence of flags used to select the keyword types\\n considered by wcslib. When ``None``, only the standard image\\n header keywords are considered (and the underlying wcspih() C\\n function is called). To use binary table image array or pixel\\n list keywords, *keysel* must be set.\\n\\n Each element in the list should be one of the following\\n strings:\\n\\n - 'image': Image header keywords\\n\\n - 'binary': Binary table image array keywords\\n\\n - 'pixel': Pixel list keywords\\n\\n Keywords such as ``EQUIna`` or ``RFRQna`` that are common to\\n binary table image arrays and pixel lists (including\\n ``WCSNna`` and ``TWCSna``) are selected by both 'binary' and\\n 'pixel'.\\n\\n colsel : sequence of int, optional\\n A sequence of table column numbers used to restrict the WCS\\n transformations considered to only those pertaining to the\\n specified columns. If `None`, there is no restriction.\\n\\n fix : bool, optional\\n When `True` (default), call `~astropy.wcs.Wcsprm.fix` on\\n the resulting object to fix any non-standard uses in the\\n header. `FITSFixedWarning` Warnings will be emitted if any\\n changes were made.\\n\\n translate_units : str, optional\\n Specify which potentially unsafe translations of non-standard\\n unit strings to perform. By default, performs none. See\\n `WCS.fix` for more information about this parameter. Only\\n effective when ``fix`` is `True`.\\n\\n Raises\\n ------\\n MemoryError\\n Memory allocation failed.\\n\\n ValueError\\n Invalid key.\\n\\n KeyError\\n Key not found in FITS header.\\n\\n ValueError\\n Lookup table distortion present in the header but *fobj* was\\n not provided.\\n\\n Notes\\n -----\\n\\n 1. astropy.wcs supports arbitrary *n* dimensions for the core WCS\\n (the transformations handled by WCSLIB). However, the\\n `distortion paper`_ lookup table and `SIP`_ distortions must be\\n two dimensional. Therefore, if you try to create a WCS object\\n where the core WCS has a different number of dimensions than 2\\n and that object also contains a `distortion paper`_ lookup\\n table or `SIP`_ distortion, a `ValueError`\\n exception will be raised. To avoid this, consider using the\\n *naxis* kwarg to select two dimensions from the core WCS.\\n\\n 2. The number of coordinate axes in the transformation is not\\n determined directly from the ``NAXIS`` keyword but instead from\\n the highest of:\\n\\n - ``NAXIS`` keyword\\n\\n - ``WCSAXESa`` keyword\\n\\n - The highest axis number in any parameterized WCS keyword.\\n The keyvalue, as well as the keyword, must be\\n syntactically valid otherwise it will not be considered.\\n\\n If none of these keyword types is present, i.e. if the header\\n only contains auxiliary WCS keywords for a particular\\n coordinate representation, then no coordinate description is\\n constructed for it.\\n\\n The number of axes, which is set as the ``naxis`` member, may\\n differ for different coordinate representations of the same\\n image.\\n\\n 3. When the header includes duplicate keywords, in most cases the\\n last encountered is used.\\n\\n 4. `~astropy.wcs.Wcsprm.set` is called immediately after\\n construction, so any invalid keywords or transformations will\\n be raised by the constructor, not when subsequently calling a\\n transformation method.\\n\\n \\\"\\\"\\\" # noqa: E501\\n\\n def __init__(self, header=None, fobj=None, key=' ', minerr=0.0,\\n relax=True, naxis=None, keysel=None, colsel=None,\\n fix=True, translate_units='', _do_set=True):\\n close_fds = []\\n\\n # these parameters are stored to be used when unpickling a WCS object:\\n self._init_kwargs = {\\n 'keysel': copy.copy(keysel),\\n 'colsel': copy.copy(colsel),\\n }\\n\\n if header is None:\\n if naxis is None:\\n naxis = 2\\n wcsprm = _wcs.Wcsprm(header=None, key=key,\\n relax=relax, naxis=naxis)\\n self.naxis = wcsprm.naxis\\n # Set some reasonable defaults.\\n det2im = (None, None)\\n cpdis = (None, None)\\n sip = None\\n else:\\n keysel_flags = _parse_keysel(keysel)\\n\\n if isinstance(header, (str, bytes)):\\n try:\\n is_path = (possible_filename(header) and\\n os.path.exists(header))\\n except (OSError, ValueError):\\n is_path = False\\n\\n if is_path:\\n if fobj is not None:\\n raise ValueError(\\n \\\"Can not provide both a FITS filename to \\\"\\n \\\"argument 1 and a FITS file object to argument 2\\\")\\n fobj = fits.open(header)\\n close_fds.append(fobj)\\n header = fobj[0].header\\n elif isinstance(header, fits.hdu.image._ImageBaseHDU):\\n header = header.header\\n elif not isinstance(header, fits.Header):\\n try:\\n # Accept any dict-like object\\n orig_header = header\\n header = fits.Header()\\n for dict_key in orig_header.keys():\\n header[dict_key] = orig_header[dict_key]\\n except TypeError:\\n raise TypeError(\\n \\\"header must be a string, an astropy.io.fits.Header \\\"\\n \\\"object, or a dict-like object\\\")\\n\\n if isinstance(header, fits.Header):\\n header_string = header.tostring().rstrip()\\n else:\\n header_string = header\\n\\n # Importantly, header is a *copy* of the passed-in header\\n # because we will be modifying it\\n if isinstance(header_string, str):\\n header_bytes = header_string.encode('ascii')\\n header_string = header_string\\n else:\\n header_bytes = header_string\\n header_string = header_string.decode('ascii')\\n\\n if not (fobj is None or isinstance(fobj, fits.HDUList)):\\n raise AssertionError(\\\"'fobj' must be either None or an \\\"\\n \\\"astropy.io.fits.HDUList object.\\\")\\n\\n est_naxis = 2\\n try:\\n tmp_header = fits.Header.fromstring(header_string)\\n self._remove_sip_kw(tmp_header)\\n tmp_header_bytes = tmp_header.tostring().rstrip()\\n if isinstance(tmp_header_bytes, str):\\n tmp_header_bytes = tmp_header_bytes.encode('ascii')\\n tmp_wcsprm = _wcs.Wcsprm(header=tmp_header_bytes, key=key,\\n relax=relax, keysel=keysel_flags,\\n colsel=colsel, warnings=False,\\n hdulist=fobj)\\n if naxis is not None:\\n try:\\n tmp_wcsprm = tmp_wcsprm.sub(naxis)\\n except ValueError:\\n pass\\n est_naxis = tmp_wcsprm.naxis if tmp_wcsprm.naxis else 2\\n\\n except _wcs.NoWcsKeywordsFoundError:\\n pass\\n\\n self.naxis = est_naxis\\n\\n header = fits.Header.fromstring(header_string)\\n\\n det2im = self._read_det2im_kw(header, fobj, err=minerr)\\n cpdis = self._read_distortion_kw(\\n header, fobj, dist='CPDIS', err=minerr)\\n sip = self._read_sip_kw(header, wcskey=key)\\n self._remove_sip_kw(header)\\n\\n header_string = header.tostring()\\n header_string = header_string.replace('END' + ' ' * 77, '')\\n\\n if isinstance(header_string, str):\\n header_bytes = header_string.encode('ascii')\\n header_string = header_string\\n else:\\n header_bytes = header_string\\n header_string = header_string.decode('ascii')\\n\\n try:\\n wcsprm = _wcs.Wcsprm(header=header_bytes, key=key,\\n relax=relax, keysel=keysel_flags,\\n colsel=colsel, hdulist=fobj)\\n except _wcs.NoWcsKeywordsFoundError:\\n # The header may have SIP or distortions, but no core\\n # WCS. That isn't an error -- we want a \\\"default\\\"\\n # (identity) core Wcs transformation in that case.\\n if colsel is None:\\n wcsprm = _wcs.Wcsprm(header=None, key=key,\\n relax=relax, keysel=keysel_flags,\\n colsel=colsel, hdulist=fobj)\\n else:\\n raise\\n\\n if naxis is not None:\\n wcsprm = wcsprm.sub(naxis)\\n self.naxis = wcsprm.naxis\\n\\n if (wcsprm.naxis != 2 and\\n (det2im[0] or det2im[1] or cpdis[0] or cpdis[1] or sip)):\\n raise ValueError(\\n \\\"\\\"\\\"\\nFITS WCS distortion paper lookup tables and SIP distortions only work\\nin 2 dimensions. However, WCSLIB has detected {} dimensions in the\\ncore WCS keywords. To use core WCS in conjunction with FITS WCS\\ndistortion paper lookup tables or SIP distortion, you must select or\\nreduce these to 2 dimensions using the naxis kwarg.\\n\\\"\\\"\\\".format(wcsprm.naxis))\\n\\n header_naxis = header.get('NAXIS', None)\\n if header_naxis is not None and header_naxis < wcsprm.naxis:\\n warnings.warn(\\n \\\"The WCS transformation has more axes ({:d}) than the \\\"\\n \\\"image it is associated with ({:d})\\\".format(\\n wcsprm.naxis, header_naxis), FITSFixedWarning)\\n\\n self._get_naxis(header)\\n WCSBase.__init__(self, sip, cpdis, wcsprm, det2im)\\n\\n if fix:\\n if header is None:\\n with warnings.catch_warnings():\\n warnings.simplefilter('ignore', FITSFixedWarning)\\n self.fix(translate_units=translate_units)\\n else:\\n self.fix(translate_units=translate_units)\\n\\n if _do_set:\\n self.wcs.set()\\n\\n for fd in close_fds:\\n fd.close()\\n\\n self._pixel_bounds = None\\n\\n def __copy__(self):\\n new_copy = self.__class__()\\n WCSBase.__init__(new_copy, self.sip,\\n (self.cpdis1, self.cpdis2),\\n self.wcs,\\n (self.det2im1, self.det2im2))\\n new_copy.__dict__.update(self.__dict__)\\n return new_copy\\n\\n def __deepcopy__(self, memo):\\n from copy import deepcopy\\n\\n new_copy = self.__class__()\\n new_copy.naxis = deepcopy(self.naxis, memo)\\n WCSBase.__init__(new_copy, deepcopy(self.sip, memo),\\n (deepcopy(self.cpdis1, memo),\\n deepcopy(self.cpdis2, memo)),\\n deepcopy(self.wcs, memo),\\n (deepcopy(self.det2im1, memo),\\n deepcopy(self.det2im2, memo)))\\n for key, val in self.__dict__.items():\\n new_copy.__dict__[key] = deepcopy(val, memo)\\n return new_copy\\n\\n def copy(self):\\n \\\"\\\"\\\"\\n Return a shallow copy of the object.\\n\\n Convenience method so user doesn't have to import the\\n :mod:`copy` stdlib module.\\n\\n .. warning::\\n Use `deepcopy` instead of `copy` unless you know why you need a\\n shallow copy.\\n \\\"\\\"\\\"\\n return copy.copy(self)\\n\\n def deepcopy(self):\\n \\\"\\\"\\\"\\n Return a deep copy of the object.\\n\\n Convenience method so user doesn't have to import the\\n :mod:`copy` stdlib module.\\n \\\"\\\"\\\"\\n return copy.deepcopy(self)\\n\\n def sub(self, axes=None):\\n\\n copy = self.deepcopy()\\n\\n # We need to know which axes have been dropped, but there is no easy\\n # way to do this with the .sub function, so instead we assign UUIDs to\\n # the CNAME parameters in copy.wcs. We can later access the original\\n # CNAME properties from self.wcs.\\n cname_uuid = [str(uuid.uuid4()) for i in range(copy.wcs.naxis)]\\n copy.wcs.cname = cname_uuid\\n\\n # Subset the WCS\\n copy.wcs = copy.wcs.sub(axes)\\n copy.naxis = copy.wcs.naxis\\n\\n # Construct a list of dimensions from the original WCS in the order\\n # in which they appear in the final WCS.\\n keep = [cname_uuid.index(cname) if cname in cname_uuid else None\\n for cname in copy.wcs.cname]\\n\\n # Restore the original CNAMEs\\n copy.wcs.cname = ['' if i is None else self.wcs.cname[i] for i in keep]\\n\\n # Subset pixel_shape and pixel_bounds\\n if self.pixel_shape:\\n copy.pixel_shape = tuple([None if i is None else self.pixel_shape[i] for i in keep])\\n if self.pixel_bounds:\\n copy.pixel_bounds = [None if i is None else self.pixel_bounds[i] for i in keep]\\n\\n return copy\\n\\n if _wcs is not None:\\n sub.__doc__ = _wcs.Wcsprm.sub.__doc__\\n\\n def _fix_scamp(self):\\n \\\"\\\"\\\"\\n Remove SCAMP's PVi_m distortion parameters if SIP distortion parameters\\n are also present. Some projects (e.g., Palomar Transient Factory)\\n convert SCAMP's distortion parameters (which abuse the PVi_m cards) to\\n SIP. However, wcslib gets confused by the presence of both SCAMP and\\n SIP distortion parameters.\\n\\n See https://github.com/astropy/astropy/issues/299.\\n \\\"\\\"\\\"\\n # Nothing to be done if no WCS attached\\n if self.wcs is None:\\n return\\n\\n # Nothing to be done if no PV parameters attached\\n pv = self.wcs.get_pv()\\n if not pv:\\n return\\n\\n # Nothing to be done if axes don't use SIP distortion parameters\\n if self.sip is None:\\n return\\n\\n # Nothing to be done if any radial terms are present...\\n # Loop over list to find any radial terms.\\n # Certain values of the `j' index are used for storing\\n # radial terms; refer to Equation (1) in\\n # .\\n pv = np.asarray(pv)\\n # Loop over distinct values of `i' index\\n for i in set(pv[:, 0]):\\n # Get all values of `j' index for this value of `i' index\\n js = set(pv[:, 1][pv[:, 0] == i])\\n # Find max value of `j' index\\n max_j = max(js)\\n for j in (3, 11, 23, 39):\\n if j < max_j and j in js:\\n return\\n\\n self.wcs.set_pv([])\\n warnings.warn(\\\"Removed redundant SCAMP distortion parameters \\\" +\\n \\\"because SIP parameters are also present\\\", FITSFixedWarning)\\n\\n def fix(self, translate_units='', naxis=None):\\n \\\"\\\"\\\"\\n Perform the fix operations from wcslib, and warn about any\\n changes it has made.\\n\\n Parameters\\n ----------\\n translate_units : str, optional\\n Specify which potentially unsafe translations of\\n non-standard unit strings to perform. By default,\\n performs none.\\n\\n Although ``\\\"S\\\"`` is commonly used to represent seconds,\\n its translation to ``\\\"s\\\"`` is potentially unsafe since the\\n standard recognizes ``\\\"S\\\"`` formally as Siemens, however\\n rarely that may be used. The same applies to ``\\\"H\\\"`` for\\n hours (Henry), and ``\\\"D\\\"`` for days (Debye).\\n\\n This string controls what to do in such cases, and is\\n case-insensitive.\\n\\n - If the string contains ``\\\"s\\\"``, translate ``\\\"S\\\"`` to\\n ``\\\"s\\\"``.\\n\\n - If the string contains ``\\\"h\\\"``, translate ``\\\"H\\\"`` to\\n ``\\\"h\\\"``.\\n\\n - If the string contains ``\\\"d\\\"``, translate ``\\\"D\\\"`` to\\n ``\\\"d\\\"``.\\n\\n Thus ``''`` doesn't do any unsafe translations, whereas\\n ``'shd'`` does all of them.\\n\\n naxis : int array, optional\\n Image axis lengths. If this array is set to zero or\\n ``None``, then `~astropy.wcs.Wcsprm.cylfix` will not be\\n invoked.\\n \\\"\\\"\\\"\\n if self.wcs is not None:\\n self._fix_scamp()\\n fixes = self.wcs.fix(translate_units, naxis)\\n for key, val in fixes.items():\\n if val != \\\"No change\\\":\\n if (key == 'datfix' and '1858-11-17' in val and\\n not np.count_nonzero(self.wcs.mjdref)):\\n continue\\n warnings.warn(\\n (\\\"'{0}' made the change '{1}'.\\\").\\n format(key, val),\\n FITSFixedWarning)\\n\\n def calc_footprint(self, header=None, undistort=True, axes=None, center=True):\\n \\\"\\\"\\\"\\n Calculates the footprint of the image on the sky.\\n\\n A footprint is defined as the positions of the corners of the\\n image on the sky after all available distortions have been\\n applied.\\n\\n Parameters\\n ----------\\n header : `~astropy.io.fits.Header` object, optional\\n Used to get ``NAXIS1`` and ``NAXIS2``\\n header and axes are mutually exclusive, alternative ways\\n to provide the same information.\\n\\n undistort : bool, optional\\n If `True`, take SIP and distortion lookup table into\\n account\\n\\n axes : (int, int), optional\\n If provided, use the given sequence as the shape of the\\n image. Otherwise, use the ``NAXIS1`` and ``NAXIS2``\\n keywords from the header that was used to create this\\n `WCS` object.\\n\\n center : bool, optional\\n If `True` use the center of the pixel, otherwise use the corner.\\n\\n Returns\\n -------\\n coord : (4, 2) array of (*x*, *y*) coordinates.\\n The order is clockwise starting with the bottom left corner.\\n \\\"\\\"\\\"\\n if axes is not None:\\n naxis1, naxis2 = axes\\n else:\\n if header is None:\\n try:\\n # classes that inherit from WCS and define naxis1/2\\n # do not require a header parameter\\n naxis1, naxis2 = self.pixel_shape\\n except (AttributeError, TypeError):\\n warnings.warn(\\n \\\"Need a valid header in order to calculate footprint\\\\n\\\", AstropyUserWarning)\\n return None\\n else:\\n naxis1 = header.get('NAXIS1', None)\\n naxis2 = header.get('NAXIS2', None)\\n\\n if naxis1 is None or naxis2 is None:\\n raise ValueError(\\n \\\"Image size could not be determined.\\\")\\n\\n if center:\\n corners = np.array([[1, 1],\\n [1, naxis2],\\n [naxis1, naxis2],\\n [naxis1, 1]], dtype=np.float64)\\n else:\\n corners = np.array([[0.5, 0.5],\\n [0.5, naxis2 + 0.5],\\n [naxis1 + 0.5, naxis2 + 0.5],\\n [naxis1 + 0.5, 0.5]], dtype=np.float64)\\n\\n if undistort:\\n return self.all_pix2world(corners, 1)\\n else:\\n return self.wcs_pix2world(corners, 1)\\n\\n def _read_det2im_kw(self, header, fobj, err=0.0):\\n \\\"\\\"\\\"\\n Create a `distortion paper`_ type lookup table for detector to\\n image plane correction.\\n \\\"\\\"\\\"\\n if fobj is None:\\n return (None, None)\\n\\n if not isinstance(fobj, fits.HDUList):\\n return (None, None)\\n\\n try:\\n axiscorr = header['AXISCORR']\\n d2imdis = self._read_d2im_old_format(header, fobj, axiscorr)\\n return d2imdis\\n except KeyError:\\n pass\\n\\n dist = 'D2IMDIS'\\n d_kw = 'D2IM'\\n err_kw = 'D2IMERR'\\n tables = {}\\n for i in range(1, self.naxis + 1):\\n d_error = header.get(err_kw + str(i), 0.0)\\n if d_error < err:\\n tables[i] = None\\n continue\\n distortion = dist + str(i)\\n if distortion in header:\\n dis = header[distortion].lower()\\n if dis == 'lookup':\\n del header[distortion]\\n assert isinstance(fobj, fits.HDUList), (\\n 'An astropy.io.fits.HDUList'\\n 'is required for Lookup table distortion.')\\n dp = (d_kw + str(i)).strip()\\n dp_extver_key = dp + '.EXTVER'\\n if dp_extver_key in header:\\n d_extver = header[dp_extver_key]\\n del header[dp_extver_key]\\n else:\\n d_extver = 1\\n dp_axis_key = dp + f'.AXIS.{i:d}'\\n if i == header[dp_axis_key]:\\n d_data = fobj['D2IMARR', d_extver].data\\n else:\\n d_data = (fobj['D2IMARR', d_extver].data).transpose()\\n del header[dp_axis_key]\\n d_header = fobj['D2IMARR', d_extver].header\\n d_crpix = (d_header.get('CRPIX1', 0.0), d_header.get('CRPIX2', 0.0))\\n d_crval = (d_header.get('CRVAL1', 0.0), d_header.get('CRVAL2', 0.0))\\n d_cdelt = (d_header.get('CDELT1', 1.0), d_header.get('CDELT2', 1.0))\\n d_lookup = DistortionLookupTable(d_data, d_crpix,\\n d_crval, d_cdelt)\\n tables[i] = d_lookup\\n else:\\n warnings.warn('Polynomial distortion is not implemented.\\\\n', AstropyUserWarning)\\n for key in set(header):\\n if key.startswith(dp + '.'):\\n del header[key]\\n else:\\n tables[i] = None\\n if not tables:\\n return (None, None)\\n else:\\n return (tables.get(1), tables.get(2))\\n\\n def _read_d2im_old_format(self, header, fobj, axiscorr):\\n warnings.warn(\\n \\\"The use of ``AXISCORR`` for D2IM correction has been deprecated.\\\"\\n \\\"`~astropy.wcs` will read in files with ``AXISCORR`` but ``to_fits()`` will write \\\"\\n \\\"out files without it.\\\",\\n AstropyDeprecationWarning)\\n cpdis = [None, None]\\n crpix = [0., 0.]\\n crval = [0., 0.]\\n cdelt = [1., 1.]\\n try:\\n d2im_data = fobj[('D2IMARR', 1)].data\\n except KeyError:\\n return (None, None)\\n except AttributeError:\\n return (None, None)\\n\\n d2im_data = np.array([d2im_data])\\n d2im_hdr = fobj[('D2IMARR', 1)].header\\n naxis = d2im_hdr['NAXIS']\\n\\n for i in range(1, naxis + 1):\\n crpix[i - 1] = d2im_hdr.get('CRPIX' + str(i), 0.0)\\n crval[i - 1] = d2im_hdr.get('CRVAL' + str(i), 0.0)\\n cdelt[i - 1] = d2im_hdr.get('CDELT' + str(i), 1.0)\\n\\n cpdis = DistortionLookupTable(d2im_data, crpix, crval, cdelt)\\n\\n if axiscorr == 1:\\n return (cpdis, None)\\n elif axiscorr == 2:\\n return (None, cpdis)\\n else:\\n warnings.warn(\\\"Expected AXISCORR to be 1 or 2\\\", AstropyUserWarning)\\n return (None, None)\\n\\n def _write_det2im(self, hdulist):\\n \\\"\\\"\\\"\\n Writes a `distortion paper`_ type lookup table to the given\\n `~astropy.io.fits.HDUList`.\\n \\\"\\\"\\\"\\n\\n if self.det2im1 is None and self.det2im2 is None:\\n return\\n dist = 'D2IMDIS'\\n d_kw = 'D2IM'\\n\\n def write_d2i(num, det2im):\\n if det2im is None:\\n return\\n\\n hdulist[0].header[f'{dist}{num:d}'] = (\\n 'LOOKUP', 'Detector to image correction type')\\n hdulist[0].header[f'{d_kw}{num:d}.EXTVER'] = (\\n num, 'Version number of WCSDVARR extension')\\n hdulist[0].header[f'{d_kw}{num:d}.NAXES'] = (\\n len(det2im.data.shape), 'Number of independent variables in D2IM function')\\n\\n for i in range(det2im.data.ndim):\\n jth = {1: '1st', 2: '2nd', 3: '3rd'}.get(i + 1, f'{i + 1}th')\\n hdulist[0].header[f'{d_kw}{num:d}.AXIS.{i + 1:d}'] = (\\n i + 1, f'Axis number of the {jth} variable in a D2IM function')\\n\\n image = fits.ImageHDU(det2im.data, name='D2IMARR')\\n header = image.header\\n\\n header['CRPIX1'] = (det2im.crpix[0],\\n 'Coordinate system reference pixel')\\n header['CRPIX2'] = (det2im.crpix[1],\\n 'Coordinate system reference pixel')\\n header['CRVAL1'] = (det2im.crval[0],\\n 'Coordinate system value at reference pixel')\\n header['CRVAL2'] = (det2im.crval[1],\\n 'Coordinate system value at reference pixel')\\n header['CDELT1'] = (det2im.cdelt[0],\\n 'Coordinate increment along axis')\\n header['CDELT2'] = (det2im.cdelt[1],\\n 'Coordinate increment along axis')\\n image.ver = int(hdulist[0].header[f'{d_kw}{num:d}.EXTVER'])\\n hdulist.append(image)\\n write_d2i(1, self.det2im1)\\n write_d2i(2, self.det2im2)\\n\\n def _read_distortion_kw(self, header, fobj, dist='CPDIS', err=0.0):\\n \\\"\\\"\\\"\\n Reads `distortion paper`_ table-lookup keywords and data, and\\n returns a 2-tuple of `~astropy.wcs.DistortionLookupTable`\\n objects.\\n\\n If no `distortion paper`_ keywords are found, ``(None, None)``\\n is returned.\\n \\\"\\\"\\\"\\n if isinstance(header, (str, bytes)):\\n return (None, None)\\n\\n if dist == 'CPDIS':\\n d_kw = 'DP'\\n err_kw = 'CPERR'\\n else:\\n d_kw = 'DQ'\\n err_kw = 'CQERR'\\n\\n tables = {}\\n for i in range(1, self.naxis + 1):\\n d_error_key = err_kw + str(i)\\n if d_error_key in header:\\n d_error = header[d_error_key]\\n del header[d_error_key]\\n else:\\n d_error = 0.0\\n if d_error < err:\\n tables[i] = None\\n continue\\n distortion = dist + str(i)\\n if distortion in header:\\n dis = header[distortion].lower()\\n del header[distortion]\\n if dis == 'lookup':\\n if not isinstance(fobj, fits.HDUList):\\n raise ValueError('an astropy.io.fits.HDUList is '\\n 'required for Lookup table distortion.')\\n dp = (d_kw + str(i)).strip()\\n dp_extver_key = dp + '.EXTVER'\\n if dp_extver_key in header:\\n d_extver = header[dp_extver_key]\\n del header[dp_extver_key]\\n else:\\n d_extver = 1\\n dp_axis_key = dp + f'.AXIS.{i:d}'\\n if i == header[dp_axis_key]:\\n d_data = fobj['WCSDVARR', d_extver].data\\n else:\\n d_data = (fobj['WCSDVARR', d_extver].data).transpose()\\n del header[dp_axis_key]\\n d_header = fobj['WCSDVARR', d_extver].header\\n d_crpix = (d_header.get('CRPIX1', 0.0),\\n d_header.get('CRPIX2', 0.0))\\n d_crval = (d_header.get('CRVAL1', 0.0),\\n d_header.get('CRVAL2', 0.0))\\n d_cdelt = (d_header.get('CDELT1', 1.0),\\n d_header.get('CDELT2', 1.0))\\n d_lookup = DistortionLookupTable(d_data, d_crpix, d_crval, d_cdelt)\\n tables[i] = d_lookup\\n\\n for key in set(header):\\n if key.startswith(dp + '.'):\\n del header[key]\\n else:\\n warnings.warn('Polynomial distortion is not implemented.\\\\n', AstropyUserWarning)\\n else:\\n tables[i] = None\\n\\n if not tables:\\n return (None, None)\\n else:\\n return (tables.get(1), tables.get(2))\\n\\n def _write_distortion_kw(self, hdulist, dist='CPDIS'):\\n \\\"\\\"\\\"\\n Write out `distortion paper`_ keywords to the given\\n `~astropy.io.fits.HDUList`.\\n \\\"\\\"\\\"\\n if self.cpdis1 is None and self.cpdis2 is None:\\n return\\n\\n if dist == 'CPDIS':\\n d_kw = 'DP'\\n else:\\n d_kw = 'DQ'\\n\\n def write_dist(num, cpdis):\\n if cpdis is None:\\n return\\n\\n hdulist[0].header[f'{dist}{num:d}'] = (\\n 'LOOKUP', 'Prior distortion function type')\\n hdulist[0].header[f'{d_kw}{num:d}.EXTVER'] = (\\n num, 'Version number of WCSDVARR extension')\\n hdulist[0].header[f'{d_kw}{num:d}.NAXES'] = (\\n len(cpdis.data.shape), f'Number of independent variables in {dist} function')\\n\\n for i in range(cpdis.data.ndim):\\n jth = {1: '1st', 2: '2nd', 3: '3rd'}.get(i + 1, f'{i + 1}th')\\n hdulist[0].header[f'{d_kw}{num:d}.AXIS.{i + 1:d}'] = (\\n i + 1,\\n f'Axis number of the {jth} variable in a {dist} function')\\n\\n image = fits.ImageHDU(cpdis.data, name='WCSDVARR')\\n header = image.header\\n\\n header['CRPIX1'] = (cpdis.crpix[0], 'Coordinate system reference pixel')\\n header['CRPIX2'] = (cpdis.crpix[1], 'Coordinate system reference pixel')\\n header['CRVAL1'] = (cpdis.crval[0], 'Coordinate system value at reference pixel')\\n header['CRVAL2'] = (cpdis.crval[1], 'Coordinate system value at reference pixel')\\n header['CDELT1'] = (cpdis.cdelt[0], 'Coordinate increment along axis')\\n header['CDELT2'] = (cpdis.cdelt[1], 'Coordinate increment along axis')\\n image.ver = int(hdulist[0].header[f'{d_kw}{num:d}.EXTVER'])\\n hdulist.append(image)\\n\\n write_dist(1, self.cpdis1)\\n write_dist(2, self.cpdis2)\\n\\n def _remove_sip_kw(self, header):\\n \\\"\\\"\\\"\\n Remove SIP information from a header.\\n \\\"\\\"\\\"\\n # Never pass SIP coefficients to wcslib\\n # CTYPE must be passed with -SIP to wcslib\\n for key in set(m.group() for m in map(SIP_KW.match, list(header))\\n if m is not None):\\n del header[key]\\n\\n def _read_sip_kw(self, header, wcskey=\\\"\\\"):\\n \\\"\\\"\\\"\\n Reads `SIP`_ header keywords and returns a `~astropy.wcs.Sip`\\n object.\\n\\n If no `SIP`_ header keywords are found, ``None`` is returned.\\n \\\"\\\"\\\"\\n if isinstance(header, (str, bytes)):\\n # TODO: Parse SIP from a string without pyfits around\\n return None\\n\\n if \\\"A_ORDER\\\" in header and header['A_ORDER'] > 1:\\n if \\\"B_ORDER\\\" not in header:\\n raise ValueError(\\n \\\"A_ORDER provided without corresponding B_ORDER \\\"\\n \\\"keyword for SIP distortion\\\")\\n\\n m = int(header[\\\"A_ORDER\\\"])\\n a = np.zeros((m + 1, m + 1), np.double)\\n for i in range(m + 1):\\n for j in range(m - i + 1):\\n key = f\\\"A_{i}_{j}\\\"\\n if key in header:\\n a[i, j] = header[key]\\n del header[key]\\n\\n m = int(header[\\\"B_ORDER\\\"])\\n if m > 1:\\n b = np.zeros((m + 1, m + 1), np.double)\\n for i in range(m + 1):\\n for j in range(m - i + 1):\\n key = f\\\"B_{i}_{j}\\\"\\n if key in header:\\n b[i, j] = header[key]\\n del header[key]\\n else:\\n a = None\\n b = None\\n\\n del header['A_ORDER']\\n del header['B_ORDER']\\n\\n ctype = [header[f'CTYPE{nax}{wcskey}'] for nax in range(1, self.naxis + 1)]\\n if any(not ctyp.endswith('-SIP') for ctyp in ctype):\\n message = \\\"\\\"\\\"\\n Inconsistent SIP distortion information is present in the FITS header and the WCS object:\\n SIP coefficients were detected, but CTYPE is missing a \\\"-SIP\\\" suffix.\\n astropy.wcs is using the SIP distortion coefficients,\\n therefore the coordinates calculated here might be incorrect.\\n\\n If you do not want to apply the SIP distortion coefficients,\\n please remove the SIP coefficients from the FITS header or the\\n WCS object. As an example, if the image is already distortion-corrected\\n (e.g., drizzled) then distortion components should not apply and the SIP\\n coefficients should be removed.\\n\\n While the SIP distortion coefficients are being applied here, if that was indeed the intent,\\n for consistency please append \\\"-SIP\\\" to the CTYPE in the FITS header or the WCS object.\\n\\n \\\"\\\"\\\" # noqa: E501\\n log.info(message)\\n elif \\\"B_ORDER\\\" in header and header['B_ORDER'] > 1:\\n raise ValueError(\\n \\\"B_ORDER provided without corresponding A_ORDER \\\" +\\n \\\"keyword for SIP distortion\\\")\\n else:\\n a = None\\n b = None\\n\\n if \\\"AP_ORDER\\\" in header and header['AP_ORDER'] > 1:\\n if \\\"BP_ORDER\\\" not in header:\\n raise ValueError(\\n \\\"AP_ORDER provided without corresponding BP_ORDER \\\"\\n \\\"keyword for SIP distortion\\\")\\n\\n m = int(header[\\\"AP_ORDER\\\"])\\n ap = np.zeros((m + 1, m + 1), np.double)\\n for i in range(m + 1):\\n for j in range(m - i + 1):\\n key = f\\\"AP_{i}_{j}\\\"\\n if key in header:\\n ap[i, j] = header[key]\\n del header[key]\\n\\n m = int(header[\\\"BP_ORDER\\\"])\\n if m > 1:\\n bp = np.zeros((m + 1, m + 1), np.double)\\n for i in range(m + 1):\\n for j in range(m - i + 1):\\n key = f\\\"BP_{i}_{j}\\\"\\n if key in header:\\n bp[i, j] = header[key]\\n del header[key]\\n else:\\n ap = None\\n bp = None\\n\\n del header['AP_ORDER']\\n del header['BP_ORDER']\\n elif \\\"BP_ORDER\\\" in header and header['BP_ORDER'] > 1:\\n raise ValueError(\\n \\\"BP_ORDER provided without corresponding AP_ORDER \\\"\\n \\\"keyword for SIP distortion\\\")\\n else:\\n ap = None\\n bp = None\\n\\n if a is None and b is None and ap is None and bp is None:\\n return None\\n\\n if f\\\"CRPIX1{wcskey}\\\" not in header or f\\\"CRPIX2{wcskey}\\\" not in header:\\n raise ValueError(\\n \\\"Header has SIP keywords without CRPIX keywords\\\")\\n\\n crpix1 = header.get(f\\\"CRPIX1{wcskey}\\\")\\n crpix2 = header.get(f\\\"CRPIX2{wcskey}\\\")\\n\\n return Sip(a, b, ap, bp, (crpix1, crpix2))\\n\\n def _write_sip_kw(self):\\n \\\"\\\"\\\"\\n Write out SIP keywords. Returns a dictionary of key-value\\n pairs.\\n \\\"\\\"\\\"\\n if self.sip is None:\\n return {}\\n\\n keywords = {}\\n\\n def write_array(name, a):\\n if a is None:\\n return\\n size = a.shape[0]\\n trdir = 'sky to detector' if name[-1] == 'P' else 'detector to sky'\\n comment = ('SIP polynomial order, axis {:d}, {:s}'\\n .format(ord(name[0]) - ord('A'), trdir))\\n keywords[f'{name}_ORDER'] = size - 1, comment\\n\\n comment = 'SIP distortion coefficient'\\n for i in range(size):\\n for j in range(size - i):\\n if a[i, j] != 0.0:\\n keywords[\\n f'{name}_{i:d}_{j:d}'] = a[i, j], comment\\n\\n write_array('A', self.sip.a)\\n write_array('B', self.sip.b)\\n write_array('AP', self.sip.ap)\\n write_array('BP', self.sip.bp)\\n\\n return keywords\\n\\n def _denormalize_sky(self, sky):\\n if self.wcs.lngtyp != 'RA':\\n raise ValueError(\\n \\\"WCS does not have longitude type of 'RA', therefore \\\" +\\n \\\"(ra, dec) data can not be used as input\\\")\\n if self.wcs.lattyp != 'DEC':\\n raise ValueError(\\n \\\"WCS does not have longitude type of 'DEC', therefore \\\" +\\n \\\"(ra, dec) data can not be used as input\\\")\\n if self.wcs.naxis == 2:\\n if self.wcs.lng == 0 and self.wcs.lat == 1:\\n return sky\\n elif self.wcs.lng == 1 and self.wcs.lat == 0:\\n # Reverse the order of the columns\\n return sky[:, ::-1]\\n else:\\n raise ValueError(\\n \\\"WCS does not have longitude and latitude celestial \\\" +\\n \\\"axes, therefore (ra, dec) data can not be used as input\\\")\\n else:\\n if self.wcs.lng < 0 or self.wcs.lat < 0:\\n raise ValueError(\\n \\\"WCS does not have both longitude and latitude \\\"\\n \\\"celestial axes, therefore (ra, dec) data can not be \\\" +\\n \\\"used as input\\\")\\n out = np.zeros((sky.shape[0], self.wcs.naxis))\\n out[:, self.wcs.lng] = sky[:, 0]\\n out[:, self.wcs.lat] = sky[:, 1]\\n return out\\n\\n def _normalize_sky(self, sky):\\n if self.wcs.lngtyp != 'RA':\\n raise ValueError(\\n \\\"WCS does not have longitude type of 'RA', therefore \\\" +\\n \\\"(ra, dec) data can not be returned\\\")\\n if self.wcs.lattyp != 'DEC':\\n raise ValueError(\\n \\\"WCS does not have longitude type of 'DEC', therefore \\\" +\\n \\\"(ra, dec) data can not be returned\\\")\\n if self.wcs.naxis == 2:\\n if self.wcs.lng == 0 and self.wcs.lat == 1:\\n return sky\\n elif self.wcs.lng == 1 and self.wcs.lat == 0:\\n # Reverse the order of the columns\\n return sky[:, ::-1]\\n else:\\n raise ValueError(\\n \\\"WCS does not have longitude and latitude celestial \\\"\\n \\\"axes, therefore (ra, dec) data can not be returned\\\")\\n else:\\n if self.wcs.lng < 0 or self.wcs.lat < 0:\\n raise ValueError(\\n \\\"WCS does not have both longitude and latitude celestial \\\"\\n \\\"axes, therefore (ra, dec) data can not be returned\\\")\\n out = np.empty((sky.shape[0], 2))\\n out[:, 0] = sky[:, self.wcs.lng]\\n out[:, 1] = sky[:, self.wcs.lat]\\n return out\\n\\n def _array_converter(self, func, sky, *args, ra_dec_order=False):\\n \\\"\\\"\\\"\\n A helper function to support reading either a pair of arrays\\n or a single Nx2 array.\\n \\\"\\\"\\\"\\n\\n def _return_list_of_arrays(axes, origin):\\n if any([x.size == 0 for x in axes]):\\n return axes\\n\\n try:\\n axes = np.broadcast_arrays(*axes)\\n except ValueError:\\n raise ValueError(\\n \\\"Coordinate arrays are not broadcastable to each other\\\")\\n\\n xy = np.hstack([x.reshape((x.size, 1)) for x in axes])\\n\\n if ra_dec_order and sky == 'input':\\n xy = self._denormalize_sky(xy)\\n output = func(xy, origin)\\n if ra_dec_order and sky == 'output':\\n output = self._normalize_sky(output)\\n return (output[:, 0].reshape(axes[0].shape),\\n output[:, 1].reshape(axes[0].shape))\\n return [output[:, i].reshape(axes[0].shape)\\n for i in range(output.shape[1])]\\n\\n def _return_single_array(xy, origin):\\n if xy.shape[-1] != self.naxis:\\n raise ValueError(\\n \\\"When providing two arguments, the array must be \\\"\\n \\\"of shape (N, {})\\\".format(self.naxis))\\n if 0 in xy.shape:\\n return xy\\n if ra_dec_order and sky == 'input':\\n xy = self._denormalize_sky(xy)\\n result = func(xy, origin)\\n if ra_dec_order and sky == 'output':\\n result = self._normalize_sky(result)\\n return result\\n\\n if len(args) == 2:\\n try:\\n xy, origin = args\\n xy = np.asarray(xy)\\n origin = int(origin)\\n except Exception:\\n raise TypeError(\\n \\\"When providing two arguments, they must be \\\"\\n \\\"(coords[N][{}], origin)\\\".format(self.naxis))\\n if xy.shape == () or len(xy.shape) == 1:\\n return _return_list_of_arrays([xy], origin)\\n return _return_single_array(xy, origin)\\n\\n elif len(args) == self.naxis + 1:\\n axes = args[:-1]\\n origin = args[-1]\\n try:\\n axes = [np.asarray(x) for x in axes]\\n origin = int(origin)\\n except Exception:\\n raise TypeError(\\n \\\"When providing more than two arguments, they must be \\\" +\\n \\\"a 1-D array for each axis, followed by an origin.\\\")\\n\\n return _return_list_of_arrays(axes, origin)\\n\\n raise TypeError(\\n \\\"WCS projection has {0} dimensions, so expected 2 (an Nx{0} array \\\"\\n \\\"and the origin argument) or {1} arguments (the position in each \\\"\\n \\\"dimension, and the origin argument). Instead, {2} arguments were \\\"\\n \\\"given.\\\".format(\\n self.naxis, self.naxis + 1, len(args)))\\n\\n def all_pix2world(self, *args, **kwargs):\\n return self._array_converter(\\n self._all_pix2world, 'output', *args, **kwargs)\\n all_pix2world.__doc__ = \\\"\\\"\\\"\\n Transforms pixel coordinates to world coordinates.\\n\\n Performs all of the following in series:\\n\\n - Detector to image plane correction (if present in the\\n FITS file)\\n\\n - `SIP`_ distortion correction (if present in the FITS\\n file)\\n\\n - `distortion paper`_ table-lookup correction (if present\\n in the FITS file)\\n\\n - `wcslib`_ \\\"core\\\" WCS transformation\\n\\n Parameters\\n ----------\\n {}\\n\\n For a transformation that is not two-dimensional, the\\n two-argument form must be used.\\n\\n {}\\n\\n Returns\\n -------\\n\\n {}\\n\\n Notes\\n -----\\n The order of the axes for the result is determined by the\\n ``CTYPEia`` keywords in the FITS header, therefore it may not\\n always be of the form (*ra*, *dec*). The\\n `~astropy.wcs.Wcsprm.lat`, `~astropy.wcs.Wcsprm.lng`,\\n `~astropy.wcs.Wcsprm.lattyp` and `~astropy.wcs.Wcsprm.lngtyp`\\n members can be used to determine the order of the axes.\\n\\n Raises\\n ------\\n MemoryError\\n Memory allocation failed.\\n\\n SingularMatrixError\\n Linear transformation matrix is singular.\\n\\n InconsistentAxisTypesError\\n Inconsistent or unrecognized coordinate axis types.\\n\\n ValueError\\n Invalid parameter value.\\n\\n ValueError\\n Invalid coordinate transformation parameters.\\n\\n ValueError\\n x- and y-coordinate arrays are not the same size.\\n\\n InvalidTransformError\\n Invalid coordinate transformation parameters.\\n\\n InvalidTransformError\\n Ill-conditioned coordinate transformation parameters.\\n \\\"\\\"\\\".format(docstrings.TWO_OR_MORE_ARGS('naxis', 8),\\n docstrings.RA_DEC_ORDER(8),\\n docstrings.RETURNS('sky coordinates, in degrees', 8))\\n\\n def wcs_pix2world(self, *args, **kwargs):\\n if self.wcs is None:\\n raise ValueError(\\\"No basic WCS settings were created.\\\")\\n return self._array_converter(\\n lambda xy, o: self.wcs.p2s(xy, o)['world'],\\n 'output', *args, **kwargs)\\n wcs_pix2world.__doc__ = \\\"\\\"\\\"\\n Transforms pixel coordinates to world coordinates by doing\\n only the basic `wcslib`_ transformation.\\n\\n No `SIP`_ or `distortion paper`_ table lookup correction is\\n applied. To perform distortion correction, see\\n `~astropy.wcs.WCS.all_pix2world`,\\n `~astropy.wcs.WCS.sip_pix2foc`, `~astropy.wcs.WCS.p4_pix2foc`,\\n or `~astropy.wcs.WCS.pix2foc`.\\n\\n Parameters\\n ----------\\n {}\\n\\n For a transformation that is not two-dimensional, the\\n two-argument form must be used.\\n\\n {}\\n\\n Returns\\n -------\\n\\n {}\\n\\n Raises\\n ------\\n MemoryError\\n Memory allocation failed.\\n\\n SingularMatrixError\\n Linear transformation matrix is singular.\\n\\n InconsistentAxisTypesError\\n Inconsistent or unrecognized coordinate axis types.\\n\\n ValueError\\n Invalid parameter value.\\n\\n ValueError\\n Invalid coordinate transformation parameters.\\n\\n ValueError\\n x- and y-coordinate arrays are not the same size.\\n\\n InvalidTransformError\\n Invalid coordinate transformation parameters.\\n\\n InvalidTransformError\\n Ill-conditioned coordinate transformation parameters.\\n\\n Notes\\n -----\\n The order of the axes for the result is determined by the\\n ``CTYPEia`` keywords in the FITS header, therefore it may not\\n always be of the form (*ra*, *dec*). The\\n `~astropy.wcs.Wcsprm.lat`, `~astropy.wcs.Wcsprm.lng`,\\n `~astropy.wcs.Wcsprm.lattyp` and `~astropy.wcs.Wcsprm.lngtyp`\\n members can be used to determine the order of the axes.\\n\\n \\\"\\\"\\\".format(docstrings.TWO_OR_MORE_ARGS('naxis', 8),\\n docstrings.RA_DEC_ORDER(8),\\n docstrings.RETURNS('world coordinates, in degrees', 8))\\n\\n def _all_world2pix(self, world, origin, tolerance, maxiter, adaptive,\\n detect_divergence, quiet):\\n # ############################################################\\n # # DESCRIPTION OF THE NUMERICAL METHOD ##\\n # ############################################################\\n # In this section I will outline the method of solving\\n # the inverse problem of converting world coordinates to\\n # pixel coordinates (*inverse* of the direct transformation\\n # `all_pix2world`) and I will summarize some of the aspects\\n # of the method proposed here and some of the issues of the\\n # original `all_world2pix` (in relation to this method)\\n # discussed in https://github.com/astropy/astropy/issues/1977\\n # A more detailed discussion can be found here:\\n # https://github.com/astropy/astropy/pull/2373\\n #\\n #\\n # ### Background ###\\n #\\n #\\n # I will refer here to the [SIP Paper]\\n # (http://fits.gsfc.nasa.gov/registry/sip/SIP_distortion_v1_0.pdf).\\n # According to this paper, the effect of distortions as\\n # described in *their* equation (1) is:\\n #\\n # (1) x = CD*(u+f(u)),\\n #\\n # where `x` is a *vector* of \\\"intermediate spherical\\n # coordinates\\\" (equivalent to (x,y) in the paper) and `u`\\n # is a *vector* of \\\"pixel coordinates\\\", and `f` is a vector\\n # function describing geometrical distortions\\n # (see equations 2 and 3 in SIP Paper.\\n # However, I prefer to use `w` for \\\"intermediate world\\n # coordinates\\\", `x` for pixel coordinates, and assume that\\n # transformation `W` performs the **linear**\\n # (CD matrix + projection onto celestial sphere) part of the\\n # conversion from pixel coordinates to world coordinates.\\n # Then we can re-write (1) as:\\n #\\n # (2) w = W*(x+f(x)) = T(x)\\n #\\n # In `astropy.wcs.WCS` transformation `W` is represented by\\n # the `wcs_pix2world` member, while the combined (\\\"total\\\")\\n # transformation (linear part + distortions) is performed by\\n # `all_pix2world`. Below I summarize the notations and their\\n # equivalents in `astropy.wcs.WCS`:\\n #\\n # | Equation term | astropy.WCS/meaning |\\n # | ------------- | ---------------------------- |\\n # | `x` | pixel coordinates |\\n # | `w` | world coordinates |\\n # | `W` | `wcs_pix2world()` |\\n # | `W^{-1}` | `wcs_world2pix()` |\\n # | `T` | `all_pix2world()` |\\n # | `x+f(x)` | `pix2foc()` |\\n #\\n #\\n # ### Direct Solving of Equation (2) ###\\n #\\n #\\n # In order to find the pixel coordinates that correspond to\\n # given world coordinates `w`, it is necessary to invert\\n # equation (2): `x=T^{-1}(w)`, or solve equation `w==T(x)`\\n # for `x`. However, this approach has the following\\n # disadvantages:\\n # 1. It requires unnecessary transformations (see next\\n # section).\\n # 2. It is prone to \\\"RA wrapping\\\" issues as described in\\n # https://github.com/astropy/astropy/issues/1977\\n # (essentially because `all_pix2world` may return points with\\n # a different phase than user's input `w`).\\n #\\n #\\n # ### Description of the Method Used here ###\\n #\\n #\\n # By applying inverse linear WCS transformation (`W^{-1}`)\\n # to both sides of equation (2) and introducing notation `x'`\\n # (prime) for the pixels coordinates obtained from the world\\n # coordinates by applying inverse *linear* WCS transformation\\n # (\\\"focal plane coordinates\\\"):\\n #\\n # (3) x' = W^{-1}(w)\\n #\\n # we obtain the following equation:\\n #\\n # (4) x' = x+f(x),\\n #\\n # or,\\n #\\n # (5) x = x'-f(x)\\n #\\n # This equation is well suited for solving using the method\\n # of fixed-point iterations\\n # (http://en.wikipedia.org/wiki/Fixed-point_iteration):\\n #\\n # (6) x_{i+1} = x'-f(x_i)\\n #\\n # As an initial value of the pixel coordinate `x_0` we take\\n # \\\"focal plane coordinate\\\" `x'=W^{-1}(w)=wcs_world2pix(w)`.\\n # We stop iterations when `|x_{i+1}-x_i||x_i-x_{i-1}|`\\n # **when** `|x_{i+1}-x_i|>=tolerance` (when current\\n # approximation is close to the true solution,\\n # `|x_{i+1}-x_i|>|x_i-x_{i-1}|` may be due to rounding errors\\n # and we ignore such \\\"divergences\\\" when\\n # `|x_{i+1}-x_i|world transformations).\\n #\\n # As an added benefit, the process converges to the correct\\n # solution in just one iteration when distortions are not\\n # present (compare to\\n # https://github.com/astropy/astropy/issues/1977 and\\n # https://github.com/astropy/astropy/pull/2294): in this case\\n # `pix2foc` is the identical transformation\\n # `x_i=pix2foc(x_i)` and from equation (7) we get:\\n #\\n # x' = x_0 = wcs_world2pix(w)\\n # x_1 = x' - pix2foc(x_0) + x_0 = x' - pix2foc(x') + x' = x'\\n # = wcs_world2pix(w) = x_0\\n # =>\\n # |x_1-x_0| = 0 < tolerance (with tolerance > 0)\\n #\\n # However, for performance reasons, it is still better to\\n # avoid iterations altogether and return the exact linear\\n # solution (`wcs_world2pix`) right-away when non-linear\\n # distortions are not present by checking that attributes\\n # `sip`, `cpdis1`, `cpdis2`, `det2im1`, and `det2im2` are\\n # *all* `None`.\\n #\\n #\\n # ### Outline of the Algorithm ###\\n #\\n #\\n # While the proposed code is relatively long (considering\\n # the simplicity of the algorithm), this is due to: 1)\\n # checking if iterative solution is necessary at all; 2)\\n # checking for divergence; 3) re-implementation of the\\n # completely vectorized algorithm as an \\\"adaptive\\\" vectorized\\n # algorithm (for cases when some points diverge for which we\\n # want to stop iterations). In my tests, the adaptive version\\n # of the algorithm is about 50% slower than non-adaptive\\n # version for all HST images.\\n #\\n # The essential part of the vectorized non-adaptive algorithm\\n # (without divergence and other checks) can be described\\n # as follows:\\n #\\n # pix0 = self.wcs_world2pix(world, origin)\\n # pix = pix0.copy() # 0-order solution\\n #\\n # for k in range(maxiter):\\n # # find correction to the previous solution:\\n # dpix = self.pix2foc(pix, origin) - pix0\\n #\\n # # compute norm (L2) of the correction:\\n # dn = np.linalg.norm(dpix, axis=1)\\n #\\n # # apply correction:\\n # pix -= dpix\\n #\\n # # check convergence:\\n # if np.max(dn) < tolerance:\\n # break\\n #\\n # return pix\\n #\\n # Here, the input parameter `world` can be a `MxN` array\\n # where `M` is the number of coordinate axes in WCS and `N`\\n # is the number of points to be converted simultaneously to\\n # image coordinates.\\n #\\n #\\n # ### IMPORTANT NOTE: ###\\n #\\n # If, in the future releases of the `~astropy.wcs`,\\n # `pix2foc` will not apply all the required distortion\\n # corrections then in the code below, calls to `pix2foc` will\\n # have to be replaced with\\n # wcs_world2pix(all_pix2world(pix_list, origin), origin)\\n #\\n\\n # ############################################################\\n # # INITIALIZE ITERATIVE PROCESS: ##\\n # ############################################################\\n\\n # initial approximation (linear WCS based only)\\n pix0 = self.wcs_world2pix(world, origin)\\n\\n # Check that an iterative solution is required at all\\n # (when any of the non-CD-matrix-based corrections are\\n # present). If not required return the initial\\n # approximation (pix0).\\n if not self.has_distortion:\\n # No non-WCS corrections detected so\\n # simply return initial approximation:\\n return pix0\\n\\n pix = pix0.copy() # 0-order solution\\n\\n # initial correction:\\n dpix = self.pix2foc(pix, origin) - pix0\\n\\n # Update initial solution:\\n pix -= dpix\\n\\n # Norm (L2) squared of the correction:\\n dn = np.sum(dpix*dpix, axis=1)\\n dnprev = dn.copy() # if adaptive else dn\\n tol2 = tolerance**2\\n\\n # Prepare for iterative process\\n k = 1\\n ind = None\\n inddiv = None\\n\\n # Turn off numpy runtime warnings for 'invalid' and 'over':\\n old_invalid = np.geterr()['invalid']\\n old_over = np.geterr()['over']\\n np.seterr(invalid='ignore', over='ignore')\\n\\n # ############################################################\\n # # NON-ADAPTIVE ITERATIONS: ##\\n # ############################################################\\n if not adaptive:\\n # Fixed-point iterations:\\n while (np.nanmax(dn) >= tol2 and k < maxiter):\\n # Find correction to the previous solution:\\n dpix = self.pix2foc(pix, origin) - pix0\\n\\n # Compute norm (L2) squared of the correction:\\n dn = np.sum(dpix*dpix, axis=1)\\n\\n # Check for divergence (we do this in two stages\\n # to optimize performance for the most common\\n # scenario when successive approximations converge):\\n if detect_divergence:\\n divergent = (dn >= dnprev)\\n if np.any(divergent):\\n # Find solutions that have not yet converged:\\n slowconv = (dn >= tol2)\\n inddiv, = np.where(divergent & slowconv)\\n\\n if inddiv.shape[0] > 0:\\n # Update indices of elements that\\n # still need correction:\\n conv = (dn < dnprev)\\n iconv = np.where(conv)\\n\\n # Apply correction:\\n dpixgood = dpix[iconv]\\n pix[iconv] -= dpixgood\\n dpix[iconv] = dpixgood\\n\\n # For the next iteration choose\\n # non-divergent points that have not yet\\n # converged to the requested accuracy:\\n ind, = np.where(slowconv & conv)\\n pix0 = pix0[ind]\\n dnprev[ind] = dn[ind]\\n k += 1\\n\\n # Switch to adaptive iterations:\\n adaptive = True\\n break\\n # Save current correction magnitudes for later:\\n dnprev = dn\\n\\n # Apply correction:\\n pix -= dpix\\n k += 1\\n\\n # ############################################################\\n # # ADAPTIVE ITERATIONS: ##\\n # ############################################################\\n if adaptive:\\n if ind is None:\\n ind, = np.where(np.isfinite(pix).all(axis=1))\\n pix0 = pix0[ind]\\n\\n # \\\"Adaptive\\\" fixed-point iterations:\\n while (ind.shape[0] > 0 and k < maxiter):\\n # Find correction to the previous solution:\\n dpixnew = self.pix2foc(pix[ind], origin) - pix0\\n\\n # Compute norm (L2) of the correction:\\n dnnew = np.sum(np.square(dpixnew), axis=1)\\n\\n # Bookkeeping of corrections:\\n dnprev[ind] = dn[ind].copy()\\n dn[ind] = dnnew\\n\\n if detect_divergence:\\n # Find indices of pixels that are converging:\\n conv = (dnnew < dnprev[ind])\\n iconv = np.where(conv)\\n iiconv = ind[iconv]\\n\\n # Apply correction:\\n dpixgood = dpixnew[iconv]\\n pix[iiconv] -= dpixgood\\n dpix[iiconv] = dpixgood\\n\\n # Find indices of solutions that have not yet\\n # converged to the requested accuracy\\n # AND that do not diverge:\\n subind, = np.where((dnnew >= tol2) & conv)\\n\\n else:\\n # Apply correction:\\n pix[ind] -= dpixnew\\n dpix[ind] = dpixnew\\n\\n # Find indices of solutions that have not yet\\n # converged to the requested accuracy:\\n subind, = np.where(dnnew >= tol2)\\n\\n # Choose solutions that need more iterations:\\n ind = ind[subind]\\n pix0 = pix0[subind]\\n\\n k += 1\\n\\n # ############################################################\\n # # FINAL DETECTION OF INVALID, DIVERGING, ##\\n # # AND FAILED-TO-CONVERGE POINTS ##\\n # ############################################################\\n # Identify diverging and/or invalid points:\\n invalid = ((~np.all(np.isfinite(pix), axis=1)) &\\n (np.all(np.isfinite(world), axis=1)))\\n\\n # When detect_divergence==False, dnprev is outdated\\n # (it is the norm of the very first correction).\\n # Still better than nothing...\\n inddiv, = np.where(((dn >= tol2) & (dn >= dnprev)) | invalid)\\n if inddiv.shape[0] == 0:\\n inddiv = None\\n\\n # Identify points that did not converge within 'maxiter'\\n # iterations:\\n if k >= maxiter:\\n ind, = np.where((dn >= tol2) & (dn < dnprev) & (~invalid))\\n if ind.shape[0] == 0:\\n ind = None\\n else:\\n ind = None\\n\\n # Restore previous numpy error settings:\\n np.seterr(invalid=old_invalid, over=old_over)\\n\\n # ############################################################\\n # # RAISE EXCEPTION IF DIVERGING OR TOO SLOWLY CONVERGING ##\\n # # DATA POINTS HAVE BEEN DETECTED: ##\\n # ############################################################\\n if (ind is not None or inddiv is not None) and not quiet:\\n if inddiv is None:\\n raise NoConvergence(\\n \\\"'WCS.all_world2pix' failed to \\\"\\n \\\"converge to the requested accuracy after {:d} \\\"\\n \\\"iterations.\\\".format(k), best_solution=pix,\\n accuracy=np.abs(dpix), niter=k,\\n slow_conv=ind, divergent=None)\\n else:\\n raise NoConvergence(\\n \\\"'WCS.all_world2pix' failed to \\\"\\n \\\"converge to the requested accuracy.\\\\n\\\"\\n \\\"After {:d} iterations, the solution is diverging \\\"\\n \\\"at least for one input point.\\\"\\n .format(k), best_solution=pix,\\n accuracy=np.abs(dpix), niter=k,\\n slow_conv=ind, divergent=inddiv)\\n\\n return pix\\n\\n @deprecated_renamed_argument('accuracy', 'tolerance', '4.3')\\n def all_world2pix(self, *args, tolerance=1e-4, maxiter=20, adaptive=False,\\n detect_divergence=True, quiet=False, **kwargs):\\n if self.wcs is None:\\n raise ValueError(\\\"No basic WCS settings were created.\\\")\\n\\n return self._array_converter(\\n lambda *args, **kwargs:\\n self._all_world2pix(\\n *args, tolerance=tolerance, maxiter=maxiter,\\n adaptive=adaptive, detect_divergence=detect_divergence,\\n quiet=quiet),\\n 'input', *args, **kwargs\\n )\\n\\n all_world2pix.__doc__ = \\\"\\\"\\\"\\n all_world2pix(*arg, tolerance=1.0e-4, maxiter=20,\\n adaptive=False, detect_divergence=True, quiet=False)\\n\\n Transforms world coordinates to pixel coordinates, using\\n numerical iteration to invert the full forward transformation\\n `~astropy.wcs.WCS.all_pix2world` with complete\\n distortion model.\\n\\n\\n Parameters\\n ----------\\n {0}\\n\\n For a transformation that is not two-dimensional, the\\n two-argument form must be used.\\n\\n {1}\\n\\n tolerance : float, optional (default = 1.0e-4)\\n Tolerance of solution. Iteration terminates when the\\n iterative solver estimates that the \\\"true solution\\\" is\\n within this many pixels current estimate, more\\n specifically, when the correction to the solution found\\n during the previous iteration is smaller\\n (in the sense of the L2 norm) than ``tolerance``.\\n\\n maxiter : int, optional (default = 20)\\n Maximum number of iterations allowed to reach a solution.\\n\\n quiet : bool, optional (default = False)\\n Do not throw :py:class:`NoConvergence` exceptions when\\n the method does not converge to a solution with the\\n required accuracy within a specified number of maximum\\n iterations set by ``maxiter`` parameter. Instead,\\n simply return the found solution.\\n\\n Other Parameters\\n ----------------\\n adaptive : bool, optional (default = False)\\n Specifies whether to adaptively select only points that\\n did not converge to a solution within the required\\n accuracy for the next iteration. Default is recommended\\n for HST as well as most other instruments.\\n\\n .. note::\\n The :py:meth:`all_world2pix` uses a vectorized\\n implementation of the method of consecutive\\n approximations (see ``Notes`` section below) in which it\\n iterates over *all* input points *regardless* until\\n the required accuracy has been reached for *all* input\\n points. In some cases it may be possible that\\n *almost all* points have reached the required accuracy\\n but there are only a few of input data points for\\n which additional iterations may be needed (this\\n depends mostly on the characteristics of the geometric\\n distortions for a given instrument). In this situation\\n it may be advantageous to set ``adaptive`` = `True` in\\n which case :py:meth:`all_world2pix` will continue\\n iterating *only* over the points that have not yet\\n converged to the required accuracy. However, for the\\n HST's ACS/WFC detector, which has the strongest\\n distortions of all HST instruments, testing has\\n shown that enabling this option would lead to a about\\n 50-100% penalty in computational time (depending on\\n specifics of the image, geometric distortions, and\\n number of input points to be converted). Therefore,\\n for HST and possibly instruments, it is recommended\\n to set ``adaptive`` = `False`. The only danger in\\n getting this setting wrong will be a performance\\n penalty.\\n\\n .. note::\\n When ``detect_divergence`` is `True`,\\n :py:meth:`all_world2pix` will automatically switch\\n to the adaptive algorithm once divergence has been\\n detected.\\n\\n detect_divergence : bool, optional (default = True)\\n Specifies whether to perform a more detailed analysis\\n of the convergence to a solution. Normally\\n :py:meth:`all_world2pix` may not achieve the required\\n accuracy if either the ``tolerance`` or ``maxiter`` arguments\\n are too low. However, it may happen that for some\\n geometric distortions the conditions of convergence for\\n the the method of consecutive approximations used by\\n :py:meth:`all_world2pix` may not be satisfied, in which\\n case consecutive approximations to the solution will\\n diverge regardless of the ``tolerance`` or ``maxiter``\\n settings.\\n\\n When ``detect_divergence`` is `False`, these divergent\\n points will be detected as not having achieved the\\n required accuracy (without further details). In addition,\\n if ``adaptive`` is `False` then the algorithm will not\\n know that the solution (for specific points) is diverging\\n and will continue iterating and trying to \\\"improve\\\"\\n diverging solutions. This may result in ``NaN`` or\\n ``Inf`` values in the return results (in addition to a\\n performance penalties). Even when ``detect_divergence``\\n is `False`, :py:meth:`all_world2pix`, at the end of the\\n iterative process, will identify invalid results\\n (``NaN`` or ``Inf``) as \\\"diverging\\\" solutions and will\\n raise :py:class:`NoConvergence` unless the ``quiet``\\n parameter is set to `True`.\\n\\n When ``detect_divergence`` is `True`,\\n :py:meth:`all_world2pix` will detect points for which\\n current correction to the coordinates is larger than\\n the correction applied during the previous iteration\\n **if** the requested accuracy **has not yet been\\n achieved**. In this case, if ``adaptive`` is `True`,\\n these points will be excluded from further iterations and\\n if ``adaptive`` is `False`, :py:meth:`all_world2pix` will\\n automatically switch to the adaptive algorithm. Thus, the\\n reported divergent solution will be the latest converging\\n solution computed immediately *before* divergence\\n has been detected.\\n\\n .. note::\\n When accuracy has been achieved, small increases in\\n current corrections may be possible due to rounding\\n errors (when ``adaptive`` is `False`) and such\\n increases will be ignored.\\n\\n .. note::\\n Based on our testing using HST ACS/WFC images, setting\\n ``detect_divergence`` to `True` will incur about 5-20%\\n performance penalty with the larger penalty\\n corresponding to ``adaptive`` set to `True`.\\n Because the benefits of enabling this\\n feature outweigh the small performance penalty,\\n especially when ``adaptive`` = `False`, it is\\n recommended to set ``detect_divergence`` to `True`,\\n unless extensive testing of the distortion models for\\n images from specific instruments show a good stability\\n of the numerical method for a wide range of\\n coordinates (even outside the image itself).\\n\\n .. note::\\n Indices of the diverging inverse solutions will be\\n reported in the ``divergent`` attribute of the\\n raised :py:class:`NoConvergence` exception object.\\n\\n Returns\\n -------\\n\\n {2}\\n\\n Notes\\n -----\\n The order of the axes for the input world array is determined by\\n the ``CTYPEia`` keywords in the FITS header, therefore it may\\n not always be of the form (*ra*, *dec*). The\\n `~astropy.wcs.Wcsprm.lat`, `~astropy.wcs.Wcsprm.lng`,\\n `~astropy.wcs.Wcsprm.lattyp`, and\\n `~astropy.wcs.Wcsprm.lngtyp`\\n members can be used to determine the order of the axes.\\n\\n Using the method of fixed-point iterations approximations we\\n iterate starting with the initial approximation, which is\\n computed using the non-distortion-aware\\n :py:meth:`wcs_world2pix` (or equivalent).\\n\\n The :py:meth:`all_world2pix` function uses a vectorized\\n implementation of the method of consecutive approximations and\\n therefore it is highly efficient (>30x) when *all* data points\\n that need to be converted from sky coordinates to image\\n coordinates are passed at *once*. Therefore, it is advisable,\\n whenever possible, to pass as input a long array of all points\\n that need to be converted to :py:meth:`all_world2pix` instead\\n of calling :py:meth:`all_world2pix` for each data point. Also\\n see the note to the ``adaptive`` parameter.\\n\\n Raises\\n ------\\n NoConvergence\\n The method did not converge to a\\n solution to the required accuracy within a specified\\n number of maximum iterations set by the ``maxiter``\\n parameter. To turn off this exception, set ``quiet`` to\\n `True`. Indices of the points for which the requested\\n accuracy was not achieved (if any) will be listed in the\\n ``slow_conv`` attribute of the\\n raised :py:class:`NoConvergence` exception object.\\n\\n See :py:class:`NoConvergence` documentation for\\n more details.\\n\\n MemoryError\\n Memory allocation failed.\\n\\n SingularMatrixError\\n Linear transformation matrix is singular.\\n\\n InconsistentAxisTypesError\\n Inconsistent or unrecognized coordinate axis types.\\n\\n ValueError\\n Invalid parameter value.\\n\\n ValueError\\n Invalid coordinate transformation parameters.\\n\\n ValueError\\n x- and y-coordinate arrays are not the same size.\\n\\n InvalidTransformError\\n Invalid coordinate transformation parameters.\\n\\n InvalidTransformError\\n Ill-conditioned coordinate transformation parameters.\\n\\n Examples\\n --------\\n >>> import astropy.io.fits as fits\\n >>> import astropy.wcs as wcs\\n >>> import numpy as np\\n >>> import os\\n\\n >>> filename = os.path.join(wcs.__path__[0], 'tests/data/j94f05bgq_flt.fits')\\n >>> hdulist = fits.open(filename)\\n >>> w = wcs.WCS(hdulist[('sci',1)].header, hdulist)\\n >>> hdulist.close()\\n\\n >>> ra, dec = w.all_pix2world([1,2,3], [1,1,1], 1)\\n >>> print(ra) # doctest: +FLOAT_CMP\\n [ 5.52645627 5.52649663 5.52653698]\\n >>> print(dec) # doctest: +FLOAT_CMP\\n [-72.05171757 -72.05171276 -72.05170795]\\n >>> radec = w.all_pix2world([[1,1], [2,1], [3,1]], 1)\\n >>> print(radec) # doctest: +FLOAT_CMP\\n [[ 5.52645627 -72.05171757]\\n [ 5.52649663 -72.05171276]\\n [ 5.52653698 -72.05170795]]\\n >>> x, y = w.all_world2pix(ra, dec, 1)\\n >>> print(x) # doctest: +FLOAT_CMP\\n [ 1.00000238 2.00000237 3.00000236]\\n >>> print(y) # doctest: +FLOAT_CMP\\n [ 0.99999996 0.99999997 0.99999997]\\n >>> xy = w.all_world2pix(radec, 1)\\n >>> print(xy) # doctest: +FLOAT_CMP\\n [[ 1.00000238 0.99999996]\\n [ 2.00000237 0.99999997]\\n [ 3.00000236 0.99999997]]\\n >>> xy = w.all_world2pix(radec, 1, maxiter=3,\\n ... tolerance=1.0e-10, quiet=False)\\n Traceback (most recent call last):\\n ...\\n NoConvergence: 'WCS.all_world2pix' failed to converge to the\\n requested accuracy. After 3 iterations, the solution is\\n diverging at least for one input point.\\n\\n >>> # Now try to use some diverging data:\\n >>> divradec = w.all_pix2world([[1.0, 1.0],\\n ... [10000.0, 50000.0],\\n ... [3.0, 1.0]], 1)\\n >>> print(divradec) # doctest: +FLOAT_CMP\\n [[ 5.52645627 -72.05171757]\\n [ 7.15976932 -70.8140779 ]\\n [ 5.52653698 -72.05170795]]\\n\\n >>> # First, turn detect_divergence on:\\n >>> try: # doctest: +FLOAT_CMP\\n ... xy = w.all_world2pix(divradec, 1, maxiter=20,\\n ... tolerance=1.0e-4, adaptive=False,\\n ... detect_divergence=True,\\n ... quiet=False)\\n ... except wcs.wcs.NoConvergence as e:\\n ... print(\\\"Indices of diverging points: {{0}}\\\"\\n ... .format(e.divergent))\\n ... print(\\\"Indices of poorly converging points: {{0}}\\\"\\n ... .format(e.slow_conv))\\n ... print(\\\"Best solution:\\\\\\\\n{{0}}\\\".format(e.best_solution))\\n ... print(\\\"Achieved accuracy:\\\\\\\\n{{0}}\\\".format(e.accuracy))\\n Indices of diverging points: [1]\\n Indices of poorly converging points: None\\n Best solution:\\n [[ 1.00000238e+00 9.99999965e-01]\\n [ -1.99441636e+06 1.44309097e+06]\\n [ 3.00000236e+00 9.99999966e-01]]\\n Achieved accuracy:\\n [[ 6.13968380e-05 8.59638593e-07]\\n [ 8.59526812e+11 6.61713548e+11]\\n [ 6.09398446e-05 8.38759724e-07]]\\n >>> raise e\\n Traceback (most recent call last):\\n ...\\n NoConvergence: 'WCS.all_world2pix' failed to converge to the\\n requested accuracy. After 5 iterations, the solution is\\n diverging at least for one input point.\\n\\n >>> # This time turn detect_divergence off:\\n >>> try: # doctest: +FLOAT_CMP\\n ... xy = w.all_world2pix(divradec, 1, maxiter=20,\\n ... tolerance=1.0e-4, adaptive=False,\\n ... detect_divergence=False,\\n ... quiet=False)\\n ... except wcs.wcs.NoConvergence as e:\\n ... print(\\\"Indices of diverging points: {{0}}\\\"\\n ... .format(e.divergent))\\n ... print(\\\"Indices of poorly converging points: {{0}}\\\"\\n ... .format(e.slow_conv))\\n ... print(\\\"Best solution:\\\\\\\\n{{0}}\\\".format(e.best_solution))\\n ... print(\\\"Achieved accuracy:\\\\\\\\n{{0}}\\\".format(e.accuracy))\\n Indices of diverging points: [1]\\n Indices of poorly converging points: None\\n Best solution:\\n [[ 1.00000009 1. ]\\n [ nan nan]\\n [ 3.00000009 1. ]]\\n Achieved accuracy:\\n [[ 2.29417358e-06 3.21222995e-08]\\n [ nan nan]\\n [ 2.27407877e-06 3.13005639e-08]]\\n >>> raise e\\n Traceback (most recent call last):\\n ...\\n NoConvergence: 'WCS.all_world2pix' failed to converge to the\\n requested accuracy. After 6 iterations, the solution is\\n diverging at least for one input point.\\n\\n \\\"\\\"\\\".format(docstrings.TWO_OR_MORE_ARGS('naxis', 8),\\n docstrings.RA_DEC_ORDER(8),\\n docstrings.RETURNS('pixel coordinates', 8))\\n\\n def wcs_world2pix(self, *args, **kwargs):\\n if self.wcs is None:\\n raise ValueError(\\\"No basic WCS settings were created.\\\")\\n return self._array_converter(\\n lambda xy, o: self.wcs.s2p(xy, o)['pixcrd'],\\n 'input', *args, **kwargs)\\n wcs_world2pix.__doc__ = \\\"\\\"\\\"\\n Transforms world coordinates to pixel coordinates, using only\\n the basic `wcslib`_ WCS transformation. No `SIP`_ or\\n `distortion paper`_ table lookup transformation is applied.\\n\\n Parameters\\n ----------\\n {}\\n\\n For a transformation that is not two-dimensional, the\\n two-argument form must be used.\\n\\n {}\\n\\n Returns\\n -------\\n\\n {}\\n\\n Notes\\n -----\\n The order of the axes for the input world array is determined by\\n the ``CTYPEia`` keywords in the FITS header, therefore it may\\n not always be of the form (*ra*, *dec*). The\\n `~astropy.wcs.Wcsprm.lat`, `~astropy.wcs.Wcsprm.lng`,\\n `~astropy.wcs.Wcsprm.lattyp` and `~astropy.wcs.Wcsprm.lngtyp`\\n members can be used to determine the order of the axes.\\n\\n Raises\\n ------\\n MemoryError\\n Memory allocation failed.\\n\\n SingularMatrixError\\n Linear transformation matrix is singular.\\n\\n InconsistentAxisTypesError\\n Inconsistent or unrecognized coordinate axis types.\\n\\n ValueError\\n Invalid parameter value.\\n\\n ValueError\\n Invalid coordinate transformation parameters.\\n\\n ValueError\\n x- and y-coordinate arrays are not the same size.\\n\\n InvalidTransformError\\n Invalid coordinate transformation parameters.\\n\\n InvalidTransformError\\n Ill-conditioned coordinate transformation parameters.\\n \\\"\\\"\\\".format(docstrings.TWO_OR_MORE_ARGS('naxis', 8),\\n docstrings.RA_DEC_ORDER(8),\\n docstrings.RETURNS('pixel coordinates', 8))\\n\\n def pix2foc(self, *args):\\n return self._array_converter(self._pix2foc, None, *args)\\n pix2foc.__doc__ = \\\"\\\"\\\"\\n Convert pixel coordinates to focal plane coordinates using the\\n `SIP`_ polynomial distortion convention and `distortion\\n paper`_ table-lookup correction.\\n\\n The output is in absolute pixel coordinates, not relative to\\n ``CRPIX``.\\n\\n Parameters\\n ----------\\n\\n {}\\n\\n Returns\\n -------\\n\\n {}\\n\\n Raises\\n ------\\n MemoryError\\n Memory allocation failed.\\n\\n ValueError\\n Invalid coordinate transformation parameters.\\n \\\"\\\"\\\".format(docstrings.TWO_OR_MORE_ARGS('2', 8),\\n docstrings.RETURNS('focal coordinates', 8))\\n\\n def p4_pix2foc(self, *args):\\n return self._array_converter(self._p4_pix2foc, None, *args)\\n p4_pix2foc.__doc__ = \\\"\\\"\\\"\\n Convert pixel coordinates to focal plane coordinates using\\n `distortion paper`_ table-lookup correction.\\n\\n The output is in absolute pixel coordinates, not relative to\\n ``CRPIX``.\\n\\n Parameters\\n ----------\\n\\n {}\\n\\n Returns\\n -------\\n\\n {}\\n\\n Raises\\n ------\\n MemoryError\\n Memory allocation failed.\\n\\n ValueError\\n Invalid coordinate transformation parameters.\\n \\\"\\\"\\\".format(docstrings.TWO_OR_MORE_ARGS('2', 8),\\n docstrings.RETURNS('focal coordinates', 8))\\n\\n def det2im(self, *args):\\n return self._array_converter(self._det2im, None, *args)\\n det2im.__doc__ = \\\"\\\"\\\"\\n Convert detector coordinates to image plane coordinates using\\n `distortion paper`_ table-lookup correction.\\n\\n The output is in absolute pixel coordinates, not relative to\\n ``CRPIX``.\\n\\n Parameters\\n ----------\\n\\n {}\\n\\n Returns\\n -------\\n\\n {}\\n\\n Raises\\n ------\\n MemoryError\\n Memory allocation failed.\\n\\n ValueError\\n Invalid coordinate transformation parameters.\\n \\\"\\\"\\\".format(docstrings.TWO_OR_MORE_ARGS('2', 8),\\n docstrings.RETURNS('pixel coordinates', 8))\\n\\n def sip_pix2foc(self, *args):\\n if self.sip is None:\\n if len(args) == 2:\\n return args[0]\\n elif len(args) == 3:\\n return args[:2]\\n else:\\n raise TypeError(\\\"Wrong number of arguments\\\")\\n return self._array_converter(self.sip.pix2foc, None, *args)\\n sip_pix2foc.__doc__ = \\\"\\\"\\\"\\n Convert pixel coordinates to focal plane coordinates using the\\n `SIP`_ polynomial distortion convention.\\n\\n The output is in pixel coordinates, relative to ``CRPIX``.\\n\\n FITS WCS `distortion paper`_ table lookup correction is not\\n applied, even if that information existed in the FITS file\\n that initialized this :class:`~astropy.wcs.WCS` object. To\\n correct for that, use `~astropy.wcs.WCS.pix2foc` or\\n `~astropy.wcs.WCS.p4_pix2foc`.\\n\\n Parameters\\n ----------\\n\\n {}\\n\\n Returns\\n -------\\n\\n {}\\n\\n Raises\\n ------\\n MemoryError\\n Memory allocation failed.\\n\\n ValueError\\n Invalid coordinate transformation parameters.\\n \\\"\\\"\\\".format(docstrings.TWO_OR_MORE_ARGS('2', 8),\\n docstrings.RETURNS('focal coordinates', 8))\\n\\n def sip_foc2pix(self, *args):\\n if self.sip is None:\\n if len(args) == 2:\\n return args[0]\\n elif len(args) == 3:\\n return args[:2]\\n else:\\n raise TypeError(\\\"Wrong number of arguments\\\")\\n return self._array_converter(self.sip.foc2pix, None, *args)\\n sip_foc2pix.__doc__ = \\\"\\\"\\\"\\n Convert focal plane coordinates to pixel coordinates using the\\n `SIP`_ polynomial distortion convention.\\n\\n FITS WCS `distortion paper`_ table lookup distortion\\n correction is not applied, even if that information existed in\\n the FITS file that initialized this `~astropy.wcs.WCS` object.\\n\\n Parameters\\n ----------\\n\\n {}\\n\\n Returns\\n -------\\n\\n {}\\n\\n Raises\\n ------\\n MemoryError\\n Memory allocation failed.\\n\\n ValueError\\n Invalid coordinate transformation parameters.\\n \\\"\\\"\\\".format(docstrings.TWO_OR_MORE_ARGS('2', 8),\\n docstrings.RETURNS('pixel coordinates', 8))\\n\\n def proj_plane_pixel_scales(self):\\n \\\"\\\"\\\"\\n Calculate pixel scales along each axis of the image pixel at\\n the ``CRPIX`` location once it is projected onto the\\n \\\"plane of intermediate world coordinates\\\" as defined in\\n `Greisen & Calabretta 2002, A&A, 395, 1061 `_.\\n\\n .. note::\\n This method is concerned **only** about the transformation\\n \\\"image plane\\\"->\\\"projection plane\\\" and **not** about the\\n transformation \\\"celestial sphere\\\"->\\\"projection plane\\\"->\\\"image plane\\\".\\n Therefore, this function ignores distortions arising due to\\n non-linear nature of most projections.\\n\\n .. note::\\n This method only returns sensible answers if the WCS contains\\n celestial axes, i.e., the `~astropy.wcs.WCS.celestial` WCS object.\\n\\n Returns\\n -------\\n scale : list of `~astropy.units.Quantity`\\n A vector of projection plane increments corresponding to each\\n pixel side (axis).\\n\\n See Also\\n --------\\n astropy.wcs.utils.proj_plane_pixel_scales\\n\\n \\\"\\\"\\\" # noqa: E501\\n from astropy.wcs.utils import proj_plane_pixel_scales # Avoid circular import\\n values = proj_plane_pixel_scales(self)\\n units = [u.Unit(x) for x in self.wcs.cunit]\\n return [value * unit for (value, unit) in zip(values, units)] # Can have different units\\n\\n def proj_plane_pixel_area(self):\\n \\\"\\\"\\\"\\n For a **celestial** WCS (see `astropy.wcs.WCS.celestial`), returns pixel\\n area of the image pixel at the ``CRPIX`` location once it is projected\\n onto the \\\"plane of intermediate world coordinates\\\" as defined in\\n `Greisen & Calabretta 2002, A&A, 395, 1061 `_.\\n\\n .. note::\\n This function is concerned **only** about the transformation\\n \\\"image plane\\\"->\\\"projection plane\\\" and **not** about the\\n transformation \\\"celestial sphere\\\"->\\\"projection plane\\\"->\\\"image plane\\\".\\n Therefore, this function ignores distortions arising due to\\n non-linear nature of most projections.\\n\\n .. note::\\n This method only returns sensible answers if the WCS contains\\n celestial axes, i.e., the `~astropy.wcs.WCS.celestial` WCS object.\\n\\n Returns\\n -------\\n area : `~astropy.units.Quantity`\\n Area (in the projection plane) of the pixel at ``CRPIX`` location.\\n\\n Raises\\n ------\\n ValueError\\n Pixel area is defined only for 2D pixels. Most likely the\\n `~astropy.wcs.Wcsprm.cd` matrix of the `~astropy.wcs.WCS.celestial`\\n WCS is not a square matrix of second order.\\n\\n Notes\\n -----\\n\\n Depending on the application, square root of the pixel area can be used to\\n represent a single pixel scale of an equivalent square pixel\\n whose area is equal to the area of a generally non-square pixel.\\n\\n See Also\\n --------\\n astropy.wcs.utils.proj_plane_pixel_area\\n\\n \\\"\\\"\\\" # noqa: E501\\n from astropy.wcs.utils import proj_plane_pixel_area # Avoid circular import\\n value = proj_plane_pixel_area(self)\\n unit = u.Unit(self.wcs.cunit[0]) * u.Unit(self.wcs.cunit[1]) # 2D only\\n return value * unit\\n\\n def to_fits(self, relax=False, key=None):\\n \\\"\\\"\\\"\\n Generate an `~astropy.io.fits.HDUList` object with all of the\\n information stored in this object. This should be logically identical\\n to the input FITS file, but it will be normalized in a number of ways.\\n\\n See `to_header` for some warnings about the output produced.\\n\\n Parameters\\n ----------\\n\\n relax : bool or int, optional\\n Degree of permissiveness:\\n\\n - `False` (default): Write all extensions that are\\n considered to be safe and recommended.\\n\\n - `True`: Write all recognized informal extensions of the\\n WCS standard.\\n\\n - `int`: a bit field selecting specific extensions to\\n write. See :ref:`astropy:relaxwrite` for details.\\n\\n key : str\\n The name of a particular WCS transform to use. This may be\\n either ``' '`` or ``'A'``-``'Z'`` and corresponds to the ``\\\"a\\\"``\\n part of the ``CTYPEia`` cards.\\n\\n Returns\\n -------\\n hdulist : `~astropy.io.fits.HDUList`\\n \\\"\\\"\\\"\\n\\n header = self.to_header(relax=relax, key=key)\\n\\n hdu = fits.PrimaryHDU(header=header)\\n hdulist = fits.HDUList(hdu)\\n\\n self._write_det2im(hdulist)\\n self._write_distortion_kw(hdulist)\\n\\n return hdulist\\n\\n def to_header(self, relax=None, key=None):\\n \\\"\\\"\\\"Generate an `astropy.io.fits.Header` object with the basic WCS\\n and SIP information stored in this object. This should be\\n logically identical to the input FITS file, but it will be\\n normalized in a number of ways.\\n\\n .. warning::\\n\\n This function does not write out FITS WCS `distortion\\n paper`_ information, since that requires multiple FITS\\n header data units. To get a full representation of\\n everything in this object, use `to_fits`.\\n\\n Parameters\\n ----------\\n relax : bool or int, optional\\n Degree of permissiveness:\\n\\n - `False` (default): Write all extensions that are\\n considered to be safe and recommended.\\n\\n - `True`: Write all recognized informal extensions of the\\n WCS standard.\\n\\n - `int`: a bit field selecting specific extensions to\\n write. See :ref:`astropy:relaxwrite` for details.\\n\\n If the ``relax`` keyword argument is not given and any\\n keywords were omitted from the output, an\\n `~astropy.utils.exceptions.AstropyWarning` is displayed.\\n To override this, explicitly pass a value to ``relax``.\\n\\n key : str\\n The name of a particular WCS transform to use. This may be\\n either ``' '`` or ``'A'``-``'Z'`` and corresponds to the ``\\\"a\\\"``\\n part of the ``CTYPEia`` cards.\\n\\n Returns\\n -------\\n header : `astropy.io.fits.Header`\\n\\n Notes\\n -----\\n The output header will almost certainly differ from the input in a\\n number of respects:\\n\\n 1. The output header only contains WCS-related keywords. In\\n particular, it does not contain syntactically-required\\n keywords such as ``SIMPLE``, ``NAXIS``, ``BITPIX``, or\\n ``END``.\\n\\n 2. Deprecated (e.g. ``CROTAn``) or non-standard usage will\\n be translated to standard (this is partially dependent on\\n whether ``fix`` was applied).\\n\\n 3. Quantities will be converted to the units used internally,\\n basically SI with the addition of degrees.\\n\\n 4. Floating-point quantities may be given to a different decimal\\n precision.\\n\\n 5. Elements of the ``PCi_j`` matrix will be written if and\\n only if they differ from the unit matrix. Thus, if the\\n matrix is unity then no elements will be written.\\n\\n 6. Additional keywords such as ``WCSAXES``, ``CUNITia``,\\n ``LONPOLEa`` and ``LATPOLEa`` may appear.\\n\\n 7. The original keycomments will be lost, although\\n `to_header` tries hard to write meaningful comments.\\n\\n 8. Keyword order may be changed.\\n\\n \\\"\\\"\\\"\\n # default precision for numerical WCS keywords\\n precision = WCSHDO_P14 # Defined by C-ext # noqa: F821\\n display_warning = False\\n if relax is None:\\n display_warning = True\\n relax = False\\n\\n if relax not in (True, False):\\n do_sip = relax & WCSHDO_SIP\\n relax &= ~WCSHDO_SIP\\n else:\\n do_sip = relax\\n relax = WCSHDO_all if relax is True else WCSHDO_safe # Defined by C-ext # noqa: F821\\n\\n relax = precision | relax\\n\\n if self.wcs is not None:\\n if key is not None:\\n orig_key = self.wcs.alt\\n self.wcs.alt = key\\n header_string = self.wcs.to_header(relax)\\n header = fits.Header.fromstring(header_string)\\n keys_to_remove = [\\\"\\\", \\\" \\\", \\\"COMMENT\\\"]\\n for kw in keys_to_remove:\\n if kw in header:\\n del header[kw]\\n # Check if we can handle TPD distortion correctly\\n if int(_parsed_version[0]) * 10 + int(_parsed_version[1]) < 71:\\n for kw, val in header.items():\\n if kw[:5] in ('CPDIS', 'CQDIS') and val == 'TPD':\\n warnings.warn(\\n f\\\"WCS contains a TPD distortion model in {kw}. WCSLIB \\\"\\n f\\\"{_wcs.__version__} is writing this in a format incompatible with \\\"\\n f\\\"current versions - please update to 7.4 or use the bundled WCSLIB.\\\",\\n AstropyWarning)\\n elif int(_parsed_version[0]) * 10 + int(_parsed_version[1]) < 74:\\n for kw, val in header.items():\\n if kw[:5] in ('CPDIS', 'CQDIS') and val == 'TPD':\\n warnings.warn(\\n f\\\"WCS contains a TPD distortion model in {kw}, which requires WCSLIB \\\"\\n f\\\"7.4 or later to store in a FITS header (having {_wcs.__version__}).\\\",\\n AstropyWarning)\\n else:\\n header = fits.Header()\\n\\n if do_sip and self.sip is not None:\\n if self.wcs is not None and any(not ctyp.endswith('-SIP') for ctyp in self.wcs.ctype):\\n self._fix_ctype(header, add_sip=True)\\n\\n for kw, val in self._write_sip_kw().items():\\n header[kw] = val\\n\\n if not do_sip and self.wcs is not None and any(self.wcs.ctype) and self.sip is not None:\\n # This is called when relax is not False or WCSHDO_SIP\\n # The default case of ``relax=None`` is handled further in the code.\\n header = self._fix_ctype(header, add_sip=False)\\n\\n if display_warning:\\n full_header = self.to_header(relax=True, key=key)\\n missing_keys = []\\n for kw, val in full_header.items():\\n if kw not in header:\\n missing_keys.append(kw)\\n\\n if len(missing_keys):\\n warnings.warn(\\n \\\"Some non-standard WCS keywords were excluded: {} \\\"\\n \\\"Use the ``relax`` kwarg to control this.\\\".format(\\n ', '.join(missing_keys)),\\n AstropyWarning)\\n # called when ``relax=None``\\n # This is different from the case of ``relax=False``.\\n if any(self.wcs.ctype) and self.sip is not None:\\n header = self._fix_ctype(header, add_sip=False, log_message=False)\\n # Finally reset the key. This must be called after ``_fix_ctype``.\\n if key is not None:\\n self.wcs.alt = orig_key\\n return header\\n\\n def _fix_ctype(self, header, add_sip=True, log_message=True):\\n \\\"\\\"\\\"\\n Parameters\\n ----------\\n header : `~astropy.io.fits.Header`\\n FITS header.\\n add_sip : bool\\n Flag indicating whether \\\"-SIP\\\" should be added or removed from CTYPE keywords.\\n\\n Remove \\\"-SIP\\\" from CTYPE when writing out a header with relax=False.\\n This needs to be done outside ``to_header`` because ``to_header`` runs\\n twice when ``relax=False`` and the second time ``relax`` is set to ``True``\\n to display the missing keywords.\\n\\n If the user requested SIP distortion to be written out add \\\"-SIP\\\" to\\n CTYPE if it is missing.\\n \\\"\\\"\\\"\\n\\n _add_sip_to_ctype = \\\"\\\"\\\"\\n Inconsistent SIP distortion information is present in the current WCS:\\n SIP coefficients were detected, but CTYPE is missing \\\"-SIP\\\" suffix,\\n therefore the current WCS is internally inconsistent.\\n\\n Because relax has been set to True, the resulting output WCS will have\\n \\\"-SIP\\\" appended to CTYPE in order to make the header internally consistent.\\n\\n However, this may produce incorrect astrometry in the output WCS, if\\n in fact the current WCS is already distortion-corrected.\\n\\n Therefore, if current WCS is already distortion-corrected (eg, drizzled)\\n then SIP distortion components should not apply. In that case, for a WCS\\n that is already distortion-corrected, please remove the SIP coefficients\\n from the header.\\n\\n \\\"\\\"\\\"\\n if log_message:\\n if add_sip:\\n log.info(_add_sip_to_ctype)\\n for i in range(1, self.naxis+1):\\n # strip() must be called here to cover the case of alt key= \\\" \\\"\\n kw = f'CTYPE{i}{self.wcs.alt}'.strip()\\n if kw in header:\\n if add_sip:\\n val = header[kw].strip(\\\"-SIP\\\") + \\\"-SIP\\\"\\n else:\\n val = header[kw].strip(\\\"-SIP\\\")\\n header[kw] = val\\n else:\\n continue\\n return header\\n\\n def to_header_string(self, relax=None):\\n \\\"\\\"\\\"\\n Identical to `to_header`, but returns a string containing the\\n header cards.\\n \\\"\\\"\\\"\\n return str(self.to_header(relax))\\n\\n def footprint_to_file(self, filename='footprint.reg', color='green',\\n width=2, coordsys=None):\\n \\\"\\\"\\\"\\n Writes out a `ds9`_ style regions file. It can be loaded\\n directly by `ds9`_.\\n\\n Parameters\\n ----------\\n filename : str, optional\\n Output file name - default is ``'footprint.reg'``\\n\\n color : str, optional\\n Color to use when plotting the line.\\n\\n width : int, optional\\n Width of the region line.\\n\\n coordsys : str, optional\\n Coordinate system. If not specified (default), the ``radesys``\\n value is used. For all possible values, see\\n http://ds9.si.edu/doc/ref/region.html#RegionFileFormat\\n\\n \\\"\\\"\\\"\\n comments = ('# Region file format: DS9 version 4.0 \\\\n'\\n '# global color=green font=\\\"helvetica 12 bold '\\n 'select=1 highlite=1 edit=1 move=1 delete=1 '\\n 'include=1 fixed=0 source\\\\n')\\n\\n coordsys = coordsys or self.wcs.radesys\\n\\n if coordsys not in ('PHYSICAL', 'IMAGE', 'FK4', 'B1950', 'FK5',\\n 'J2000', 'GALACTIC', 'ECLIPTIC', 'ICRS', 'LINEAR',\\n 'AMPLIFIER', 'DETECTOR'):\\n raise ValueError(\\\"Coordinate system '{}' is not supported. A valid\\\"\\n \\\" one can be given with the 'coordsys' argument.\\\"\\n .format(coordsys))\\n\\n with open(filename, mode='w') as f:\\n f.write(comments)\\n f.write(f'{coordsys}\\\\n')\\n f.write('polygon(')\\n ftpr = self.calc_footprint()\\n if ftpr is not None:\\n ftpr.tofile(f, sep=',')\\n f.write(f') # color={color}, width={width:d} \\\\n')\\n\\n def _get_naxis(self, header=None):\\n _naxis = []\\n if (header is not None and\\n not isinstance(header, (str, bytes))):\\n for naxis in itertools.count(1):\\n try:\\n _naxis.append(header[f'NAXIS{naxis}'])\\n except KeyError:\\n break\\n if len(_naxis) == 0:\\n _naxis = [0, 0]\\n elif len(_naxis) == 1:\\n _naxis.append(0)\\n self._naxis = _naxis\\n\\n def printwcs(self):\\n print(repr(self))\\n\\n def __repr__(self):\\n '''\\n Return a short description. Simply porting the behavior from\\n the `printwcs()` method.\\n '''\\n description = [\\\"WCS Keywords\\\\n\\\",\\n f\\\"Number of WCS axes: {self.naxis!r}\\\"]\\n sfmt = ' : ' + \\\"\\\".join([\\\"{\\\"+f\\\"{i}\\\"+\\\"!r} \\\" for i in range(self.naxis)])\\n\\n keywords = ['CTYPE', 'CRVAL', 'CRPIX']\\n values = [self.wcs.ctype, self.wcs.crval, self.wcs.crpix]\\n for keyword, value in zip(keywords, values):\\n description.append(keyword+sfmt.format(*value))\\n\\n if hasattr(self.wcs, 'pc'):\\n for i in range(self.naxis):\\n s = ''\\n for j in range(self.naxis):\\n s += ''.join(['PC', str(i+1), '_', str(j+1), ' '])\\n s += sfmt\\n description.append(s.format(*self.wcs.pc[i]))\\n s = 'CDELT' + sfmt\\n description.append(s.format(*self.wcs.cdelt))\\n elif hasattr(self.wcs, 'cd'):\\n for i in range(self.naxis):\\n s = ''\\n for j in range(self.naxis):\\n s += \\\"\\\".join(['CD', str(i+1), '_', str(j+1), ' '])\\n s += sfmt\\n description.append(s.format(*self.wcs.cd[i]))\\n\\n description.append(f\\\"NAXIS : {' '.join(map(str, self._naxis))}\\\")\\n return '\\\\n'.join(description)\\n\\n def get_axis_types(self):\\n \\\"\\\"\\\"\\n Similar to `self.wcsprm.axis_types `\\n but provides the information in a more Python-friendly format.\\n\\n Returns\\n -------\\n result : list of dict\\n\\n Returns a list of dictionaries, one for each axis, each\\n containing attributes about the type of that axis.\\n\\n Each dictionary has the following keys:\\n\\n - 'coordinate_type':\\n\\n - None: Non-specific coordinate type.\\n\\n - 'stokes': Stokes coordinate.\\n\\n - 'celestial': Celestial coordinate (including ``CUBEFACE``).\\n\\n - 'spectral': Spectral coordinate.\\n\\n - 'scale':\\n\\n - 'linear': Linear axis.\\n\\n - 'quantized': Quantized axis (``STOKES``, ``CUBEFACE``).\\n\\n - 'non-linear celestial': Non-linear celestial axis.\\n\\n - 'non-linear spectral': Non-linear spectral axis.\\n\\n - 'logarithmic': Logarithmic axis.\\n\\n - 'tabular': Tabular axis.\\n\\n - 'group'\\n\\n - Group number, e.g. lookup table number\\n\\n - 'number'\\n\\n - For celestial axes:\\n\\n - 0: Longitude coordinate.\\n\\n - 1: Latitude coordinate.\\n\\n - 2: ``CUBEFACE`` number.\\n\\n - For lookup tables:\\n\\n - the axis number in a multidimensional table.\\n\\n ``CTYPEia`` in ``\\\"4-3\\\"`` form with unrecognized algorithm code will\\n generate an error.\\n \\\"\\\"\\\"\\n if self.wcs is None:\\n raise AttributeError(\\n \\\"This WCS object does not have a wcsprm object.\\\")\\n\\n coordinate_type_map = {\\n 0: None,\\n 1: 'stokes',\\n 2: 'celestial',\\n 3: 'spectral'}\\n\\n scale_map = {\\n 0: 'linear',\\n 1: 'quantized',\\n 2: 'non-linear celestial',\\n 3: 'non-linear spectral',\\n 4: 'logarithmic',\\n 5: 'tabular'}\\n\\n result = []\\n for axis_type in self.wcs.axis_types:\\n subresult = {}\\n\\n coordinate_type = (axis_type // 1000) % 10\\n subresult['coordinate_type'] = coordinate_type_map[coordinate_type]\\n\\n scale = (axis_type // 100) % 10\\n subresult['scale'] = scale_map[scale]\\n\\n group = (axis_type // 10) % 10\\n subresult['group'] = group\\n\\n number = axis_type % 10\\n subresult['number'] = number\\n\\n result.append(subresult)\\n\\n return result\\n\\n def __reduce__(self):\\n \\\"\\\"\\\"\\n Support pickling of WCS objects. This is done by serializing\\n to an in-memory FITS file and dumping that as a string.\\n \\\"\\\"\\\"\\n\\n hdulist = self.to_fits(relax=True)\\n\\n buffer = io.BytesIO()\\n hdulist.writeto(buffer)\\n\\n dct = self.__dict__.copy()\\n dct['_alt_wcskey'] = self.wcs.alt\\n\\n return (__WCS_unpickle__,\\n (self.__class__, dct, buffer.getvalue(),))\\n\\n def dropaxis(self, dropax):\\n \\\"\\\"\\\"\\n Remove an axis from the WCS.\\n\\n Parameters\\n ----------\\n wcs : `~astropy.wcs.WCS`\\n The WCS with naxis to be chopped to naxis-1\\n dropax : int\\n The index of the WCS to drop, counting from 0 (i.e., python convention,\\n not FITS convention)\\n\\n Returns\\n -------\\n `~astropy.wcs.WCS`\\n A new `~astropy.wcs.WCS` instance with one axis fewer\\n \\\"\\\"\\\"\\n inds = list(range(self.wcs.naxis))\\n inds.pop(dropax)\\n\\n # axis 0 has special meaning to sub\\n # if wcs.wcs.ctype == ['RA','DEC','VLSR'], you want\\n # wcs.sub([1,2]) to get 'RA','DEC' back\\n return self.sub([i+1 for i in inds])\\n\\n def swapaxes(self, ax0, ax1):\\n \\\"\\\"\\\"\\n Swap axes in a WCS.\\n\\n Parameters\\n ----------\\n wcs : `~astropy.wcs.WCS`\\n The WCS to have its axes swapped\\n ax0 : int\\n ax1 : int\\n The indices of the WCS to be swapped, counting from 0 (i.e., python\\n convention, not FITS convention)\\n\\n Returns\\n -------\\n `~astropy.wcs.WCS`\\n A new `~astropy.wcs.WCS` instance with the same number of axes,\\n but two swapped\\n \\\"\\\"\\\"\\n inds = list(range(self.wcs.naxis))\\n inds[ax0], inds[ax1] = inds[ax1], inds[ax0]\\n\\n return self.sub([i+1 for i in inds])\\n\\n def reorient_celestial_first(self):\\n \\\"\\\"\\\"\\n Reorient the WCS such that the celestial axes are first, followed by\\n the spectral axis, followed by any others.\\n Assumes at least celestial axes are present.\\n \\\"\\\"\\\"\\n return self.sub([WCSSUB_CELESTIAL, WCSSUB_SPECTRAL, WCSSUB_STOKES, WCSSUB_TIME]) # Defined by C-ext # noqa: F821 E501\\n\\n def slice(self, view, numpy_order=True):\\n \\\"\\\"\\\"\\n Slice a WCS instance using a Numpy slice. The order of the slice should\\n be reversed (as for the data) compared to the natural WCS order.\\n\\n Parameters\\n ----------\\n view : tuple\\n A tuple containing the same number of slices as the WCS system.\\n The ``step`` method, the third argument to a slice, is not\\n presently supported.\\n numpy_order : bool\\n Use numpy order, i.e. slice the WCS so that an identical slice\\n applied to a numpy array will slice the array and WCS in the same\\n way. If set to `False`, the WCS will be sliced in FITS order,\\n meaning the first slice will be applied to the *last* numpy index\\n but the *first* WCS axis.\\n\\n Returns\\n -------\\n wcs_new : `~astropy.wcs.WCS`\\n A new resampled WCS axis\\n \\\"\\\"\\\"\\n if hasattr(view, '__len__') and len(view) > self.wcs.naxis:\\n raise ValueError(\\\"Must have # of slices <= # of WCS axes\\\")\\n elif not hasattr(view, '__len__'): # view MUST be an iterable\\n view = [view]\\n\\n if not all(isinstance(x, slice) for x in view):\\n # We need to drop some dimensions, but this may not always be\\n # possible with .sub due to correlated axes, so instead we use the\\n # generalized slicing infrastructure from astropy.wcs.wcsapi.\\n return SlicedFITSWCS(self, view)\\n\\n # NOTE: we could in principle use SlicedFITSWCS as above for all slicing,\\n # but in the simple case where there are no axes dropped, we can just\\n # create a full WCS object with updated WCS parameters which is faster\\n # for this specific case and also backward-compatible.\\n\\n wcs_new = self.deepcopy()\\n if wcs_new.sip is not None:\\n sip_crpix = wcs_new.sip.crpix.tolist()\\n\\n for i, iview in enumerate(view):\\n if iview.step is not None and iview.step < 0:\\n raise NotImplementedError(\\\"Reversing an axis is not \\\"\\n \\\"implemented.\\\")\\n\\n if numpy_order:\\n wcs_index = self.wcs.naxis - 1 - i\\n else:\\n wcs_index = i\\n\\n if iview.step is not None and iview.start is None:\\n # Slice from \\\"None\\\" is equivalent to slice from 0 (but one\\n # might want to downsample, so allow slices with\\n # None,None,step or None,stop,step)\\n iview = slice(0, iview.stop, iview.step)\\n\\n if iview.start is not None:\\n if iview.step not in (None, 1):\\n crpix = self.wcs.crpix[wcs_index]\\n cdelt = self.wcs.cdelt[wcs_index]\\n # equivalently (keep this comment so you can compare eqns):\\n # wcs_new.wcs.crpix[wcs_index] =\\n # (crpix - iview.start)*iview.step + 0.5 - iview.step/2.\\n crp = ((crpix - iview.start - 1.)/iview.step\\n + 0.5 + 1./iview.step/2.)\\n wcs_new.wcs.crpix[wcs_index] = crp\\n if wcs_new.sip is not None:\\n sip_crpix[wcs_index] = crp\\n wcs_new.wcs.cdelt[wcs_index] = cdelt * iview.step\\n else:\\n wcs_new.wcs.crpix[wcs_index] -= iview.start\\n if wcs_new.sip is not None:\\n sip_crpix[wcs_index] -= iview.start\\n\\n try:\\n # range requires integers but the other attributes can also\\n # handle arbitrary values, so this needs to be in a try/except.\\n nitems = len(builtins.range(self._naxis[wcs_index])[iview])\\n except TypeError as exc:\\n if 'indices must be integers' not in str(exc):\\n raise\\n warnings.warn(\\\"NAXIS{} attribute is not updated because at \\\"\\n \\\"least one index ('{}') is no integer.\\\"\\n \\\"\\\".format(wcs_index, iview), AstropyUserWarning)\\n else:\\n wcs_new._naxis[wcs_index] = nitems\\n\\n if wcs_new.sip is not None:\\n wcs_new.sip = Sip(self.sip.a, self.sip.b, self.sip.ap, self.sip.bp,\\n sip_crpix)\\n\\n return wcs_new\\n\\n def __getitem__(self, item):\\n # \\\"getitem\\\" is a shortcut for self.slice; it is very limited\\n # there is no obvious and unambiguous interpretation of wcs[1,2,3]\\n # We COULD allow wcs[1] to link to wcs.sub([2])\\n # (wcs[i] -> wcs.sub([i+1])\\n return self.slice(item)\\n\\n def __iter__(self):\\n # Having __getitem__ makes Python think WCS is iterable. However,\\n # Python first checks whether __iter__ is present, so we can raise an\\n # exception here.\\n raise TypeError(f\\\"'{self.__class__.__name__}' object is not iterable\\\")\\n\\n @property\\n def axis_type_names(self):\\n \\\"\\\"\\\"\\n World names for each coordinate axis\\n\\n Returns\\n -------\\n list of str\\n A list of names along each axis.\\n \\\"\\\"\\\"\\n names = list(self.wcs.cname)\\n types = self.wcs.ctype\\n for i in range(len(names)):\\n if len(names[i]) > 0:\\n continue\\n names[i] = types[i].split('-')[0]\\n return names\\n\\n @property\\n def celestial(self):\\n \\\"\\\"\\\"\\n A copy of the current WCS with only the celestial axes included\\n \\\"\\\"\\\"\\n return self.sub([WCSSUB_CELESTIAL]) # Defined by C-ext # noqa: F821\\n\\n @property\\n def is_celestial(self):\\n return self.has_celestial and self.naxis == 2\\n\\n @property\\n def has_celestial(self):\\n try:\\n return self.wcs.lng >= 0 and self.wcs.lat >= 0\\n except InconsistentAxisTypesError:\\n return False\\n\\n @property\\n def spectral(self):\\n \\\"\\\"\\\"\\n A copy of the current WCS with only the spectral axes included\\n \\\"\\\"\\\"\\n return self.sub([WCSSUB_SPECTRAL]) # Defined by C-ext # noqa: F821\\n\\n @property\\n def is_spectral(self):\\n return self.has_spectral and self.naxis == 1\\n\\n @property\\n def has_spectral(self):\\n try:\\n return self.wcs.spec >= 0\\n except InconsistentAxisTypesError:\\n return False\\n\\n @property\\n def has_distortion(self):\\n \\\"\\\"\\\"\\n Returns `True` if any distortion terms are present.\\n \\\"\\\"\\\"\\n return (self.sip is not None or\\n self.cpdis1 is not None or self.cpdis2 is not None or\\n self.det2im1 is not None and self.det2im2 is not None)\\n\\n @property\\n def pixel_scale_matrix(self):\\n\\n try:\\n cdelt = np.diag(self.wcs.get_cdelt())\\n pc = self.wcs.get_pc()\\n except InconsistentAxisTypesError:\\n try:\\n # for non-celestial axes, get_cdelt doesn't work\\n with warnings.catch_warnings():\\n warnings.filterwarnings(\\n 'ignore', 'cdelt will be ignored since cd is present', RuntimeWarning)\\n cdelt = np.dot(self.wcs.cd, np.diag(self.wcs.cdelt))\\n except AttributeError:\\n cdelt = np.diag(self.wcs.cdelt)\\n\\n try:\\n pc = self.wcs.pc\\n except AttributeError:\\n pc = 1\\n\\n pccd = np.dot(cdelt, pc)\\n\\n return pccd\\n\\n def footprint_contains(self, coord, **kwargs):\\n \\\"\\\"\\\"\\n Determines if a given SkyCoord is contained in the wcs footprint.\\n\\n Parameters\\n ----------\\n coord : `~astropy.coordinates.SkyCoord`\\n The coordinate to check if it is within the wcs coordinate.\\n **kwargs :\\n Additional arguments to pass to `~astropy.coordinates.SkyCoord.to_pixel`\\n\\n Returns\\n -------\\n response : bool\\n True means the WCS footprint contains the coordinate, False means it does not.\\n \\\"\\\"\\\"\\n\\n return coord.contained_by(self, **kwargs)\\n\\n\\ndef __WCS_unpickle__(cls, dct, fits_data):\\n \\\"\\\"\\\"\\n Unpickles a WCS object from a serialized FITS string.\\n \\\"\\\"\\\"\\n\\n self = cls.__new__(cls)\\n\\n buffer = io.BytesIO(fits_data)\\n hdulist = fits.open(buffer)\\n\\n naxis = dct.pop('naxis', None)\\n if naxis:\\n hdulist[0].header['naxis'] = naxis\\n naxes = dct.pop('_naxis', [])\\n for k, na in enumerate(naxes):\\n hdulist[0].header[f'naxis{k + 1:d}'] = na\\n\\n kwargs = dct.pop('_init_kwargs', {})\\n self.__dict__.update(dct)\\n\\n wcskey = dct.pop('_alt_wcskey', ' ')\\n WCS.__init__(self, hdulist[0].header, hdulist, key=wcskey, **kwargs)\\n self.pixel_bounds = dct.get('_pixel_bounds', None)\\n\\n return self\\n\\n\\ndef find_all_wcs(header, relax=True, keysel=None, fix=True,\\n translate_units='',\\n _do_set=True):\\n \\\"\\\"\\\"\\n Find all the WCS transformations in the given header.\\n\\n Parameters\\n ----------\\n header : str or `~astropy.io.fits.Header` object.\\n\\n relax : bool or int, optional\\n Degree of permissiveness:\\n\\n - `True` (default): Admit all recognized informal extensions of the\\n WCS standard.\\n\\n - `False`: Recognize only FITS keywords defined by the\\n published WCS standard.\\n\\n - `int`: a bit field selecting specific extensions to accept.\\n See :ref:`astropy:relaxread` for details.\\n\\n keysel : sequence of str, optional\\n A list of flags used to select the keyword types considered by\\n wcslib. When ``None``, only the standard image header\\n keywords are considered (and the underlying wcspih() C\\n function is called). To use binary table image array or pixel\\n list keywords, *keysel* must be set.\\n\\n Each element in the list should be one of the following strings:\\n\\n - 'image': Image header keywords\\n\\n - 'binary': Binary table image array keywords\\n\\n - 'pixel': Pixel list keywords\\n\\n Keywords such as ``EQUIna`` or ``RFRQna`` that are common to\\n binary table image arrays and pixel lists (including\\n ``WCSNna`` and ``TWCSna``) are selected by both 'binary' and\\n 'pixel'.\\n\\n fix : bool, optional\\n When `True` (default), call `~astropy.wcs.Wcsprm.fix` on\\n the resulting objects to fix any non-standard uses in the\\n header. `FITSFixedWarning` warnings will be emitted if any\\n changes were made.\\n\\n translate_units : str, optional\\n Specify which potentially unsafe translations of non-standard\\n unit strings to perform. By default, performs none. See\\n `WCS.fix` for more information about this parameter. Only\\n effective when ``fix`` is `True`.\\n\\n Returns\\n -------\\n wcses : list of `WCS`\\n \\\"\\\"\\\"\\n\\n if isinstance(header, (str, bytes)):\\n header_string = header\\n elif isinstance(header, fits.Header):\\n header_string = header.tostring()\\n else:\\n raise TypeError(\\n \\\"header must be a string or astropy.io.fits.Header object\\\")\\n\\n keysel_flags = _parse_keysel(keysel)\\n\\n if isinstance(header_string, str):\\n header_bytes = header_string.encode('ascii')\\n else:\\n header_bytes = header_string\\n\\n wcsprms = _wcs.find_all_wcs(header_bytes, relax, keysel_flags)\\n\\n result = []\\n for wcsprm in wcsprms:\\n subresult = WCS(fix=False, _do_set=False)\\n subresult.wcs = wcsprm\\n result.append(subresult)\\n\\n if fix:\\n subresult.fix(translate_units)\\n\\n if _do_set:\\n subresult.wcs.set()\\n\\n return result\\n\\n\\ndef validate(source):\\n \\\"\\\"\\\"\\n Prints a WCS validation report for the given FITS file.\\n\\n Parameters\\n ----------\\n source : str or file-like or `~astropy.io.fits.HDUList`\\n The FITS file to validate.\\n\\n Returns\\n -------\\n results : list subclass instance\\n The result is returned as nested lists. The first level\\n corresponds to the HDUs in the given file. The next level has\\n an entry for each WCS found in that header. The special\\n subclass of list will pretty-print the results as a table when\\n printed.\\n\\n \\\"\\\"\\\"\\n class _WcsValidateWcsResult(list):\\n def __init__(self, key):\\n self._key = key\\n\\n def __repr__(self):\\n result = [f\\\" WCS key '{self._key or ' '}':\\\"]\\n if len(self):\\n for entry in self:\\n for i, line in enumerate(entry.splitlines()):\\n if i == 0:\\n initial_indent = ' - '\\n else:\\n initial_indent = ' '\\n result.extend(\\n textwrap.wrap(\\n line,\\n initial_indent=initial_indent,\\n subsequent_indent=' '))\\n else:\\n result.append(\\\" No issues.\\\")\\n return '\\\\n'.join(result)\\n\\n class _WcsValidateHduResult(list):\\n def __init__(self, hdu_index, hdu_name):\\n self._hdu_index = hdu_index\\n self._hdu_name = hdu_name\\n list.__init__(self)\\n\\n def __repr__(self):\\n if len(self):\\n if self._hdu_name:\\n hdu_name = f' ({self._hdu_name})'\\n else:\\n hdu_name = ''\\n result = [f'HDU {self._hdu_index}{hdu_name}:']\\n for wcs in self:\\n result.append(repr(wcs))\\n return '\\\\n'.join(result)\\n return ''\\n\\n class _WcsValidateResults(list):\\n def __repr__(self):\\n result = []\\n for hdu in self:\\n content = repr(hdu)\\n if len(content):\\n result.append(content)\\n return '\\\\n\\\\n'.join(result)\\n\\n global __warningregistry__\\n\\n if isinstance(source, fits.HDUList):\\n hdulist = source\\n else:\\n hdulist = fits.open(source)\\n\\n results = _WcsValidateResults()\\n\\n for i, hdu in enumerate(hdulist):\\n hdu_results = _WcsValidateHduResult(i, hdu.name)\\n results.append(hdu_results)\\n\\n with warnings.catch_warnings(record=True) as warning_lines:\\n wcses = find_all_wcs(\\n hdu.header, relax=_wcs.WCSHDR_reject,\\n fix=False, _do_set=False)\\n\\n for wcs in wcses:\\n wcs_results = _WcsValidateWcsResult(wcs.wcs.alt)\\n hdu_results.append(wcs_results)\\n\\n try:\\n del __warningregistry__\\n except NameError:\\n pass\\n\\n with warnings.catch_warnings(record=True) as warning_lines:\\n warnings.resetwarnings()\\n warnings.simplefilter(\\n \\\"always\\\", FITSFixedWarning, append=True)\\n\\n try:\\n WCS(hdu.header,\\n key=wcs.wcs.alt or ' ',\\n relax=_wcs.WCSHDR_reject,\\n fix=True, _do_set=False)\\n except WcsError as e:\\n wcs_results.append(str(e))\\n\\n wcs_results.extend([str(x.message) for x in warning_lines])\\n\\n return results\\n\", \"docs/changes/wcs/13094.feature.rst\": null}"},"non_py_patch":{"kind":"string","value":"diff --git a/docs/changes/wcs/13094.feature.rst b/docs/changes/wcs/13094.feature.rst\nnew file mode 100644\nindex 000000000000..e6b718e0a4e0\n--- /dev/null\n+++ b/docs/changes/wcs/13094.feature.rst\n@@ -0,0 +1,2 @@\n+Add ``temporal`` properties for convenient access of/selection of/testing for\n+the ``TIME`` axis introduced in WCSLIB version 7.8.\n"},"new_components":{"kind":"string","value":"{\"astropy/wcs/wcs.py\": [{\"type\": \"function\", \"name\": \"WCS.temporal\", \"lines\": [3230, 3234], \"signature\": \"def temporal(self):\", \"doc\": \"A copy of the current WCS with only the time axes included\"}, {\"type\": \"function\", \"name\": \"WCS.is_temporal\", \"lines\": [3237, 3238], \"signature\": \"def is_temporal(self):\", \"doc\": \"\"}, {\"type\": \"function\", \"name\": \"WCS.has_temporal\", \"lines\": [3241, 3242], \"signature\": \"def has_temporal(self):\", \"doc\": \"\"}]}"},"version":{"kind":"string","value":"5.0"},"FAIL_TO_PASS":{"kind":"string","value":"[\"astropy/wcs/tests/test_wcs.py::test_temporal\"]"},"PASS_TO_PASS":{"kind":"string","value":"[\"astropy/wcs/tests/test_wcs.py::test_fixes\", \"astropy/wcs/tests/test_wcs.py::test_outside_sky\", \"astropy/wcs/tests/test_wcs.py::test_pix2world\", \"astropy/wcs/tests/test_wcs.py::test_load_fits_path\", \"astropy/wcs/tests/test_wcs.py::test_dict_init\", \"astropy/wcs/tests/test_wcs.py::test_extra_kwarg\", \"astropy/wcs/tests/test_wcs.py::test_3d_shapes\", \"astropy/wcs/tests/test_wcs.py::test_preserve_shape\", \"astropy/wcs/tests/test_wcs.py::test_broadcasting\", \"astropy/wcs/tests/test_wcs.py::test_shape_mismatch\", \"astropy/wcs/tests/test_wcs.py::test_invalid_shape\", \"astropy/wcs/tests/test_wcs.py::test_warning_about_defunct_keywords\", \"astropy/wcs/tests/test_wcs.py::test_warning_about_defunct_keywords_exception\", \"astropy/wcs/tests/test_wcs.py::test_to_header_string\", \"astropy/wcs/tests/test_wcs.py::test_to_fits\", \"astropy/wcs/tests/test_wcs.py::test_to_header_warning\", \"astropy/wcs/tests/test_wcs.py::test_no_comments_in_header\", \"astropy/wcs/tests/test_wcs.py::test_find_all_wcs_crash\", \"astropy/wcs/tests/test_wcs.py::test_validate\", \"astropy/wcs/tests/test_wcs.py::test_validate_with_2_wcses\", \"astropy/wcs/tests/test_wcs.py::test_crpix_maps_to_crval\", \"astropy/wcs/tests/test_wcs.py::test_all_world2pix\", \"astropy/wcs/tests/test_wcs.py::test_scamp_sip_distortion_parameters\", \"astropy/wcs/tests/test_wcs.py::test_fixes2\", \"astropy/wcs/tests/test_wcs.py::test_unit_normalization\", \"astropy/wcs/tests/test_wcs.py::test_footprint_to_file\", \"astropy/wcs/tests/test_wcs.py::test_validate_faulty_wcs\", \"astropy/wcs/tests/test_wcs.py::test_error_message\", \"astropy/wcs/tests/test_wcs.py::test_out_of_bounds\", \"astropy/wcs/tests/test_wcs.py::test_calc_footprint_1\", \"astropy/wcs/tests/test_wcs.py::test_calc_footprint_2\", \"astropy/wcs/tests/test_wcs.py::test_calc_footprint_3\", \"astropy/wcs/tests/test_wcs.py::test_sip\", \"astropy/wcs/tests/test_wcs.py::test_sub_3d_with_sip\", \"astropy/wcs/tests/test_wcs.py::test_printwcs\", \"astropy/wcs/tests/test_wcs.py::test_invalid_spherical\", \"astropy/wcs/tests/test_wcs.py::test_no_iteration\", \"astropy/wcs/tests/test_wcs.py::test_sip_tpv_agreement\", \"astropy/wcs/tests/test_wcs.py::test_tpv_copy\", \"astropy/wcs/tests/test_wcs.py::test_hst_wcs\", \"astropy/wcs/tests/test_wcs.py::test_cpdis_comments\", \"astropy/wcs/tests/test_wcs.py::test_d2im_comments\", \"astropy/wcs/tests/test_wcs.py::test_sip_broken\", \"astropy/wcs/tests/test_wcs.py::test_no_truncate_crval\", \"astropy/wcs/tests/test_wcs.py::test_no_truncate_crval_try2\", \"astropy/wcs/tests/test_wcs.py::test_no_truncate_crval_p17\", \"astropy/wcs/tests/test_wcs.py::test_no_truncate_using_compare\", \"astropy/wcs/tests/test_wcs.py::test_passing_ImageHDU\", \"astropy/wcs/tests/test_wcs.py::test_inconsistent_sip\", \"astropy/wcs/tests/test_wcs.py::test_bounds_check\", \"astropy/wcs/tests/test_wcs.py::test_naxis\", \"astropy/wcs/tests/test_wcs.py::test_sip_with_altkey\", \"astropy/wcs/tests/test_wcs.py::test_to_fits_1\", \"astropy/wcs/tests/test_wcs.py::test_keyedsip\", \"astropy/wcs/tests/test_wcs.py::test_zero_size_input\", \"astropy/wcs/tests/test_wcs.py::test_scalar_inputs\", \"astropy/wcs/tests/test_wcs.py::test_footprint_contains\", \"astropy/wcs/tests/test_wcs.py::test_cunit\", \"astropy/wcs/tests/test_wcs.py::test_invalid_coordinate_masking\", \"astropy/wcs/tests/test_wcs.py::test_no_pixel_area\", \"astropy/wcs/tests/test_wcs.py::test_distortion_header\", \"astropy/wcs/tests/test_wcs.py::test_pixlist_wcs_colsel\", \"astropy/wcs/tests/test_wcs.py::test_time_axis_selection\"]"},"environment_setup_commit":{"kind":"string","value":"7cbba866a8c5749b90a5cb4f9877ddfad2d36037"},"problem_statement":{"kind":"string","value":"{\"first_commit_time\": 1649160155.0, \"pr_title\": \"Add wcs temporal properties\", \"pr_body\": \"### Description\\r\\nThis PR add \\\"temporal\\\" properties to access 'TIME' axis in the WCS. This is the second part of the original PR - https://github.com/astropy/astropy/pull/13062\\r\\n\\r\\n### Checklist for package maintainer(s)\\r\\n\\r\\nThis checklist is meant to remind the package maintainer(s) who will review this pull request of some common things to look for. This list is not exhaustive.\\r\\n\\r\\n- [ ] Do the proposed changes actually accomplish desired goals?\\r\\n- [ ] Do the proposed changes follow the [Astropy coding guidelines](https://docs.astropy.org/en/latest/development/codeguide.html)?\\r\\n- [ ] Are tests added/updated as required? If so, do they follow the [Astropy testing guidelines](https://docs.astropy.org/en/latest/development/testguide.html)?\\r\\n- [ ] Are docs added/updated as required? If so, do they follow the [Astropy documentation guidelines](https://docs.astropy.org/en/latest/development/docguide.html#astropy-documentation-rules-and-guidelines)?\\r\\n- [ ] Is rebase and/or squash necessary? If so, please provide the author with appropriate instructions. Also see [\\\"When to rebase and squash commits\\\"](https://docs.astropy.org/en/latest/development/when_to_rebase.html).\\r\\n- [ ] Did the CI pass? If no, are the failures related? If you need to run daily and weekly cron jobs as part of the PR, please apply the `Extra CI` label.\\r\\n- [ ] Is a change log needed? If yes, did the change log check pass? If no, add the `no-changelog-entry-needed` label. If this is a manual backport, use the `skip-changelog-checks` label unless special changelog handling is necessary.\\r\\n- [ ] Is this a big PR that makes a \\\"What's new?\\\" entry worthwhile and if so, is (1) a \\\"what's new\\\" entry included in this PR and (2) the \\\"whatsnew-needed\\\" label applied?\\r\\n- [ ] Is a milestone set? Milestone must be set but `astropy-bot` check might be missing; do not let the green checkmark fool you.\\r\\n- [ ] At the time of adding the milestone, if the milestone set requires a backport to release branch(es), apply the appropriate `backport-X.Y.x` label(s) *before* merge.\\r\\n\", \"pr_timeline\": [], \"issues\": {}}"}}},{"rowIdx":12,"cells":{"repo":{"kind":"string","value":"astropy/astropy"},"pull_number":{"kind":"number","value":13508,"string":"13,508"},"url":{"kind":"string","value":"https://github.com/astropy/astropy/pull/13508"},"instance_id":{"kind":"string","value":"astropy__astropy-13508"},"issue_numbers":{"kind":"string","value":"[\"13507\"]"},"base_commit":{"kind":"string","value":"093e96735f6bc4dd87f154c54b6c42667489b602"},"patch":{"kind":"string","value":"diff --git a/astropy/time/core.py b/astropy/time/core.py\nindex 3716665aadde..50be00fcfb2a 100644\n--- a/astropy/time/core.py\n+++ b/astropy/time/core.py\n@@ -1356,6 +1356,82 @@ def sort(self, axis=-1):\n return self[self._advanced_index(self.argsort(axis), axis,\n keepdims=True)]\n \n+ def mean(self, axis=None, dtype=None, out=None, keepdims=False, *, where=True):\n+ \"\"\"Mean along a given axis.\n+\n+ This is similar to :meth:`~numpy.ndarray.mean`, but adapted to ensure\n+ that the full precision given by the two doubles ``jd1`` and ``jd2`` is\n+ used, and that corresponding attributes are copied.\n+\n+ Note that the ``out`` argument is present only for compatibility with\n+ ``np.mean``; since `Time` instances are immutable, it is not possible\n+ to have an actual ``out`` to store the result in.\n+\n+ Similarly, the ``dtype`` argument is also present for compatibility\n+ only; it has no meaning for `Time`.\n+\n+ Parameters\n+ ----------\n+ axis : None or int or tuple of ints, optional\n+ Axis or axes along which the means are computed. The default is to\n+ compute the mean of the flattened array.\n+ dtype : None\n+ Only present for compatibility with :meth:`~numpy.ndarray.mean`,\n+ must be `None`.\n+ out : None\n+ Only present for compatibility with :meth:`~numpy.ndarray.mean`,\n+ must be `None`.\n+ keepdims : bool, optional\n+ If this is set to True, the axes which are reduced are left\n+ in the result as dimensions with size one. With this option,\n+ the result will broadcast correctly against the input array.\n+ where : array_like of bool, optional\n+ Elements to include in the mean. See `~numpy.ufunc.reduce` for\n+ details.\n+\n+ Returns\n+ -------\n+ m : Time\n+ A new Time instance containing the mean values\n+ \"\"\"\n+ if dtype is not None:\n+ raise ValueError('Cannot set ``dtype`` on `Time` instances')\n+ if out is not None:\n+ raise ValueError(\"Since `Time` instances are immutable, ``out`` \"\n+ \"cannot be set to anything but ``None``.\")\n+\n+ where = where & ~self.mask\n+ where_broadcasted = np.broadcast_to(where, self.shape)\n+\n+ kwargs = dict(\n+ axis=axis,\n+ keepdims=keepdims,\n+ where=where,\n+ )\n+\n+ divisor = np.sum(where_broadcasted, axis=axis, keepdims=keepdims)\n+ if np.any(divisor == 0):\n+ raise ValueError(\n+ 'Mean over zero elements is not supported as it would give an undefined time;'\n+ 'see issue https://github.com/astropy/astropy/issues/6509'\n+ )\n+\n+ jd1, jd2 = day_frac(\n+ val1=np.sum(np.ma.getdata(self.jd1), **kwargs),\n+ val2=np.sum(np.ma.getdata(self.jd2), **kwargs),\n+ divisor=divisor,\n+ )\n+\n+ result = type(self)(\n+ val=jd1,\n+ val2=jd2,\n+ format='jd',\n+ scale=self.scale,\n+ copy=False,\n+ )\n+ result.format = self.format\n+ return result\n+\n @property\n def cache(self):\n \"\"\"\n@@ -2275,6 +2351,44 @@ def __add__(self, other):\n def __radd__(self, other):\n return self.__add__(other)\n \n+ def mean(self, axis=None, dtype=None, out=None, keepdims=False, *, where=True):\n+\n+ scale = self.scale\n+ if scale == 'utc':\n+ self = self.tai\n+ result = super().mean(axis=axis, dtype=dtype, out=out, keepdims=keepdims, where=where)\n+ if scale == 'utc':\n+ result = result.utc\n+\n+ result.out_subfmt = self.out_subfmt\n+\n+ location = self.location\n+ if self.location is not None:\n+ if self.location.shape:\n+\n+ if axis is None:\n+ axis_normalized = tuple(range(self.ndim))\n+ elif isinstance(axis, int):\n+ axis_normalized = axis,\n+ else:\n+ axis_normalized = axis\n+\n+ sl = [slice(None)] * self.location.ndim\n+ for a in axis_normalized:\n+ sl[a] = slice(0, 1)\n+\n+ if np.any(self.location != self.location[tuple(sl)]):\n+ raise ValueError(\"`location` must be constant over the reduction axes.\")\n+\n+ if not keepdims:\n+ for a in axis_normalized:\n+ sl[a] = 0\n+\n+ location = self.location[tuple(sl)]\n+\n+ result.location = location\n+ return result\n+\n def __array_function__(self, function, types, args, kwargs):\n \"\"\"\n Wrap numpy functions.\ndiff --git a/docs/changes/time/13508.feature.rst b/docs/changes/time/13508.feature.rst\nnew file mode 100644\nindex 000000000000..d6dffaa3b3db\n--- /dev/null\n+++ b/docs/changes/time/13508.feature.rst\n@@ -0,0 +1,1 @@\n+Added the ``astropy.time.Time.mean()`` method which also enables the ``numpy.mean()`` function to be used on instances of ``astropy.time.Time``.\n"},"test_patch":{"kind":"string","value":"diff --git a/astropy/table/tests/test_info.py b/astropy/table/tests/test_info.py\nindex 9a2977074bb9..6ea33917c75e 100644\n--- a/astropy/table/tests/test_info.py\n+++ b/astropy/table/tests/test_info.py\n@@ -67,7 +67,7 @@ def test_table_info_stats(table_types):\n a = np.array([1, 2, 1, 2], dtype='int32')\n b = np.array([1, 2, 1, 2], dtype='float32')\n c = np.array(['a', 'c', 'e', 'f'], dtype='|S1')\n- d = time.Time([1, 2, 1, 2], format='mjd')\n+ d = time.Time([1, 2, 1, 2], format='mjd', scale='tai')\n t = table_types.Table([a, b, c, d], names=['a', 'b', 'c', 'd'])\n \n # option = 'stats'\n@@ -81,14 +81,14 @@ def test_table_info_stats(table_types):\n ' a 1.5 0.5 1 2',\n ' b 1.5 0.5 1 2',\n ' c -- -- -- --',\n- ' d -- -- 1.0 2.0']\n+ ' d 1.5 -- 1.0 2.0']\n assert out.getvalue().splitlines() == exp\n \n # option = ['attributes', 'stats']\n tinfo = t.info(['attributes', 'stats'], out=None)\n assert tinfo.colnames == ['name', 'dtype', 'shape', 'unit', 'format', 'description',\n 'class', 'mean', 'std', 'min', 'max', 'n_bad', 'length']\n- assert np.all(tinfo['mean'] == ['1.5', '1.5', '--', '--'])\n+ assert np.all(tinfo['mean'] == ['1.5', '1.5', '--', '1.5'])\n assert np.all(tinfo['std'] == ['0.5', '0.5', '--', '--'])\n assert np.all(tinfo['min'] == ['1', '1', '--', '1.0'])\n assert np.all(tinfo['max'] == ['2', '2', '--', '2.0'])\n@@ -101,7 +101,7 @@ def test_table_info_stats(table_types):\n ' a 1.5 0.5 1 2',\n ' b 1.5 0.5 1 2',\n ' c -- -- -- --',\n- ' d -- -- 1.0 2.0']\n+ ' d 1.5 -- 1.0 2.0']\n assert out.getvalue().splitlines() == exp\n \n # option = ['attributes', custom]\ndiff --git a/astropy/time/tests/test_delta.py b/astropy/time/tests/test_delta.py\nindex 1bc2915d694e..7ce39db9ce1c 100644\n--- a/astropy/time/tests/test_delta.py\n+++ b/astropy/time/tests/test_delta.py\n@@ -209,6 +209,16 @@ def test_mul_div(self):\n with pytest.raises(TypeError):\n self.dt * object()\n \n+ def test_mean(self):\n+\n+ def is_consistent(time_delta: TimeDelta):\n+ mean_expected = (np.sum(time_delta.jd1) + np.sum(time_delta.jd2)) / time_delta.size\n+ mean_test = time_delta.mean().jd1 + time_delta.mean().jd2\n+ return mean_test == mean_expected\n+\n+ assert is_consistent(self.dt)\n+ assert is_consistent(self.dt_array)\n+\n def test_keep_properties(self):\n # closes #1924 (partially)\n dt = TimeDelta(1000., format='sec')\ndiff --git a/astropy/time/tests/test_methods.py b/astropy/time/tests/test_methods.py\nindex 8fac951171fc..65bb05722884 100644\n--- a/astropy/time/tests/test_methods.py\n+++ b/astropy/time/tests/test_methods.py\n@@ -7,7 +7,9 @@\n import numpy as np\n import pytest\n \n+import astropy.units as u\n from astropy.time import Time\n+from astropy.time.utils import day_frac\n from astropy.units.quantity_helper.function_helpers import ARRAY_FUNCTION_ENABLED\n from astropy.utils import iers\n \n@@ -479,9 +481,17 @@ def setup_class(cls):\n 'masked': mjd + frac_masked\n }\n \n+ cls.t2 = {\n+ 'not_masked': Time(mjd + frac, format='mjd', scale='utc',\n+ location=(np.arange(len(frac)), np.arange(len(frac)))),\n+ 'masked': Time(mjd + frac_masked, format='mjd', scale='utc',\n+ location=(np.arange(len(frac_masked)), np.arange(len(frac_masked)))),\n+ }\n+\n def create_data(self, use_mask):\n self.t0 = self.__class__.t0[use_mask]\n self.t1 = self.__class__.t1[use_mask]\n+ self.t2 = self.__class__.t2[use_mask]\n self.jd = self.__class__.jd[use_mask]\n \n @pytest.mark.parametrize('kw, func', itertools.product(kwargs, functions))\n@@ -619,6 +629,92 @@ def test_sort(self, use_mask):\n assert np.all(self.t0.sort(-1)[:, :, 0] == self.t0.min(-1))\n assert np.all(self.t0.sort(-1)[:, :, -1] == self.t0.max(-1))\n \n+ @pytest.mark.parametrize('axis', [None, 0, 1, 2, (0, 1)])\n+ @pytest.mark.parametrize('where', [True, np.array([True, False, True, True, False])[..., np.newaxis]])\n+ @pytest.mark.parametrize('keepdims', [False, True])\n+ def test_mean(self, use_mask, axis, where, keepdims):\n+ self.create_data(use_mask)\n+\n+ kwargs = dict(axis=axis, where=where, keepdims=keepdims)\n+\n+ def is_consistent(time):\n+\n+ where_expected = where & ~time.mask\n+ where_expected = np.broadcast_to(where_expected, time.shape)\n+\n+ kw = kwargs.copy()\n+ kw['where'] = where_expected\n+\n+ divisor = where_expected.sum(axis=axis, keepdims=keepdims)\n+\n+ if np.any(divisor == 0):\n+ with pytest.raises(ValueError):\n+ time.mean(**kwargs)\n+\n+ else:\n+ time_mean = time.mean(**kwargs)\n+ time_expected = Time(\n+ *day_frac(\n+ val1=np.ma.getdata(time.tai.jd1).sum(**kw),\n+ val2=np.ma.getdata(time.tai.jd2).sum(**kw),\n+ divisor=divisor\n+ ),\n+ format='jd',\n+ scale='tai',\n+ )\n+ time_expected._set_scale(time.scale)\n+ assert np.all(time_mean == time_expected)\n+\n+ is_consistent(self.t0)\n+ is_consistent(self.t1)\n+\n+ axes_location_not_constant = [None, 2]\n+ if axis in axes_location_not_constant:\n+ with pytest.raises(ValueError):\n+ self.t2.mean(**kwargs)\n+ else:\n+ is_consistent(self.t2)\n+\n+ def test_mean_precision(self, use_mask):\n+\n+ scale = 'tai'\n+ epsilon = 1 * u.ns\n+\n+ t0 = Time('2021-07-27T00:00:00', scale=scale)\n+ t1 = Time('2022-07-27T00:00:00', scale=scale)\n+ t2 = Time('2023-07-27T00:00:00', scale=scale)\n+\n+ t = Time([t0, t2 + epsilon])\n+\n+ if use_mask == 'masked':\n+ t[0] = np.ma.masked\n+ assert t.mean() == (t2 + epsilon)\n+\n+ else:\n+ assert t.mean() == (t1 + epsilon / 2)\n+\n+ def test_mean_dtype(self, use_mask):\n+ self.create_data(use_mask)\n+ with pytest.raises(ValueError):\n+ self.t0.mean(dtype=int)\n+\n+ def test_mean_out(self, use_mask):\n+ self.create_data(use_mask)\n+ with pytest.raises(ValueError):\n+ self.t0.mean(out=Time(np.zeros_like(self.t0.jd1), format='jd'))\n+\n+ def test_mean_leap_second(self, use_mask):\n+ # Check that leap second is dealt with correctly: for UTC, across a leap\n+ # second bounday, one cannot just average jd, but has to go through TAI.\n+ if use_mask == 'not_masked':\n+ t = Time(['2012-06-30 23:59:60.000', '2012-07-01 00:00:01.000'])\n+ mean_expected = t[0] + (t[1] - t[0]) / 2\n+ mean_expected_explicit = Time('2012-07-01 00:00:00')\n+ mean_test = t.mean()\n+ assert mean_expected == mean_expected_explicit\n+ assert mean_expected == mean_test\n+ assert mean_test != Time(*day_frac(t.jd1.sum(), t.jd2.sum(), divisor=2), format='jd')\n+\n \n def test_regression():\n # For #5225, where a time with a single-element delta_ut1_utc could not\n"},"created_at":{"kind":"timestamp","value":"2022-07-27T18:03:06","string":"2022-07-27T18:03:06"},"readmes":{"kind":"string","value":"{}"},"files":{"kind":"string","value":"{\"astropy/time/core.py\": \"# Licensed under a 3-clause BSD style license - see LICENSE.rst\\n\\\"\\\"\\\"\\nThe astropy.time package provides functionality for manipulating times and\\ndates. Specific emphasis is placed on supporting time scales (e.g. UTC, TAI,\\nUT1) and time representations (e.g. JD, MJD, ISO 8601) that are used in\\nastronomy.\\n\\\"\\\"\\\"\\n\\nimport copy\\nimport enum\\nimport operator\\nimport os\\nimport threading\\nfrom datetime import date, datetime, timedelta\\nfrom time import strftime\\nfrom warnings import warn\\n\\nimport erfa\\nimport numpy as np\\n\\nfrom astropy import constants as const\\nfrom astropy import units as u\\nfrom astropy.extern import _strptime\\nfrom astropy.units import UnitConversionError\\nfrom astropy.utils import ShapedLikeNDArray\\nfrom astropy.utils.data_info import MixinInfo, data_info_factory\\nfrom astropy.utils.exceptions import AstropyDeprecationWarning, AstropyWarning\\n\\n# Import TimeFromEpoch to avoid breaking code that followed the old example of\\n# making a custom timescale in the documentation.\\nfrom .formats import TimeFromEpoch # noqa: F401\\nfrom .formats import (\\n TIME_DELTA_FORMATS, TIME_FORMATS, TimeAstropyTime, TimeDatetime, TimeJD, TimeUnique)\\nfrom .time_helper.function_helpers import CUSTOM_FUNCTIONS, UNSUPPORTED_FUNCTIONS\\nfrom .utils import day_frac\\n\\n__all__ = ['TimeBase', 'Time', 'TimeDelta', 'TimeInfo', 'TimeInfoBase', 'update_leap_seconds',\\n 'TIME_SCALES', 'STANDARD_TIME_SCALES', 'TIME_DELTA_SCALES',\\n 'ScaleValueError', 'OperandTypeError', 'TimeDeltaMissingUnitWarning']\\n\\n\\nSTANDARD_TIME_SCALES = ('tai', 'tcb', 'tcg', 'tdb', 'tt', 'ut1', 'utc')\\nLOCAL_SCALES = ('local',)\\nTIME_TYPES = {scale: scales for scales in (STANDARD_TIME_SCALES, LOCAL_SCALES) for scale in scales}\\nTIME_SCALES = STANDARD_TIME_SCALES + LOCAL_SCALES\\nMULTI_HOPS = {('tai', 'tcb'): ('tt', 'tdb'),\\n ('tai', 'tcg'): ('tt',),\\n ('tai', 'ut1'): ('utc',),\\n ('tai', 'tdb'): ('tt',),\\n ('tcb', 'tcg'): ('tdb', 'tt'),\\n ('tcb', 'tt'): ('tdb',),\\n ('tcb', 'ut1'): ('tdb', 'tt', 'tai', 'utc'),\\n ('tcb', 'utc'): ('tdb', 'tt', 'tai'),\\n ('tcg', 'tdb'): ('tt',),\\n ('tcg', 'ut1'): ('tt', 'tai', 'utc'),\\n ('tcg', 'utc'): ('tt', 'tai'),\\n ('tdb', 'ut1'): ('tt', 'tai', 'utc'),\\n ('tdb', 'utc'): ('tt', 'tai'),\\n ('tt', 'ut1'): ('tai', 'utc'),\\n ('tt', 'utc'): ('tai',),\\n }\\nGEOCENTRIC_SCALES = ('tai', 'tt', 'tcg')\\nBARYCENTRIC_SCALES = ('tcb', 'tdb')\\nROTATIONAL_SCALES = ('ut1',)\\nTIME_DELTA_TYPES = {scale: scales\\n for scales in (GEOCENTRIC_SCALES, BARYCENTRIC_SCALES,\\n ROTATIONAL_SCALES, LOCAL_SCALES) for scale in scales}\\nTIME_DELTA_SCALES = GEOCENTRIC_SCALES + BARYCENTRIC_SCALES + ROTATIONAL_SCALES + LOCAL_SCALES\\n# For time scale changes, we need L_G and L_B, which are stored in erfam.h as\\n# /* L_G = 1 - d(TT)/d(TCG) */\\n# define ERFA_ELG (6.969290134e-10)\\n# /* L_B = 1 - d(TDB)/d(TCB), and TDB (s) at TAI 1977/1/1.0 */\\n# define ERFA_ELB (1.550519768e-8)\\n# These are exposed in erfa as erfa.ELG and erfa.ELB.\\n# Implied: d(TT)/d(TCG) = 1-L_G\\n# and d(TCG)/d(TT) = 1/(1-L_G) = 1 + (1-(1-L_G))/(1-L_G) = 1 + L_G/(1-L_G)\\n# scale offsets as second = first + first * scale_offset[(first,second)]\\nSCALE_OFFSETS = {('tt', 'tai'): None,\\n ('tai', 'tt'): None,\\n ('tcg', 'tt'): -erfa.ELG,\\n ('tt', 'tcg'): erfa.ELG / (1. - erfa.ELG),\\n ('tcg', 'tai'): -erfa.ELG,\\n ('tai', 'tcg'): erfa.ELG / (1. - erfa.ELG),\\n ('tcb', 'tdb'): -erfa.ELB,\\n ('tdb', 'tcb'): erfa.ELB / (1. - erfa.ELB)}\\n\\n# triple-level dictionary, yay!\\nSIDEREAL_TIME_MODELS = {\\n 'mean': {\\n 'IAU2006': {'function': erfa.gmst06, 'scales': ('ut1', 'tt')},\\n 'IAU2000': {'function': erfa.gmst00, 'scales': ('ut1', 'tt')},\\n 'IAU1982': {'function': erfa.gmst82, 'scales': ('ut1',), 'include_tio': False}\\n },\\n 'apparent': {\\n 'IAU2006A': {'function': erfa.gst06a, 'scales': ('ut1', 'tt')},\\n 'IAU2000A': {'function': erfa.gst00a, 'scales': ('ut1', 'tt')},\\n 'IAU2000B': {'function': erfa.gst00b, 'scales': ('ut1',)},\\n 'IAU1994': {'function': erfa.gst94, 'scales': ('ut1',), 'include_tio': False}\\n }}\\n\\n\\nclass _LeapSecondsCheck(enum.Enum):\\n NOT_STARTED = 0 # No thread has reached the check\\n RUNNING = 1 # A thread is running update_leap_seconds (_LEAP_SECONDS_LOCK is held)\\n DONE = 2 # update_leap_seconds has completed\\n\\n\\n_LEAP_SECONDS_CHECK = _LeapSecondsCheck.NOT_STARTED\\n_LEAP_SECONDS_LOCK = threading.RLock()\\n\\n\\nclass TimeInfoBase(MixinInfo):\\n \\\"\\\"\\\"\\n Container for meta information like name, description, format. This is\\n required when the object is used as a mixin column within a table, but can\\n be used as a general way to store meta information.\\n\\n This base class is common between TimeInfo and TimeDeltaInfo.\\n \\\"\\\"\\\"\\n attr_names = MixinInfo.attr_names | {'serialize_method'}\\n _supports_indexing = True\\n\\n # The usual tuple of attributes needed for serialization is replaced\\n # by a property, since Time can be serialized different ways.\\n _represent_as_dict_extra_attrs = ('format', 'scale', 'precision',\\n 'in_subfmt', 'out_subfmt', 'location',\\n '_delta_ut1_utc', '_delta_tdb_tt')\\n\\n # When serializing, write out the `value` attribute using the column name.\\n _represent_as_dict_primary_data = 'value'\\n\\n mask_val = np.ma.masked\\n\\n @property\\n def _represent_as_dict_attrs(self):\\n method = self.serialize_method[self._serialize_context]\\n\\n if method == 'formatted_value':\\n out = ('value',)\\n elif method == 'jd1_jd2':\\n out = ('jd1', 'jd2')\\n else:\\n raise ValueError(\\\"serialize method must be 'formatted_value' or 'jd1_jd2'\\\")\\n\\n return out + self._represent_as_dict_extra_attrs\\n\\n def __init__(self, bound=False):\\n super().__init__(bound)\\n\\n # If bound to a data object instance then create the dict of attributes\\n # which stores the info attribute values.\\n if bound:\\n # Specify how to serialize this object depending on context.\\n # If ``True`` for a context, then use formatted ``value`` attribute\\n # (e.g. the ISO time string). If ``False`` then use float jd1 and jd2.\\n self.serialize_method = {'fits': 'jd1_jd2',\\n 'ecsv': 'formatted_value',\\n 'hdf5': 'jd1_jd2',\\n 'yaml': 'jd1_jd2',\\n 'parquet': 'jd1_jd2',\\n None: 'jd1_jd2'}\\n\\n def get_sortable_arrays(self):\\n \\\"\\\"\\\"\\n Return a list of arrays which can be lexically sorted to represent\\n the order of the parent column.\\n\\n Returns\\n -------\\n arrays : list of ndarray\\n \\\"\\\"\\\"\\n parent = self._parent\\n jd_approx = parent.jd\\n jd_remainder = (parent - parent.__class__(jd_approx, format='jd')).jd\\n return [jd_approx, jd_remainder]\\n\\n @property\\n def unit(self):\\n return None\\n\\n info_summary_stats = staticmethod(\\n data_info_factory(names=MixinInfo._stats,\\n funcs=[getattr(np, stat) for stat in MixinInfo._stats]))\\n # When Time has mean, std, min, max methods:\\n # funcs = [lambda x: getattr(x, stat)() for stat_name in MixinInfo._stats])\\n\\n def _construct_from_dict(self, map):\\n if 'jd1' in map and 'jd2' in map:\\n # Initialize as JD but revert to desired format and out_subfmt (if needed)\\n format = map.pop('format')\\n out_subfmt = map.pop('out_subfmt', None)\\n map['format'] = 'jd'\\n map['val'] = map.pop('jd1')\\n map['val2'] = map.pop('jd2')\\n out = self._parent_cls(**map)\\n out.format = format\\n if out_subfmt is not None:\\n out.out_subfmt = out_subfmt\\n\\n else:\\n map['val'] = map.pop('value')\\n out = self._parent_cls(**map)\\n\\n return out\\n\\n def new_like(self, cols, length, metadata_conflicts='warn', name=None):\\n \\\"\\\"\\\"\\n Return a new Time instance which is consistent with the input Time objects\\n ``cols`` and has ``length`` rows.\\n\\n This is intended for creating an empty Time instance whose elements can\\n be set in-place for table operations like join or vstack. It checks\\n that the input locations and attributes are consistent. This is used\\n when a Time object is used as a mixin column in an astropy Table.\\n\\n Parameters\\n ----------\\n cols : list\\n List of input columns (Time objects)\\n length : int\\n Length of the output column object\\n metadata_conflicts : str ('warn'|'error'|'silent')\\n How to handle metadata conflicts\\n name : str\\n Output column name\\n\\n Returns\\n -------\\n col : Time (or subclass)\\n Empty instance of this class consistent with ``cols``\\n\\n \\\"\\\"\\\"\\n # Get merged info attributes like shape, dtype, format, description, etc.\\n attrs = self.merge_cols_attributes(cols, metadata_conflicts, name,\\n ('meta', 'description'))\\n attrs.pop('dtype') # Not relevant for Time\\n col0 = cols[0]\\n\\n # Check that location is consistent for all Time objects\\n for col in cols[1:]:\\n # This is the method used by __setitem__ to ensure that the right side\\n # has a consistent location (and coerce data if necessary, but that does\\n # not happen in this case since `col` is already a Time object). If this\\n # passes then any subsequent table operations via setitem will work.\\n try:\\n col0._make_value_equivalent(slice(None), col)\\n except ValueError:\\n raise ValueError('input columns have inconsistent locations')\\n\\n # Make a new Time object with the desired shape and attributes\\n shape = (length,) + attrs.pop('shape')\\n jd2000 = 2451544.5 # Arbitrary JD value J2000.0 that will work with ERFA\\n jd1 = np.full(shape, jd2000, dtype='f8')\\n jd2 = np.zeros(shape, dtype='f8')\\n tm_attrs = {attr: getattr(col0, attr)\\n for attr in ('scale', 'location', 'precision')}\\n out = self._parent_cls(jd1, jd2, format='jd', **tm_attrs)\\n out.format = col0.format\\n out.out_subfmt = col0.out_subfmt\\n out.in_subfmt = col0.in_subfmt\\n\\n # Set remaining info attributes\\n for attr, value in attrs.items():\\n setattr(out.info, attr, value)\\n\\n return out\\n\\n\\nclass TimeInfo(TimeInfoBase):\\n \\\"\\\"\\\"\\n Container for meta information like name, description, format. This is\\n required when the object is used as a mixin column within a table, but can\\n be used as a general way to store meta information.\\n \\\"\\\"\\\"\\n def _represent_as_dict(self, attrs=None):\\n \\\"\\\"\\\"Get the values for the parent ``attrs`` and return as a dict.\\n\\n By default, uses '_represent_as_dict_attrs'.\\n \\\"\\\"\\\"\\n map = super()._represent_as_dict(attrs=attrs)\\n\\n # TODO: refactor these special cases into the TimeFormat classes?\\n\\n # The datetime64 format requires special handling for ECSV (see #12840).\\n # The `value` has numpy dtype datetime64 but this is not an allowed\\n # datatype for ECSV. Instead convert to a string representation.\\n if (self._serialize_context == 'ecsv'\\n and map['format'] == 'datetime64'\\n and 'value' in map):\\n map['value'] = map['value'].astype('U')\\n\\n # The datetime format is serialized as ISO with no loss of precision.\\n if map['format'] == 'datetime' and 'value' in map:\\n map['value'] = np.vectorize(lambda x: x.isoformat())(map['value'])\\n\\n return map\\n\\n def _construct_from_dict(self, map):\\n # See comment above. May need to convert string back to datetime64.\\n # Note that _serialize_context is not set here so we just look for the\\n # string value directly.\\n if (map['format'] == 'datetime64'\\n and 'value' in map\\n and map['value'].dtype.kind == 'U'):\\n map['value'] = map['value'].astype('datetime64')\\n\\n # Convert back to datetime objects for datetime format.\\n if map['format'] == 'datetime' and 'value' in map:\\n from datetime import datetime\\n map['value'] = np.vectorize(datetime.fromisoformat)(map['value'])\\n\\n delta_ut1_utc = map.pop('_delta_ut1_utc', None)\\n delta_tdb_tt = map.pop('_delta_tdb_tt', None)\\n\\n out = super()._construct_from_dict(map)\\n\\n if delta_ut1_utc is not None:\\n out._delta_ut1_utc = delta_ut1_utc\\n if delta_tdb_tt is not None:\\n out._delta_tdb_tt = delta_tdb_tt\\n\\n return out\\n\\n\\nclass TimeDeltaInfo(TimeInfoBase):\\n \\\"\\\"\\\"\\n Container for meta information like name, description, format. This is\\n required when the object is used as a mixin column within a table, but can\\n be used as a general way to store meta information.\\n \\\"\\\"\\\"\\n _represent_as_dict_extra_attrs = ('format', 'scale')\\n\\n def new_like(self, cols, length, metadata_conflicts='warn', name=None):\\n \\\"\\\"\\\"\\n Return a new TimeDelta instance which is consistent with the input Time objects\\n ``cols`` and has ``length`` rows.\\n\\n This is intended for creating an empty Time instance whose elements can\\n be set in-place for table operations like join or vstack. It checks\\n that the input locations and attributes are consistent. This is used\\n when a Time object is used as a mixin column in an astropy Table.\\n\\n Parameters\\n ----------\\n cols : list\\n List of input columns (Time objects)\\n length : int\\n Length of the output column object\\n metadata_conflicts : str ('warn'|'error'|'silent')\\n How to handle metadata conflicts\\n name : str\\n Output column name\\n\\n Returns\\n -------\\n col : Time (or subclass)\\n Empty instance of this class consistent with ``cols``\\n\\n \\\"\\\"\\\"\\n # Get merged info attributes like shape, dtype, format, description, etc.\\n attrs = self.merge_cols_attributes(cols, metadata_conflicts, name,\\n ('meta', 'description'))\\n attrs.pop('dtype') # Not relevant for Time\\n col0 = cols[0]\\n\\n # Make a new Time object with the desired shape and attributes\\n shape = (length,) + attrs.pop('shape')\\n jd1 = np.zeros(shape, dtype='f8')\\n jd2 = np.zeros(shape, dtype='f8')\\n out = self._parent_cls(jd1, jd2, format='jd', scale=col0.scale)\\n out.format = col0.format\\n\\n # Set remaining info attributes\\n for attr, value in attrs.items():\\n setattr(out.info, attr, value)\\n\\n return out\\n\\n\\nclass TimeBase(ShapedLikeNDArray):\\n \\\"\\\"\\\"Base time class from which Time and TimeDelta inherit.\\\"\\\"\\\"\\n\\n # Make sure that reverse arithmetic (e.g., TimeDelta.__rmul__)\\n # gets called over the __mul__ of Numpy arrays.\\n __array_priority__ = 20000\\n\\n # Declare that Time can be used as a Table column by defining the\\n # attribute where column attributes will be stored.\\n _astropy_column_attrs = None\\n\\n def __getnewargs__(self):\\n return (self._time,)\\n\\n def _init_from_vals(self, val, val2, format, scale, copy,\\n precision=None, in_subfmt=None, out_subfmt=None):\\n \\\"\\\"\\\"\\n Set the internal _format, scale, and _time attrs from user\\n inputs. This handles coercion into the correct shapes and\\n some basic input validation.\\n \\\"\\\"\\\"\\n if precision is None:\\n precision = 3\\n if in_subfmt is None:\\n in_subfmt = '*'\\n if out_subfmt is None:\\n out_subfmt = '*'\\n\\n # Coerce val into an array\\n val = _make_array(val, copy)\\n\\n # If val2 is not None, ensure consistency\\n if val2 is not None:\\n val2 = _make_array(val2, copy)\\n try:\\n np.broadcast(val, val2)\\n except ValueError:\\n raise ValueError('Input val and val2 have inconsistent shape; '\\n 'they cannot be broadcast together.')\\n\\n if scale is not None:\\n if not (isinstance(scale, str)\\n and scale.lower() in self.SCALES):\\n raise ScaleValueError(\\\"Scale {!r} is not in the allowed scales \\\"\\n \\\"{}\\\".format(scale,\\n sorted(self.SCALES)))\\n\\n # If either of the input val, val2 are masked arrays then\\n # find the masked elements and fill them.\\n mask, val, val2 = _check_for_masked_and_fill(val, val2)\\n\\n # Parse / convert input values into internal jd1, jd2 based on format\\n self._time = self._get_time_fmt(val, val2, format, scale,\\n precision, in_subfmt, out_subfmt)\\n self._format = self._time.name\\n\\n # Hack from #9969 to allow passing the location value that has been\\n # collected by the TimeAstropyTime format class up to the Time level.\\n # TODO: find a nicer way.\\n if hasattr(self._time, '_location'):\\n self.location = self._time._location\\n del self._time._location\\n\\n # If any inputs were masked then masked jd2 accordingly. From above\\n # routine ``mask`` must be either Python bool False or an bool ndarray\\n # with shape broadcastable to jd2.\\n if mask is not False:\\n mask = np.broadcast_to(mask, self._time.jd2.shape)\\n self._time.jd1[mask] = 2451544.5 # Set to JD for 2000-01-01\\n self._time.jd2[mask] = np.nan\\n\\n def _get_time_fmt(self, val, val2, format, scale,\\n precision, in_subfmt, out_subfmt):\\n \\\"\\\"\\\"\\n Given the supplied val, val2, format and scale try to instantiate\\n the corresponding TimeFormat class to convert the input values into\\n the internal jd1 and jd2.\\n\\n If format is `None` and the input is a string-type or object array then\\n guess available formats and stop when one matches.\\n \\\"\\\"\\\"\\n\\n if (format is None\\n and (val.dtype.kind in ('S', 'U', 'O', 'M') or val.dtype.names)):\\n # Input is a string, object, datetime, or a table-like ndarray\\n # (structured array, recarray). These input types can be\\n # uniquely identified by the format classes.\\n formats = [(name, cls) for name, cls in self.FORMATS.items()\\n if issubclass(cls, TimeUnique)]\\n\\n # AstropyTime is a pseudo-format that isn't in the TIME_FORMATS registry,\\n # but try to guess it at the end.\\n formats.append(('astropy_time', TimeAstropyTime))\\n\\n elif not (isinstance(format, str)\\n and format.lower() in self.FORMATS):\\n if format is None:\\n raise ValueError(\\\"No time format was given, and the input is \\\"\\n \\\"not unique\\\")\\n else:\\n raise ValueError(\\\"Format {!r} is not one of the allowed \\\"\\n \\\"formats {}\\\".format(format,\\n sorted(self.FORMATS)))\\n else:\\n formats = [(format, self.FORMATS[format])]\\n\\n assert formats\\n problems = {}\\n for name, cls in formats:\\n try:\\n return cls(val, val2, scale, precision, in_subfmt, out_subfmt)\\n except UnitConversionError:\\n raise\\n except (ValueError, TypeError) as err:\\n # If ``format`` specified then there is only one possibility, so raise\\n # immediately and include the upstream exception message to make it\\n # easier for user to see what is wrong.\\n if len(formats) == 1:\\n raise ValueError(\\n f'Input values did not match the format class {format}:'\\n + os.linesep\\n + f'{err.__class__.__name__}: {err}'\\n ) from err\\n else:\\n problems[name] = err\\n else:\\n raise ValueError(f'Input values did not match any of the formats '\\n f'where the format keyword is optional: '\\n f'{problems}') from problems[formats[0][0]]\\n\\n @property\\n def writeable(self):\\n return self._time.jd1.flags.writeable & self._time.jd2.flags.writeable\\n\\n @writeable.setter\\n def writeable(self, value):\\n self._time.jd1.flags.writeable = value\\n self._time.jd2.flags.writeable = value\\n\\n @property\\n def format(self):\\n \\\"\\\"\\\"\\n Get or set time format.\\n\\n The format defines the way times are represented when accessed via the\\n ``.value`` attribute. By default it is the same as the format used for\\n initializing the `Time` instance, but it can be set to any other value\\n that could be used for initialization. These can be listed with::\\n\\n >>> list(Time.FORMATS)\\n ['jd', 'mjd', 'decimalyear', 'unix', 'unix_tai', 'cxcsec', 'gps', 'plot_date',\\n 'stardate', 'datetime', 'ymdhms', 'iso', 'isot', 'yday', 'datetime64',\\n 'fits', 'byear', 'jyear', 'byear_str', 'jyear_str']\\n \\\"\\\"\\\"\\n return self._format\\n\\n @format.setter\\n def format(self, format):\\n \\\"\\\"\\\"Set time format\\\"\\\"\\\"\\n if format not in self.FORMATS:\\n raise ValueError(f'format must be one of {list(self.FORMATS)}')\\n format_cls = self.FORMATS[format]\\n\\n # Get the new TimeFormat object to contain time in new format. Possibly\\n # coerce in/out_subfmt to '*' (default) if existing subfmt values are\\n # not valid in the new format.\\n self._time = format_cls(\\n self._time.jd1, self._time.jd2,\\n self._time._scale, self.precision,\\n in_subfmt=format_cls._get_allowed_subfmt(self.in_subfmt),\\n out_subfmt=format_cls._get_allowed_subfmt(self.out_subfmt),\\n from_jd=True)\\n\\n self._format = format\\n\\n def __repr__(self):\\n return (\\\"<{} object: scale='{}' format='{}' value={}>\\\"\\n .format(self.__class__.__name__, self.scale, self.format,\\n getattr(self, self.format)))\\n\\n def __str__(self):\\n return str(getattr(self, self.format))\\n\\n def __hash__(self):\\n\\n try:\\n loc = getattr(self, 'location', None)\\n if loc is not None:\\n loc = loc.x.to_value(u.m), loc.y.to_value(u.m), loc.z.to_value(u.m)\\n\\n return hash((self.jd1, self.jd2, self.scale, loc))\\n\\n except TypeError:\\n if self.ndim != 0:\\n reason = '(must be scalar)'\\n elif self.masked:\\n reason = '(value is masked)'\\n else:\\n raise\\n\\n raise TypeError(f\\\"unhashable type: '{self.__class__.__name__}' {reason}\\\")\\n\\n @property\\n def scale(self):\\n \\\"\\\"\\\"Time scale\\\"\\\"\\\"\\n return self._time.scale\\n\\n def _set_scale(self, scale):\\n \\\"\\\"\\\"\\n This is the key routine that actually does time scale conversions.\\n This is not public and not connected to the read-only scale property.\\n \\\"\\\"\\\"\\n\\n if scale == self.scale:\\n return\\n if scale not in self.SCALES:\\n raise ValueError(\\\"Scale {!r} is not in the allowed scales {}\\\"\\n .format(scale, sorted(self.SCALES)))\\n\\n if scale == 'utc' or self.scale == 'utc':\\n # If doing a transform involving UTC then check that the leap\\n # seconds table is up to date.\\n _check_leapsec()\\n\\n # Determine the chain of scale transformations to get from the current\\n # scale to the new scale. MULTI_HOPS contains a dict of all\\n # transformations (xforms) that require intermediate xforms.\\n # The MULTI_HOPS dict is keyed by (sys1, sys2) in alphabetical order.\\n xform = (self.scale, scale)\\n xform_sort = tuple(sorted(xform))\\n multi = MULTI_HOPS.get(xform_sort, ())\\n xforms = xform_sort[:1] + multi + xform_sort[-1:]\\n # If we made the reverse xform then reverse it now.\\n if xform_sort != xform:\\n xforms = tuple(reversed(xforms))\\n\\n # Transform the jd1,2 pairs through the chain of scale xforms.\\n jd1, jd2 = self._time.jd1, self._time.jd2_filled\\n for sys1, sys2 in zip(xforms[:-1], xforms[1:]):\\n # Some xforms require an additional delta_ argument that is\\n # provided through Time methods. These values may be supplied by\\n # the user or computed based on available approximations. The\\n # get_delta_ methods are available for only one combination of\\n # sys1, sys2 though the property applies for both xform directions.\\n args = [jd1, jd2]\\n for sys12 in ((sys1, sys2), (sys2, sys1)):\\n dt_method = '_get_delta_{}_{}'.format(*sys12)\\n try:\\n get_dt = getattr(self, dt_method)\\n except AttributeError:\\n pass\\n else:\\n args.append(get_dt(jd1, jd2))\\n break\\n\\n conv_func = getattr(erfa, sys1 + sys2)\\n jd1, jd2 = conv_func(*args)\\n\\n jd1, jd2 = day_frac(jd1, jd2)\\n if self.masked:\\n jd2[self.mask] = np.nan\\n\\n self._time = self.FORMATS[self.format](jd1, jd2, scale, self.precision,\\n self.in_subfmt, self.out_subfmt,\\n from_jd=True)\\n\\n @property\\n def precision(self):\\n \\\"\\\"\\\"\\n Decimal precision when outputting seconds as floating point (int\\n value between 0 and 9 inclusive).\\n \\\"\\\"\\\"\\n return self._time.precision\\n\\n @precision.setter\\n def precision(self, val):\\n del self.cache\\n self._time.precision = val\\n\\n @property\\n def in_subfmt(self):\\n \\\"\\\"\\\"\\n Unix wildcard pattern to select subformats for parsing string input\\n times.\\n \\\"\\\"\\\"\\n return self._time.in_subfmt\\n\\n @in_subfmt.setter\\n def in_subfmt(self, val):\\n self._time.in_subfmt = val\\n del self.cache\\n\\n @property\\n def out_subfmt(self):\\n \\\"\\\"\\\"\\n Unix wildcard pattern to select subformats for outputting times.\\n \\\"\\\"\\\"\\n return self._time.out_subfmt\\n\\n @out_subfmt.setter\\n def out_subfmt(self, val):\\n # Setting the out_subfmt property here does validation of ``val``\\n self._time.out_subfmt = val\\n del self.cache\\n\\n @property\\n def shape(self):\\n \\\"\\\"\\\"The shape of the time instances.\\n\\n Like `~numpy.ndarray.shape`, can be set to a new shape by assigning a\\n tuple. Note that if different instances share some but not all\\n underlying data, setting the shape of one instance can make the other\\n instance unusable. Hence, it is strongly recommended to get new,\\n reshaped instances with the ``reshape`` method.\\n\\n Raises\\n ------\\n ValueError\\n If the new shape has the wrong total number of elements.\\n AttributeError\\n If the shape of the ``jd1``, ``jd2``, ``location``,\\n ``delta_ut1_utc``, or ``delta_tdb_tt`` attributes cannot be changed\\n without the arrays being copied. For these cases, use the\\n `Time.reshape` method (which copies any arrays that cannot be\\n reshaped in-place).\\n \\\"\\\"\\\"\\n return self._time.jd1.shape\\n\\n @shape.setter\\n def shape(self, shape):\\n del self.cache\\n\\n # We have to keep track of arrays that were already reshaped,\\n # since we may have to return those to their original shape if a later\\n # shape-setting fails.\\n reshaped = []\\n oldshape = self.shape\\n\\n # In-place reshape of data/attributes. Need to access _time.jd1/2 not\\n # self.jd1/2 because the latter are not guaranteed to be the actual\\n # data, and in fact should not be directly changeable from the public\\n # API.\\n for obj, attr in ((self._time, 'jd1'),\\n (self._time, 'jd2'),\\n (self, '_delta_ut1_utc'),\\n (self, '_delta_tdb_tt'),\\n (self, 'location')):\\n val = getattr(obj, attr, None)\\n if val is not None and val.size > 1:\\n try:\\n val.shape = shape\\n except Exception:\\n for val2 in reshaped:\\n val2.shape = oldshape\\n raise\\n else:\\n reshaped.append(val)\\n\\n def _shaped_like_input(self, value):\\n if self._time.jd1.shape:\\n if isinstance(value, np.ndarray):\\n return value\\n else:\\n raise TypeError(\\n f\\\"JD is an array ({self._time.jd1!r}) but value \\\"\\n f\\\"is not ({value!r})\\\")\\n else:\\n # zero-dimensional array, is it safe to unbox?\\n if (isinstance(value, np.ndarray)\\n and not value.shape\\n and not np.ma.is_masked(value)):\\n if value.dtype.kind == 'M':\\n # existing test doesn't want datetime64 converted\\n return value[()]\\n elif value.dtype.fields:\\n # Unpack but keep field names; .item() doesn't\\n # Still don't get python types in the fields\\n return value[()]\\n else:\\n return value.item()\\n else:\\n return value\\n\\n @property\\n def jd1(self):\\n \\\"\\\"\\\"\\n First of the two doubles that internally store time value(s) in JD.\\n \\\"\\\"\\\"\\n jd1 = self._time.mask_if_needed(self._time.jd1)\\n return self._shaped_like_input(jd1)\\n\\n @property\\n def jd2(self):\\n \\\"\\\"\\\"\\n Second of the two doubles that internally store time value(s) in JD.\\n \\\"\\\"\\\"\\n jd2 = self._time.mask_if_needed(self._time.jd2)\\n return self._shaped_like_input(jd2)\\n\\n def to_value(self, format, subfmt='*'):\\n \\\"\\\"\\\"Get time values expressed in specified output format.\\n\\n This method allows representing the ``Time`` object in the desired\\n output ``format`` and optional sub-format ``subfmt``. Available\\n built-in formats include ``jd``, ``mjd``, ``iso``, and so forth. Each\\n format can have its own sub-formats\\n\\n For built-in numerical formats like ``jd`` or ``unix``, ``subfmt`` can\\n be one of 'float', 'long', 'decimal', 'str', or 'bytes'. Here, 'long'\\n uses ``numpy.longdouble`` for somewhat enhanced precision (with\\n the enhancement depending on platform), and 'decimal'\\n :class:`decimal.Decimal` for full precision. For 'str' and 'bytes', the\\n number of digits is also chosen such that time values are represented\\n accurately.\\n\\n For built-in date-like string formats, one of 'date_hms', 'date_hm', or\\n 'date' (or 'longdate_hms', etc., for 5-digit years in\\n `~astropy.time.TimeFITS`). For sub-formats including seconds, the\\n number of digits used for the fractional seconds is as set by\\n `~astropy.time.Time.precision`.\\n\\n Parameters\\n ----------\\n format : str\\n The format in which one wants the time values. Default: the current\\n format.\\n subfmt : str or None, optional\\n Value or wildcard pattern to select the sub-format in which the\\n values should be given. The default of '*' picks the first\\n available for a given format, i.e., 'float' or 'date_hms'.\\n If `None`, use the instance's ``out_subfmt``.\\n\\n \\\"\\\"\\\"\\n # TODO: add a precision argument (but ensure it is keyword argument\\n # only, to make life easier for TimeDelta.to_value()).\\n if format not in self.FORMATS:\\n raise ValueError(f'format must be one of {list(self.FORMATS)}')\\n\\n cache = self.cache['format']\\n # Try to keep cache behaviour like it was in astropy < 4.0.\\n key = format if subfmt is None else (format, subfmt)\\n if key not in cache:\\n if format == self.format:\\n tm = self\\n else:\\n tm = self.replicate(format=format)\\n\\n # Some TimeFormat subclasses may not be able to handle being passes\\n # on a out_subfmt. This includes some core classes like\\n # TimeBesselianEpochString that do not have any allowed subfmts. But\\n # those do deal with `self.out_subfmt` internally, so if subfmt is\\n # the same, we do not pass it on.\\n kwargs = {}\\n if subfmt is not None and subfmt != tm.out_subfmt:\\n kwargs['out_subfmt'] = subfmt\\n try:\\n value = tm._time.to_value(parent=tm, **kwargs)\\n except TypeError as exc:\\n # Try validating subfmt, e.g. for formats like 'jyear_str' that\\n # do not implement out_subfmt in to_value() (because there are\\n # no allowed subformats). If subfmt is not valid this gives the\\n # same exception as would have occurred if the call to\\n # `to_value()` had succeeded.\\n tm._time._select_subfmts(subfmt)\\n\\n # Subfmt was valid, so fall back to the original exception to see\\n # if it was lack of support for out_subfmt as a call arg.\\n if \\\"unexpected keyword argument 'out_subfmt'\\\" in str(exc):\\n raise ValueError(\\n f\\\"to_value() method for format {format!r} does not \\\"\\n f\\\"support passing a 'subfmt' argument\\\") from None\\n else:\\n # Some unforeseen exception so raise.\\n raise\\n\\n value = tm._shaped_like_input(value)\\n cache[key] = value\\n return cache[key]\\n\\n @property\\n def value(self):\\n \\\"\\\"\\\"Time value(s) in current format\\\"\\\"\\\"\\n return self.to_value(self.format, None)\\n\\n @property\\n def masked(self):\\n return self._time.masked\\n\\n @property\\n def mask(self):\\n return self._time.mask\\n\\n def insert(self, obj, values, axis=0):\\n \\\"\\\"\\\"\\n Insert values before the given indices in the column and return\\n a new `~astropy.time.Time` or `~astropy.time.TimeDelta` object.\\n\\n The values to be inserted must conform to the rules for in-place setting\\n of ``Time`` objects (see ``Get and set values`` in the ``Time``\\n documentation).\\n\\n The API signature matches the ``np.insert`` API, but is more limited.\\n The specification of insert index ``obj`` must be a single integer,\\n and the ``axis`` must be ``0`` for simple row insertion before the\\n index.\\n\\n Parameters\\n ----------\\n obj : int\\n Integer index before which ``values`` is inserted.\\n values : array-like\\n Value(s) to insert. If the type of ``values`` is different\\n from that of quantity, ``values`` is converted to the matching type.\\n axis : int, optional\\n Axis along which to insert ``values``. Default is 0, which is the\\n only allowed value and will insert a row.\\n\\n Returns\\n -------\\n out : `~astropy.time.Time` subclass\\n New time object with inserted value(s)\\n\\n \\\"\\\"\\\"\\n # Validate inputs: obj arg is integer, axis=0, self is not a scalar, and\\n # input index is in bounds.\\n try:\\n idx0 = operator.index(obj)\\n except TypeError:\\n raise TypeError('obj arg must be an integer')\\n\\n if axis != 0:\\n raise ValueError('axis must be 0')\\n\\n if not self.shape:\\n raise TypeError('cannot insert into scalar {} object'\\n .format(self.__class__.__name__))\\n\\n if abs(idx0) > len(self):\\n raise IndexError('index {} is out of bounds for axis 0 with size {}'\\n .format(idx0, len(self)))\\n\\n # Turn negative index into positive\\n if idx0 < 0:\\n idx0 = len(self) + idx0\\n\\n # For non-Time object, use numpy to help figure out the length. (Note annoying\\n # case of a string input that has a length which is not the length we want).\\n if not isinstance(values, self.__class__):\\n values = np.asarray(values)\\n n_values = len(values) if values.shape else 1\\n\\n # Finally make the new object with the correct length and set values for the\\n # three sections, before insert, the insert, and after the insert.\\n out = self.__class__.info.new_like([self], len(self) + n_values, name=self.info.name)\\n\\n out._time.jd1[:idx0] = self._time.jd1[:idx0]\\n out._time.jd2[:idx0] = self._time.jd2[:idx0]\\n\\n # This uses the Time setting machinery to coerce and validate as necessary.\\n out[idx0:idx0 + n_values] = values\\n\\n out._time.jd1[idx0 + n_values:] = self._time.jd1[idx0:]\\n out._time.jd2[idx0 + n_values:] = self._time.jd2[idx0:]\\n\\n return out\\n\\n def __setitem__(self, item, value):\\n if not self.writeable:\\n if self.shape:\\n raise ValueError('{} object is read-only. Make a '\\n 'copy() or set \\\"writeable\\\" attribute to True.'\\n .format(self.__class__.__name__))\\n else:\\n raise ValueError('scalar {} object is read-only.'\\n .format(self.__class__.__name__))\\n\\n # Any use of setitem results in immediate cache invalidation\\n del self.cache\\n\\n # Setting invalidates transform deltas\\n for attr in ('_delta_tdb_tt', '_delta_ut1_utc'):\\n if hasattr(self, attr):\\n delattr(self, attr)\\n\\n if value is np.ma.masked or value is np.nan:\\n self._time.jd2[item] = np.nan\\n return\\n\\n value = self._make_value_equivalent(item, value)\\n\\n # Finally directly set the jd1/2 values. Locations are known to match.\\n if self.scale is not None:\\n value = getattr(value, self.scale)\\n self._time.jd1[item] = value._time.jd1\\n self._time.jd2[item] = value._time.jd2\\n\\n def isclose(self, other, atol=None):\\n \\\"\\\"\\\"Returns a boolean or boolean array where two Time objects are\\n element-wise equal within a time tolerance.\\n\\n This evaluates the expression below::\\n\\n abs(self - other) <= atol\\n\\n Parameters\\n ----------\\n other : `~astropy.time.Time`\\n Time object for comparison.\\n atol : `~astropy.units.Quantity` or `~astropy.time.TimeDelta`\\n Absolute tolerance for equality with units of time (e.g. ``u.s`` or\\n ``u.day``). Default is two bits in the 128-bit JD time representation,\\n equivalent to about 40 picosecs.\\n \\\"\\\"\\\"\\n if atol is None:\\n # Note: use 2 bits instead of 1 bit based on experience in precision\\n # tests, since taking the difference with a UTC time means one has\\n # to do a scale change.\\n atol = 2 * np.finfo(float).eps * u.day\\n\\n if not isinstance(atol, (u.Quantity, TimeDelta)):\\n raise TypeError(\\\"'atol' argument must be a Quantity or TimeDelta instance, got \\\"\\n f'{atol.__class__.__name__} instead')\\n\\n try:\\n # Separate these out so user sees where the problem is\\n dt = self - other\\n dt = abs(dt)\\n out = dt <= atol\\n except Exception as err:\\n raise TypeError(\\\"'other' argument must support subtraction with Time \\\"\\n f\\\"and return a value that supports comparison with \\\"\\n f\\\"{atol.__class__.__name__}: {err}\\\")\\n\\n return out\\n\\n def copy(self, format=None):\\n \\\"\\\"\\\"\\n Return a fully independent copy the Time object, optionally changing\\n the format.\\n\\n If ``format`` is supplied then the time format of the returned Time\\n object will be set accordingly, otherwise it will be unchanged from the\\n original.\\n\\n In this method a full copy of the internal time arrays will be made.\\n The internal time arrays are normally not changeable by the user so in\\n most cases the ``replicate()`` method should be used.\\n\\n Parameters\\n ----------\\n format : str, optional\\n Time format of the copy.\\n\\n Returns\\n -------\\n tm : Time object\\n Copy of this object\\n \\\"\\\"\\\"\\n return self._apply('copy', format=format)\\n\\n def replicate(self, format=None, copy=False, cls=None):\\n \\\"\\\"\\\"\\n Return a replica of the Time object, optionally changing the format.\\n\\n If ``format`` is supplied then the time format of the returned Time\\n object will be set accordingly, otherwise it will be unchanged from the\\n original.\\n\\n If ``copy`` is set to `True` then a full copy of the internal time arrays\\n will be made. By default the replica will use a reference to the\\n original arrays when possible to save memory. The internal time arrays\\n are normally not changeable by the user so in most cases it should not\\n be necessary to set ``copy`` to `True`.\\n\\n The convenience method copy() is available in which ``copy`` is `True`\\n by default.\\n\\n Parameters\\n ----------\\n format : str, optional\\n Time format of the replica.\\n copy : bool, optional\\n Return a true copy instead of using references where possible.\\n\\n Returns\\n -------\\n tm : Time object\\n Replica of this object\\n \\\"\\\"\\\"\\n return self._apply('copy' if copy else 'replicate', format=format, cls=cls)\\n\\n def _apply(self, method, *args, format=None, cls=None, **kwargs):\\n \\\"\\\"\\\"Create a new time object, possibly applying a method to the arrays.\\n\\n Parameters\\n ----------\\n method : str or callable\\n If string, can be 'replicate' or the name of a relevant\\n `~numpy.ndarray` method. In the former case, a new time instance\\n with unchanged internal data is created, while in the latter the\\n method is applied to the internal ``jd1`` and ``jd2`` arrays, as\\n well as to possible ``location``, ``_delta_ut1_utc``, and\\n ``_delta_tdb_tt`` arrays.\\n If a callable, it is directly applied to the above arrays.\\n Examples: 'copy', '__getitem__', 'reshape', `~numpy.broadcast_to`.\\n args : tuple\\n Any positional arguments for ``method``.\\n kwargs : dict\\n Any keyword arguments for ``method``. If the ``format`` keyword\\n argument is present, this will be used as the Time format of the\\n replica.\\n\\n Examples\\n --------\\n Some ways this is used internally::\\n\\n copy : ``_apply('copy')``\\n replicate : ``_apply('replicate')``\\n reshape : ``_apply('reshape', new_shape)``\\n index or slice : ``_apply('__getitem__', item)``\\n broadcast : ``_apply(np.broadcast, shape=new_shape)``\\n \\\"\\\"\\\"\\n new_format = self.format if format is None else format\\n\\n if callable(method):\\n apply_method = lambda array: method(array, *args, **kwargs)\\n\\n else:\\n if method == 'replicate':\\n apply_method = None\\n else:\\n apply_method = operator.methodcaller(method, *args, **kwargs)\\n\\n jd1, jd2 = self._time.jd1, self._time.jd2\\n if apply_method:\\n jd1 = apply_method(jd1)\\n jd2 = apply_method(jd2)\\n\\n # Get a new instance of our class and set its attributes directly.\\n tm = super().__new__(cls or self.__class__)\\n tm._time = TimeJD(jd1, jd2, self.scale, precision=0,\\n in_subfmt='*', out_subfmt='*', from_jd=True)\\n\\n # Optional ndarray attributes.\\n for attr in ('_delta_ut1_utc', '_delta_tdb_tt', 'location'):\\n try:\\n val = getattr(self, attr)\\n except AttributeError:\\n continue\\n\\n if apply_method:\\n # Apply the method to any value arrays (though skip if there is\\n # only an array scalar and the method would return a view,\\n # since in that case nothing would change).\\n if getattr(val, 'shape', ()):\\n val = apply_method(val)\\n elif method == 'copy' or method == 'flatten':\\n # flatten should copy also for a single element array, but\\n # we cannot use it directly for array scalars, since it\\n # always returns a one-dimensional array. So, just copy.\\n val = copy.copy(val)\\n\\n setattr(tm, attr, val)\\n\\n # Copy other 'info' attr only if it has actually been defined and the\\n # time object is not a scalar (issue #10688).\\n # See PR #3898 for further explanation and justification, along\\n # with Quantity.__array_finalize__\\n if 'info' in self.__dict__:\\n tm.info = self.info\\n\\n # Make the new internal _time object corresponding to the format\\n # in the copy. If the format is unchanged this process is lightweight\\n # and does not create any new arrays.\\n if new_format not in tm.FORMATS:\\n raise ValueError(f'format must be one of {list(tm.FORMATS)}')\\n\\n NewFormat = tm.FORMATS[new_format]\\n\\n tm._time = NewFormat(\\n tm._time.jd1, tm._time.jd2,\\n tm._time._scale,\\n precision=self.precision,\\n in_subfmt=NewFormat._get_allowed_subfmt(self.in_subfmt),\\n out_subfmt=NewFormat._get_allowed_subfmt(self.out_subfmt),\\n from_jd=True)\\n tm._format = new_format\\n tm.SCALES = self.SCALES\\n\\n return tm\\n\\n def __copy__(self):\\n \\\"\\\"\\\"\\n Overrides the default behavior of the `copy.copy` function in\\n the python stdlib to behave like `Time.copy`. Does *not* make a\\n copy of the JD arrays - only copies by reference.\\n \\\"\\\"\\\"\\n return self.replicate()\\n\\n def __deepcopy__(self, memo):\\n \\\"\\\"\\\"\\n Overrides the default behavior of the `copy.deepcopy` function\\n in the python stdlib to behave like `Time.copy`. Does make a\\n copy of the JD arrays.\\n \\\"\\\"\\\"\\n return self.copy()\\n\\n def _advanced_index(self, indices, axis=None, keepdims=False):\\n \\\"\\\"\\\"Turn argmin, argmax output into an advanced index.\\n\\n Argmin, argmax output contains indices along a given axis in an array\\n shaped like the other dimensions. To use this to get values at the\\n correct location, a list is constructed in which the other axes are\\n indexed sequentially. For ``keepdims`` is ``True``, the net result is\\n the same as constructing an index grid with ``np.ogrid`` and then\\n replacing the ``axis`` item with ``indices`` with its shaped expanded\\n at ``axis``. For ``keepdims`` is ``False``, the result is the same but\\n with the ``axis`` dimension removed from all list entries.\\n\\n For ``axis`` is ``None``, this calls :func:`~numpy.unravel_index`.\\n\\n Parameters\\n ----------\\n indices : array\\n Output of argmin or argmax.\\n axis : int or None\\n axis along which argmin or argmax was used.\\n keepdims : bool\\n Whether to construct indices that keep or remove the axis along\\n which argmin or argmax was used. Default: ``False``.\\n\\n Returns\\n -------\\n advanced_index : list of arrays\\n Suitable for use as an advanced index.\\n \\\"\\\"\\\"\\n if axis is None:\\n return np.unravel_index(indices, self.shape)\\n\\n ndim = self.ndim\\n if axis < 0:\\n axis = axis + ndim\\n\\n if keepdims and indices.ndim < self.ndim:\\n indices = np.expand_dims(indices, axis)\\n\\n index = [indices\\n if i == axis\\n else np.arange(s).reshape(\\n (1,) * (i if keepdims or i < axis else i - 1)\\n + (s,)\\n + (1,) * (ndim - i - (1 if keepdims or i > axis else 2))\\n )\\n for i, s in enumerate(self.shape)]\\n\\n return tuple(index)\\n\\n def argmin(self, axis=None, out=None):\\n \\\"\\\"\\\"Return indices of the minimum values along the given axis.\\n\\n This is similar to :meth:`~numpy.ndarray.argmin`, but adapted to ensure\\n that the full precision given by the two doubles ``jd1`` and ``jd2``\\n is used. See :func:`~numpy.argmin` for detailed documentation.\\n \\\"\\\"\\\"\\n # First get the minimum at normal precision.\\n jd1, jd2 = self.jd1, self.jd2\\n approx = np.min(jd1 + jd2, axis, keepdims=True)\\n\\n # Approx is very close to the true minimum, and by subtracting it at\\n # full precision, all numbers near 0 can be represented correctly,\\n # so we can be sure we get the true minimum.\\n # The below is effectively what would be done for\\n # dt = (self - self.__class__(approx, format='jd')).jd\\n # which translates to:\\n # approx_jd1, approx_jd2 = day_frac(approx, 0.)\\n # dt = (self.jd1 - approx_jd1) + (self.jd2 - approx_jd2)\\n dt = (jd1 - approx) + jd2\\n\\n return dt.argmin(axis, out)\\n\\n def argmax(self, axis=None, out=None):\\n \\\"\\\"\\\"Return indices of the maximum values along the given axis.\\n\\n This is similar to :meth:`~numpy.ndarray.argmax`, but adapted to ensure\\n that the full precision given by the two doubles ``jd1`` and ``jd2``\\n is used. See :func:`~numpy.argmax` for detailed documentation.\\n \\\"\\\"\\\"\\n # For procedure, see comment on argmin.\\n jd1, jd2 = self.jd1, self.jd2\\n approx = np.max(jd1 + jd2, axis, keepdims=True)\\n\\n dt = (jd1 - approx) + jd2\\n\\n return dt.argmax(axis, out)\\n\\n def argsort(self, axis=-1):\\n \\\"\\\"\\\"Returns the indices that would sort the time array.\\n\\n This is similar to :meth:`~numpy.ndarray.argsort`, but adapted to ensure\\n that the full precision given by the two doubles ``jd1`` and ``jd2``\\n is used, and that corresponding attributes are copied. Internally,\\n it uses :func:`~numpy.lexsort`, and hence no sort method can be chosen.\\n \\\"\\\"\\\"\\n # For procedure, see comment on argmin.\\n jd1, jd2 = self.jd1, self.jd2\\n approx = jd1 + jd2\\n remainder = (jd1 - approx) + jd2\\n\\n if axis is None:\\n return np.lexsort((remainder.ravel(), approx.ravel()))\\n else:\\n return np.lexsort(keys=(remainder, approx), axis=axis)\\n\\n def min(self, axis=None, out=None, keepdims=False):\\n \\\"\\\"\\\"Minimum along a given axis.\\n\\n This is similar to :meth:`~numpy.ndarray.min`, but adapted to ensure\\n that the full precision given by the two doubles ``jd1`` and ``jd2``\\n is used, and that corresponding attributes are copied.\\n\\n Note that the ``out`` argument is present only for compatibility with\\n ``np.min``; since `Time` instances are immutable, it is not possible\\n to have an actual ``out`` to store the result in.\\n \\\"\\\"\\\"\\n if out is not None:\\n raise ValueError(\\\"Since `Time` instances are immutable, ``out`` \\\"\\n \\\"cannot be set to anything but ``None``.\\\")\\n return self[self._advanced_index(self.argmin(axis), axis, keepdims)]\\n\\n def max(self, axis=None, out=None, keepdims=False):\\n \\\"\\\"\\\"Maximum along a given axis.\\n\\n This is similar to :meth:`~numpy.ndarray.max`, but adapted to ensure\\n that the full precision given by the two doubles ``jd1`` and ``jd2``\\n is used, and that corresponding attributes are copied.\\n\\n Note that the ``out`` argument is present only for compatibility with\\n ``np.max``; since `Time` instances are immutable, it is not possible\\n to have an actual ``out`` to store the result in.\\n \\\"\\\"\\\"\\n if out is not None:\\n raise ValueError(\\\"Since `Time` instances are immutable, ``out`` \\\"\\n \\\"cannot be set to anything but ``None``.\\\")\\n return self[self._advanced_index(self.argmax(axis), axis, keepdims)]\\n\\n def ptp(self, axis=None, out=None, keepdims=False):\\n \\\"\\\"\\\"Peak to peak (maximum - minimum) along a given axis.\\n\\n This is similar to :meth:`~numpy.ndarray.ptp`, but adapted to ensure\\n that the full precision given by the two doubles ``jd1`` and ``jd2``\\n is used.\\n\\n Note that the ``out`` argument is present only for compatibility with\\n `~numpy.ptp`; since `Time` instances are immutable, it is not possible\\n to have an actual ``out`` to store the result in.\\n \\\"\\\"\\\"\\n if out is not None:\\n raise ValueError(\\\"Since `Time` instances are immutable, ``out`` \\\"\\n \\\"cannot be set to anything but ``None``.\\\")\\n return (self.max(axis, keepdims=keepdims)\\n - self.min(axis, keepdims=keepdims))\\n\\n def sort(self, axis=-1):\\n \\\"\\\"\\\"Return a copy sorted along the specified axis.\\n\\n This is similar to :meth:`~numpy.ndarray.sort`, but internally uses\\n indexing with :func:`~numpy.lexsort` to ensure that the full precision\\n given by the two doubles ``jd1`` and ``jd2`` is kept, and that\\n corresponding attributes are properly sorted and copied as well.\\n\\n Parameters\\n ----------\\n axis : int or None\\n Axis to be sorted. If ``None``, the flattened array is sorted.\\n By default, sort over the last axis.\\n \\\"\\\"\\\"\\n return self[self._advanced_index(self.argsort(axis), axis,\\n keepdims=True)]\\n\\n @property\\n def cache(self):\\n \\\"\\\"\\\"\\n Return the cache associated with this instance.\\n \\\"\\\"\\\"\\n return self._time.cache\\n\\n @cache.deleter\\n def cache(self):\\n del self._time.cache\\n\\n def __getattr__(self, attr):\\n \\\"\\\"\\\"\\n Get dynamic attributes to output format or do timescale conversion.\\n \\\"\\\"\\\"\\n if attr in self.SCALES and self.scale is not None:\\n cache = self.cache['scale']\\n if attr not in cache:\\n if attr == self.scale:\\n tm = self\\n else:\\n tm = self.replicate()\\n tm._set_scale(attr)\\n if tm.shape:\\n # Prevent future modification of cached array-like object\\n tm.writeable = False\\n cache[attr] = tm\\n return cache[attr]\\n\\n elif attr in self.FORMATS:\\n return self.to_value(attr, subfmt=None)\\n\\n elif attr in TIME_SCALES: # allowed ones done above (self.SCALES)\\n if self.scale is None:\\n raise ScaleValueError(\\\"Cannot convert TimeDelta with \\\"\\n \\\"undefined scale to any defined scale.\\\")\\n else:\\n raise ScaleValueError(\\\"Cannot convert {} with scale \\\"\\n \\\"'{}' to scale '{}'\\\"\\n .format(self.__class__.__name__,\\n self.scale, attr))\\n\\n else:\\n # Should raise AttributeError\\n return self.__getattribute__(attr)\\n\\n def __dir__(self):\\n return sorted(set(super().__dir__()) | set(self.SCALES) | set(self.FORMATS))\\n\\n def _match_shape(self, val):\\n \\\"\\\"\\\"\\n Ensure that `val` is matched to length of self. If val has length 1\\n then broadcast, otherwise cast to double and make sure shape matches.\\n \\\"\\\"\\\"\\n val = _make_array(val, copy=True) # be conservative and copy\\n if val.size > 1 and val.shape != self.shape:\\n try:\\n # check the value can be broadcast to the shape of self.\\n val = np.broadcast_to(val, self.shape, subok=True)\\n except Exception:\\n raise ValueError('Attribute shape must match or be '\\n 'broadcastable to that of Time object. '\\n 'Typically, give either a single value or '\\n 'one for each time.')\\n\\n return val\\n\\n def _time_comparison(self, other, op):\\n \\\"\\\"\\\"If other is of same class as self, compare difference in self.scale.\\n Otherwise, return NotImplemented\\n \\\"\\\"\\\"\\n if other.__class__ is not self.__class__:\\n try:\\n other = self.__class__(other, scale=self.scale)\\n except Exception:\\n # Let other have a go.\\n return NotImplemented\\n\\n if(self.scale is not None and self.scale not in other.SCALES\\n or other.scale is not None and other.scale not in self.SCALES):\\n # Other will also not be able to do it, so raise a TypeError\\n # immediately, allowing us to explain why it doesn't work.\\n raise TypeError(\\\"Cannot compare {} instances with scales \\\"\\n \\\"'{}' and '{}'\\\".format(self.__class__.__name__,\\n self.scale, other.scale))\\n\\n if self.scale is not None and other.scale is not None:\\n other = getattr(other, self.scale)\\n\\n return op((self.jd1 - other.jd1) + (self.jd2 - other.jd2), 0.)\\n\\n def __lt__(self, other):\\n return self._time_comparison(other, operator.lt)\\n\\n def __le__(self, other):\\n return self._time_comparison(other, operator.le)\\n\\n def __eq__(self, other):\\n \\\"\\\"\\\"\\n If other is an incompatible object for comparison, return `False`.\\n Otherwise, return `True` if the time difference between self and\\n other is zero.\\n \\\"\\\"\\\"\\n return self._time_comparison(other, operator.eq)\\n\\n def __ne__(self, other):\\n \\\"\\\"\\\"\\n If other is an incompatible object for comparison, return `True`.\\n Otherwise, return `False` if the time difference between self and\\n other is zero.\\n \\\"\\\"\\\"\\n return self._time_comparison(other, operator.ne)\\n\\n def __gt__(self, other):\\n return self._time_comparison(other, operator.gt)\\n\\n def __ge__(self, other):\\n return self._time_comparison(other, operator.ge)\\n\\n\\nclass Time(TimeBase):\\n \\\"\\\"\\\"\\n Represent and manipulate times and dates for astronomy.\\n\\n A `Time` object is initialized with one or more times in the ``val``\\n argument. The input times in ``val`` must conform to the specified\\n ``format`` and must correspond to the specified time ``scale``. The\\n optional ``val2`` time input should be supplied only for numeric input\\n formats (e.g. JD) where very high precision (better than 64-bit precision)\\n is required.\\n\\n The allowed values for ``format`` can be listed with::\\n\\n >>> list(Time.FORMATS)\\n ['jd', 'mjd', 'decimalyear', 'unix', 'unix_tai', 'cxcsec', 'gps', 'plot_date',\\n 'stardate', 'datetime', 'ymdhms', 'iso', 'isot', 'yday', 'datetime64',\\n 'fits', 'byear', 'jyear', 'byear_str', 'jyear_str']\\n\\n See also: http://docs.astropy.org/en/stable/time/\\n\\n Parameters\\n ----------\\n val : sequence, ndarray, number, str, bytes, or `~astropy.time.Time` object\\n Value(s) to initialize the time or times. Bytes are decoded as ascii.\\n val2 : sequence, ndarray, or number; optional\\n Value(s) to initialize the time or times. Only used for numerical\\n input, to help preserve precision.\\n format : str, optional\\n Format of input value(s)\\n scale : str, optional\\n Time scale of input value(s), must be one of the following:\\n ('tai', 'tcb', 'tcg', 'tdb', 'tt', 'ut1', 'utc')\\n precision : int, optional\\n Digits of precision in string representation of time\\n in_subfmt : str, optional\\n Unix glob to select subformats for parsing input times\\n out_subfmt : str, optional\\n Unix glob to select subformat for outputting times\\n location : `~astropy.coordinates.EarthLocation` or tuple, optional\\n If given as an tuple, it should be able to initialize an\\n an EarthLocation instance, i.e., either contain 3 items with units of\\n length for geocentric coordinates, or contain a longitude, latitude,\\n and an optional height for geodetic coordinates.\\n Can be a single location, or one for each input time.\\n If not given, assumed to be the center of the Earth for time scale\\n transformations to and from the solar-system barycenter.\\n copy : bool, optional\\n Make a copy of the input values\\n \\\"\\\"\\\"\\n SCALES = TIME_SCALES\\n \\\"\\\"\\\"List of time scales\\\"\\\"\\\"\\n\\n FORMATS = TIME_FORMATS\\n \\\"\\\"\\\"Dict of time formats\\\"\\\"\\\"\\n\\n def __new__(cls, val, val2=None, format=None, scale=None,\\n precision=None, in_subfmt=None, out_subfmt=None,\\n location=None, copy=False):\\n\\n if isinstance(val, Time):\\n self = val.replicate(format=format, copy=copy, cls=cls)\\n else:\\n self = super().__new__(cls)\\n\\n return self\\n\\n def __init__(self, val, val2=None, format=None, scale=None,\\n precision=None, in_subfmt=None, out_subfmt=None,\\n location=None, copy=False):\\n\\n if location is not None:\\n from astropy.coordinates import EarthLocation\\n if isinstance(location, EarthLocation):\\n self.location = location\\n else:\\n self.location = EarthLocation(*location)\\n if self.location.size == 1:\\n self.location = self.location.squeeze()\\n else:\\n if not hasattr(self, 'location'):\\n self.location = None\\n\\n if isinstance(val, Time):\\n # Update _time formatting parameters if explicitly specified\\n if precision is not None:\\n self._time.precision = precision\\n if in_subfmt is not None:\\n self._time.in_subfmt = in_subfmt\\n if out_subfmt is not None:\\n self._time.out_subfmt = out_subfmt\\n self.SCALES = TIME_TYPES[self.scale]\\n if scale is not None:\\n self._set_scale(scale)\\n else:\\n self._init_from_vals(val, val2, format, scale, copy,\\n precision, in_subfmt, out_subfmt)\\n self.SCALES = TIME_TYPES[self.scale]\\n\\n if self.location is not None and (self.location.size > 1\\n and self.location.shape != self.shape):\\n try:\\n # check the location can be broadcast to self's shape.\\n self.location = np.broadcast_to(self.location, self.shape,\\n subok=True)\\n except Exception as err:\\n raise ValueError('The location with shape {} cannot be '\\n 'broadcast against time with shape {}. '\\n 'Typically, either give a single location or '\\n 'one for each time.'\\n .format(self.location.shape, self.shape)) from err\\n\\n def _make_value_equivalent(self, item, value):\\n \\\"\\\"\\\"Coerce setitem value into an equivalent Time object\\\"\\\"\\\"\\n\\n # If there is a vector location then broadcast to the Time shape\\n # and then select with ``item``\\n if self.location is not None and self.location.shape:\\n self_location = np.broadcast_to(self.location, self.shape, subok=True)[item]\\n else:\\n self_location = self.location\\n\\n if isinstance(value, Time):\\n # Make sure locations are compatible. Location can be either None or\\n # a Location object.\\n if self_location is None and value.location is None:\\n match = True\\n elif ((self_location is None and value.location is not None)\\n or (self_location is not None and value.location is None)):\\n match = False\\n else:\\n match = np.all(self_location == value.location)\\n if not match:\\n raise ValueError('cannot set to Time with different location: '\\n 'expected location={} and '\\n 'got location={}'\\n .format(self_location, value.location))\\n else:\\n try:\\n value = self.__class__(value, scale=self.scale, location=self_location)\\n except Exception:\\n try:\\n value = self.__class__(value, scale=self.scale, format=self.format,\\n location=self_location)\\n except Exception as err:\\n raise ValueError('cannot convert value to a compatible Time object: {}'\\n .format(err))\\n return value\\n\\n @classmethod\\n def now(cls):\\n \\\"\\\"\\\"\\n Creates a new object corresponding to the instant in time this\\n method is called.\\n\\n .. note::\\n \\\"Now\\\" is determined using the `~datetime.datetime.utcnow`\\n function, so its accuracy and precision is determined by that\\n function. Generally that means it is set by the accuracy of\\n your system clock.\\n\\n Returns\\n -------\\n nowtime : :class:`~astropy.time.Time`\\n A new `Time` object (or a subclass of `Time` if this is called from\\n such a subclass) at the current time.\\n \\\"\\\"\\\"\\n # call `utcnow` immediately to be sure it's ASAP\\n dtnow = datetime.utcnow()\\n return cls(val=dtnow, format='datetime', scale='utc')\\n\\n info = TimeInfo()\\n\\n @classmethod\\n def strptime(cls, time_string, format_string, **kwargs):\\n \\\"\\\"\\\"\\n Parse a string to a Time according to a format specification.\\n See `time.strptime` documentation for format specification.\\n\\n >>> Time.strptime('2012-Jun-30 23:59:60', '%Y-%b-%d %H:%M:%S')\\n