content
stringlengths
1
103k
path
stringlengths
8
216
filename
stringlengths
2
179
language
stringclasses
15 values
size_bytes
int64
2
189k
quality_score
float64
0.5
0.95
complexity
float64
0
1
documentation_ratio
float64
0
1
repository
stringclasses
5 values
stars
int64
0
1k
created_date
stringdate
2023-07-10 19:21:08
2025-07-09 19:11:45
license
stringclasses
4 values
is_test
bool
2 classes
file_hash
stringlengths
32
32
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom pygments.style import Style\nfrom pygments.token import (\n Comment, Error, Generic, Keyword, Literal, Name, Number, Operator, Other,\n Punctuation, String, Text, Whitespace)\n\n\nclass JupyterStyle(Style):\n """\n A pygments style using JupyterLab CSS variables.\n\n The goal is to mimick JupyterLab's codemirror theme.\n\n Known impossibilities:\n\n - With pygments, the dot in `foo.bar` is considered an Operator (class: 'o'),\n while in codemirror, it is bare text.\n - With pygments, in both `from foo import bar`, and `foo.bar`, "bar" is\n considered a Name (class: 'n'), while in coremirror, the latter is a property.\n\nAvailable CSS variables are\n\n --jp-mirror-editor-keyword-color\n --jp-mirror-editor-atom-color\n --jp-mirror-editor-number-color\n --jp-mirror-editor-def-color\n --jp-mirror-editor-variable-color\n --jp-mirror-editor-variable-2-color\n --jp-mirror-editor-variable-3-color\n --jp-mirror-editor-punctuation-color\n --jp-mirror-editor-property-color\n --jp-mirror-editor-operator-color\n --jp-mirror-editor-comment-color\n --jp-mirror-editor-string-color\n --jp-mirror-editor-string-2-color\n --jp-mirror-editor-meta-color\n --jp-mirror-editor-qualifier-color\n --jp-mirror-editor-builtin-color\n --jp-mirror-editor-bracket-color\n --jp-mirror-editor-tag-color\n --jp-mirror-editor-attribute-color\n --jp-mirror-editor-header-color\n --jp-mirror-editor-quote-color\n --jp-mirror-editor-link-color\n --jp-mirror-editor-error-color\n """\n\n default_style = ''\n background_color = 'var(--jp-cell-editor-background)'\n highlight_color = 'var(--jp-cell-editor-active-background)'\n\n styles = {\n Text: 'var(--jp-mirror-editor-variable-color)', # no class\n Whitespace: '', # class: 'w'\n Error: 'var(--jp-mirror-editor-error-color)', # class: 'err'\n Other: '', # class: 'x'\n\n Comment: 'italic var(--jp-mirror-editor-comment-color)', # class: 'c'\n #Comment.Multiline: '', # class: 'cm'\n #Comment.Preproc: '', # class: 'cp'\n #Comment.Single: '', # class: 'c1'\n #Comment.Special: '', # class: 'cs'\n\n Keyword: 'bold var(--jp-mirror-editor-keyword-color)', # class: 'k'\n #Keyword.Constant: '', # class: 'kc'\n #Keyword.Declaration: '', # class: 'kd'\n #Keyword.Namespace: '', # class: 'kn'\n #Keyword.Pseudo: '', # class: 'kp'\n #Keyword.Reserved: '', # class: 'kr'\n #Keyword.Type: '', # class: 'kt'\n\n Operator: 'bold var(--jp-mirror-editor-operator-color)', # class: 'o'\n Operator.Word: '', # class: 'ow'\n\n Literal: '', # class: 'l'\n Literal.Date: '', # class: 'ld'\n\n String: 'var(--jp-mirror-editor-string-color)',\n #String.Backtick: '', # class: 'sb'\n #String.Char: '', # class: 'sc'\n #String.Doc: '', # class: 'sd'\n #String.Double: '', # class: 's2'\n #String.Escape: '', # class: 'se'\n #String.Heredoc: '', # class: 'sh'\n #String.Interpol: '', # class: 'si'\n #String.Other: '', # class: 'sx'\n #String.Regex: '', # class: 'sr'\n #String.Single: '', # class: 's1'\n #String.Symbol: '', # class: 'ss'\n\n Number: 'var(--jp-mirror-editor-number-color)', # class: 'm'\n #Number.Float: '', # class: 'mf'\n #Number.Hex: '', # class: 'mh'\n #Number.Integer: '', # class: 'mi'\n #Number.Integer.Long: '', # class: 'il'\n #Number.Oct: '', # class: 'mo'\n\n Name: '', # class: 'n'\n #Name.Attribute: '', # class: 'na'\n #Name.Builtin: '', # class: 'nb'\n #Name.Builtin.Pseudo: '', # class: 'bp'\n #Name.Class: '', # class: 'nc'\n #Name.Constant: '', # class: 'no'\n #Name.Decorator: '', # class: 'nd'\n #Name.Entity: '', # class: 'ni'\n #Name.Exception: '', # class: 'ne'\n #Name.Function: '', # class: 'nf'\n #Name.Property: '', # class 'py'\n #Name.Label: '', # class: 'nl'\n #Name.Namespace: '', # class: 'nn'\n #Name.Other: '', # class: 'nx'\n #Name.Tag: '', # class: 'nt'\n #Name.Variable: '', # class: 'nv'\n #Name.Variable.Class: '', # class: 'vc'\n #Name.Variable.Global: '', # class: 'vg'\n #Name.Variable.Instance: '', # class: 'vi'\n\n Generic: '', # class: 'g'\n #Generic.Deleted: '', # class: 'gd',\n #Generic.Emph: 'italic', # class: 'ge'\n #Generic.Error: '', # class: 'gr'\n #Generic.Heading: '', # class: 'gh'\n #Generic.Inserted: '', # class: 'gi'\n #Generic.Output: '', # class: 'go'\n #Generic.Prompt: '', # class: 'gp'\n #Generic.Strong: '', # class: 'gs'\n #Generic.Subheading: '', # class: 'gu'\n #Generic.Traceback: '', # class: 'gt'\n\n Punctuation: 'var(--jp-mirror-editor-punctuation-color)' # class: 'p'\n }\n
.venv\Lib\site-packages\jupyterlab_pygments\style.py
style.py
Python
8,492
0.95
0.556391
0.491228
vue-tools
973
2024-10-30T11:17:59.564392
Apache-2.0
false
c639967265bd4443af7cc3916898757e
# This file is auto-generated by Hatchling. As such, do not:\n# - modify\n# - track in version control e.g. be sure to add to .gitignore\n__version__ = VERSION = '0.3.0'\n
.venv\Lib\site-packages\jupyterlab_pygments\_version.py
_version.py
Python
171
0.8
0
0.75
node-utils
94
2025-05-11T11:07:39.533878
GPL-3.0
false
66e1a4d11ccf5af3acb1c3828b036d31
try:\n from ._version import __version__ # noqa\nexcept ImportError:\n # Fallback when using the package in dev mode without installing\n # in editable mode with pip. Here this is particularly important\n # to be able to run the generate_css.py script.\n __version__ = "dev"\nfrom .style import JupyterStyle # noqa\n\n\ndef _jupyter_labextension_paths():\n return [{\n "src": "labextension",\n "dest": "jupyterlab_pygments"\n }]\n
.venv\Lib\site-packages\jupyterlab_pygments\__init__.py
__init__.py
Python
452
0.95
0.133333
0.230769
awesome-app
141
2024-01-26T19:03:53.633024
GPL-3.0
false
a1c445af36be5031177c481e33fc89d6
\n\n
.venv\Lib\site-packages\jupyterlab_pygments\__pycache__\style.cpython-313.pyc
style.cpython-313.pyc
Other
2,830
0.95
0.078125
0.035088
react-lib
135
2024-12-30T00:13:24.644827
Apache-2.0
false
ca2ee03abb2764ac44f89130f738afab
\n\n
.venv\Lib\site-packages\jupyterlab_pygments\__pycache__\_version.cpython-313.pyc
_version.cpython-313.pyc
Other
240
0.7
0
0
awesome-app
747
2025-01-11T20:41:03.486946
Apache-2.0
false
74d65f7aace47a0fcceca67e542fced7
\n\n
.venv\Lib\site-packages\jupyterlab_pygments\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
573
0.7
0
0
vue-tools
830
2023-09-12T05:56:56.467367
BSD-3-Clause
false
d3481bcf20570e821635940b02356acd
pip\n
.venv\Lib\site-packages\jupyterlab_pygments-0.3.0.dist-info\INSTALLER
INSTALLER
Other
4
0.5
0
0
vue-tools
459
2024-07-09T05:23:48.589082
MIT
false
365c9bfeb7d89244f2ce01c1de44cb85
Metadata-Version: 2.1\nName: jupyterlab_pygments\nVersion: 0.3.0\nSummary: Pygments theme using JupyterLab CSS variables\nProject-URL: Homepage, https://github.com/jupyterlab/jupyterlab_pygments\nProject-URL: Bug Tracker, https://github.com/jupyterlab/jupyterlab_pygments/issues\nProject-URL: Repository, https://github.com/jupyterlab/jupyterlab_pygments.git\nAuthor-email: Jupyter Development Team <jupyter@googlegroups.com>\nLicense: Copyright (c) 2015 Project Jupyter Contributors\n All rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n \n 1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n \n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n \n 3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nLicense-File: LICENSE\nClassifier: Framework :: Jupyter\nClassifier: Framework :: Jupyter :: JupyterLab\nClassifier: Framework :: Jupyter :: JupyterLab :: 4\nClassifier: Framework :: Jupyter :: JupyterLab :: Extensions\nClassifier: Framework :: Jupyter :: JupyterLab :: Extensions :: Prebuilt\nClassifier: License :: OSI Approved :: BSD License\nClassifier: Programming Language :: Python\nClassifier: Programming Language :: Python :: 3\nClassifier: Programming Language :: Python :: 3.8\nClassifier: Programming Language :: Python :: 3.9\nClassifier: Programming Language :: Python :: 3.10\nClassifier: Programming Language :: Python :: 3.11\nClassifier: Programming Language :: Python :: 3.12\nRequires-Python: >=3.8\nDescription-Content-Type: text/markdown\n\n# JupyterLab Pygments Theme\n\nThis package contains a syntax coloring theme for [pygments](http://pygments.org/) making use of\nthe JupyterLab CSS variables.\n\nThe goal is to enable the use of JupyterLab's themes with pygments-generated HTML.\n\n## Screencast\n\nIn the following screencast, we demonstrate how Pygments-highlighted code can make use of the JupyterLab theme.\n\n![pygments screencast](pygments.gif)\n\n## Installation\n\n`jupyterlab_pygments` can be installed with the conda package manager\n\n```\nconda install -c conda-forge jupyterlab_pygments\n```\n\nor from pypi\n\n```\npip install jupyterlab_pygments\n```\n\n## Dependencies\n\n- `jupyterlab_pygments` requires [pygments](http://pygments.org) version `2.4.1`.\n- The CSS variables used by the theme correspond to the CodeMirror syntex coloring\n theme defined in the NPM package [@jupyterlab/codemirror](https://www.npmjs.com/package/@jupyterlab/codemirror). Supported versions for `@jupyterlab/codemirror`'s CSS include `0.19.1`, `^1.0`, and, `^2.0`.\n\n## Limitations\n\nPygments-generated HTML and CSS classes are not granular enough to reproduce\nall of the details of codemirror (the JavaScript text editor used by JupyterLab).\n\nThis includes the ability to differentiate properties from general names.\n\n## License\n\n`jupyterlab_pygments` uses a shared copyright model that enables all contributors to maintain the\ncopyright on their contributions. All code is licensed under the terms of the revised [BSD license](LICENSE).\n
.venv\Lib\site-packages\jupyterlab_pygments-0.3.0.dist-info\METADATA
METADATA
Other
4,366
0.95
0.020833
0.082192
awesome-app
490
2023-08-29T14:50:12.492544
GPL-3.0
false
2f1ed0b8556713d3c3aa1c27b1f0fc79
../../share/jupyter/labextensions/jupyterlab_pygments/install.json,sha256=W5DBo8cH4DWPv5C1cIpga9JGLYK7aKme_IxHFSfiPKw,199\n../../share/jupyter/labextensions/jupyterlab_pygments/package.json,sha256=P6Zj2f5uFXb17IlAwOL6gZePHICGHMFggrM29-H3L_k,5919\n../../share/jupyter/labextensions/jupyterlab_pygments/static/568.1e2faa2ba0bbe59c4780.js,sha256=Hi-qK6C75ZxHgFHerpeEb3gTGXaqmOtP_foktiYk2O8,224\n../../share/jupyter/labextensions/jupyterlab_pygments/static/747.67662283a5707eeb4d4c.js,sha256=Z2Yig6VwfutNTATGQ4hZArKElOuj5hiPsW3OVhyILsc,8351\n../../share/jupyter/labextensions/jupyterlab_pygments/static/remoteEntry.5cbb9d2323598fbda535.js,sha256=XLudIyNZj72lNUZBpZ-OShD3yI-1n9CObZ42f51qC3s,3925\n../../share/jupyter/labextensions/jupyterlab_pygments/static/style.js,sha256=47AJL3RNz7UGd8uO9Ui6glwsOcWTzQiIJgQ0vwN0RjY,162\n../../share/jupyter/labextensions/jupyterlab_pygments/static/third-party-licenses.json,sha256=5z5gY0sStbT_P2WqbrAlmEtTHDPn0-v6dtp4O8CCBTs,2452\njupyterlab_pygments-0.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4\njupyterlab_pygments-0.3.0.dist-info/METADATA,sha256=d5gCzLIxqRWmfkL9YkfarPbG9cKinTphkUtYtMNcrkY,4366\njupyterlab_pygments-0.3.0.dist-info/RECORD,,\njupyterlab_pygments-0.3.0.dist-info/WHEEL,sha256=9QBuHhg6FNW7lppboF2vKVbCGTVzsFykgRQjjlajrhA,87\njupyterlab_pygments-0.3.0.dist-info/licenses/LICENSE,sha256=5awr4wsrzv4zDunlrX_lsNEVb-yzVV_KqpCKjSn5_e0,1513\njupyterlab_pygments/__init__.py,sha256=EA-4Ul4Y9xGSDXHVYxE7tkeyHLfxlKEEBj6qoOsRt1c,452\njupyterlab_pygments/__pycache__/__init__.cpython-313.pyc,,\njupyterlab_pygments/__pycache__/_version.cpython-313.pyc,,\njupyterlab_pygments/__pycache__/style.cpython-313.pyc,,\njupyterlab_pygments/_version.py,sha256=W6DIaBZh3c4iERseQh1LSFmmsS5lqkkAwTOt20QcsZg,171\njupyterlab_pygments/style.py,sha256=l_Ka1hiqJC-91n3blki3mkkCNDK6GN-RAukFoF4mWOE,8492\n
.venv\Lib\site-packages\jupyterlab_pygments-0.3.0.dist-info\RECORD
RECORD
Other
1,856
0.7
0
0
react-lib
789
2025-05-12T19:11:36.568551
MIT
false
4fdf247372572b32396ab96dccbe0888
Wheel-Version: 1.0\nGenerator: hatchling 1.18.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n
.venv\Lib\site-packages\jupyterlab_pygments-0.3.0.dist-info\WHEEL
WHEEL
Other
87
0.5
0
0
python-kit
622
2024-09-21T00:18:18.666359
GPL-3.0
false
c3c172be777b2014a95410712715e881
Copyright (c) 2015 Project Jupyter Contributors\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n
.venv\Lib\site-packages\jupyterlab_pygments-0.3.0.dist-info\licenses\LICENSE
LICENSE
Other
1,513
0.7
0
0
node-utils
360
2025-05-01T21:04:39.665644
GPL-3.0
false
20a40995a0b2f0ae1f2a70d2dc995bbf
"""JupyterLab Server Application"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom glob import glob\nfrom os.path import relpath\nfrom typing import Any\n\nfrom jupyter_server.extension.application import ExtensionApp, ExtensionAppJinjaMixin\nfrom jupyter_server.utils import url_path_join as ujoin\nfrom traitlets import Dict, Integer, Unicode, observe\n\nfrom ._version import __version__\nfrom .handlers import LabConfig, add_handlers\n\n\nclass LabServerApp(ExtensionAppJinjaMixin, LabConfig, ExtensionApp):\n """A Lab Server Application that runs out-of-the-box"""\n\n name = "jupyterlab_server"\n extension_url = "/lab"\n app_name = "JupyterLab Server Application" # type:ignore[assignment]\n file_url_prefix = "/lab/tree" # type:ignore[assignment]\n\n @property\n def app_namespace(self) -> str: # type:ignore[override]\n return self.name\n\n default_url = Unicode("/lab", help="The default URL to redirect to from `/`")\n\n # Should your extension expose other server extensions when launched directly?\n load_other_extensions = True\n\n app_version = Unicode("", help="The version of the application.").tag(default=__version__)\n\n blacklist_uris = Unicode(\n "", config=True, help="Deprecated, use `LabServerApp.blocked_extensions_uris`"\n )\n\n blocked_extensions_uris = Unicode(\n "",\n config=True,\n help="""\n A list of comma-separated URIs to get the blocked extensions list\n\n .. versionchanged:: 2.0.0\n `LabServerApp.blacklist_uris` renamed to `blocked_extensions_uris`\n """,\n )\n\n whitelist_uris = Unicode(\n "", config=True, help="Deprecated, use `LabServerApp.allowed_extensions_uris`"\n )\n\n allowed_extensions_uris = Unicode(\n "",\n config=True,\n help="""\n "A list of comma-separated URIs to get the allowed extensions list\n\n .. versionchanged:: 2.0.0\n `LabServerApp.whitetlist_uris` renamed to `allowed_extensions_uris`\n """,\n )\n\n listings_refresh_seconds = Integer(\n 60 * 60, config=True, help="The interval delay in seconds to refresh the lists"\n )\n\n listings_request_options = Dict(\n {},\n config=True,\n help="The optional kwargs to use for the listings HTTP requests \\n as described on https://2.python-requests.org/en/v2.7.0/api/#requests.request",\n )\n\n _deprecated_aliases = {\n "blacklist_uris": ("blocked_extensions_uris", "1.2"),\n "whitelist_uris": ("allowed_extensions_uris", "1.2"),\n }\n\n # Method copied from\n # https://github.com/jupyterhub/jupyterhub/blob/d1a85e53dccfc7b1dd81b0c1985d158cc6b61820/jupyterhub/auth.py#L143-L161\n @observe(*list(_deprecated_aliases))\n def _deprecated_trait(self, change: Any) -> None:\n """observer for deprecated traits"""\n old_attr = change.name\n new_attr, version = self._deprecated_aliases.get(old_attr) # type:ignore[misc]\n new_value = getattr(self, new_attr)\n if new_value != change.new:\n # only warn if different\n # protects backward-compatible config from warnings\n # if they set the same value under both names\n self.log.warning(\n "%s.%s is deprecated in JupyterLab %s, use %s.%s instead",\n self.__class__.__name__,\n old_attr,\n version,\n self.__class__.__name__,\n new_attr,\n )\n\n setattr(self, new_attr, change.new)\n\n def initialize_settings(self) -> None:\n """Initialize the settings:\n\n set the static files as immutable, since they should have all hashed name.\n """\n immutable_cache = set(self.settings.get("static_immutable_cache", []))\n\n # Set lab static files as immutables\n immutable_cache.add(self.static_url_prefix)\n\n # Set extensions static files as immutables\n for extension_path in self.labextensions_path + self.extra_labextensions_path:\n extensions_url = [\n ujoin(self.labextensions_url, relpath(path, extension_path))\n for path in glob(f"{extension_path}/**/static", recursive=True)\n ]\n\n immutable_cache.update(extensions_url)\n\n self.settings.update({"static_immutable_cache": list(immutable_cache)})\n\n def initialize_templates(self) -> None:\n """Initialize templates."""\n self.static_paths = [self.static_dir]\n self.template_paths = [self.templates_dir]\n\n def initialize_handlers(self) -> None:\n """Initialize handlers."""\n add_handlers(self.handlers, self)\n\n\nmain = launch_new_instance = LabServerApp.launch_instance\n
.venv\Lib\site-packages\jupyterlab_server\app.py
app.py
Python
4,753
0.95
0.094891
0.095238
react-lib
553
2025-04-04T21:14:04.862194
Apache-2.0
false
3d93c91708211719a3d58cabb69e5f46
"""JupyterLab Server config"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport json\nimport os.path as osp\nfrom glob import iglob\nfrom itertools import chain\nfrom logging import Logger\nfrom os.path import join as pjoin\nfrom typing import Any\n\nimport json5\nfrom jupyter_core.paths import SYSTEM_CONFIG_PATH, jupyter_config_dir, jupyter_path\nfrom jupyter_server.services.config.manager import ConfigManager, recursive_update\nfrom jupyter_server.utils import url_path_join as ujoin\nfrom traitlets import Bool, HasTraits, List, Unicode, default\n\n# -----------------------------------------------------------------------------\n# Module globals\n# -----------------------------------------------------------------------------\n\nDEFAULT_TEMPLATE_PATH = osp.join(osp.dirname(__file__), "templates")\n\n\ndef get_package_url(data: dict[str, Any]) -> str:\n """Get the url from the extension data"""\n # homepage, repository are optional\n if "homepage" in data:\n url = data["homepage"]\n elif "repository" in data and isinstance(data["repository"], dict):\n url = data["repository"].get("url", "")\n else:\n url = ""\n return url\n\n\ndef get_federated_extensions(labextensions_path: list[str]) -> dict[str, Any]:\n """Get the metadata about federated extensions"""\n federated_extensions = {}\n for ext_dir in labextensions_path:\n # extensions are either top-level directories, or two-deep in @org directories\n for ext_path in chain(\n iglob(pjoin(ext_dir, "[!@]*", "package.json")),\n iglob(pjoin(ext_dir, "@*", "*", "package.json")),\n ):\n with open(ext_path, encoding="utf-8") as fid:\n pkgdata = json.load(fid)\n if pkgdata["name"] not in federated_extensions:\n data = dict(\n name=pkgdata["name"],\n version=pkgdata["version"],\n description=pkgdata.get("description", ""),\n url=get_package_url(pkgdata),\n ext_dir=ext_dir,\n ext_path=osp.dirname(ext_path),\n is_local=False,\n dependencies=pkgdata.get("dependencies", dict()),\n jupyterlab=pkgdata.get("jupyterlab", dict()),\n )\n\n # Add repository info if available\n if "repository" in pkgdata and "url" in pkgdata.get("repository", {}):\n data["repository"] = dict(url=pkgdata.get("repository").get("url"))\n\n install_path = osp.join(osp.dirname(ext_path), "install.json")\n if osp.exists(install_path):\n with open(install_path, encoding="utf-8") as fid:\n data["install"] = json.load(fid)\n federated_extensions[data["name"]] = data\n return federated_extensions\n\n\ndef get_static_page_config(\n app_settings_dir: str | None = None, # noqa: ARG001\n logger: Logger | None = None, # noqa: ARG001\n level: str = "all",\n include_higher_levels: bool = False,\n) -> dict[str, Any]:\n """Get the static page config for JupyterLab\n\n Parameters\n ----------\n logger: logger, optional\n An optional logging object\n level: string, optional ['all']\n The level at which to get config: can be 'all', 'user', 'sys_prefix', or 'system'\n """\n cm = _get_config_manager(level, include_higher_levels)\n return cm.get("page_config") # type:ignore[no-untyped-call]\n\n\ndef load_config(path: str) -> Any:\n """Load either a json5 or a json config file.\n\n Parameters\n ----------\n path : str\n Path to the file to be loaded\n\n Returns\n -------\n Dict[Any, Any]\n Dictionary of json or json5 data\n """\n with open(path, encoding="utf-8") as fid:\n if path.endswith(".json5"):\n return json5.load(fid)\n return json.load(fid)\n\n\ndef get_page_config(\n labextensions_path: list[str], app_settings_dir: str | None = None, logger: Logger | None = None\n) -> dict[str, Any]:\n """Get the page config for the application handler"""\n # Build up the full page config\n page_config: dict = {}\n\n disabled_key = "disabledExtensions"\n\n # Start with the app_settings_dir as lowest priority\n if app_settings_dir:\n config_paths = [\n pjoin(app_settings_dir, "page_config.json5"),\n pjoin(app_settings_dir, "page_config.json"),\n ]\n for path in config_paths:\n if osp.exists(path) and osp.getsize(path):\n data = load_config(path)\n # Convert lists to dicts\n for key in [disabled_key, "deferredExtensions"]:\n if key in data:\n data[key] = {key: True for key in data[key]}\n\n recursive_update(page_config, data)\n break\n\n # Get the traitlets config\n static_page_config = get_static_page_config(logger=logger, level="all")\n recursive_update(page_config, static_page_config)\n\n # Handle federated extensions that disable other extensions\n disabled_by_extensions_all = {}\n extensions = page_config["federated_extensions"] = []\n\n federated_exts = get_federated_extensions(labextensions_path)\n\n # Ensure there is a disabled key\n page_config.setdefault(disabled_key, {})\n\n for _, ext_data in federated_exts.items():\n if "_build" not in ext_data["jupyterlab"]:\n if logger:\n logger.warning("%s is not a valid extension", ext_data["name"])\n continue\n extbuild = ext_data["jupyterlab"]["_build"]\n extension = {"name": ext_data["name"], "load": extbuild["load"]}\n\n if "extension" in extbuild:\n extension["extension"] = extbuild["extension"]\n if "mimeExtension" in extbuild:\n extension["mimeExtension"] = extbuild["mimeExtension"]\n if "style" in extbuild:\n extension["style"] = extbuild["style"]\n # FIXME @experimental for plugin with no-code entrypoints.\n extension["entrypoints"] = extbuild.get("entrypoints")\n extensions.append(extension)\n\n # If there is disabledExtensions metadata, consume it.\n name = ext_data["name"]\n\n if ext_data["jupyterlab"].get(disabled_key):\n disabled_by_extensions_all[ext_data["name"]] = ext_data["jupyterlab"][disabled_key]\n\n # Handle source extensions that disable other extensions\n # Check for `jupyterlab`:`extensionMetadata` in the built application directory's package.json\n if app_settings_dir:\n app_dir = osp.dirname(app_settings_dir)\n package_data_file = pjoin(app_dir, "static", "package.json")\n if osp.exists(package_data_file):\n with open(package_data_file, encoding="utf-8") as fid:\n app_data = json.load(fid)\n all_ext_data = app_data["jupyterlab"].get("extensionMetadata", {})\n for ext, ext_data in all_ext_data.items():\n if ext in disabled_by_extensions_all:\n continue\n if ext_data.get(disabled_key):\n disabled_by_extensions_all[ext] = ext_data[disabled_key]\n\n disabled_by_extensions = {}\n for name in sorted(disabled_by_extensions_all):\n # skip if the extension itself is disabled by other config\n if page_config[disabled_key].get(name) is True:\n continue\n\n disabled_list = disabled_by_extensions_all[name]\n for item in disabled_list:\n disabled_by_extensions[item] = True\n\n rollup_disabled = disabled_by_extensions\n rollup_disabled.update(page_config.get(disabled_key, []))\n page_config[disabled_key] = rollup_disabled\n\n # Convert dictionaries to lists to give to the front end\n for key, value in page_config.items():\n if isinstance(value, dict):\n page_config[key] = [subkey for subkey in value if value[subkey]]\n\n return page_config\n\n\ndef write_page_config(page_config: dict[str, Any], level: str = "all") -> None:\n """Write page config to disk"""\n cm = _get_config_manager(level)\n cm.set("page_config", page_config) # type:ignore[no-untyped-call]\n\n\nclass LabConfig(HasTraits):\n """The lab application configuration object."""\n\n app_name = Unicode("", help="The name of the application.").tag(config=True)\n\n app_version = Unicode("", help="The version of the application.").tag(config=True)\n\n app_namespace = Unicode("", help="The namespace of the application.").tag(config=True)\n\n app_url = Unicode("/lab", help="The url path for the application.").tag(config=True)\n\n app_settings_dir = Unicode("", help="The application settings directory.").tag(config=True)\n\n extra_labextensions_path = List(\n Unicode(), help="""Extra paths to look for federated JupyterLab extensions"""\n ).tag(config=True)\n\n labextensions_path = List(\n Unicode(), help="The standard paths to look in for federated JupyterLab extensions"\n ).tag(config=True)\n\n templates_dir = Unicode("", help="The application templates directory.").tag(config=True)\n\n static_dir = Unicode(\n "",\n help=(\n "The optional location of local static files. "\n "If given, a static file handler will be "\n "added."\n ),\n ).tag(config=True)\n\n labextensions_url = Unicode("", help="The url for federated JupyterLab extensions").tag(\n config=True\n )\n\n settings_url = Unicode(help="The url path of the settings handler.").tag(config=True)\n\n user_settings_dir = Unicode(\n "", help=("The optional location of the user settings directory.")\n ).tag(config=True)\n\n schemas_dir = Unicode(\n "",\n help=(\n "The optional location of the settings "\n "schemas directory. If given, a handler will "\n "be added for settings."\n ),\n ).tag(config=True)\n\n workspaces_api_url = Unicode(help="The url path of the workspaces API.").tag(config=True)\n\n workspaces_dir = Unicode(\n "",\n help=(\n "The optional location of the saved "\n "workspaces directory. If given, a handler "\n "will be added for workspaces."\n ),\n ).tag(config=True)\n\n listings_url = Unicode(help="The listings url.").tag(config=True)\n\n themes_url = Unicode(help="The theme url.").tag(config=True)\n\n licenses_url = Unicode(help="The third-party licenses url.")\n\n themes_dir = Unicode(\n "",\n help=(\n "The optional location of the themes "\n "directory. If given, a handler will be added "\n "for themes."\n ),\n ).tag(config=True)\n\n translations_api_url = Unicode(help="The url path of the translations handler.").tag(\n config=True\n )\n\n tree_url = Unicode(help="The url path of the tree handler.").tag(config=True)\n\n cache_files = Bool(\n True,\n help=("Whether to cache files on the server. This should be `True` except in dev mode."),\n ).tag(config=True)\n\n notebook_starts_kernel = Bool(\n True, help="Whether a notebook should start a kernel automatically."\n ).tag(config=True)\n\n copy_absolute_path = Bool(\n False,\n help="Whether getting a relative (False) or absolute (True) path when copying a path.",\n ).tag(config=True)\n\n @default("template_dir")\n def _default_template_dir(self) -> str:\n return DEFAULT_TEMPLATE_PATH\n\n @default("labextensions_url")\n def _default_labextensions_url(self) -> str:\n return ujoin(self.app_url, "extensions/")\n\n @default("labextensions_path")\n def _default_labextensions_path(self) -> list[str]:\n return jupyter_path("labextensions")\n\n @default("workspaces_url")\n def _default_workspaces_url(self) -> str:\n return ujoin(self.app_url, "workspaces/")\n\n @default("workspaces_api_url")\n def _default_workspaces_api_url(self) -> str:\n return ujoin(self.app_url, "api", "workspaces/")\n\n @default("settings_url")\n def _default_settings_url(self) -> str:\n return ujoin(self.app_url, "api", "settings/")\n\n @default("listings_url")\n def _default_listings_url(self) -> str:\n return ujoin(self.app_url, "api", "listings/")\n\n @default("themes_url")\n def _default_themes_url(self) -> str:\n return ujoin(self.app_url, "api", "themes/")\n\n @default("licenses_url")\n def _default_licenses_url(self) -> str:\n return ujoin(self.app_url, "api", "licenses/")\n\n @default("tree_url")\n def _default_tree_url(self) -> str:\n return ujoin(self.app_url, "tree/")\n\n @default("translations_api_url")\n def _default_translations_api_url(self) -> str:\n return ujoin(self.app_url, "api", "translations/")\n\n\ndef get_allowed_levels() -> list[str]:\n """\n Returns the levels where configs can be stored.\n """\n return ["all", "user", "sys_prefix", "system", "app", "extension"]\n\n\ndef _get_config_manager(level: str, include_higher_levels: bool = False) -> ConfigManager:\n """Get the location of config files for the current context\n Returns the string to the environment\n """\n # Delayed import since this gets monkey-patched in tests\n from jupyter_core.paths import ENV_CONFIG_PATH\n\n allowed = get_allowed_levels()\n if level not in allowed:\n msg = f"Page config level must be one of: {allowed}"\n raise ValueError(msg)\n\n config_name = "labconfig"\n\n if level == "all":\n return ConfigManager(config_dir_name=config_name)\n\n paths: dict[str, list] = {\n "app": [],\n "system": SYSTEM_CONFIG_PATH,\n "sys_prefix": [ENV_CONFIG_PATH[0]],\n "user": [jupyter_config_dir()],\n "extension": [],\n }\n\n levels = allowed[allowed.index(level) :] if include_higher_levels else [level]\n\n read_config_paths, write_config_dir = [], None\n\n for _level in levels:\n for p in paths[_level]:\n read_config_paths.append(osp.join(p, config_name))\n if write_config_dir is None and paths[_level]: # type: ignore[redundant-expr]\n write_config_dir = osp.join(paths[_level][0], config_name)\n\n return ConfigManager(read_config_path=read_config_paths, write_config_dir=write_config_dir)\n
.venv\Lib\site-packages\jupyterlab_server\config.py
config.py
Python
14,297
0.95
0.178218
0.066456
awesome-app
138
2023-10-20T10:40:52.662065
Apache-2.0
false
785bace70ec476b03296e2720707ae19
"""JupyterLab Server handlers"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport os\nimport pathlib\nimport warnings\nfrom functools import lru_cache\nfrom typing import TYPE_CHECKING, Any\nfrom urllib.parse import urlparse\n\nfrom jupyter_server.base.handlers import FileFindHandler, JupyterHandler\nfrom jupyter_server.extension.handler import ExtensionHandlerJinjaMixin, ExtensionHandlerMixin\nfrom jupyter_server.utils import url_path_join as ujoin\nfrom tornado import template, web\n\nfrom .config import LabConfig, get_page_config, recursive_update\nfrom .licenses_handler import LicensesHandler, LicensesManager\nfrom .listings_handler import ListingsHandler, fetch_listings\nfrom .settings_handler import SettingsHandler\nfrom .settings_utils import _get_overrides\nfrom .themes_handler import ThemesHandler\nfrom .translations_handler import TranslationsHandler\nfrom .workspaces_handler import WorkspacesHandler, WorkspacesManager\n\nif TYPE_CHECKING:\n from .app import LabServerApp\n# -----------------------------------------------------------------------------\n# Module globals\n# -----------------------------------------------------------------------------\n\nMASTER_URL_PATTERN = (\n r"/(?P<mode>{}|doc)(?P<workspace>/workspaces/[a-zA-Z0-9\-\_]+)?(?P<tree>/tree/.*)?"\n)\n\nDEFAULT_TEMPLATE = template.Template(\n """\n<!DOCTYPE html>\n<html>\n<head>\n <meta charset="utf-8">\n <title>Error</title>\n</head>\n<body>\n<h2>Cannot find template: "{{name}}"</h2>\n<p>In "{{path}}"</p>\n</body>\n</html>\n"""\n)\n\n\ndef is_url(url: str) -> bool:\n """Test whether a string is a full url (e.g. https://nasa.gov)\n\n https://stackoverflow.com/a/52455972\n """\n try:\n result = urlparse(url)\n return all([result.scheme, result.netloc])\n except ValueError:\n return False\n\n\nclass LabHandler(ExtensionHandlerJinjaMixin, ExtensionHandlerMixin, JupyterHandler):\n """Render the JupyterLab View."""\n\n @lru_cache # noqa: B019\n def get_page_config(self) -> dict[str, Any]:\n """Construct the page config object"""\n self.application.store_id = getattr( # type:ignore[attr-defined]\n self.application, "store_id", 0\n )\n config = LabConfig()\n app: LabServerApp = self.extensionapp # type:ignore[assignment]\n settings_dir = app.app_settings_dir\n # Handle page config data.\n page_config = self.settings.setdefault("page_config_data", {})\n terminals = self.settings.get("terminals_available", False)\n server_root = self.settings.get("server_root_dir", "")\n server_root = server_root.replace(os.sep, "/")\n base_url = self.settings.get("base_url")\n\n # Remove the trailing slash for compatibility with html-webpack-plugin.\n full_static_url = self.static_url_prefix.rstrip("/")\n page_config.setdefault("fullStaticUrl", full_static_url)\n\n page_config.setdefault("terminalsAvailable", terminals)\n page_config.setdefault("ignorePlugins", [])\n page_config.setdefault("serverRoot", server_root)\n page_config["store_id"] = self.application.store_id # type:ignore[attr-defined]\n\n server_root = os.path.normpath(os.path.expanduser(server_root))\n preferred_path = ""\n try:\n preferred_path = self.serverapp.contents_manager.preferred_dir\n except Exception:\n # FIXME: Remove fallback once CM.preferred_dir is ubiquitous.\n try:\n # Remove the server_root from app pref dir\n if self.serverapp.preferred_dir and self.serverapp.preferred_dir != server_root:\n preferred_path = (\n pathlib.Path(self.serverapp.preferred_dir)\n .relative_to(server_root)\n .as_posix()\n )\n except Exception: # noqa: S110\n pass\n # JupyterLab relies on an unset/default path being "/"\n page_config["preferredPath"] = preferred_path or "/"\n\n self.application.store_id += 1 # type:ignore[attr-defined]\n\n mathjax_config = self.settings.get("mathjax_config", "TeX-AMS_HTML-full,Safe")\n # TODO Remove CDN usage.\n mathjax_url = self.mathjax_url\n if not mathjax_url:\n mathjax_url = "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js"\n\n page_config.setdefault("mathjaxConfig", mathjax_config)\n page_config.setdefault("fullMathjaxUrl", mathjax_url)\n\n # Put all our config in page_config\n for name in config.trait_names():\n page_config[_camelCase(name)] = getattr(app, name)\n\n # Add full versions of all the urls\n for name in config.trait_names():\n if not name.endswith("_url"):\n continue\n full_name = _camelCase("full_" + name)\n full_url = getattr(app, name)\n if base_url is not None and not is_url(full_url):\n # Relative URL will be prefixed with base_url\n full_url = ujoin(base_url, full_url)\n page_config[full_name] = full_url\n\n # Update the page config with the data from disk\n labextensions_path = app.extra_labextensions_path + app.labextensions_path\n recursive_update(\n page_config, get_page_config(labextensions_path, settings_dir, logger=self.log)\n )\n\n # modify page config with custom hook\n page_config_hook = self.settings.get("page_config_hook", None)\n if page_config_hook:\n page_config = page_config_hook(self, page_config)\n\n return page_config\n\n @web.authenticated\n @web.removeslash\n def get(\n self, mode: str | None = None, workspace: str | None = None, tree: str | None = None\n ) -> None:\n """Get the JupyterLab html page."""\n workspace = "default" if workspace is None else workspace.replace("/workspaces/", "")\n tree_path = "" if tree is None else tree.replace("/tree/", "")\n\n page_config = self.get_page_config()\n\n # Add parameters parsed from the URL\n if mode == "doc":\n page_config["mode"] = "single-document"\n else:\n page_config["mode"] = "multiple-document"\n page_config["workspace"] = workspace\n page_config["treePath"] = tree_path\n\n # Write the template with the config.\n tpl = self.render_template("index.html", page_config=page_config) # type:ignore[no-untyped-call]\n self.write(tpl)\n\n\nclass NotFoundHandler(LabHandler):\n """A handler for page not found."""\n\n @lru_cache # noqa: B019\n def get_page_config(self) -> dict[str, Any]:\n """Get the page config."""\n # Making a copy of the page_config to ensure changes do not affect the original\n page_config = super().get_page_config().copy()\n page_config["notFoundUrl"] = self.request.path\n return page_config\n\n\ndef add_handlers(handlers: list[Any], extension_app: LabServerApp) -> None:\n """Add the appropriate handlers to the web app."""\n # Normalize directories.\n for name in LabConfig.class_trait_names():\n if not name.endswith("_dir"):\n continue\n value = getattr(extension_app, name)\n setattr(extension_app, name, value.replace(os.sep, "/"))\n\n # Normalize urls\n # Local urls should have a leading slash but no trailing slash\n for name in LabConfig.class_trait_names():\n if not name.endswith("_url"):\n continue\n value = getattr(extension_app, name)\n if is_url(value):\n continue\n if not value.startswith("/"):\n value = "/" + value\n if value.endswith("/"):\n value = value[:-1]\n setattr(extension_app, name, value)\n\n url_pattern = MASTER_URL_PATTERN.format(extension_app.app_url.replace("/", ""))\n handlers.append((url_pattern, LabHandler))\n\n # Cache all or none of the files depending on the `cache_files` setting.\n no_cache_paths = [] if extension_app.cache_files else ["/"]\n\n # Handle federated lab extensions.\n labextensions_path = extension_app.extra_labextensions_path + extension_app.labextensions_path\n labextensions_url = ujoin(extension_app.labextensions_url, "(.*)")\n handlers.append(\n (\n labextensions_url,\n FileFindHandler,\n {"path": labextensions_path, "no_cache_paths": no_cache_paths},\n )\n )\n\n # Handle local settings.\n if extension_app.schemas_dir:\n # Load overrides once, rather than in each copy of the settings handler\n overrides, error = _get_overrides(extension_app.app_settings_dir)\n\n if error:\n overrides_warning = "Failed loading overrides: %s"\n extension_app.log.warning(overrides_warning, error)\n\n settings_config: dict[str, Any] = {\n "app_settings_dir": extension_app.app_settings_dir,\n "schemas_dir": extension_app.schemas_dir,\n "settings_dir": extension_app.user_settings_dir,\n "labextensions_path": labextensions_path,\n "overrides": overrides,\n }\n\n # Handle requests for the list of settings. Make slash optional.\n settings_path = ujoin(extension_app.settings_url, "?")\n handlers.append((settings_path, SettingsHandler, settings_config))\n\n # Handle requests for an individual set of settings.\n setting_path = ujoin(extension_app.settings_url, "(?P<schema_name>.+)")\n handlers.append((setting_path, SettingsHandler, settings_config))\n\n # Handle translations.\n # Translations requires settings as the locale source of truth is stored in it\n if extension_app.translations_api_url:\n # Handle requests for the list of language packs available.\n # Make slash optional.\n translations_path = ujoin(extension_app.translations_api_url, "?")\n handlers.append((translations_path, TranslationsHandler, settings_config))\n\n # Handle requests for an individual language pack.\n translations_lang_path = ujoin(extension_app.translations_api_url, "(?P<locale>.*)")\n handlers.append((translations_lang_path, TranslationsHandler, settings_config))\n\n # Handle saved workspaces.\n if extension_app.workspaces_dir:\n workspaces_config = {"manager": WorkspacesManager(extension_app.workspaces_dir)}\n\n # Handle requests for the list of workspaces. Make slash optional.\n workspaces_api_path = ujoin(extension_app.workspaces_api_url, "?")\n handlers.append((workspaces_api_path, WorkspacesHandler, workspaces_config))\n\n # Handle requests for an individually named workspace.\n workspace_api_path = ujoin(extension_app.workspaces_api_url, "(?P<space_name>.+)")\n handlers.append((workspace_api_path, WorkspacesHandler, workspaces_config))\n\n # Handle local listings.\n\n settings_config = extension_app.settings.get("config", {}).get("LabServerApp", {})\n blocked_extensions_uris: str = settings_config.get("blocked_extensions_uris", "")\n allowed_extensions_uris: str = settings_config.get("allowed_extensions_uris", "")\n\n if (blocked_extensions_uris) and (allowed_extensions_uris):\n warnings.warn(\n "Simultaneous blocked_extensions_uris and allowed_extensions_uris is not supported. Please define only one of those.",\n stacklevel=2,\n )\n import sys\n\n sys.exit(-1)\n\n ListingsHandler.listings_refresh_seconds = settings_config.get(\n "listings_refresh_seconds", 60 * 60\n )\n ListingsHandler.listings_request_opts = settings_config.get("listings_request_options", {})\n listings_url = ujoin(extension_app.listings_url)\n listings_path = ujoin(listings_url, "(.*)")\n\n if blocked_extensions_uris:\n ListingsHandler.blocked_extensions_uris = set(blocked_extensions_uris.split(","))\n if allowed_extensions_uris:\n ListingsHandler.allowed_extensions_uris = set(allowed_extensions_uris.split(","))\n\n fetch_listings(None)\n\n if (\n len(ListingsHandler.blocked_extensions_uris) > 0\n or len(ListingsHandler.allowed_extensions_uris) > 0\n ):\n from tornado import ioloop\n\n callback_time = ListingsHandler.listings_refresh_seconds * 1000\n ListingsHandler.pc = ioloop.PeriodicCallback(\n lambda: fetch_listings(None), # type:ignore[assignment]\n callback_time=callback_time,\n jitter=0.1,\n )\n ListingsHandler.pc.start() # type:ignore[attr-defined]\n\n handlers.append((listings_path, ListingsHandler, {}))\n\n # Handle local themes.\n if extension_app.themes_dir:\n themes_url = extension_app.themes_url\n themes_path = ujoin(themes_url, "(.*)")\n handlers.append(\n (\n themes_path,\n ThemesHandler,\n {\n "themes_url": themes_url,\n "path": extension_app.themes_dir,\n "labextensions_path": labextensions_path,\n "no_cache_paths": no_cache_paths,\n },\n )\n )\n\n # Handle licenses.\n if extension_app.licenses_url:\n licenses_url = extension_app.licenses_url\n licenses_path = ujoin(licenses_url, "(.*)")\n handlers.append(\n (licenses_path, LicensesHandler, {"manager": LicensesManager(parent=extension_app)})\n )\n\n # Let the lab handler act as the fallthrough option instead of a 404.\n fallthrough_url = ujoin(extension_app.app_url, r".*")\n handlers.append((fallthrough_url, NotFoundHandler))\n\n\ndef _camelCase(base: str) -> str:\n """Convert a string to camelCase.\n https://stackoverflow.com/a/20744956\n """\n output = "".join(x for x in base.title() if x.isalpha())\n return output[0].lower() + output[1:]\n
.venv\Lib\site-packages\jupyterlab_server\handlers.py
handlers.py
Python
13,897
0.95
0.139665
0.135135
node-utils
872
2023-11-15T07:59:51.965976
Apache-2.0
false
5e4662ffc3667241edca60c2915cbb3e
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""A license reporting CLI\n\nMostly ready-to-use, the downstream must provide the location of the application's\nstatic resources. Licenses from an app's federated_extensions will also be discovered\nas configured in `labextensions_path` and `extra_labextensions_path`.\n\n from traitlets import default\n from jupyterlab_server import LicensesApp\n\n class MyLicensesApp(LicensesApp):\n version = "0.1.0"\n\n @default("static_dir")\n def _default_static_dir(self):\n return "my-static/"\n\n class MyApp(JupyterApp, LabConfig):\n ...\n subcommands = dict(\n licenses=(MyLicensesApp, MyLicensesApp.description.splitlines()[0])\n )\n\n"""\nfrom typing import Any\n\nfrom jupyter_core.application import JupyterApp, base_aliases, base_flags\nfrom traitlets import Bool, Enum, Instance, Unicode\n\nfrom ._version import __version__\nfrom .config import LabConfig\nfrom .licenses_handler import LicensesManager\n\n\nclass LicensesApp(JupyterApp, LabConfig):\n """A license management app."""\n\n version = __version__\n\n description = """\n Report frontend licenses\n """\n\n static_dir = Unicode("", config=True, help="The static directory from which to show licenses")\n\n full_text = Bool(False, config=True, help="Also print out full license text (if available)")\n\n report_format = Enum(\n ["markdown", "json", "csv"], "markdown", config=True, help="Reporter format"\n )\n\n bundles_pattern = Unicode(".*", config=True, help="A regular expression of bundles to print")\n\n licenses_manager = Instance(LicensesManager)\n\n aliases = {\n **base_aliases,\n "bundles": "LicensesApp.bundles_pattern",\n "report-format": "LicensesApp.report_format",\n }\n\n flags = {\n **base_flags,\n "full-text": (\n {"LicensesApp": {"full_text": True}},\n "Print out full license text (if available)",\n ),\n "json": (\n {"LicensesApp": {"report_format": "json"}},\n "Print out report as JSON (implies --full-text)",\n ),\n "csv": (\n {"LicensesApp": {"report_format": "csv"}},\n "Print out report as CSV (implies --full-text)",\n ),\n }\n\n def initialize(self, *args: Any, **kwargs: Any) -> None:\n """Initialize the app."""\n super().initialize(*args, **kwargs)\n self.init_licenses_manager()\n\n def init_licenses_manager(self) -> None:\n """Initialize the license manager."""\n self.licenses_manager = LicensesManager(\n parent=self,\n )\n\n def start(self) -> None:\n """Start the app."""\n report = self.licenses_manager.report(\n report_format=self.report_format,\n full_text=self.full_text,\n bundles_pattern=self.bundles_pattern,\n )[0]\n print(report)\n self.exit(0)\n
.venv\Lib\site-packages\jupyterlab_server\licenses_app.py
licenses_app.py
Python
2,963
0.95
0.090909
0.052632
node-utils
973
2024-09-25T10:10:34.014237
BSD-3-Clause
false
d0269ec4990389f1dac45a4049062d1d
"""Manager and Tornado handlers for license reporting."""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport asyncio\nimport csv\nimport io\nimport json\nimport mimetypes\nimport re\nfrom concurrent.futures import ThreadPoolExecutor\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any\n\nfrom jupyter_server.base.handlers import APIHandler\nfrom tornado import web\nfrom traitlets import List, Unicode\nfrom traitlets.config import LoggingConfigurable\n\nfrom .config import get_federated_extensions\n\n# this is duplicated in @juptyerlab/builder\nDEFAULT_THIRD_PARTY_LICENSE_FILE = "third-party-licenses.json"\nUNKNOWN_PACKAGE_NAME = "UNKNOWN"\n\nif mimetypes.guess_extension("text/markdown") is None: # pragma: no cover\n # for python <3.8 https://bugs.python.org/issue39324\n mimetypes.add_type("text/markdown", ".md")\n\n\nclass LicensesManager(LoggingConfigurable):\n """A manager for listing the licenses for all frontend end code distributed\n by an application and any federated extensions\n """\n\n executor = ThreadPoolExecutor(max_workers=1)\n\n third_party_licenses_files = List(\n Unicode(),\n default_value=[\n DEFAULT_THIRD_PARTY_LICENSE_FILE,\n f"static/{DEFAULT_THIRD_PARTY_LICENSE_FILE}",\n ],\n help="the license report data in built app and federated extensions",\n )\n\n @property\n def federated_extensions(self) -> dict[str, Any]:\n """Lazily load the currrently-available federated extensions.\n\n This is expensive, but probably the only way to be sure to get\n up-to-date license information for extensions installed interactively.\n """\n if TYPE_CHECKING:\n from .app import LabServerApp\n\n assert isinstance(self.parent, LabServerApp)\n\n per_paths = [\n self.parent.labextensions_path,\n self.parent.extra_labextensions_path,\n ]\n labextensions_path = [extension for extensions in per_paths for extension in extensions]\n return get_federated_extensions(labextensions_path)\n\n async def report_async(\n self, report_format: str = "markdown", bundles_pattern: str = ".*", full_text: bool = False\n ) -> tuple[str, str]:\n """Asynchronous wrapper around the potentially slow job of locating\n and encoding all of the licenses\n """\n return await asyncio.wrap_future(\n self.executor.submit(\n self.report,\n report_format=report_format,\n bundles_pattern=bundles_pattern,\n full_text=full_text,\n )\n )\n\n def report(self, report_format: str, bundles_pattern: str, full_text: bool) -> tuple[str, str]:\n """create a human- or machine-readable report"""\n bundles = self.bundles(bundles_pattern=bundles_pattern)\n if report_format == "json":\n return self.report_json(bundles), "application/json"\n if report_format == "csv":\n return self.report_csv(bundles), "text/csv"\n if report_format == "markdown":\n return (\n self.report_markdown(bundles, full_text=full_text),\n "text/markdown",\n )\n\n msg = f"Unsupported report format {report_format}."\n raise ValueError(msg)\n\n def report_json(self, bundles: dict[str, Any]) -> str:\n """create a JSON report\n TODO: SPDX\n """\n return json.dumps({"bundles": bundles}, indent=2, sort_keys=True)\n\n def report_csv(self, bundles: dict[str, Any]) -> str:\n """create a CSV report"""\n outfile = io.StringIO()\n fieldnames = ["name", "versionInfo", "licenseId", "extractedText"]\n writer = csv.DictWriter(outfile, fieldnames=["bundle", *fieldnames])\n writer.writeheader()\n for bundle_name, bundle in bundles.items():\n for package in bundle["packages"]:\n writer.writerow(\n {\n "bundle": bundle_name,\n **{field: package.get(field, "") for field in fieldnames},\n }\n )\n return outfile.getvalue()\n\n def report_markdown(self, bundles: dict[str, Any], full_text: bool = True) -> str:\n """create a markdown report"""\n lines = []\n library_names = [\n len(package.get("name", UNKNOWN_PACKAGE_NAME))\n for bundle_name, bundle in bundles.items()\n for package in bundle.get("packages", [])\n ]\n longest_name = max(library_names) if library_names else 1\n\n for bundle_name, bundle in bundles.items():\n # TODO: parametrize template\n lines += [f"# {bundle_name}", ""]\n\n packages = bundle.get("packages", [])\n if not packages:\n lines += ["> No licenses found", ""]\n continue\n\n for package in packages:\n name = package.get("name", UNKNOWN_PACKAGE_NAME).strip()\n version_info = package.get("versionInfo", UNKNOWN_PACKAGE_NAME).strip()\n license_id = package.get("licenseId", UNKNOWN_PACKAGE_NAME).strip()\n extracted_text = package.get("extractedText", "")\n\n lines += [\n "## "\n + (\n "\t".join(\n [\n f"""**{name}**""".ljust(longest_name),\n f"""`{version_info}`""".ljust(20),\n license_id,\n ]\n )\n )\n ]\n\n if full_text:\n if not extracted_text:\n lines += ["", "> No license text available", ""]\n else:\n lines += ["", "", "<pre/>", extracted_text, "</pre>", ""]\n return "\n".join(lines)\n\n def license_bundle(self, path: Path, bundle: str | None) -> dict[str, Any]:\n """Return the content of a packages's license bundles"""\n bundle_json: dict = {"packages": []}\n checked_paths = []\n\n for license_file in self.third_party_licenses_files:\n licenses_path = path / license_file\n self.log.debug("Loading licenses from %s", licenses_path)\n if not licenses_path.exists():\n checked_paths += [licenses_path]\n continue\n\n try:\n file_json = json.loads(licenses_path.read_text(encoding="utf-8"))\n except Exception as err:\n self.log.warning(\n "Failed to open third-party licenses for %s: %s\n%s",\n bundle,\n licenses_path,\n err,\n )\n continue\n\n try:\n bundle_json["packages"].extend(file_json["packages"])\n except Exception as err:\n self.log.warning(\n "Failed to find packages for %s: %s\n%s",\n bundle,\n licenses_path,\n err,\n )\n continue\n\n if not bundle_json["packages"]:\n self.log.warning("Third-party licenses not found for %s: %s", bundle, checked_paths)\n\n return bundle_json\n\n def app_static_info(self) -> tuple[Path | None, str | None]:\n """get the static directory for this app\n\n This will usually be in `static_dir`, but may also appear in the\n parent of `static_dir`.\n """\n if TYPE_CHECKING:\n from .app import LabServerApp\n\n assert isinstance(self.parent, LabServerApp)\n path = Path(self.parent.static_dir)\n package_json = path / "package.json"\n if not package_json.exists():\n parent_package_json = path.parent / "package.json"\n if parent_package_json.exists():\n package_json = parent_package_json\n else:\n return None, None\n name = json.loads(package_json.read_text(encoding="utf-8"))["name"]\n return path, name\n\n def bundles(self, bundles_pattern: str = ".*") -> dict[str, Any]:\n """Read all of the licenses\n TODO: schema\n """\n bundles = {\n name: self.license_bundle(Path(ext["ext_path"]), name)\n for name, ext in self.federated_extensions.items()\n if re.match(bundles_pattern, name)\n }\n\n app_path, app_name = self.app_static_info()\n if app_path is not None:\n assert app_name is not None\n if re.match(bundles_pattern, app_name):\n bundles[app_name] = self.license_bundle(app_path, app_name)\n\n if not bundles:\n self.log.warning("No license bundles found at all")\n\n return bundles\n\n\nclass LicensesHandler(APIHandler):\n """A handler for serving licenses used by the application"""\n\n def initialize(self, manager: LicensesManager) -> None:\n """Initialize the handler."""\n super().initialize()\n self.manager = manager\n\n @web.authenticated\n async def get(self, _args: Any) -> None:\n """Return all the frontend licenses"""\n full_text = bool(json.loads(self.get_argument("full_text", "true")))\n report_format = self.get_argument("format", "json")\n bundles_pattern = self.get_argument("bundles", ".*")\n download = bool(json.loads(self.get_argument("download", "0")))\n\n report, mime = await self.manager.report_async(\n report_format=report_format,\n bundles_pattern=bundles_pattern,\n full_text=full_text,\n )\n\n if TYPE_CHECKING:\n from .app import LabServerApp\n\n assert isinstance(self.manager.parent, LabServerApp)\n\n if download:\n filename = "{}-licenses{}".format(\n self.manager.parent.app_name.lower(), mimetypes.guess_extension(mime)\n )\n self.set_attachment_header(filename)\n self.write(report)\n await self.finish(_mime_type=mime)\n\n async def finish( # type:ignore[override]\n self, _mime_type: str, *args: Any, **kwargs: Any\n ) -> Any:\n """Overload the regular finish, which (sensibly) always sets JSON"""\n self.update_api_activity()\n self.set_header("Content-Type", _mime_type)\n return await super(APIHandler, self).finish(*args, **kwargs)\n
.venv\Lib\site-packages\jupyterlab_server\licenses_handler.py
licenses_handler.py
Python
10,529
0.95
0.197232
0.024793
vue-tools
830
2024-01-06T03:28:06.809612
GPL-3.0
false
faabc9f35336ff50684b19cb164b19b8
"""Tornado handlers for listing extensions."""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport json\nfrom logging import Logger\n\nimport requests\nimport tornado\nfrom jupyter_server.base.handlers import APIHandler\n\nLISTINGS_URL_SUFFIX = "@jupyterlab/extensionmanager-extension/listings.json"\n\n\ndef fetch_listings(logger: Logger | None) -> None:\n """Fetch the listings for the extension manager."""\n if not logger:\n from traitlets import log\n\n logger = log.get_logger() # type:ignore[assignment]\n assert logger is not None\n if len(ListingsHandler.blocked_extensions_uris) > 0:\n blocked_extensions = []\n for blocked_extensions_uri in ListingsHandler.blocked_extensions_uris:\n logger.info(\n "Fetching blocked_extensions from %s", ListingsHandler.blocked_extensions_uris\n )\n r = requests.request(\n "GET", blocked_extensions_uri, **ListingsHandler.listings_request_opts\n )\n j = json.loads(r.text)\n for b in j["blocked_extensions"]:\n blocked_extensions.append(b)\n ListingsHandler.blocked_extensions = blocked_extensions\n if len(ListingsHandler.allowed_extensions_uris) > 0:\n allowed_extensions = []\n for allowed_extensions_uri in ListingsHandler.allowed_extensions_uris:\n logger.info(\n "Fetching allowed_extensions from %s", ListingsHandler.allowed_extensions_uris\n )\n r = requests.request(\n "GET", allowed_extensions_uri, **ListingsHandler.listings_request_opts\n )\n j = json.loads(r.text)\n for w in j["allowed_extensions"]:\n allowed_extensions.append(w)\n ListingsHandler.allowed_extensions = allowed_extensions\n ListingsHandler.listings = json.dumps( # type:ignore[attr-defined]\n {\n "blocked_extensions_uris": list(ListingsHandler.blocked_extensions_uris),\n "allowed_extensions_uris": list(ListingsHandler.allowed_extensions_uris),\n "blocked_extensions": ListingsHandler.blocked_extensions,\n "allowed_extensions": ListingsHandler.allowed_extensions,\n }\n )\n\n\nclass ListingsHandler(APIHandler):\n """An handler that returns the listings specs."""\n\n """Below fields are class level fields that are accessed and populated\n by the initialization and the fetch_listings methods.\n Some fields are initialized before the handler creation in the\n handlers.py#add_handlers method.\n Having those fields predefined reduces the guards in the methods using\n them.\n """\n # The list of blocked_extensions URIS.\n blocked_extensions_uris: set = set()\n # The list of allowed_extensions URIS.\n allowed_extensions_uris: set = set()\n # The blocked extensions extensions.\n blocked_extensions: list = []\n # The allowed extensions extensions.\n allowed_extensions: list = []\n # The provider request options to be used for the request library.\n listings_request_opts: dict = {}\n # The callback time for the periodic callback in seconds.\n listings_refresh_seconds: int\n # The PeriodicCallback that schedule the call to fetch_listings method.\n pc = None\n\n def get(self, path: str) -> None:\n """Get the listings for the extension manager."""\n self.set_header("Content-Type", "application/json")\n if path == LISTINGS_URL_SUFFIX:\n self.write(ListingsHandler.listings) # type:ignore[attr-defined]\n else:\n raise tornado.web.HTTPError(400)\n
.venv\Lib\site-packages\jupyterlab_server\listings_handler.py
listings_handler.py
Python
3,676
0.95
0.186813
0.1125
node-utils
546
2024-04-17T10:34:10.437014
Apache-2.0
false
5324c3183ba13f0fdf53645a9a787c8b
"""JupyterLab Server process handler"""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport atexit\nimport logging\nimport os\nimport re\nimport signal\nimport subprocess\nimport sys\nimport threading\nimport time\nimport weakref\nfrom logging import Logger\nfrom shutil import which as _which\nfrom typing import Any\n\nfrom tornado import gen\n\ntry:\n import pty\nexcept ImportError:\n pty = None # type:ignore[assignment]\n\nif sys.platform == "win32":\n list2cmdline = subprocess.list2cmdline\nelse:\n\n def list2cmdline(cmd_list: list[str]) -> str:\n """Shim for list2cmdline on posix."""\n import shlex\n\n return " ".join(map(shlex.quote, cmd_list))\n\n\ndef which(command: str, env: dict[str, str] | None = None) -> str:\n """Get the full path to a command.\n\n Parameters\n ----------\n command: str\n The command name or path.\n env: dict, optional\n The environment variables, defaults to `os.environ`.\n """\n env = env or os.environ # type:ignore[assignment]\n path = env.get("PATH") or os.defpath # type:ignore[union-attr]\n command_with_path = _which(command, path=path)\n\n # Allow nodejs as an alias to node.\n if command == "node" and not command_with_path:\n command = "nodejs"\n command_with_path = _which("nodejs", path=path)\n\n if not command_with_path:\n if command in ["nodejs", "node", "npm"]:\n msg = "Please install Node.js and npm before continuing installation. You may be able to install Node.js from your package manager, from conda, or directly from the Node.js website (https://nodejs.org)."\n raise ValueError(msg)\n raise ValueError("The command was not found or was not " + "executable: %s." % command)\n return os.path.abspath(command_with_path)\n\n\nclass Process:\n """A wrapper for a child process."""\n\n _procs: weakref.WeakSet = weakref.WeakSet()\n _pool = None\n\n def __init__(\n self,\n cmd: list[str],\n logger: Logger | None = None,\n cwd: str | None = None,\n kill_event: threading.Event | None = None,\n env: dict[str, str] | None = None,\n quiet: bool = False,\n ) -> None:\n """Start a subprocess that can be run asynchronously.\n\n Parameters\n ----------\n cmd: list\n The command to run.\n logger: :class:`~logger.Logger`, optional\n The logger instance.\n cwd: string, optional\n The cwd of the process.\n env: dict, optional\n The environment for the process.\n kill_event: :class:`~threading.Event`, optional\n An event used to kill the process operation.\n quiet: bool, optional\n Whether to suppress output.\n """\n if not isinstance(cmd, (list, tuple)):\n msg = "Command must be given as a list" # type:ignore[unreachable]\n raise ValueError(msg)\n\n if kill_event and kill_event.is_set():\n msg = "Process aborted"\n raise ValueError(msg)\n\n self.logger = logger or self.get_log()\n self._last_line = ""\n if not quiet:\n self.logger.info("> %s", list2cmdline(cmd))\n self.cmd = cmd\n\n kwargs = {}\n if quiet:\n kwargs["stdout"] = subprocess.DEVNULL\n\n self.proc = self._create_process(cwd=cwd, env=env, **kwargs)\n self._kill_event = kill_event or threading.Event()\n\n Process._procs.add(self)\n\n def terminate(self) -> int:\n """Terminate the process and return the exit code."""\n proc = self.proc\n\n # Kill the process.\n if proc.poll() is None:\n os.kill(proc.pid, signal.SIGTERM)\n\n # Wait for the process to close.\n try:\n proc.wait(timeout=2.0)\n except subprocess.TimeoutExpired:\n if os.name == "nt": # noqa: SIM108\n sig = signal.SIGBREAK # type:ignore[attr-defined]\n else:\n sig = signal.SIGKILL\n\n if proc.poll() is None:\n os.kill(proc.pid, sig)\n\n finally:\n if self in Process._procs:\n Process._procs.remove(self)\n\n return proc.wait()\n\n def wait(self) -> int:\n """Wait for the process to finish.\n\n Returns\n -------\n The process exit code.\n """\n proc = self.proc\n kill_event = self._kill_event\n while proc.poll() is None:\n if kill_event.is_set():\n self.terminate()\n msg = "Process was aborted"\n raise ValueError(msg)\n time.sleep(1.0)\n return self.terminate()\n\n @gen.coroutine\n def wait_async(self) -> Any:\n """Asynchronously wait for the process to finish."""\n proc = self.proc\n kill_event = self._kill_event\n while proc.poll() is None:\n if kill_event.is_set():\n self.terminate()\n msg = "Process was aborted"\n raise ValueError(msg)\n yield gen.sleep(1.0)\n\n raise gen.Return(self.terminate())\n\n def _create_process(self, **kwargs: Any) -> subprocess.Popen[str]:\n """Create the process."""\n cmd = list(self.cmd)\n kwargs.setdefault("stderr", subprocess.STDOUT)\n\n cmd[0] = which(cmd[0], kwargs.get("env"))\n\n if os.name == "nt":\n kwargs["shell"] = True\n\n return subprocess.Popen(cmd, **kwargs) # noqa: S603\n\n @classmethod\n def _cleanup(cls: type[Process]) -> None:\n """Clean up the started subprocesses at exit."""\n for proc in list(cls._procs):\n proc.terminate()\n\n def get_log(self) -> Logger:\n """Get our logger."""\n if hasattr(self, "logger") and self.logger is not None:\n return self.logger\n # fallback logger\n self.logger = logging.getLogger("jupyterlab")\n self.logger.setLevel(logging.INFO)\n return self.logger\n\n\nclass WatchHelper(Process):\n """A process helper for a watch process."""\n\n def __init__(\n self,\n cmd: list[str],\n startup_regex: str,\n logger: Logger | None = None,\n cwd: str | None = None,\n kill_event: threading.Event | None = None,\n env: dict[str, str] | None = None,\n ) -> None:\n """Initialize the process helper.\n\n Parameters\n ----------\n cmd: list\n The command to run.\n startup_regex: string\n The regex to wait for at startup.\n logger: :class:`~logger.Logger`, optional\n The logger instance.\n cwd: string, optional\n The cwd of the process.\n env: dict, optional\n The environment for the process.\n kill_event: callable, optional\n A function to call to check if we should abort.\n """\n super().__init__(cmd, logger=logger, cwd=cwd, kill_event=kill_event, env=env)\n\n if pty is None:\n self._stdout = self.proc.stdout # type:ignore[unreachable]\n\n while 1:\n line = self._stdout.readline().decode("utf-8") # type:ignore[has-type]\n if not line:\n msg = "Process ended improperly"\n raise RuntimeError(msg)\n print(line.rstrip())\n if re.match(startup_regex, line):\n break\n\n self._read_thread = threading.Thread(target=self._read_incoming, daemon=True)\n self._read_thread.start()\n\n def terminate(self) -> int:\n """Terminate the process."""\n proc = self.proc\n\n if proc.poll() is None:\n if os.name != "nt":\n # Kill the process group if we started a new session.\n os.killpg(os.getpgid(proc.pid), signal.SIGTERM)\n else:\n os.kill(proc.pid, signal.SIGTERM)\n\n # Wait for the process to close.\n try:\n proc.wait()\n finally:\n if self in Process._procs:\n Process._procs.remove(self)\n\n return proc.returncode\n\n def _read_incoming(self) -> None:\n """Run in a thread to read stdout and print"""\n fileno = self._stdout.fileno() # type:ignore[has-type]\n while 1:\n try:\n buf = os.read(fileno, 1024)\n except OSError as e:\n self.logger.debug("Read incoming error %s", e)\n return\n\n if not buf:\n return\n\n print(buf.decode("utf-8"), end="")\n\n def _create_process(self, **kwargs: Any) -> subprocess.Popen[str]:\n """Create the watcher helper process."""\n kwargs["bufsize"] = 0\n\n if pty is not None:\n master, slave = pty.openpty()\n kwargs["stderr"] = kwargs["stdout"] = slave\n kwargs["start_new_session"] = True\n self._stdout = os.fdopen(master, "rb") # type:ignore[has-type]\n else:\n kwargs["stdout"] = subprocess.PIPE # type:ignore[unreachable]\n\n if os.name == "nt":\n startupinfo = subprocess.STARTUPINFO()\n startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\n kwargs["startupinfo"] = startupinfo\n kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP\n kwargs["shell"] = True\n\n return super()._create_process(**kwargs)\n\n\n# Register the cleanup handler.\natexit.register(Process._cleanup)\n
.venv\Lib\site-packages\jupyterlab_server\process.py
process.py
Python
9,484
0.95
0.209677
0.035714
vue-tools
25
2024-12-23T18:03:07.011787
Apache-2.0
false
125849ec54f078716ecaa2430ad76ab2
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""A lab app that runs a sub process for a demo or a test."""\nfrom __future__ import annotations\n\nimport sys\nfrom typing import Any\n\nfrom jupyter_server.extension.application import ExtensionApp, ExtensionAppJinjaMixin\nfrom tornado.ioloop import IOLoop\n\nfrom .handlers import LabConfig, add_handlers\nfrom .process import Process\n\n\nclass ProcessApp(ExtensionAppJinjaMixin, LabConfig, ExtensionApp):\n """A jupyterlab app that runs a separate process and exits on completion."""\n\n load_other_extensions = True\n\n # Do not open a browser for process apps\n open_browser = False # type:ignore[assignment]\n\n def get_command(self) -> tuple[list[str], dict[str, Any]]:\n """Get the command and kwargs to run with `Process`.\n This is intended to be overridden.\n """\n return [sys.executable, "--version"], {}\n\n def initialize_settings(self) -> None:\n """Start the application."""\n IOLoop.current().add_callback(self._run_command)\n\n def initialize_handlers(self) -> None:\n """Initialize the handlers."""\n add_handlers(self.handlers, self) # type:ignore[arg-type]\n\n def _run_command(self) -> None:\n command, kwargs = self.get_command()\n kwargs.setdefault("logger", self.log)\n future = Process(command, **kwargs).wait_async()\n IOLoop.current().add_future(future, self._process_finished)\n\n def _process_finished(self, future: Any) -> None:\n try:\n IOLoop.current().stop()\n sys.exit(future.result())\n except Exception as e:\n self.log.error(str(e))\n sys.exit(1)\n
.venv\Lib\site-packages\jupyterlab_server\process_app.py
process_app.py
Python
1,715
0.95
0.176471
0.078947
vue-tools
471
2024-07-09T07:25:54.344511
MIT
false
2a277bef6c13ac50d8ecdc934d44d0fd
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""pytest fixtures."""\nfrom __future__ import annotations\n\nimport json\nimport os\nimport os.path as osp\nimport shutil\nfrom os.path import join as pjoin\nfrom pathlib import Path\nfrom typing import Any, Callable\n\nimport pytest\nfrom jupyter_server.serverapp import ServerApp\n\nfrom jupyterlab_server import LabServerApp\n\npytest_plugins = ["pytest_jupyter.jupyter_server"]\n\n\ndef mkdir(tmp_path: Path, *parts: str) -> Path:\n """Util for making a directory."""\n path = tmp_path.joinpath(*parts)\n if not path.exists():\n path.mkdir(parents=True)\n return path\n\n\nHERE = os.path.abspath(os.path.dirname(__file__))\n\napp_settings_dir = pytest.fixture(lambda tmp_path: mkdir(tmp_path, "app_settings"))\nuser_settings_dir = pytest.fixture(lambda tmp_path: mkdir(tmp_path, "user_settings"))\nschemas_dir = pytest.fixture(lambda tmp_path: mkdir(tmp_path, "schemas"))\nworkspaces_dir = pytest.fixture(lambda tmp_path: mkdir(tmp_path, "workspaces"))\nlabextensions_dir = pytest.fixture(lambda tmp_path: mkdir(tmp_path, "labextensions_dir"))\n\n\n@pytest.fixture\ndef make_labserver_extension_app(\n jp_root_dir: Path,\n jp_template_dir: Path,\n app_settings_dir: Path,\n user_settings_dir: Path,\n schemas_dir: Path,\n workspaces_dir: Path,\n labextensions_dir: Path,\n) -> Callable[..., LabServerApp]:\n """Return a factory function for a labserver extension app."""\n\n def _make_labserver_extension_app(**kwargs: Any) -> LabServerApp: # noqa: ARG001\n """Factory function for lab server extension apps."""\n return LabServerApp(\n static_dir=str(jp_root_dir),\n templates_dir=str(jp_template_dir),\n app_url="/lab",\n app_settings_dir=str(app_settings_dir),\n user_settings_dir=str(user_settings_dir),\n schemas_dir=str(schemas_dir),\n workspaces_dir=str(workspaces_dir),\n extra_labextensions_path=[str(labextensions_dir)],\n )\n\n # Create the index files.\n index = jp_template_dir.joinpath("index.html")\n index.write_text(\n """\n<!DOCTYPE html>\n<html>\n<head>\n <title>{{page_config['appName'] | e}}</title>\n</head>\n<body>\n {# Copy so we do not modify the page_config with updates. #}\n {% set page_config_full = page_config.copy() %}\n\n {# Set a dummy variable - we just want the side effect of the update. #}\n {% set _ = page_config_full.update(baseUrl=base_url, wsUrl=ws_url) %}\n\n <script id="jupyter-config-data" type="application/json">\n {{ page_config_full | tojson }}\n </script>\n <script src="{{page_config['fullStaticUrl'] | e}}/bundle.js" main="index"></script>\n\n <script type="text/javascript">\n /* Remove token from URL. */\n (function () {\n var parsedUrl = new URL(window.location.href);\n if (parsedUrl.searchParams.get('token')) {\n parsedUrl.searchParams.delete('token');\n window.history.replaceState({ }, '', parsedUrl.href);\n }\n })();\n </script>\n</body>\n</html>\n"""\n )\n\n # Copy the schema files.\n src = pjoin(HERE, "test_data", "schemas", "@jupyterlab")\n dst = pjoin(str(schemas_dir), "@jupyterlab")\n if os.path.exists(dst):\n shutil.rmtree(dst)\n shutil.copytree(src, dst)\n\n # Create the federated extensions\n for name in ["apputils-extension", "codemirror-extension"]:\n target_name = name + "-federated"\n target = pjoin(str(labextensions_dir), "@jupyterlab", target_name)\n src = pjoin(HERE, "test_data", "schemas", "@jupyterlab", name)\n dst = pjoin(target, "schemas", "@jupyterlab", target_name)\n if osp.exists(dst):\n shutil.rmtree(dst)\n shutil.copytree(src, dst)\n with open(pjoin(target, "package.orig.json"), "w") as fid:\n data = dict(name=target_name, jupyterlab=dict(extension=True))\n json.dump(data, fid)\n\n # Copy the overrides file.\n src = pjoin(HERE, "test_data", "app-settings", "overrides.json")\n dst = pjoin(str(app_settings_dir), "overrides.json")\n if os.path.exists(dst):\n os.remove(dst)\n shutil.copyfile(src, dst)\n\n # Copy workspaces.\n ws_path = pjoin(HERE, "test_data", "workspaces")\n for item in os.listdir(ws_path):\n src = pjoin(ws_path, item)\n dst = pjoin(str(workspaces_dir), item)\n if os.path.exists(dst):\n os.remove(dst)\n shutil.copy(src, str(workspaces_dir))\n\n return _make_labserver_extension_app\n\n\n@pytest.fixture\ndef labserverapp(\n jp_serverapp: ServerApp, make_labserver_extension_app: Callable[..., LabServerApp]\n) -> LabServerApp:\n """A lab server app."""\n app = make_labserver_extension_app()\n app._link_jupyter_server_extension(jp_serverapp)\n app.initialize() # type:ignore[no-untyped-call]\n return app\n
.venv\Lib\site-packages\jupyterlab_server\pytest_plugin.py
pytest_plugin.py
Python
4,844
0.95
0.121622
0.064516
node-utils
726
2024-03-24T08:05:32.972795
GPL-3.0
true
046fed9abddbe41c2957ac6128cc2c9e
# see me at: https://petstore.swagger.io/?url=https://raw.githubusercontent.com/jupyterlab/jupyterlab_server/main/jupyterlab_server/rest-api.yml#/default\nopenapi: "3.0.3"\ninfo:\n title: JupyterLab Server\n description: The REST API for JupyterLab Server\n version: 1.0.0\n license:\n name: BSD-3-Clause\n\npaths:\n /lab/api/listings/%40jupyterlab/extensionmanager-extension/listings.json:\n get:\n summary: Get Extension Listings Specs\n description: |\n Gets the list of extension metadata for the application\n responses:\n "200":\n description: The Extension Listing specs\n content:\n application/json:\n schema:\n properties:\n blocked_extension_uris:\n type: array\n description: list of blocked extension uris\n items:\n type: string\n allowed_extension_uris:\n type: array\n description: list of allowed extension uris\n items:\n type: string\n blocked_extensions:\n type: array\n description: list of blocked extensions\n items:\n $ref: "#/components/schemas/ListEntry"\n allowed_extensions:\n type: array\n description: list of blocked extensions\n items:\n $ref: "#/components/schemas/ListEntry"\n\n /lab/api/settings/:\n get:\n summary: Get Settings List\n description: |\n Gets the list of all application settings data\n responses:\n "200":\n description: The Application Settings Data\n content:\n application/json:\n schema:\n properties:\n settings:\n type: array\n description: List of application settings entries\n items:\n $ref: "#/components/schemas/SettingsEntry"\n\n /lab/api/settings/{schema_name}:\n parameters:\n - name: schema_name\n description: Schema Name\n in: path\n required: true\n schema:\n type: string\n get:\n summary: Get the settings data for a given schema\n description: |\n Gets the settings data for a given schema\n responses:\n "200":\n description: The Settings Data\n content:\n application/json:\n schema:\n $ref: "#/components/schemas/SettingsEntry"\n put:\n summary: Override the settings data for a given schema\n description: |\n Overrides the settings data for a given schema\n requestBody:\n required: true\n description: raw settings data\n content:\n application/json:\n schema:\n type: object\n properties:\n raw:\n type: string\n responses:\n "204":\n description: The setting has been updated\n\n /lab/api/themes/{theme_file}:\n parameters:\n - name: theme_file\n description: Theme file path\n in: path\n required: true\n schema:\n type: string\n get:\n summary: Get a static theme file\n description: |\n Gets the static theme file at a given path\n responses:\n "200":\n description: The Theme File\n\n /lab/api/translations/:\n get:\n summary: Get Translation Bundles\n description: |\n Gets the list of translation bundles\n responses:\n "200":\n description: The Extension Listing specs\n content:\n application/json:\n schema:\n type: object\n properties:\n data:\n type: object\n additionalProperties:\n $ref: "#/components/schemas/TranslationEntry"\n message:\n type: string\n\n /lab/api/translations/{locale}:\n parameters:\n - name: locale\n description: Locale name\n in: path\n required: true\n schema:\n type: string\n get:\n summary: Get the translation data for locale\n description: |\n Gets the translation data for a given locale\n responses:\n "200":\n description: The Local Data\n content:\n application/json:\n schema:\n type: object\n properties:\n data:\n type: object\n message:\n type: string\n\n /lab/api/workspaces/:\n get:\n summary: Get Workspace Data\n description: |\n Gets the list of workspace data\n responses:\n "200":\n description: The Workspace specs\n content:\n application/json:\n schema:\n type: object\n properties:\n workspaces:\n type: object\n properties:\n ids:\n type: array\n items:\n type: string\n values:\n type: array\n items:\n $ref: "#/components/schemas/Workspace"\n\n /lab/api/workspaces/{space_name}:\n parameters:\n - name: space_name\n description: Workspace name\n in: path\n required: true\n schema:\n type: string\n get:\n summary: Get the workspace data for name\n description: |\n Gets the workspace data for a given workspace name\n responses:\n "200":\n description: The Workspace Data\n content:\n application/json:\n schema:\n $ref: "#/components/schemas/Workspace"\n put:\n summary: Override the workspace data for a given name\n description: |\n Overrides the workspace data for a given workspace name\n requestBody:\n required: true\n description: raw workspace data\n content:\n application/json:\n schema:\n $ref: "#/components/schemas/Workspace"\n responses:\n "204":\n description: The workspace has been updated\n\n delete:\n summary: Delete the workspace data for a given name\n description: |\n Deletes the workspace data for a given workspace name\n responses:\n "204":\n description: The workspace has been deleted\n /lab/api/licenses/:\n get:\n summary: License report\n description: |\n Get the third-party licenses for the core application and all federated\n extensions\n parameters:\n - name: full_text\n description: Return full license texts\n in: query\n schema:\n type: boolean\n - name: format\n in: query\n description: The format in which to report licenses\n schema:\n type: string\n enum:\n - csv\n - json\n - markdown\n - name: bundles\n description: A regular expression to limit the names of bundles reported\n in: query\n schema:\n type: string\n - name: download\n in: query\n description: Whether to set a representative filename header\n schema:\n type: boolean\n responses:\n "200":\n description: A license report\n content:\n application/markdown:\n schema:\n type: string\n text/csv:\n schema:\n type: string\n application/json:\n schema:\n $ref: "#/components/schemas/LicenseBundles"\n\ncomponents:\n schemas:\n ListEntry:\n type: object\n properties:\n name:\n type: string\n regexp:\n type: string\n type:\n type: string\n reason:\n type: string\n creation_date:\n type: string\n last_update_date:\n type: string\n SettingsEntry:\n type: object\n properties:\n id:\n type: string\n schema:\n type: object\n version:\n type: string\n raw:\n type: string\n settings:\n type: object\n warning:\n type: string\n nullable: true\n last_modified:\n type: string\n nullable: true\n created:\n type: string\n nullable: true\n TranslationEntry:\n type: object\n properties:\n data:\n type: object\n properties:\n displayName:\n type: string\n nativeName:\n type: string\n message:\n type: string\n Workspace:\n type: object\n properties:\n data:\n type: object\n metadata:\n type: object\n properties:\n id:\n type: string\n last_modified:\n type: string\n created:\n type: string\n LicenseBundles:\n type: object\n properties:\n bundles:\n type: object\n additionalProperties:\n type: object\n properties:\n packages:\n type: array\n items:\n type: object\n properties:\n extractedText:\n type: string\n licenseId:\n type: string\n name:\n type: string\n versionInfo:\n type: string\n
.venv\Lib\site-packages\jupyterlab_server\rest-api.yml
rest-api.yml
YAML
9,794
0.95
0.042135
0.00289
node-utils
328
2025-05-08T21:41:58.521338
MIT
false
ea08104a66287c9af8a0357d5bc6f2d5
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Server api."""\n# FIXME TODO Deprecated remove this file for the next major version\n# Downstream package must import those items from `jupyter_server` directly\nfrom jupyter_server import _tz as tz\nfrom jupyter_server.base.handlers import (\n APIHandler,\n FileFindHandler,\n JupyterHandler,\n json_errors,\n)\nfrom jupyter_server.extension.serverextension import (\n GREEN_ENABLED,\n GREEN_OK,\n RED_DISABLED,\n RED_X,\n)\nfrom jupyter_server.serverapp import ServerApp, aliases, flags\nfrom jupyter_server.utils import url_escape, url_path_join\n
.venv\Lib\site-packages\jupyterlab_server\server.py
server.py
Python
663
0.95
0.047619
0.2
awesome-app
655
2023-12-29T09:21:38.072569
GPL-3.0
false
931108b2809d4fbf9def332bdc6327b2
"""Tornado handlers for frontend config storage."""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport json\nfrom typing import Any\n\nfrom jsonschema import ValidationError\nfrom jupyter_server.extension.handler import ExtensionHandlerJinjaMixin, ExtensionHandlerMixin\nfrom tornado import web\n\nfrom .settings_utils import SchemaHandler, get_settings, save_settings\nfrom .translation_utils import translator\n\n\nclass SettingsHandler(ExtensionHandlerMixin, ExtensionHandlerJinjaMixin, SchemaHandler):\n """A settings API handler."""\n\n def initialize( # type:ignore[override]\n self,\n name: str,\n app_settings_dir: str,\n schemas_dir: str,\n settings_dir: str,\n labextensions_path: list[str],\n overrides: dict[str, Any] | None = None,\n **kwargs: Any, # noqa: ARG002\n ) -> None:\n """Initialize the handler."""\n SchemaHandler.initialize(\n self, app_settings_dir, schemas_dir, settings_dir, labextensions_path, overrides\n )\n ExtensionHandlerMixin.initialize(self, name)\n\n @web.authenticated\n def get(self, schema_name: str = "") -> Any:\n """\n Get setting(s)\n\n Parameters\n ----------\n schema_name: str\n The id of a unique schema to send, added to the URL\n\n ## NOTES:\n An optional argument `ids_only=true` can be provided in the URL to get only the\n ids of the schemas instead of the content.\n """\n # Need to be update here as translator locale is not change when a new locale is put\n # from frontend\n locale = self.get_current_locale()\n translator.set_locale(locale)\n\n ids_only = self.get_argument("ids_only", "") == "true"\n\n result, warnings = get_settings(\n self.app_settings_dir,\n self.schemas_dir,\n self.settings_dir,\n labextensions_path=self.labextensions_path,\n schema_name=schema_name,\n overrides=self.overrides,\n translator=translator.translate_schema,\n ids_only=ids_only,\n )\n\n # Print all warnings.\n for w in warnings:\n if w:\n self.log.warning(w)\n\n return self.finish(json.dumps(result))\n\n @web.authenticated\n def put(self, schema_name: str) -> None:\n """Update a setting"""\n overrides = self.overrides\n schemas_dir = self.schemas_dir\n settings_dir = self.settings_dir\n settings_error = "No current settings directory"\n invalid_json_error = "Failed parsing JSON payload: %s"\n invalid_payload_format_error = (\n "Invalid format for JSON payload. Must be in the form {'raw': ...}"\n )\n validation_error = "Failed validating input: %s"\n\n if not settings_dir:\n raise web.HTTPError(500, settings_error)\n\n raw_payload = self.request.body.strip().decode("utf-8")\n try:\n raw_settings = json.loads(raw_payload)["raw"]\n save_settings(\n schemas_dir,\n settings_dir,\n schema_name,\n raw_settings,\n overrides,\n self.labextensions_path,\n )\n except json.decoder.JSONDecodeError as e:\n raise web.HTTPError(400, invalid_json_error % str(e)) from None\n except (KeyError, TypeError):\n raise web.HTTPError(400, invalid_payload_format_error) from None\n except ValidationError as e:\n raise web.HTTPError(400, validation_error % str(e)) from None\n\n self.set_status(204)\n
.venv\Lib\site-packages\jupyterlab_server\settings_handler.py
settings_handler.py
Python
3,705
0.95
0.090909
0.076087
python-kit
343
2024-01-02T01:42:25.786383
BSD-3-Clause
false
3a97b2bcb9fd60ec29b39e70b7589ac5
"""Frontend config storage helpers."""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport json\nimport os\nfrom glob import glob\nfrom typing import Any\n\nimport json5\nfrom jsonschema import Draft7Validator as Validator\nfrom jsonschema import ValidationError\nfrom jupyter_server import _tz as tz\nfrom jupyter_server.base.handlers import APIHandler\nfrom jupyter_server.services.config.manager import ConfigManager, recursive_update\nfrom tornado import web\n\nfrom .translation_utils import (\n DEFAULT_LOCALE,\n L10N_SCHEMA_NAME,\n PSEUDO_LANGUAGE,\n SYS_LOCALE,\n is_valid_locale,\n)\n\n# The JupyterLab settings file extension.\nSETTINGS_EXTENSION = ".jupyterlab-settings"\n\n\ndef _get_schema(\n schemas_dir: str,\n schema_name: str,\n overrides: dict[str, Any],\n labextensions_path: list[str] | None,\n) -> tuple[dict[str, Any], str]:\n """Returns a dict containing a parsed and validated JSON schema."""\n notfound_error = "Schema not found: %s"\n parse_error = "Failed parsing schema (%s): %s"\n validation_error = "Failed validating schema (%s): %s"\n\n path = None\n\n # Look for the setting in all of the labextension paths first\n # Use the first one\n if labextensions_path is not None:\n ext_name, _, plugin_name = schema_name.partition(":")\n for ext_path in labextensions_path:\n target = os.path.join(ext_path, ext_name, "schemas", ext_name, plugin_name + ".json")\n if os.path.exists(target):\n schemas_dir = os.path.join(ext_path, ext_name, "schemas")\n path = target\n break\n\n # Fall back on the default location\n if path is None:\n path = _path(schemas_dir, schema_name)\n\n if not os.path.exists(path):\n raise web.HTTPError(404, notfound_error % path)\n\n with open(path, encoding="utf-8") as fid:\n # Attempt to load the schema file.\n try:\n schema = json.load(fid)\n except Exception as e:\n name = schema_name\n raise web.HTTPError(500, parse_error % (name, str(e))) from None\n\n schema = _override(schema_name, schema, overrides)\n\n # Validate the schema.\n try:\n Validator.check_schema(schema)\n except Exception as e:\n name = schema_name\n raise web.HTTPError(500, validation_error % (name, str(e))) from None\n\n version = _get_version(schemas_dir, schema_name)\n\n return schema, version\n\n\ndef _get_user_settings(settings_dir: str, schema_name: str, schema: Any) -> dict[str, Any]:\n """\n Returns a dictionary containing the raw user settings, the parsed user\n settings, a validation warning for a schema, and file times.\n """\n path = _path(settings_dir, schema_name, False, SETTINGS_EXTENSION)\n raw = "{}"\n settings = {}\n warning = None\n validation_warning = "Failed validating settings (%s): %s"\n parse_error = "Failed loading settings (%s): %s"\n last_modified = None\n created = None\n\n if os.path.exists(path):\n stat = os.stat(path)\n last_modified = tz.utcfromtimestamp(stat.st_mtime).isoformat()\n created = tz.utcfromtimestamp(stat.st_ctime).isoformat()\n with open(path, encoding="utf-8") as fid:\n try: # to load and parse the settings file.\n raw = fid.read() or raw\n settings = json5.loads(raw)\n except Exception as e:\n raise web.HTTPError(500, parse_error % (schema_name, str(e))) from None\n\n # Validate the parsed data against the schema.\n if len(settings):\n validator = Validator(schema)\n try:\n validator.validate(settings)\n except ValidationError as e:\n warning = validation_warning % (schema_name, str(e))\n raw = "{}"\n settings = {}\n\n return dict(\n raw=raw, settings=settings, warning=warning, last_modified=last_modified, created=created\n )\n\n\ndef _get_version(schemas_dir: str, schema_name: str) -> str:\n """Returns the package version for a given schema or 'N/A' if not found."""\n\n path = _path(schemas_dir, schema_name)\n package_path = os.path.join(os.path.split(path)[0], "package.json.orig")\n\n try: # to load and parse the package.json.orig file.\n with open(package_path, encoding="utf-8") as fid:\n package = json.load(fid)\n return package["version"]\n except Exception:\n return "N/A"\n\n\ndef _list_settings(\n schemas_dir: str,\n settings_dir: str,\n overrides: dict[str, Any],\n extension: str = ".json",\n labextensions_path: list[str] | None = None,\n translator: Any = None,\n ids_only: bool = False,\n) -> tuple[list[Any], list[Any]]:\n """\n Returns a tuple containing:\n - the list of plugins, schemas, and their settings,\n respecting any defaults that may have been overridden if `ids_only=False`,\n otherwise a list of dict containing only the ids of plugins.\n - the list of warnings that were generated when\n validating the user overrides against the schemas.\n """\n\n settings: dict[str, Any] = {}\n federated_settings: dict[str, Any] = {}\n warnings = []\n\n if not os.path.exists(schemas_dir):\n warnings = ["Settings directory does not exist at %s" % schemas_dir]\n return ([], warnings)\n\n schema_pattern = schemas_dir + "/**/*" + extension\n schema_paths = [path for path in glob(schema_pattern, recursive=True)] # noqa: C416\n schema_paths.sort()\n\n for schema_path in schema_paths:\n # Generate the schema_name used to request individual settings.\n rel_path = os.path.relpath(schema_path, schemas_dir)\n rel_schema_dir, schema_base = os.path.split(rel_path)\n _id = schema_name = ":".join(\n [rel_schema_dir, schema_base[: -len(extension)]] # Remove file extension.\n ).replace("\\", "/") # Normalize slashes.\n\n if ids_only:\n settings[_id] = dict(id=_id)\n else:\n schema, version = _get_schema(schemas_dir, schema_name, overrides, None)\n if translator is not None:\n schema = translator(schema)\n user_settings = _get_user_settings(settings_dir, schema_name, schema)\n\n if user_settings["warning"]:\n warnings.append(user_settings.pop("warning"))\n\n # Add the plugin to the list of settings.\n settings[_id] = dict(id=_id, schema=schema, version=version, **user_settings)\n\n if labextensions_path is not None:\n schema_paths = []\n for ext_dir in labextensions_path:\n schema_pattern = ext_dir + "/**/schemas/**/*" + extension\n schema_paths.extend(path for path in glob(schema_pattern, recursive=True))\n\n schema_paths.sort()\n\n for schema_path_ in schema_paths:\n schema_path = schema_path_.replace(os.sep, "/")\n\n base_dir, rel_path = schema_path.split("schemas/")\n\n # Generate the schema_name used to request individual settings.\n rel_schema_dir, schema_base = os.path.split(rel_path)\n _id = schema_name = ":".join(\n [rel_schema_dir, schema_base[: -len(extension)]] # Remove file extension.\n ).replace("\\", "/") # Normalize slashes.\n\n # bail if we've already handled the highest federated setting\n if _id in federated_settings:\n continue\n\n if ids_only:\n federated_settings[_id] = dict(id=_id)\n else:\n schema, version = _get_schema(\n schemas_dir, schema_name, overrides, labextensions_path=labextensions_path\n )\n user_settings = _get_user_settings(settings_dir, schema_name, schema)\n\n if user_settings["warning"]:\n warnings.append(user_settings.pop("warning"))\n\n # Add the plugin to the list of settings.\n federated_settings[_id] = dict(\n id=_id, schema=schema, version=version, **user_settings\n )\n\n settings.update(federated_settings)\n settings_list = [settings[key] for key in sorted(settings.keys(), reverse=True)]\n\n return (settings_list, warnings)\n\n\ndef _override(\n schema_name: str, schema: dict[str, Any], overrides: dict[str, Any]\n) -> dict[str, Any]:\n """Override default values in the schema if necessary."""\n if schema_name in overrides:\n defaults = overrides[schema_name]\n for key in defaults:\n if key in schema["properties"]:\n new_defaults = schema["properties"][key]["default"]\n # If values for defaults are dicts do a recursive update\n if isinstance(new_defaults, dict):\n recursive_update(new_defaults, defaults[key])\n else:\n new_defaults = defaults[key]\n\n schema["properties"][key]["default"] = new_defaults\n else:\n schema["properties"][key] = dict(default=defaults[key])\n\n return schema\n\n\ndef _path(\n root_dir: str, schema_name: str, make_dirs: bool = False, extension: str = ".json"\n) -> str:\n """\n Returns the local file system path for a schema name in the given root\n directory. This function can be used to filed user overrides in addition to\n schema files. If the `make_dirs` flag is set to `True` it will create the\n parent directory for the calculated path if it does not exist.\n """\n\n notfound_error = "Settings not found (%s)"\n write_error = "Failed writing settings (%s): %s"\n\n try: # to parse path, e.g. @jupyterlab/apputils-extension:themes.\n package_dir, plugin = schema_name.split(":")\n parent_dir = os.path.join(root_dir, package_dir)\n path = os.path.join(parent_dir, plugin + extension)\n except Exception:\n raise web.HTTPError(404, notfound_error % schema_name) from None\n\n if make_dirs and not os.path.exists(parent_dir):\n try:\n os.makedirs(parent_dir)\n except Exception as e:\n raise web.HTTPError(500, write_error % (schema_name, str(e))) from None\n\n return path\n\n\ndef _get_overrides(app_settings_dir: str) -> tuple[dict[str, Any], str]:\n """Get overrides settings from `app_settings_dir`.\n\n The ordering of paths is:\n - {app_settings_dir}/overrides.d/*.{json,json5} (many, namespaced by package)\n - {app_settings_dir}/overrides.{json,json5} (singleton, owned by the user)\n """\n overrides: dict[str, Any]\n error: str\n overrides, error = {}, ""\n\n overrides_d = os.path.join(app_settings_dir, "overrides.d")\n\n # find (and sort) the conf.d overrides files\n all_override_paths = sorted(\n [\n *(glob(os.path.join(overrides_d, "*.json"))),\n *(glob(os.path.join(overrides_d, "*.json5"))),\n ]\n )\n\n all_override_paths += [\n os.path.join(app_settings_dir, "overrides.json"),\n os.path.join(app_settings_dir, "overrides.json5"),\n ]\n\n for overrides_path in all_override_paths:\n if not os.path.exists(overrides_path):\n continue\n\n with open(overrides_path, encoding="utf-8") as fid:\n try:\n if overrides_path.endswith(".json5"):\n path_overrides = json5.load(fid)\n else:\n path_overrides = json.load(fid)\n for plugin_id, config in path_overrides.items():\n recursive_update(overrides.setdefault(plugin_id, {}), config)\n except Exception as e:\n error = e # type:ignore[assignment]\n\n # Allow `default_settings_overrides.json` files in <jupyter_config>/labconfig dirs\n # to allow layering of defaults\n cm = ConfigManager(config_dir_name="labconfig")\n\n for plugin_id, config in cm.get("default_setting_overrides").items(): # type:ignore[no-untyped-call]\n recursive_update(overrides.setdefault(plugin_id, {}), config)\n\n return overrides, error\n\n\ndef get_settings(\n app_settings_dir: str,\n schemas_dir: str,\n settings_dir: str,\n schema_name: str = "",\n overrides: dict[str, Any] | None = None,\n labextensions_path: list[str] | None = None,\n translator: Any = None,\n ids_only: bool = False,\n) -> tuple[dict[str, Any], list[Any]]:\n """\n Get settings.\n\n Parameters\n ----------\n app_settings_dir:\n Path to applications settings.\n schemas_dir: str\n Path to schemas.\n settings_dir:\n Path to settings.\n schema_name str, optional\n Schema name. Default is "".\n overrides: dict, optional\n Settings overrides. If not provided, the overrides will be loaded\n from the `app_settings_dir`. Default is None.\n labextensions_path: list, optional\n List of paths to federated labextensions containing their own schema files.\n translator: Callable[[Dict], Dict] or None, optional\n Translate a schema. It requires the schema dictionary and returns its translation\n\n Returns\n -------\n tuple\n The first item is a dictionary with a list of setting if no `schema_name`\n was provided (only the ids if `ids_only=True`), otherwise it is a dictionary\n with id, raw, scheme, settings and version keys.\n The second item is a list of warnings. Warnings will either be a list of\n i) strings with the warning messages or ii) `None`.\n """\n result = {}\n warnings = []\n\n if overrides is None:\n overrides, _error = _get_overrides(app_settings_dir)\n\n if schema_name:\n schema, version = _get_schema(schemas_dir, schema_name, overrides, labextensions_path)\n if translator is not None:\n schema = translator(schema)\n user_settings = _get_user_settings(settings_dir, schema_name, schema)\n warnings = [user_settings.pop("warning")]\n result = {"id": schema_name, "schema": schema, "version": version, **user_settings}\n else:\n settings_list, warnings = _list_settings(\n schemas_dir,\n settings_dir,\n overrides,\n labextensions_path=labextensions_path,\n translator=translator,\n ids_only=ids_only,\n )\n result = {\n "settings": settings_list,\n }\n\n return result, warnings\n\n\ndef save_settings(\n schemas_dir: str,\n settings_dir: str,\n schema_name: str,\n raw_settings: str,\n overrides: dict[str, Any],\n labextensions_path: list[str] | None = None,\n) -> None:\n """\n Save ``raw_settings`` settings for ``schema_name``.\n\n Parameters\n ----------\n schemas_dir: str\n Path to schemas.\n settings_dir: str\n Path to settings.\n schema_name str\n Schema name.\n raw_settings: str\n Raw serialized settings dictionary\n overrides: dict\n Settings overrides.\n labextensions_path: list, optional\n List of paths to federated labextensions containing their own schema files.\n """\n payload = json5.loads(raw_settings)\n\n # Validate the data against the schema.\n schema, _ = _get_schema(\n schemas_dir, schema_name, overrides, labextensions_path=labextensions_path\n )\n validator = Validator(schema)\n validator.validate(payload)\n\n # Write the raw data (comments included) to a file.\n path = _path(settings_dir, schema_name, True, SETTINGS_EXTENSION)\n with open(path, "w", encoding="utf-8") as fid:\n fid.write(raw_settings)\n\n\nclass SchemaHandler(APIHandler):\n """Base handler for handler requiring access to settings."""\n\n def initialize(\n self,\n app_settings_dir: str,\n schemas_dir: str,\n settings_dir: str,\n labextensions_path: list[str] | None,\n overrides: dict[str, Any] | None = None,\n **kwargs: Any,\n ) -> None:\n """Initialize the handler."""\n super().initialize(**kwargs)\n error = None\n if not overrides:\n overrides, error = _get_overrides(app_settings_dir)\n self.overrides = overrides\n self.app_settings_dir = app_settings_dir\n self.schemas_dir = schemas_dir\n self.settings_dir = settings_dir\n self.labextensions_path = labextensions_path\n\n if error:\n overrides_warning = "Failed loading overrides: %s"\n self.log.warning(overrides_warning, error)\n\n def get_current_locale(self) -> str:\n """\n Get the current locale as specified in the translation-extension settings.\n\n Returns\n -------\n str\n The current locale string.\n\n Notes\n -----\n If the locale setting is not available or not valid, it will default to jupyterlab_server.translation_utils.DEFAULT_LOCALE.\n """\n try:\n settings, _ = get_settings(\n self.app_settings_dir,\n self.schemas_dir,\n self.settings_dir,\n schema_name=L10N_SCHEMA_NAME,\n overrides=self.overrides,\n labextensions_path=self.labextensions_path,\n )\n except web.HTTPError as e:\n schema_warning = "Missing or misshapen translation settings schema:\n%s"\n self.log.warning(schema_warning, e)\n\n settings = {}\n\n current_locale = settings.get("settings", {}).get("locale") or SYS_LOCALE\n if current_locale == "default":\n current_locale = SYS_LOCALE\n if not is_valid_locale(current_locale) and current_locale != PSEUDO_LANGUAGE:\n current_locale = DEFAULT_LOCALE\n\n return current_locale\n
.venv\Lib\site-packages\jupyterlab_server\settings_utils.py
settings_utils.py
Python
17,628
0.95
0.147348
0.054632
python-kit
63
2024-11-06T00:42:14.141611
GPL-3.0
false
e4a5b99821a5c231890aa384f1c80c71
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""OpenAPI spec utils."""\nfrom __future__ import annotations\n\nimport os\nimport typing\nfrom pathlib import Path\n\nif typing.TYPE_CHECKING:\n from openapi_core.spec.paths import Spec\n\nHERE = Path(os.path.dirname(__file__)).resolve()\n\n\ndef get_openapi_spec() -> Spec:\n """Get the OpenAPI spec object."""\n from openapi_core.spec.paths import Spec\n\n openapi_spec_dict = get_openapi_spec_dict()\n return Spec.from_dict(openapi_spec_dict) # type:ignore[arg-type]\n\n\ndef get_openapi_spec_dict() -> dict[str, typing.Any]:\n """Get the OpenAPI spec as a dictionary."""\n from ruamel.yaml import YAML\n\n path = HERE / "rest-api.yml"\n yaml = YAML(typ="safe")\n return yaml.load(path.read_text(encoding="utf-8"))\n
.venv\Lib\site-packages\jupyterlab_server\spec.py
spec.py
Python
825
0.95
0.096774
0.095238
vue-tools
953
2024-12-23T04:46:59.900338
GPL-3.0
false
aa28b511f23d7230f4a9bc690d5fc4b4
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""Testing utils."""\nfrom __future__ import annotations\n\nimport json\nimport os\nimport sys\nfrom http.cookies import SimpleCookie\nfrom pathlib import Path\nfrom urllib.parse import parse_qs, urlparse\n\nimport tornado.httpclient\nimport tornado.web\nfrom openapi_core import V30RequestValidator, V30ResponseValidator\nfrom openapi_core.spec.paths import Spec\nfrom openapi_core.validation.request.datatypes import RequestParameters\nfrom tornado.httpclient import HTTPRequest, HTTPResponse\nfrom werkzeug.datastructures import Headers, ImmutableMultiDict\n\nfrom jupyterlab_server.spec import get_openapi_spec\n\nHERE = Path(os.path.dirname(__file__)).resolve()\n\nwith open(HERE / "test_data" / "app-settings" / "overrides.json", encoding="utf-8") as fid:\n big_unicode_string = json.load(fid)["@jupyterlab/unicode-extension:plugin"]["comment"]\n\n\nclass TornadoOpenAPIRequest:\n """\n Converts a torando request to an OpenAPI one\n """\n\n def __init__(self, request: HTTPRequest, spec: Spec):\n """Initialize the request."""\n self.request = request\n self.spec = spec\n if request.url is None:\n msg = "Request URL is missing" # type:ignore[unreachable]\n raise RuntimeError(msg)\n self._url_parsed = urlparse(request.url)\n\n cookie: SimpleCookie = SimpleCookie()\n cookie.load(request.headers.get("Set-Cookie", ""))\n cookies = {}\n for key, morsel in cookie.items():\n cookies[key] = morsel.value\n\n # extract the path\n o = urlparse(request.url)\n\n # gets deduced by path finder against spec\n path: dict = {}\n\n self.parameters = RequestParameters(\n query=ImmutableMultiDict(parse_qs(o.query)),\n header=dict(request.headers),\n cookie=ImmutableMultiDict(cookies),\n path=path,\n )\n\n @property\n def content_type(self) -> str:\n return "application/json"\n\n @property\n def host_url(self) -> str:\n url = self.request.url\n return url[: url.index("/lab")]\n\n @property\n def path(self) -> str:\n # extract the best matching url\n # work around lack of support for path parameters which can contain slashes\n # https://github.com/OAI/OpenAPI-Specification/issues/892\n url = None\n o = urlparse(self.request.url)\n for path_ in self.spec["paths"]:\n if url:\n continue # type:ignore[unreachable]\n has_arg = "{" in path_\n path = path_[: path_.index("{")] if has_arg else path_\n if path in o.path:\n u = o.path[o.path.index(path) :]\n if not has_arg and len(u) == len(path):\n url = u\n if has_arg and not u.endswith("/"):\n url = u[: len(path)] + r"foo"\n\n if url is None:\n msg = f"Could not find matching pattern for {o.path}"\n raise ValueError(msg)\n return url\n\n @property\n def method(self) -> str:\n method = self.request.method\n return method and method.lower() or ""\n\n @property\n def body(self) -> bytes | None:\n if self.request.body is None:\n return None # type:ignore[unreachable]\n if not isinstance(self.request.body, bytes):\n msg = "Request body is invalid" # type:ignore[unreachable]\n raise AssertionError(msg)\n return self.request.body\n\n @property\n def mimetype(self) -> str:\n # Order matters because all tornado requests\n # include Accept */* which does not necessarily match the content type\n request = self.request\n return (\n request.headers.get("Content-Type")\n or request.headers.get("Accept")\n or "application/json"\n )\n\n\nclass TornadoOpenAPIResponse:\n """A tornado open API response."""\n\n def __init__(self, response: HTTPResponse):\n """Initialize the response."""\n self.response = response\n\n @property\n def data(self) -> bytes | None:\n if not isinstance(self.response.body, bytes):\n msg = "Response body is invalid" # type:ignore[unreachable]\n raise AssertionError(msg)\n return self.response.body\n\n @property\n def status_code(self) -> int:\n return int(self.response.code)\n\n @property\n def content_type(self) -> str:\n return "application/json"\n\n @property\n def mimetype(self) -> str:\n return str(self.response.headers.get("Content-Type", "application/json"))\n\n @property\n def headers(self) -> Headers:\n return Headers(dict(self.response.headers))\n\n\ndef validate_request(response: HTTPResponse) -> None:\n """Validate an API request"""\n openapi_spec = get_openapi_spec()\n\n request = TornadoOpenAPIRequest(response.request, openapi_spec)\n V30RequestValidator(openapi_spec).validate(request)\n\n torn_response = TornadoOpenAPIResponse(response)\n V30ResponseValidator(openapi_spec).validate(request, torn_response)\n\n\ndef maybe_patch_ioloop() -> None:\n """a windows 3.8+ patch for the asyncio loop"""\n if (\n sys.platform.startswith("win")\n and tornado.version_info < (6, 1)\n and sys.version_info >= (3, 8)\n ):\n try:\n from asyncio import WindowsProactorEventLoopPolicy, WindowsSelectorEventLoopPolicy\n except ImportError:\n pass\n # not affected\n else:\n from asyncio import get_event_loop_policy, set_event_loop_policy\n\n if type(get_event_loop_policy()) is WindowsProactorEventLoopPolicy:\n # WindowsProactorEventLoopPolicy is not compatible with tornado 6\n # fallback to the pre-3.8 default of Selector\n set_event_loop_policy(WindowsSelectorEventLoopPolicy())\n\n\ndef expected_http_error(\n error: Exception, expected_code: int, expected_message: str | None = None\n) -> bool:\n """Check that the error matches the expected output error."""\n e = error.value # type:ignore[attr-defined]\n if isinstance(e, tornado.web.HTTPError):\n if expected_code != e.status_code:\n return False\n if expected_message is not None and expected_message != str(e):\n return False\n return True\n if any(\n [\n isinstance(e, tornado.httpclient.HTTPClientError),\n isinstance(e, tornado.httpclient.HTTPError),\n ]\n ):\n if expected_code != e.code:\n return False\n if expected_message:\n message = json.loads(e.response.body.decode())["message"]\n if expected_message != message:\n return False\n return True\n\n return False\n
.venv\Lib\site-packages\jupyterlab_server\test_utils.py
test_utils.py
Python
6,794
0.95
0.204762
0.069767
node-utils
434
2023-10-18T19:29:26.196251
Apache-2.0
true
489709ede745cc81c2d94e8b2ba3d3d5
"""Tornado handlers for dynamic theme loading."""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport os\nimport re\nfrom glob import glob\nfrom typing import Any, Generator\nfrom urllib.parse import urlparse\n\nfrom jupyter_server.base.handlers import FileFindHandler\nfrom jupyter_server.utils import url_path_join as ujoin\n\n\nclass ThemesHandler(FileFindHandler):\n """A file handler that mangles local urls in CSS files."""\n\n def initialize(\n self,\n path: str | list[str],\n default_filename: str | None = None,\n no_cache_paths: list[str] | None = None,\n themes_url: str | None = None,\n labextensions_path: list[str] | None = None,\n **kwargs: Any, # noqa: ARG002\n ) -> None:\n """Initialize the handler."""\n # Get all of the available theme paths in order\n labextensions_path = labextensions_path or []\n ext_paths: list[str] = []\n for ext_dir in labextensions_path:\n theme_pattern = ext_dir + "/**/themes"\n ext_paths.extend(path for path in glob(theme_pattern, recursive=True))\n\n # Add the core theme path last\n if not isinstance(path, list):\n path = [path]\n path = ext_paths + path\n\n FileFindHandler.initialize(\n self, path, default_filename=default_filename, no_cache_paths=no_cache_paths\n )\n self.themes_url = themes_url\n\n def get_content( # type:ignore[override]\n self, abspath: str, start: int | None = None, end: int | None = None\n ) -> bytes | Generator[bytes, None, None]:\n """Retrieve the content of the requested resource which is located\n at the given absolute path.\n\n This method should either return a byte string or an iterator\n of byte strings.\n """\n base, ext = os.path.splitext(abspath)\n if ext != ".css":\n return FileFindHandler.get_content(abspath, start, end)\n\n return self._get_css()\n\n def get_content_size(self) -> int:\n """Retrieve the total size of the resource at the given path."""\n assert self.absolute_path is not None\n base, ext = os.path.splitext(self.absolute_path)\n if ext != ".css":\n return FileFindHandler.get_content_size(self)\n return len(self._get_css())\n\n def _get_css(self) -> bytes:\n """Get the mangled css file contents."""\n assert self.absolute_path is not None\n with open(self.absolute_path, "rb") as fid:\n data = fid.read().decode("utf-8")\n\n if not self.themes_url:\n return b""\n\n basedir = os.path.dirname(self.path).replace(os.sep, "/")\n basepath = ujoin(self.themes_url, basedir)\n\n # Replace local paths with mangled paths.\n # We only match strings that are local urls,\n # e.g. `url('../foo.css')`, `url('images/foo.png')`\n pattern = r"url\('(.*)'\)|url\('(.*)'\)"\n\n def replacer(m: Any) -> Any:\n """Replace the matched relative url with the mangled url."""\n group = m.group()\n # Get the part that matched\n part = next(g for g in m.groups() if g)\n\n # Ignore urls that start with `/` or have a protocol like `http`.\n parsed = urlparse(part)\n if part.startswith("/") or parsed.scheme:\n return group\n\n return group.replace(part, ujoin(basepath, part))\n\n return re.sub(pattern, replacer, data).encode("utf-8")\n
.venv\Lib\site-packages\jupyterlab_server\themes_handler.py
themes_handler.py
Python
3,560
0.95
0.16
0.125
react-lib
217
2025-04-18T20:35:36.396202
GPL-3.0
false
2ec9ae368c9d149168a910cc07980a21
"""\nTranslation handler.\n"""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport json\nimport traceback\nfrom functools import partial\n\nimport tornado\n\nfrom .settings_utils import SchemaHandler\nfrom .translation_utils import (\n SYS_LOCALE,\n get_language_pack,\n get_language_packs,\n is_valid_locale,\n translator,\n)\n\n\nclass TranslationsHandler(SchemaHandler):\n """An API handler for translations."""\n\n @tornado.web.authenticated\n async def get(self, locale: str | None = None) -> None:\n """\n Get installed language packs.\n\n If `locale` is equals to "default", the default locale will be used.\n\n Parameters\n ----------\n locale: str, optional\n If no locale is provided, it will list all the installed language packs.\n Default is `None`.\n """\n data: dict\n data, message = {}, ""\n try:\n current_loop = tornado.ioloop.IOLoop.current()\n if locale is None:\n data, message = await current_loop.run_in_executor(\n None,\n partial(get_language_packs, display_locale=self.get_current_locale()),\n )\n else:\n locale = locale or SYS_LOCALE\n if locale == "default":\n locale = SYS_LOCALE\n data, message = await current_loop.run_in_executor(\n None, partial(get_language_pack, locale)\n )\n if data == {} and not message:\n if is_valid_locale(locale):\n message = f"Language pack '{locale}' not installed!"\n else:\n message = f"Language pack '{locale}' not valid!"\n elif is_valid_locale(locale):\n # only change locale if the language pack is installed and valid\n translator.set_locale(locale)\n except Exception:\n message = traceback.format_exc()\n\n self.set_status(200)\n self.finish(json.dumps({"data": data, "message": message}))\n
.venv\Lib\site-packages\jupyterlab_server\translations_handler.py
translations_handler.py
Python
2,191
0.95
0.132353
0.050847
python-kit
352
2024-08-17T13:13:03.286722
GPL-3.0
false
895e01cac27be3375277d9847303f517
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""\nLocalization utilities to find available language packs and packages with\nlocalization data.\n"""\n\nfrom __future__ import annotations\n\nimport gettext\nimport importlib\nimport json\nimport locale\nimport os\nimport re\nimport sys\nimport traceback\nfrom functools import lru_cache\nfrom typing import Any, Pattern\n\nimport babel\nfrom packaging.version import parse as parse_version\n\n# See compatibility note on `group` keyword in https://docs.python.org/3/library/importlib.metadata.html#entry-points\nif sys.version_info < (3, 10): # pragma: no cover\n from importlib_metadata import entry_points\nelse: # pragma: no cover\n from importlib.metadata import entry_points\n\n# Entry points\nJUPYTERLAB_LANGUAGEPACK_ENTRY = "jupyterlab.languagepack"\nJUPYTERLAB_LOCALE_ENTRY = "jupyterlab.locale"\n\n# Constants\nDEFAULT_LOCALE = "en"\nSYS_LOCALE = locale.getlocale()[0] or DEFAULT_LOCALE\nLOCALE_DIR = "locale"\nLC_MESSAGES_DIR = "LC_MESSAGES"\nDEFAULT_DOMAIN = "jupyterlab"\nL10N_SCHEMA_NAME = "@jupyterlab/translation-extension:plugin"\nPY37_OR_LOWER = sys.version_info[:2] <= (3, 7)\n\n# Pseudo language locale for in-context translation\nPSEUDO_LANGUAGE = "ach_UG"\n\n_default_schema_context = "schema"\n_default_settings_context = "settings"\n_lab_i18n_config = "jupyter.lab.internationalization"\n\n# mapping of schema translatable string selectors to translation context\nDEFAULT_SCHEMA_SELECTORS = {\n "properties/.*/title": _default_settings_context,\n "properties/.*/description": _default_settings_context,\n "definitions/.*/properties/.*/title": _default_settings_context,\n "definitions/.*/properties/.*/description": _default_settings_context,\n "title": _default_schema_context,\n "description": _default_schema_context,\n # JupyterLab-specific\n r"jupyter\.lab\.setting-icon-label": _default_settings_context,\n r"jupyter\.lab\.menus/.*/label": "menu",\n r"jupyter\.lab\.toolbars/.*/label": "toolbar",\n}\n\n\n@lru_cache\ndef _get_default_schema_selectors() -> dict[Pattern, str]:\n return {\n re.compile("^/" + pattern + "$"): context\n for pattern, context in DEFAULT_SCHEMA_SELECTORS.items()\n }\n\n\ndef _prepare_schema_patterns(schema: dict) -> dict[Pattern, str]:\n return {\n **_get_default_schema_selectors(),\n **{\n re.compile("^/" + selector + "$"): _default_schema_context\n for selector in schema.get(_lab_i18n_config, {}).get("selectors", [])\n },\n }\n\n\n# --- Private process helpers\n# ----------------------------------------------------------------------------\ndef _get_installed_language_pack_locales() -> tuple[dict[str, Any], str]:\n """\n Get available installed language pack locales.\n\n Returns\n -------\n tuple\n A tuple, where the first item is the result and the second item any\n error messages.\n """\n data = {}\n messages = []\n for entry_point in entry_points(group=JUPYTERLAB_LANGUAGEPACK_ENTRY):\n try:\n data[entry_point.name] = os.path.dirname(entry_point.load().__file__)\n except Exception: # pragma: no cover\n messages.append(traceback.format_exc())\n\n message = "\n".join(messages)\n return data, message\n\n\ndef _get_installed_package_locales() -> tuple[dict[str, Any], str]:\n """\n Get available installed packages containing locale information.\n\n Returns\n -------\n tuple\n A tuple, where the first item is the result and the second item any\n error messages. The value for the key points to the root location\n the package.\n """\n data = {}\n messages = []\n for entry_point in entry_points(group=JUPYTERLAB_LOCALE_ENTRY):\n try:\n data[entry_point.name] = os.path.dirname(entry_point.load().__file__)\n except Exception:\n messages.append(traceback.format_exc())\n\n message = "\n".join(messages)\n return data, message\n\n\n# --- Helpers\n# ----------------------------------------------------------------------------\ndef is_valid_locale(locale_: str) -> bool:\n """\n Check if a `locale_` value is valid.\n\n Parameters\n ----------\n locale_: str\n Language locale code.\n\n Notes\n -----\n A valid locale is in the form language (See ISO-639 standard) and an\n optional territory (See ISO-3166 standard).\n\n Examples of valid locales:\n - English: DEFAULT_LOCALE\n - Australian English: "en_AU"\n - Portuguese: "pt"\n - Brazilian Portuguese: "pt_BR"\n\n Examples of invalid locales:\n - Australian Spanish: "es_AU"\n - Brazilian German: "de_BR"\n """\n # Add exception for Norwegian\n if locale_ in {\n "no_NO",\n }:\n return True\n\n valid = False\n try:\n babel.Locale.parse(locale_)\n valid = True\n except (babel.core.UnknownLocaleError, ValueError):\n # Expected error if the locale is unknown\n pass\n\n return valid\n\n\ndef get_display_name(locale_: str, display_locale: str = DEFAULT_LOCALE) -> str:\n """\n Return the language name to use with a `display_locale` for a given language locale.\n\n Parameters\n ----------\n locale_: str\n The language name to use.\n display_locale: str, optional\n The language to display the `locale_`.\n\n Returns\n -------\n str\n Localized `locale_` and capitalized language name using `display_locale` as language.\n """\n locale_ = locale_ if is_valid_locale(locale_) else DEFAULT_LOCALE\n display_locale = display_locale if is_valid_locale(display_locale) else DEFAULT_LOCALE\n try:\n loc = babel.Locale.parse(locale_)\n display_name = loc.get_display_name(display_locale)\n except babel.UnknownLocaleError:\n display_name = display_locale\n if display_name:\n display_name = display_name[0].upper() + display_name[1:]\n return display_name # type:ignore[return-value]\n\n\ndef merge_locale_data(\n language_pack_locale_data: dict[str, Any], package_locale_data: dict[str, Any]\n) -> dict[str, Any]:\n """\n Merge language pack data with locale data bundled in packages.\n\n Parameters\n ----------\n language_pack_locale_data: dict\n The dictionary with language pack locale data.\n package_locale_data: dict\n The dictionary with package locale data.\n\n Returns\n -------\n dict\n Merged locale data.\n """\n result = language_pack_locale_data\n package_lp_metadata = language_pack_locale_data.get("", {})\n package_lp_version = package_lp_metadata.get("version", None)\n package_lp_domain = package_lp_metadata.get("domain", None)\n\n package_metadata = package_locale_data.get("", {})\n package_version = package_metadata.get("version", None)\n package_domain = package_metadata.get("domain", "None")\n\n if package_lp_version and package_version and package_domain == package_lp_domain:\n package_version = parse_version(package_version)\n package_lp_version = parse_version(package_lp_version)\n\n if package_version > package_lp_version:\n # If package version is more recent, then update keys of the language pack\n result = language_pack_locale_data.copy()\n result.update(package_locale_data)\n\n return result\n\n\ndef get_installed_packages_locale(locale_: str) -> tuple[dict, str]:\n """\n Get all jupyterlab extensions installed that contain locale data.\n\n Returns\n -------\n tuple\n A tuple in the form `(locale_data_dict, message)`,\n where the `locale_data_dict` is an ordered list\n of available language packs:\n >>> {"package-name": locale_data, ...}\n\n Examples\n --------\n - `entry_points={"jupyterlab.locale": "package-name = package_module"}`\n - `entry_points={"jupyterlab.locale": "jupyterlab-git = jupyterlab_git"}`\n """\n found_package_locales, message = _get_installed_package_locales()\n packages_locale_data = {}\n messages = message.split("\n")\n if not message:\n for package_name, package_root_path in found_package_locales.items():\n locales = {}\n try:\n locale_path = os.path.join(package_root_path, LOCALE_DIR)\n # Handle letter casing\n locales = {\n loc.lower(): loc\n for loc in os.listdir(locale_path)\n if os.path.isdir(os.path.join(locale_path, loc))\n }\n except Exception:\n messages.append(traceback.format_exc())\n\n if locale_.lower() in locales:\n locale_json_path = os.path.join(\n locale_path,\n locales[locale_.lower()],\n LC_MESSAGES_DIR,\n f"{package_name}.json",\n )\n if os.path.isfile(locale_json_path):\n try:\n with open(locale_json_path, encoding="utf-8") as fh:\n packages_locale_data[package_name] = json.load(fh)\n except Exception:\n messages.append(traceback.format_exc())\n\n return packages_locale_data, "\n".join(messages)\n\n\n# --- API\n# ----------------------------------------------------------------------------\ndef get_language_packs(display_locale: str = DEFAULT_LOCALE) -> tuple[dict, str]:\n """\n Return the available language packs installed in the system.\n\n The returned information contains the languages displayed in the current\n locale.\n\n Parameters\n ----------\n display_locale: str, optional\n Default is DEFAULT_LOCALE.\n\n Returns\n -------\n tuple\n A tuple in the form `(locale_data_dict, message)`.\n """\n found_locales, message = _get_installed_language_pack_locales()\n locales = {}\n messages = message.split("\n")\n if not message:\n invalid_locales = []\n valid_locales = []\n messages = []\n for locale_ in found_locales:\n if is_valid_locale(locale_):\n valid_locales.append(locale_)\n else:\n invalid_locales.append(locale_)\n\n display_locale_ = display_locale if display_locale in valid_locales else DEFAULT_LOCALE\n locales = {\n DEFAULT_LOCALE: {\n "displayName": (\n get_display_name(DEFAULT_LOCALE, display_locale_)\n if display_locale != PSEUDO_LANGUAGE\n else "Default"\n ),\n "nativeName": get_display_name(DEFAULT_LOCALE, DEFAULT_LOCALE),\n }\n }\n for locale_ in valid_locales:\n locales[locale_] = {\n "displayName": get_display_name(locale_, display_locale_),\n "nativeName": get_display_name(locale_, locale_),\n }\n\n if invalid_locales:\n if PSEUDO_LANGUAGE in invalid_locales:\n invalid_locales.remove(PSEUDO_LANGUAGE)\n locales[PSEUDO_LANGUAGE] = {\n "displayName": "Pseudo-language",\n # Trick to ensure the proper language is selected in the language menu\n "nativeName": (\n "to translate the UI"\n if display_locale != PSEUDO_LANGUAGE\n else "Pseudo-language"\n ),\n }\n # Check again as the pseudo-language was maybe the only invalid locale\n if invalid_locales:\n messages.append(f"The following locales are invalid: {invalid_locales}!")\n\n return locales, "\n".join(messages)\n\n\ndef get_language_pack(locale_: str) -> tuple:\n """\n Get a language pack for a given `locale_` and update with any installed\n package locales.\n\n Returns\n -------\n tuple\n A tuple in the form `(locale_data_dict, message)`.\n\n Notes\n -----\n We call `_get_installed_language_pack_locales` via a subprocess to\n guarantee the results represent the most up-to-date entry point\n information, which seems to be defined on interpreter startup.\n """\n found_locales, message = _get_installed_language_pack_locales()\n found_packages_locales, message = get_installed_packages_locale(locale_)\n locale_data = {}\n messages = message.split("\n")\n if (\n not message\n and (locale_ == PSEUDO_LANGUAGE or is_valid_locale(locale_))\n and locale_ in found_locales\n ):\n path = found_locales[locale_]\n for root, __, files in os.walk(path, topdown=False):\n for name in files:\n if name.endswith(".json"):\n pkg_name = name.replace(".json", "")\n json_path = os.path.join(root, name)\n try:\n with open(json_path, encoding="utf-8") as fh:\n merged_data = json.load(fh)\n except Exception:\n messages.append(traceback.format_exc())\n\n # Load packages with locale data and merge them\n if pkg_name in found_packages_locales:\n pkg_data = found_packages_locales[pkg_name]\n merged_data = merge_locale_data(merged_data, pkg_data)\n\n locale_data[pkg_name] = merged_data\n\n # Check if package locales exist that do not exists in language pack\n for pkg_name, data in found_packages_locales.items():\n if pkg_name not in locale_data:\n locale_data[pkg_name] = data\n\n return locale_data, "\n".join(messages)\n\n\n# --- Translators\n# ----------------------------------------------------------------------------\nclass TranslationBundle:\n """\n Translation bundle providing gettext translation functionality.\n """\n\n def __init__(self, domain: str, locale_: str):\n """Initialize the bundle."""\n self._domain = domain\n self._locale = locale_\n self._translator = gettext.NullTranslations()\n\n self.update_locale(locale_)\n\n def update_locale(self, locale_: str) -> None:\n """\n Update the locale.\n\n Parameters\n ----------\n locale_: str\n The language name to use.\n """\n # TODO: Need to handle packages that provide their own .mo files\n self._locale = locale_\n localedir = None\n if locale_ != DEFAULT_LOCALE:\n language_pack_module = f"jupyterlab_language_pack_{locale_}"\n try:\n mod = importlib.import_module(language_pack_module)\n assert mod.__file__ is not None\n localedir = os.path.join(os.path.dirname(mod.__file__), LOCALE_DIR)\n except Exception: # noqa: S110\n # no-op\n pass\n\n self._translator = gettext.translation(\n self._domain, localedir=localedir, languages=(self._locale,), fallback=True\n )\n\n def gettext(self, msgid: str) -> str:\n """\n Translate a singular string.\n\n Parameters\n ----------\n msgid: str\n The singular string to translate.\n\n Returns\n -------\n str\n The translated string.\n """\n return self._translator.gettext(msgid)\n\n def ngettext(self, msgid: str, msgid_plural: str, n: int) -> str:\n """\n Translate a singular string with pluralization.\n\n Parameters\n ----------\n msgid: str\n The singular string to translate.\n msgid_plural: str\n The plural string to translate.\n n: int\n The number for pluralization.\n\n Returns\n -------\n str\n The translated string.\n """\n return self._translator.ngettext(msgid, msgid_plural, n)\n\n def pgettext(self, msgctxt: str, msgid: str) -> str:\n """\n Translate a singular string with context.\n\n Parameters\n ----------\n msgctxt: str\n The message context.\n msgid: str\n The singular string to translate.\n\n Returns\n -------\n str\n The translated string.\n """\n # Python 3.7 or lower does not offer translations based on context.\n # On these versions `pgettext` falls back to `gettext`\n if PY37_OR_LOWER:\n translation = self._translator.gettext(msgid)\n else:\n translation = self._translator.pgettext(msgctxt, msgid)\n\n return translation\n\n def npgettext(self, msgctxt: str, msgid: str, msgid_plural: str, n: int) -> str:\n """\n Translate a singular string with context and pluralization.\n\n Parameters\n ----------\n msgctxt: str\n The message context.\n msgid: str\n The singular string to translate.\n msgid_plural: str\n The plural string to translate.\n n: int\n The number for pluralization.\n\n Returns\n -------\n str\n The translated string.\n """\n # Python 3.7 or lower does not offer translations based on context.\n # On these versions `npgettext` falls back to `ngettext`\n if PY37_OR_LOWER:\n translation = self._translator.ngettext(msgid, msgid_plural, n)\n else:\n translation = self._translator.npgettext(msgctxt, msgid, msgid_plural, n)\n\n return translation\n\n # Shorthands\n def __(self, msgid: str) -> str:\n """\n Shorthand for gettext.\n\n Parameters\n ----------\n msgid: str\n The singular string to translate.\n\n Returns\n -------\n str\n The translated string.\n """\n return self.gettext(msgid)\n\n def _n(self, msgid: str, msgid_plural: str, n: int) -> str:\n """\n Shorthand for ngettext.\n\n Parameters\n ----------\n msgid: str\n The singular string to translate.\n msgid_plural: str\n The plural string to translate.\n n: int\n The number for pluralization.\n\n Returns\n -------\n str\n The translated string.\n """\n return self.ngettext(msgid, msgid_plural, n)\n\n def _p(self, msgctxt: str, msgid: str) -> str:\n """\n Shorthand for pgettext.\n\n Parameters\n ----------\n msgctxt: str\n The message context.\n msgid: str\n The singular string to translate.\n\n Returns\n -------\n str\n The translated string.\n """\n return self.pgettext(msgctxt, msgid)\n\n def _np(self, msgctxt: str, msgid: str, msgid_plural: str, n: int) -> str:\n """\n Shorthand for npgettext.\n\n Parameters\n ----------\n msgctxt: str\n The message context.\n msgid: str\n The singular string to translate.\n msgid_plural: str\n The plural string to translate.\n n: int\n The number for pluralization.\n\n Returns\n -------\n str\n The translated string.\n """\n return self.npgettext(msgctxt, msgid, msgid_plural, n)\n\n\nclass translator:\n """\n Translations manager.\n """\n\n _TRANSLATORS: dict[str, TranslationBundle] = {}\n _LOCALE = SYS_LOCALE\n\n @staticmethod\n def normalize_domain(domain: str) -> str:\n """Normalize a domain name.\n\n Parameters\n ----------\n domain: str\n Domain to normalize\n\n Returns\n -------\n str\n Normalized domain\n """\n return domain.replace("-", "_")\n\n @classmethod\n def set_locale(cls, locale_: str) -> None:\n """\n Set locale for the translation bundles based on the settings.\n\n Parameters\n ----------\n locale_: str\n The language name to use.\n """\n if locale_ == cls._LOCALE:\n # Nothing to do bail early\n return\n\n if is_valid_locale(locale_):\n cls._LOCALE = locale_\n for _, bundle in cls._TRANSLATORS.items():\n bundle.update_locale(locale_)\n\n @classmethod\n def load(cls, domain: str) -> TranslationBundle:\n """\n Load translation domain.\n\n The domain is usually the normalized ``package_name``.\n\n Parameters\n ----------\n domain: str\n The translations domain. The normalized python package name.\n\n Returns\n -------\n Translator\n A translator instance bound to the domain.\n """\n norm_domain = translator.normalize_domain(domain)\n if norm_domain in cls._TRANSLATORS:\n trans = cls._TRANSLATORS[norm_domain]\n else:\n trans = TranslationBundle(norm_domain, cls._LOCALE)\n cls._TRANSLATORS[norm_domain] = trans\n\n return trans\n\n @staticmethod\n def _translate_schema_strings(\n translations: Any,\n schema: dict,\n prefix: str = "",\n to_translate: dict[Pattern, str] | None = None,\n ) -> None:\n """Translate a schema in-place."""\n if to_translate is None:\n to_translate = _prepare_schema_patterns(schema)\n\n for key, value in schema.items():\n path = prefix + "/" + key\n\n if isinstance(value, str):\n matched = False\n for pattern, context in to_translate.items(): # noqa: B007\n if pattern.fullmatch(path):\n matched = True\n break\n if matched:\n schema[key] = translations.pgettext(context, value)\n elif isinstance(value, dict):\n translator._translate_schema_strings(\n translations,\n value,\n prefix=path,\n to_translate=to_translate,\n )\n elif isinstance(value, list):\n for i, element in enumerate(value):\n if not isinstance(element, dict):\n continue\n translator._translate_schema_strings(\n translations,\n element,\n prefix=path + "[" + str(i) + "]",\n to_translate=to_translate,\n )\n\n @staticmethod\n def translate_schema(schema: dict) -> dict:\n """Translate a schema.\n\n Parameters\n ----------\n schema: dict\n The schema to be translated\n\n Returns\n -------\n Dict\n The translated schema\n """\n if translator._LOCALE == DEFAULT_LOCALE:\n return schema\n\n translations = translator.load(\n schema.get(_lab_i18n_config, {}).get("domain", DEFAULT_DOMAIN)\n )\n\n new_schema = schema.copy()\n translator._translate_schema_strings(translations, new_schema)\n\n return new_schema\n
.venv\Lib\site-packages\jupyterlab_server\translation_utils.py
translation_utils.py
Python
23,009
0.95
0.135279
0.053628
node-utils
455
2023-09-26T18:27:21.949713
BSD-3-Clause
false
be9011809a3a6810f31a343b5e8cd0c8
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""A workspace management CLI"""\nfrom __future__ import annotations\n\nimport json\nimport sys\nimport warnings\nfrom pathlib import Path\nfrom typing import Any\n\nfrom jupyter_core.application import JupyterApp\nfrom traitlets import Bool, Unicode\n\nfrom ._version import __version__\nfrom .config import LabConfig\nfrom .workspaces_handler import WorkspacesManager\n\n# Default workspace ID\n# Needs to match PageConfig.defaultWorkspace define in packages/coreutils/src/pageconfig.ts\nDEFAULT_WORKSPACE = "default"\n\n\nclass WorkspaceListApp(JupyterApp, LabConfig):\n """An app to list workspaces."""\n\n version = __version__\n description = """\n Print all the workspaces available\n\n If '--json' flag is passed in, a single 'json' object is printed.\n If '--jsonlines' flag is passed in, 'json' object of each workspace separated by a new line is printed.\n If nothing is passed in, workspace ids list is printed.\n """\n flags = dict(\n jsonlines=(\n {"WorkspaceListApp": {"jsonlines": True}},\n ("Produce machine-readable JSON Lines output."),\n ),\n json=(\n {"WorkspaceListApp": {"json": True}},\n ("Produce machine-readable JSON object output."),\n ),\n )\n\n jsonlines = Bool(\n False,\n config=True,\n help=(\n "If True, the output will be a newline-delimited JSON (see https://jsonlines.org/) of objects, "\n "one per JupyterLab workspace, each with the details of the relevant workspace"\n ),\n )\n json = Bool(\n False,\n config=True,\n help=(\n "If True, each line of output will be a JSON object with the "\n "details of the workspace."\n ),\n )\n\n def initialize(self, *args: Any, **kwargs: Any) -> None:\n """Initialize the app."""\n super().initialize(*args, **kwargs)\n self.manager = WorkspacesManager(self.workspaces_dir)\n\n def start(self) -> None:\n """Start the app."""\n workspaces = self.manager.list_workspaces()\n if self.jsonlines:\n for workspace in workspaces:\n print(json.dumps(workspace))\n elif self.json:\n print(json.dumps(workspaces))\n else:\n for workspace in workspaces:\n print(workspace["metadata"]["id"])\n\n\nclass WorkspaceExportApp(JupyterApp, LabConfig):\n """A workspace export app."""\n\n version = __version__\n description = """\n Export a JupyterLab workspace\n\n If no arguments are passed in, this command will export the default\n workspace.\n If a workspace name is passed in, this command will export that workspace.\n If no workspace is found, this command will export an empty workspace.\n """\n\n def initialize(self, *args: Any, **kwargs: Any) -> None:\n """Initialize the app."""\n super().initialize(*args, **kwargs)\n self.manager = WorkspacesManager(self.workspaces_dir)\n\n def start(self) -> None:\n """Start the app."""\n if len(self.extra_args) > 1: # pragma: no cover\n warnings.warn("Too many arguments were provided for workspace export.")\n self.exit(1)\n\n raw = DEFAULT_WORKSPACE if not self.extra_args else self.extra_args[0]\n try:\n workspace = self.manager.load(raw)\n print(json.dumps(workspace))\n except Exception: # pragma: no cover\n self.log.error(json.dumps(dict(data=dict(), metadata=dict(id=raw))))\n\n\nclass WorkspaceImportApp(JupyterApp, LabConfig):\n """A workspace import app."""\n\n version = __version__\n description = """\n Import a JupyterLab workspace\n\n This command will import a workspace from a JSON file. The format of the\n file must be the same as what the export functionality emits.\n """\n workspace_name = Unicode(\n None,\n config=True,\n allow_none=True,\n help="""\n Workspace name. If given, the workspace ID in the imported\n file will be replaced with a new ID pointing to this\n workspace name.\n """,\n )\n\n aliases = {"name": "WorkspaceImportApp.workspace_name"}\n\n def initialize(self, *args: Any, **kwargs: Any) -> None:\n """Initialize the app."""\n super().initialize(*args, **kwargs)\n self.manager = WorkspacesManager(self.workspaces_dir)\n\n def start(self) -> None:\n """Start the app."""\n if len(self.extra_args) != 1: # pragma: no cover\n self.log.info("One argument is required for workspace import.")\n self.exit(1)\n\n with self._smart_open() as fid:\n try: # to load, parse, and validate the workspace file.\n workspace = self._validate(fid)\n except Exception as e: # pragma: no cover\n self.log.info("%s is not a valid workspace:\n%s", fid.name, e)\n self.exit(1)\n\n try:\n workspace_path = self.manager.save(workspace["metadata"]["id"], json.dumps(workspace))\n except Exception as e: # pragma: no cover\n self.log.info("Workspace could not be exported:\n%s", e)\n self.exit(1)\n\n self.log.info("Saved workspace: %s", workspace_path)\n\n def _smart_open(self) -> Any:\n file_name = self.extra_args[0]\n\n if file_name == "-": # pragma: no cover\n return sys.stdin\n\n file_path = Path(file_name).resolve()\n\n if not file_path.exists(): # pragma: no cover\n self.log.info("%s does not exist.", file_name)\n self.exit(1)\n\n return file_path.open(encoding="utf-8")\n\n def _validate(self, data: Any) -> Any:\n workspace = json.load(data)\n\n if "data" not in workspace:\n msg = "The `data` field is missing."\n raise Exception(msg)\n\n # If workspace_name is set in config, inject the\n # name into the workspace metadata.\n if self.workspace_name is not None and self.workspace_name:\n workspace["metadata"] = {"id": self.workspace_name}\n elif "id" not in workspace["metadata"]:\n msg = "The `id` field is missing in `metadata`."\n raise Exception(msg)\n\n return workspace\n
.venv\Lib\site-packages\jupyterlab_server\workspaces_app.py
workspaces_app.py
Python
6,296
0.95
0.135417
0.038961
react-lib
422
2024-01-17T09:46:06.576391
Apache-2.0
false
3a8618572a59befc70d00f4a0572bbee
"""Tornado handlers for frontend config storage."""\n\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport hashlib\nimport json\nimport re\nimport unicodedata\nimport urllib\nfrom pathlib import Path\nfrom typing import Any\n\nfrom jupyter_server import _tz as tz\nfrom jupyter_server.base.handlers import APIHandler\nfrom jupyter_server.extension.handler import ExtensionHandlerJinjaMixin, ExtensionHandlerMixin\nfrom jupyter_server.utils import url_path_join as ujoin\nfrom tornado import web\nfrom traitlets.config import LoggingConfigurable\n\n# The JupyterLab workspace file extension.\nWORKSPACE_EXTENSION = ".jupyterlab-workspace"\n\n\ndef _list_workspaces(directory: Path, prefix: str) -> list[dict[str, Any]]:\n """\n Return the list of workspaces in a given directory beginning with the\n given prefix.\n """\n workspaces: list = []\n if not directory.exists():\n return workspaces\n\n items = [\n item\n for item in directory.iterdir()\n if item.name.startswith(prefix) and item.name.endswith(WORKSPACE_EXTENSION)\n ]\n items.sort()\n\n for slug in items:\n workspace_path: Path = directory / slug\n if workspace_path.exists():\n workspace = _load_with_file_times(workspace_path)\n workspaces.append(workspace)\n\n return workspaces\n\n\ndef _load_with_file_times(workspace_path: Path) -> dict:\n """\n Load workspace JSON from disk, overwriting the `created` and `last_modified`\n metadata with current file stat information\n """\n stat = workspace_path.stat()\n with workspace_path.open(encoding="utf-8") as fid:\n workspace = json.load(fid)\n workspace["metadata"].update(\n last_modified=tz.utcfromtimestamp(stat.st_mtime).isoformat(),\n created=tz.utcfromtimestamp(stat.st_ctime).isoformat(),\n )\n return workspace\n\n\ndef slugify(\n raw: str, base: str = "", sign: bool = True, max_length: int = 128 - len(WORKSPACE_EXTENSION)\n) -> str:\n """\n Use the common superset of raw and base values to build a slug shorter\n than max_length. By default, base value is an empty string.\n Convert spaces to hyphens. Remove characters that aren't alphanumerics\n underscores, or hyphens. Convert to lowercase. Strip leading and trailing\n whitespace.\n Add an optional short signature suffix to prevent collisions.\n Modified from Django utils:\n https://github.com/django/django/blob/master/django/utils/text.py\n """\n raw = raw if raw.startswith("/") else "/" + raw\n signature = ""\n if sign:\n data = raw[1:] # Remove initial slash that always exists for digest.\n signature = "-" + hashlib.sha256(data.encode("utf-8")).hexdigest()[:4]\n base = (base if base.startswith("/") else "/" + base).lower()\n raw = raw.lower()\n common = 0\n limit = min(len(base), len(raw))\n while common < limit and base[common] == raw[common]:\n common += 1\n value = ujoin(base[common:], raw)\n value = urllib.parse.unquote(value)\n value = unicodedata.normalize("NFKC", value).encode("ascii", "ignore").decode("ascii")\n value = re.sub(r"[^\w\s-]", "", value).strip()\n value = re.sub(r"[-\s]+", "-", value)\n return value[: max_length - len(signature)] + signature\n\n\nclass WorkspacesManager(LoggingConfigurable):\n """A manager for workspaces."""\n\n def __init__(self, path: str) -> None:\n """Initialize a workspaces manager with content in ``path``."""\n super()\n if not path:\n msg = "Workspaces directory is not set"\n raise ValueError(msg)\n self.workspaces_dir = Path(path)\n\n def delete(self, space_name: str) -> None:\n """Remove a workspace ``space_name``."""\n slug = slugify(space_name)\n workspace_path = self.workspaces_dir / (slug + WORKSPACE_EXTENSION)\n\n if not workspace_path.exists():\n msg = f"Workspace {space_name!r} ({slug!r}) not found"\n raise FileNotFoundError(msg)\n\n # to delete the workspace file.\n workspace_path.unlink()\n\n def list_workspaces(self) -> list:\n """List all available workspaces."""\n prefix = slugify("", sign=False)\n return _list_workspaces(self.workspaces_dir, prefix)\n\n def load(self, space_name: str) -> dict:\n """Load the workspace ``space_name``."""\n slug = slugify(space_name)\n workspace_path = self.workspaces_dir / (slug + WORKSPACE_EXTENSION)\n\n if workspace_path.exists():\n # to load and parse the workspace file.\n return _load_with_file_times(workspace_path)\n _id = space_name if space_name.startswith("/") else "/" + space_name\n return dict(data=dict(), metadata=dict(id=_id))\n\n def save(self, space_name: str, raw: str) -> Path:\n """Save the ``raw`` data as workspace ``space_name``."""\n if not self.workspaces_dir.exists():\n self.workspaces_dir.mkdir(parents=True)\n\n workspace = {}\n\n # Make sure the data is valid JSON.\n try:\n decoder = json.JSONDecoder()\n workspace = decoder.decode(raw)\n except Exception as e:\n raise ValueError(str(e)) from e\n\n # Make sure metadata ID matches the workspace name.\n # Transparently support an optional initial root `/`.\n metadata_id = workspace["metadata"]["id"]\n metadata_id = metadata_id if metadata_id.startswith("/") else "/" + metadata_id\n metadata_id = urllib.parse.unquote(metadata_id)\n if metadata_id != "/" + space_name:\n message = f"Workspace metadata ID mismatch: expected {space_name!r} got {metadata_id!r}"\n raise ValueError(message)\n\n slug = slugify(space_name)\n workspace_path = self.workspaces_dir / (slug + WORKSPACE_EXTENSION)\n\n # Write the workspace data to a file.\n workspace_path.write_text(raw, encoding="utf-8")\n\n return workspace_path\n\n\nclass WorkspacesHandler(ExtensionHandlerMixin, ExtensionHandlerJinjaMixin, APIHandler):\n """A workspaces API handler."""\n\n def initialize(self, name: str, manager: WorkspacesManager, **kwargs: Any) -> None: # noqa: ARG002\n """Initialize the handler."""\n super().initialize(name)\n self.manager = manager\n\n @web.authenticated\n def delete(self, space_name: str) -> None:\n """Remove a workspace"""\n if not space_name:\n raise web.HTTPError(400, "Workspace name is required for DELETE")\n\n try:\n self.manager.delete(space_name)\n return self.set_status(204)\n except FileNotFoundError as e:\n raise web.HTTPError(404, str(e)) from e\n except Exception as e: # pragma: no cover\n raise web.HTTPError(500, str(e)) from e\n\n @web.authenticated\n async def get(self, space_name: str = "") -> Any:\n """Get workspace(s) data"""\n\n try:\n if not space_name:\n workspaces = self.manager.list_workspaces()\n ids = []\n values = []\n for workspace in workspaces:\n ids.append(workspace["metadata"]["id"])\n values.append(workspace)\n return self.finish(json.dumps({"workspaces": {"ids": ids, "values": values}}))\n\n workspace = self.manager.load(space_name)\n return self.finish(json.dumps(workspace))\n except Exception as e: # pragma: no cover\n raise web.HTTPError(500, str(e)) from e\n\n @web.authenticated\n def put(self, space_name: str = "") -> None:\n """Update workspace data"""\n if not space_name:\n raise web.HTTPError(400, "Workspace name is required for PUT.")\n\n raw = self.request.body.strip().decode("utf-8")\n\n # Make sure the data is valid JSON.\n try:\n self.manager.save(space_name, raw)\n except ValueError as e:\n raise web.HTTPError(400, str(e)) from e\n except Exception as e: # pragma: no cover\n raise web.HTTPError(500, str(e)) from e\n\n self.set_status(204)\n
.venv\Lib\site-packages\jupyterlab_server\workspaces_handler.py
workspaces_handler.py
Python
8,151
0.95
0.190265
0.054054
node-utils
388
2025-02-18T14:03:06.889995
BSD-3-Clause
false
2b7ef62bc830452d9a17a5a3dd0a6494
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""\nstore the current version info of the server.\n\n"""\nimport re\n\n__version__ = "2.27.3"\n\n# Build up version_info tuple for backwards compatibility\npattern = r"(?P<major>\d+).(?P<minor>\d+).(?P<patch>\d+)(?P<rest>.*)"\nmatch = re.match(pattern, __version__)\nassert match is not None\nparts: list = [int(match[part]) for part in ["major", "minor", "patch"]]\nif match["rest"]:\n parts.append(match["rest"])\nversion_info = tuple(parts)\n
.venv\Lib\site-packages\jupyterlab_server\_version.py
_version.py
Python
535
0.95
0.157895
0.2
react-lib
295
2024-02-02T20:48:36.540930
GPL-3.0
false
605dec6d36b40c62dcdc930b4a9cf2fb
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom typing import Any\n\nfrom ._version import __version__\nfrom .app import LabServerApp\nfrom .handlers import LabConfig, LabHandler, add_handlers\nfrom .licenses_app import LicensesApp\nfrom .spec import get_openapi_spec, get_openapi_spec_dict # noqa: F401\nfrom .translation_utils import translator\nfrom .workspaces_app import WorkspaceExportApp, WorkspaceImportApp, WorkspaceListApp\nfrom .workspaces_handler import WORKSPACE_EXTENSION, slugify\n\n__all__ = [\n "__version__",\n "add_handlers",\n "LabConfig",\n "LabHandler",\n "LabServerApp",\n "LicensesApp",\n "slugify",\n "translator",\n "WORKSPACE_EXTENSION",\n "WorkspaceExportApp",\n "WorkspaceImportApp",\n "WorkspaceListApp",\n]\n\n\ndef _jupyter_server_extension_points() -> Any:\n return [{"module": "jupyterlab_server", "app": LabServerApp}]\n
.venv\Lib\site-packages\jupyterlab_server\__init__.py
__init__.py
Python
924
0.95
0.032258
0.074074
awesome-app
94
2025-02-05T15:49:38.811514
BSD-3-Clause
false
2bd20d98c1b8ccf264352bb28601f6ff
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n"""CLI entry point for jupyterlab server."""\nimport sys\n\nfrom jupyterlab_server.app import main\n\nsys.exit(main()) # type:ignore[no-untyped-call]\n
.venv\Lib\site-packages\jupyterlab_server\__main__.py
__main__.py
Python
248
0.95
0.111111
0.333333
react-lib
525
2025-06-01T09:52:47.571262
MIT
false
7be85311975d690fee8c274f2d9e9a0e
<!--\n ~ Copyright (c) Jupyter Development Team.\n ~ Distributed under the terms of the Modified BSD License.\n-->\n\n<!doctype html>\n<html>\n <head>\n <meta charset="utf-8" />\n <title>403 Forbidden</title>\n </head>\n <body>\n <h2>Sorry ..</h2>\n <p>.. you are not allowed to see this content!</p>\n </body>\n</html>\n
.venv\Lib\site-packages\jupyterlab_server\templates\403.html
403.html
HTML
323
0.7
0
0
awesome-app
621
2024-07-23T17:26:23.210272
BSD-3-Clause
false
a31592494b0554422b40bb68280231f0
<!DOCTYPE html>\n<!--\nCopyright (c) Jupyter Development Team.\nDistributed under the terms of the Modified BSD License.\n-->\n<html>\n\n<head>\n <meta charset="utf-8">\n\n <title>{% block title %}{{page_title | escape}{% endblock %}</title>\n\n {% block favicon %}<link rel="shortcut icon" type="image/x-icon" href="/static/base/images/favicon.ico">{% endblock %}\n\n</head>\n\n<body>\n\n{% block stylesheet %}\n<style type="text/css">\n/* disable initial hide */\ndiv#header, div#site {\n display: block;\n}\n</style>\n{% endblock %}\n{% block site %}\n\n<div class="error">\n {% block h1_error %}\n <h1>{{status_code | escape }} : {{status_message | escape }}</h1>\n {% endblock h1_error %}\n {% block error_detail %}\n {% if message %}\n <p>The error was:</p>\n <div class="traceback-wrapper">\n <pre class="traceback">{{message | escape }}</pre>\n </div>\n {% endif %}\n {% endblock %}\n</header>\n\n{% endblock %}\n\n{% block script %}\n<script type='text/javascript'>\nwindow.onload = function () {\n var tb = document.getElementsByClassName('traceback')[0];\n tb.scrollTop = tb.scrollHeight;\n {% if message %}\n console.error("{{message | escape}}")\n {% endif %}\n};\n</script>\n{% endblock script %}\n\n</body>\n\n</html>\n
.venv\Lib\site-packages\jupyterlab_server\templates\error.html
error.html
HTML
1,219
0.95
0.101695
0.020833
node-utils
121
2024-03-02T23:51:09.778924
BSD-3-Clause
false
3ce1a32af9905b219cc4f860bd8d2324
<!--\n ~ Copyright (c) Jupyter Development Team.\n ~ Distributed under the terms of the Modified BSD License.\n-->\n\n<!doctype html>\n<html lang="en">\n <head>\n <meta charset="utf-8" />\n <title>{% block title %}{{page_title | escape }}{% endblock %}</title>\n\n {% block stylesheet %} {% for css_file in css_files %}\n <link href="{{ css_file | escape }}" rel="stylesheet" />\n {% endfor %} {% endblock %} {# Copy so we do not modify the page_config with\n updates. #} {% set page_config_full = page_config.copy() %} {# Set a dummy\n variable - we just want the side effect of the update. #} {% set _ =\n page_config_full.update(baseUrl=base_url, wsUrl=ws_url) %}\n\n <script id="jupyter-config-data" type="application/json">\n {{ page_config_full | tojson }}\n </script>\n\n {% block favicon %} {% endblock %} {% for js_file in js_files %}\n <script\n src="{{ js_file | escape }}"\n type="text/javascript"\n charset="utf-8"\n ></script>\n {% endfor %} {% block meta %} {% endblock %}\n </head>\n\n <body>\n <script type="text/javascript">\n // Remove token from URL.\n (function () {\n var parsedUrl = new URL(window.location.href);\n if (parsedUrl.searchParams.get("token")) {\n parsedUrl.searchParams.delete("token");\n window.history.replaceState({}, "", parsedUrl.href);\n }\n })();\n </script>\n </body>\n</html>\n
.venv\Lib\site-packages\jupyterlab_server\templates\index.html
index.html
HTML
1,407
0.95
0.090909
0.025641
node-utils
331
2024-10-14T03:28:05.938882
BSD-3-Clause
false
e8d608627857e37836afab1497b11bd4
{\n "@jupyterlab/apputils-extension:themes": {\n "theme": "JupyterLab Dark",\n "codeCellConfig": {\n "lineNumbers": true\n }\n },\n "@jupyterlab/unicode-extension:plugin": {\n "comment": "Here are some languages with unicode in their names: id: Bahasa Indonesia, ms: Bahasa Melayu, bs: Bosanski, ca: Català, cs: Čeština, da: Dansk, de: Deutsch, et: Eesti, en: English, es: Español, fil: Filipino, fr: Français, it: Italiano, hu: Magyar, nl: Nederlands, no: Norsk, pl: Polski, pt-br: Português (Brasil), pt: Português (Portugal), ro: Română, fi: Suomi, sv: Svenska, vi: Tiếng Việt, tr: Türkçe, el: Ελληνικά, ru: Русский, sr: Српски, uk: Українська, he: עברית, ar: العربية, th: ไทย, ko: 한국어, ja: 日本語, zh: 中文(中国), zh-tw: 中文(台灣)"\n }\n}\n
.venv\Lib\site-packages\jupyterlab_server\test_data\app-settings\overrides.json
overrides.json
JSON
844
0.7
0
0
vue-tools
878
2024-01-22T07:37:05.361123
BSD-3-Clause
true
29d93d1d5502538c237c10eca27299ff
{\n "title": "Theme",\n "description": "Theme manager settings.",\n "properties": {\n "theme": {\n "type": "string",\n "title": "Selected Theme",\n "default": "JupyterLab Light"\n },\n "codeCellConfig": {\n "title": "Code Cell Configuration",\n "description": "The configuration for all code cells.",\n "$ref": "#/definitions/editorConfig",\n "default": {\n "autoClosingBrackets": true,\n "cursorBlinkRate": 530,\n "fontFamily": null,\n "fontSize": null,\n "lineHeight": null,\n "lineNumbers": false,\n "lineWrap": "off",\n "matchBrackets": true,\n "readOnly": false,\n "insertSpaces": true,\n "tabSize": 4,\n "wordWrapColumn": 80,\n "rulers": [],\n "codeFolding": false,\n "lineWiseCopyCut": true\n }\n }\n },\n "type": "object"\n}\n
.venv\Lib\site-packages\jupyterlab_server\test_data\schemas\@jupyterlab\apputils-extension\themes.json
themes.json
JSON
862
0.8
0.029412
0
awesome-app
993
2024-05-03T22:28:59.257847
BSD-3-Clause
true
622cafefb41739c7df377be5d60b7705
{\n "jupyter.lab.setting-icon-class": "jp-TextEditorIcon",\n "jupyter.lab.setting-icon-label": "CodeMirror",\n "title": "CodeMirror",\n "description": "Text editor settings for all CodeMirror editors.",\n "properties": {\n "keyMap": { "type": "string", "title": "Key Map", "default": "default" },\n "theme": { "type": "string", "title": "Theme", "default": "default" }\n },\n "type": "object"\n}\n
.venv\Lib\site-packages\jupyterlab_server\test_data\schemas\@jupyterlab\codemirror-extension\commands.json
commands.json
JSON
399
0.7
0.181818
0
react-lib
867
2024-12-23T22:32:16.220528
Apache-2.0
true
fc0520f7e400f738faf7dcc4c197955c
{\n "name": "@jupyterlab/shortcuts-extension",\n "version": "test-version"\n}\n
.venv\Lib\site-packages\jupyterlab_server\test_data\schemas\@jupyterlab\shortcuts-extension\package.json.orig
package.json.orig
Other
77
0.5
0
0
react-lib
833
2024-01-24T21:19:00.776055
MIT
true
7ac5b3d6d170161ff757c9254f42b14a
{\n "jupyter.lab.setting-icon-class": "jp-LauncherIcon",\n "jupyter.lab.setting-icon-label": "Keyboard Shortcuts",\n "title": "Keyboard Shortcuts",\n "description": "Keyboard shortcut settings for JupyterLab.",\n "properties": {\n "application:activate-next-tab": {\n "default": {},\n "properties": {\n "command": { "default": "application:activate-next-tab" },\n "keys": { "default": ["Ctrl Shift ]"] },\n "selector": { "default": "body" }\n },\n "type": "object"\n },\n "application:activate-previous-tab": {\n "default": {},\n "properties": {\n "command": { "default": "application:activate-previous-tab" },\n "keys": { "default": ["Ctrl Shift ["] },\n "selector": { "default": "body" }\n },\n "type": "object"\n },\n "application:toggle-mode": {\n "default": {},\n "properties": {\n "command": { "default": "application:toggle-mode" },\n "keys": { "default": ["Accel Shift Enter"] },\n "selector": { "default": "body" }\n },\n "type": "object"\n },\n "command-palette:toggle": {\n "default": {},\n "properties": {\n "command": { "default": "apputils:toggle-command-palette" },\n "keys": { "default": ["Accel Shift C"] },\n "selector": { "default": "body" }\n },\n "type": "object"\n },\n "completer:invoke-console": {\n "default": {},\n "properties": {\n "command": { "default": "completer:invoke-console" },\n "keys": { "default": ["Tab"] },\n "selector": {\n "default": ".jp-CodeConsole-promptCell .jp-mod-completer-enabled"\n }\n },\n "type": "object"\n },\n "completer:invoke-notebook": {\n "default": {},\n "properties": {\n "command": { "default": "completer:invoke-notebook" },\n "keys": { "default": ["Tab"] },\n "selector": {\n "default": ".jp-Notebook.jp-mod-editMode .jp-mod-completer-enabled"\n }\n },\n "type": "object"\n },\n "console:linebreak": {\n "default": {},\n "properties": {\n "command": { "default": "console:linebreak" },\n "keys": { "default": ["Ctrl Enter"] },\n "selector": { "default": ".jp-CodeConsole-promptCell" }\n },\n "type": "object"\n },\n "console:run": {\n "default": {},\n "properties": {\n "command": { "default": "console:run" },\n "keys": { "default": ["Enter"] },\n "selector": { "default": ".jp-CodeConsole-promptCell" }\n },\n "type": "object"\n },\n "console:run-forced": {\n "default": {},\n "properties": {\n "command": { "default": "console:run-forced" },\n "keys": { "default": ["Shift Enter"] },\n "selector": { "default": ".jp-CodeConsole-promptCell" }\n },\n "type": "object"\n },\n "docmanager:close": {\n "default": {},\n "properties": {\n "command": { "default": "docmanager:close" },\n "keys": { "default": ["Ctrl Q"] },\n "selector": { "default": ".jp-Activity" }\n },\n "type": "object"\n },\n "docmanager:create-launcher": {\n "default": {},\n "properties": {\n "command": { "default": "docmanager:create-launcher" },\n "keys": { "default": ["Accel Shift L"] },\n "selector": { "default": "body" }\n },\n "type": "object"\n },\n "docmanager:save": {\n "default": {},\n "properties": {\n "command": { "default": "docmanager:save" },\n "keys": { "default": ["Accel S"] },\n "selector": { "default": "body" }\n },\n "type": "object"\n },\n "filebrowser:toggle-main": {\n "default": {},\n "properties": {\n "command": { "default": "filebrowser:toggle-main" },\n "keys": { "default": ["Accel Shift F"] },\n "selector": { "default": "body" }\n },\n "type": "object"\n },\n "fileeditor:run-code": {\n "default": {},\n "properties": {\n "command": { "default": "fileeditor:run-code" },\n "keys": { "default": ["Shift Enter"] },\n "selector": { "default": ".jp-FileEditor" }\n },\n "type": "object"\n },\n "help:toggle": {\n "default": {},\n "properties": {\n "command": { "default": "help:toggle" },\n "keys": { "default": ["Ctrl Shift H"] },\n "selector": { "default": "body" }\n },\n "type": "object"\n },\n "imageviewer:reset-zoom": {\n "default": {},\n "properties": {\n "command": { "default": "imageviewer:reset-zoom" },\n "keys": { "default": ["0"] },\n "selector": { "default": ".jp-ImageViewer" }\n },\n "type": "object"\n },\n "imageviewer:zoom-in": {\n "default": {},\n "properties": {\n "command": { "default": "imageviewer:zoom-in" },\n "keys": { "default": ["="] },\n "selector": { "default": ".jp-ImageViewer" }\n },\n "type": "object"\n },\n "imageviewer:zoom-out": {\n "default": {},\n "properties": {\n "command": { "default": "imageviewer:zoom-out" },\n "keys": { "default": ["-"] },\n "selector": { "default": ".jp-ImageViewer" }\n },\n "type": "object"\n },\n "inspector:open": {\n "default": {},\n "properties": {\n "command": { "default": "inspector:open" },\n "keys": { "default": ["Accel I"] },\n "selector": { "default": "body" }\n },\n "type": "object"\n },\n "notebook:change-cell-to-code": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:change-cell-to-code" },\n "keys": { "default": ["Y"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:change-to-cell-heading-1": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:change-to-cell-heading-1" },\n "keys": { "default": ["1"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:change-to-cell-heading-2": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:change-to-cell-heading-2" },\n "keys": { "default": ["2"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:change-to-cell-heading-3": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:change-to-cell-heading-3" },\n "keys": { "default": ["3"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:change-to-cell-heading-4": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:change-to-cell-heading-4" },\n "keys": { "default": ["4"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:change-to-cell-heading-5": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:change-to-cell-heading-5" },\n "keys": { "default": ["5"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:change-to-cell-heading-6": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:change-to-cell-heading-6" },\n "keys": { "default": ["6"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:change-cell-to-markdown": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:change-cell-to-markdown" },\n "keys": { "default": ["M"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:change-cell-to-raw": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:change-cell-to-raw" },\n "keys": { "default": ["R"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:copy-cell": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:copy-cell" },\n "keys": { "default": ["C"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:cut-cell": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:cut-cell" },\n "keys": { "default": ["X"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:delete-cell": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:delete-cell" },\n "keys": { "default": ["D", "D"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:enter-command-mode-1": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:enter-command-mode" },\n "keys": { "default": ["Escape"] },\n "selector": {\n "default": ".jp-Notebook.jp-mod-editMode"\n }\n },\n "type": "object"\n },\n "notebook:enter-command-mode-2": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:enter-command-mode" },\n "keys": { "default": ["Ctrl M"] },\n "selector": { "default": ".jp-Notebook.jp-mod-editMode" }\n },\n "type": "object"\n },\n "notebook:enter-edit-mode": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:enter-edit-mode" },\n "keys": { "default": ["Enter"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:extend-marked-cells-above-1": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:extend-marked-cells-above" },\n "keys": { "default": ["Shift ArrowUp"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:extend-marked-cells-above-2": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:extend-marked-cells-above" },\n "keys": { "default": ["Shift K"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:extend-marked-cells-below-1": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:extend-marked-cells-below" },\n "keys": { "default": ["Shift ArrowDown"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:extend-marked-cells-below-2": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:extend-marked-cells-below" },\n "keys": { "default": ["Shift J"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:insert-cell-above": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:insert-cell-above" },\n "keys": { "default": ["A"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:insert-cell-below": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:insert-cell-below" },\n "keys": { "default": ["B"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:interrupt-kernel": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:interrupt-kernel" },\n "keys": { "default": ["I", "I"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:merge-cells": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:merge-cells" },\n "keys": { "default": ["Shift M"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:move-cursor-down-1": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:move-cursor-down" },\n "keys": { "default": ["ArrowDown"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:move-cursor-down-2": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:move-cursor-down" },\n "keys": { "default": ["J"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:move-cursor-up-1": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:move-cursor-up" },\n "keys": { "default": ["ArrowUp"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:move-cursor-up-2": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:move-cursor-up" },\n "keys": { "default": ["K"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:paste-cell": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:paste-cell" },\n "keys": { "default": ["V"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:redo-cell-action": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:redo-cell-action" },\n "keys": { "default": ["Shift Z"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:restart-kernel": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:restart-kernel" },\n "keys": { "default": ["0", "0"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:run-cell-1": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:run-cell" },\n "keys": { "default": ["Ctrl Enter"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:run-cell-2": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:run-cell" },\n "keys": { "default": ["Ctrl Enter"] },\n "selector": { "default": ".jp-Notebook.jp-mod-editMode" }\n },\n "type": "object"\n },\n "notebook:run-cell-and-insert-below-1": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:run-cell-and-insert-below" },\n "keys": { "default": ["Alt Enter"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:run-cell-and-insert-below-2": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:run-cell-and-insert-below" },\n "keys": { "default": ["Alt Enter"] },\n "selector": { "default": ".jp-Notebook.jp-mod-editMode" }\n },\n "type": "object"\n },\n "notebook:run-cell-and-select-next-1": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:run-cell-and-select-next" },\n "keys": { "default": ["Shift Enter"] },\n "selector": { "default": ".jp-Notebook.jp-mod-editMode" }\n },\n "type": "object"\n },\n "notebook:run-cell-and-select-next-2": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:run-cell-and-select-next" },\n "keys": { "default": ["Shift Enter"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:split-cell-at-cursor": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:split-cell-at-cursor" },\n "keys": { "default": ["Ctrl Shift -"] },\n "selector": { "default": ".jp-Notebook.jp-mod-editMode" }\n },\n "type": "object"\n },\n "notebook:toggle-all-cell-line-numbers": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:toggle-all-cell-line-numbers" },\n "keys": { "default": ["Shift L"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:toggle-cell-line-numbers": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:toggle-cell-line-numbers" },\n "keys": { "default": ["L"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "notebook:undo-cell-action": {\n "default": {},\n "properties": {\n "command": { "default": "notebook:undo-cell-action" },\n "keys": { "default": ["Z"] },\n "selector": { "default": ".jp-Notebook:focus" }\n },\n "type": "object"\n },\n "settingeditor:open": {\n "default": {},\n "properties": {\n "command": { "default": "settingeditor:open" },\n "keys": { "default": ["Accel ,"] },\n "selector": { "default": "body" }\n },\n "type": "object"\n },\n "tooltip:dismiss-console": {\n "default": {},\n "properties": {\n "command": { "default": "tooltip:dismiss" },\n "keys": { "default": ["Escape"] },\n "selector": { "default": "body.jp-mod-tooltip .jp-CodeConsole" }\n },\n "type": "object"\n },\n "tooltip:dismiss-notebook": {\n "default": {},\n "properties": {\n "command": { "default": "tooltip:dismiss" },\n "keys": { "default": ["Escape"] },\n "selector": { "default": "body.jp-mod-tooltip .jp-Notebook" }\n },\n "type": "object"\n },\n "tooltip:launch-console": {\n "default": {},\n "properties": {\n "command": { "default": "tooltip:launch-console" },\n "keys": { "default": ["Shift Tab"] },\n "selector": {\n "default": ".jp-CodeConsole-promptCell .jp-InputArea-editor:not(.jp-mod-has-primary-selection)"\n }\n },\n "type": "object"\n },\n "tooltip:launch-notebook": {\n "default": {},\n "properties": {\n "command": { "default": "tooltip:launch-notebook" },\n "keys": { "default": ["Shift Tab"] },\n "selector": {\n "default": ".jp-Notebook.jp-mod-editMode .jp-InputArea-editor:not(.jp-mod-has-primary-selection)"\n }\n },\n "type": "object"\n }\n },\n "oneOf": [{ "$ref": "#/definitions/shortcut" }],\n "type": "object",\n "definitions": {\n "shortcut": {\n "properties": {\n "command": { "type": "string" },\n "keys": {\n "items": { "type": "string" },\n "minItems": 1,\n "type": "array"\n },\n "selector": { "type": "string" }\n },\n "type": "object"\n }\n }\n}\n
.venv\Lib\site-packages\jupyterlab_server\test_data\schemas\@jupyterlab\shortcuts-extension\plugin.json
plugin.json
JSON
18,757
0.8
0.003279
0
react-lib
116
2024-11-04T22:02:36.420985
MIT
true
286671d63ffe7a4ace0b08cbb2c00a2f
{\n "jupyter.lab.setting-icon": "ui-components:settings",\n "jupyter.lab.setting-icon-label": "Language",\n "title": "Language",\n "description": "Language settings.",\n "type": "object",\n "properties": {\n "locale": {\n "type": "string",\n "title": "Language locale",\n "description": "Set the interface display language. Examples: 'es_CO', 'fr'.",\n "default": "en"\n }\n }\n}\n
.venv\Lib\site-packages\jupyterlab_server\test_data\schemas\@jupyterlab\translation-extension\plugin.json
plugin.json
JSON
399
0.7
0
0
vue-tools
402
2024-11-11T19:00:47.429913
MIT
true
42651ab0095caf1d02583145a5ef08bb
{\n "jupyter.lab.setting-icon": "ui-components:unicode",\n "jupyter.lab.setting-icon-label": "Unicode",\n "title": "Unicode",\n "description": "Unicode",\n "type": "object",\n "properties": {\n "comment": {\n "type": "string",\n "title": "Comment",\n "description": "Here are some languages with unicode in their names: id: Bahasa Indonesia, ms: Bahasa Melayu, bs: Bosanski, ca: Català, cs: Čeština, da: Dansk, de: Deutsch, et: Eesti, en: English, es: Español, fil: Filipino, fr: Français, it: Italiano, hu: Magyar, nl: Nederlands, no: Norsk, pl: Polski, pt-br: Português (Brasil), pt: Português (Portugal), ro: Română, fi: Suomi, sv: Svenska, vi: Tiếng Việt, tr: Türkçe, el: Ελληνικά, ru: Русский, sr: Српски, uk: Українська, he: עברית, ar: العربية, th: ไทย, ko: 한국어, ja: 日本語, zh: 中文(中国), zh-tw: 中文(台灣)",\n "default": "no comment"\n }\n }\n}\n
.venv\Lib\site-packages\jupyterlab_server\test_data\schemas\@jupyterlab\unicode-extension\plugin.json
plugin.json
JSON
962
0.7
0
0
awesome-app
434
2024-06-03T02:57:55.332888
Apache-2.0
true
a305852b433732cde9075c980d56a912
{"data": {}, "metadata": {"id": "foo"}}\n
.venv\Lib\site-packages\jupyterlab_server\test_data\workspaces\foo-2c26.jupyterlab-workspace
foo-2c26.jupyterlab-workspace
Other
40
0.5
0
0
awesome-app
776
2025-02-13T06:11:41.252584
GPL-3.0
true
048047699f5850a592c3398cbaecf2e6
{"data": {}, "metadata": {"id": "f/o/o/"}}\n
.venv\Lib\site-packages\jupyterlab_server\test_data\workspaces\foo-92dd.jupyterlab-workspace
foo-92dd.jupyterlab-workspace
Other
43
0.5
0
0
react-lib
603
2023-10-22T10:21:41.425056
Apache-2.0
true
2d3939125c5522ecb5f957ce49b51851
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\app.cpython-313.pyc
app.cpython-313.pyc
Other
5,547
0.8
0.03125
0.017544
python-kit
73
2024-01-05T08:26:14.143947
MIT
false
9a5eaa405e25426c2e4987830e61d7b5
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\config.cpython-313.pyc
config.cpython-313.pyc
Other
16,737
0.8
0.057143
0.012195
awesome-app
491
2023-08-18T08:19:18.135160
BSD-3-Clause
false
24f9b90e2e74834b094cdb69473f4324
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\handlers.cpython-313.pyc
handlers.cpython-313.pyc
Other
14,956
0.8
0.008696
0.009346
node-utils
587
2024-04-14T06:52:53.017467
GPL-3.0
false
c53ff643ae4aec86d6069fd07b88694f
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\licenses_app.cpython-313.pyc
licenses_app.cpython-313.pyc
Other
3,698
0.95
0.076923
0
awesome-app
917
2024-04-05T16:32:16.121943
MIT
false
68d6f6073c9ec7f7037ddd2ead2c46d5
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\licenses_handler.cpython-313.pyc
licenses_handler.cpython-313.pyc
Other
13,414
0.8
0.057692
0
node-utils
354
2023-09-09T08:04:50.307541
BSD-3-Clause
false
c3e338042553f38a6235e22cca2b5575
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\listings_handler.cpython-313.pyc
listings_handler.cpython-313.pyc
Other
3,807
0.8
0.075
0
react-lib
239
2024-08-26T16:40:53.719098
BSD-3-Clause
false
77cf8a6fbc82ce7a89a06676597ae460
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\process.cpython-313.pyc
process.cpython-313.pyc
Other
13,829
0.95
0.099237
0
react-lib
809
2023-11-23T06:54:01.785739
Apache-2.0
false
513e84dd51f39f5a35f8c14e3ddc1533
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\process_app.cpython-313.pyc
process_app.cpython-313.pyc
Other
3,142
0.8
0.029412
0
awesome-app
212
2025-06-02T20:39:55.961457
BSD-3-Clause
false
7c5fd77b44eff9cd68225356301ef630
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\pytest_plugin.cpython-313.pyc
pytest_plugin.cpython-313.pyc
Other
7,001
0.95
0.066667
0.020408
node-utils
231
2024-12-09T11:28:24.784150
BSD-3-Clause
true
9ec9da80b1624683b27e4dd78189f312
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\server.cpython-313.pyc
server.cpython-313.pyc
Other
741
0.7
0
0
python-kit
572
2024-08-18T07:26:36.269424
Apache-2.0
false
5d3ff6c15a9bf4e9875461249a48be9d
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\settings_handler.cpython-313.pyc
settings_handler.cpython-313.pyc
Other
4,740
0.8
0.04
0.021277
awesome-app
653
2025-05-21T01:36:10.976391
Apache-2.0
false
474548261923647bc4a87524cf73bd00
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\settings_utils.cpython-313.pyc
settings_utils.cpython-313.pyc
Other
19,798
0.95
0.048327
0.003846
python-kit
752
2023-08-01T08:32:44.582892
GPL-3.0
false
7a75ac8907bc928742da48242b2f1296
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\spec.cpython-313.pyc
spec.cpython-313.pyc
Other
1,376
0.7
0
0
node-utils
277
2025-06-25T17:23:56.524657
MIT
false
0448b72cdc3c5d33d405b7236adf501b
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\test_utils.cpython-313.pyc
test_utils.cpython-313.pyc
Other
10,262
0.8
0.025641
0.012987
awesome-app
167
2024-07-28T02:45:55.062361
BSD-3-Clause
true
dbda3a41ecbcd19a22801e8db7fbd607
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\themes_handler.cpython-313.pyc
themes_handler.cpython-313.pyc
Other
5,278
0.8
0.018182
0.018868
node-utils
480
2025-01-30T04:15:01.031346
MIT
false
847575c85fc1ec4e53068302b7b1e5d8
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\translations_handler.cpython-313.pyc
translations_handler.cpython-313.pyc
Other
2,852
0.8
0.02439
0
react-lib
866
2024-03-08T19:57:52.627487
Apache-2.0
false
6d6b63dde430231a8825b4ba98b504fb
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\translation_utils.cpython-313.pyc
translation_utils.cpython-313.pyc
Other
24,090
0.95
0.030879
0
node-utils
729
2024-01-09T11:51:22.153550
BSD-3-Clause
false
497cbe2b2fb5e894f43b120ffa72b562
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\workspaces_app.cpython-313.pyc
workspaces_app.cpython-313.pyc
Other
8,591
0.95
0.019417
0
react-lib
953
2025-04-05T05:48:56.273406
GPL-3.0
false
dab00c5b145f81c1231da1a4d84468c2
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\workspaces_handler.cpython-313.pyc
workspaces_handler.cpython-313.pyc
Other
12,166
0.95
0.035714
0
react-lib
676
2025-01-16T02:15:14.912608
BSD-3-Clause
false
fee4ef5fd44c4bc455e2e9cd31639876
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\_version.cpython-313.pyc
_version.cpython-313.pyc
Other
809
0.7
0
0
awesome-app
668
2024-02-29T07:10:58.593914
BSD-3-Clause
false
72757b6ad1a4c52d48262b71034bc385
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
1,091
0.8
0
0
vue-tools
294
2024-02-07T22:26:55.885115
MIT
false
7c329bfa75474d0db9d95578dbd93b09
\n\n
.venv\Lib\site-packages\jupyterlab_server\__pycache__\__main__.cpython-313.pyc
__main__.cpython-313.pyc
Other
385
0.7
0.333333
0
vue-tools
752
2023-10-24T20:11:37.590155
MIT
false
3b36d1af83f8c3306d98c53499ce7248
pip\n
.venv\Lib\site-packages\jupyterlab_server-2.27.3.dist-info\INSTALLER
INSTALLER
Other
4
0.5
0
0
react-lib
588
2025-06-11T21:29:21.821338
BSD-3-Clause
false
365c9bfeb7d89244f2ce01c1de44cb85
Metadata-Version: 2.3\nName: jupyterlab_server\nVersion: 2.27.3\nSummary: A set of server components for JupyterLab and JupyterLab like applications.\nProject-URL: Homepage, https://jupyterlab-server.readthedocs.io\nProject-URL: Documentation, https://jupyterlab-server.readthedocs.io\nProject-URL: Funding, https://numfocus.org/donate-to-jupyter\nProject-URL: Source, https://github.com/jupyterlab/jupyterlab_server\nProject-URL: Tracker, https://github.com/jupyterlab/jupyterlab_server/issues\nAuthor-email: Jupyter Development Team <jupyter@googlegroups.com>\nLicense: Copyright (c) 2015-2017, Project Jupyter Contributors\n All rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n \n 1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n \n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n \n 3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nLicense-File: LICENSE\nKeywords: jupyter,jupyterlab\nClassifier: Framework :: Jupyter\nClassifier: Framework :: Jupyter :: JupyterLab\nClassifier: Intended Audience :: Developers\nClassifier: Intended Audience :: Science/Research\nClassifier: Intended Audience :: System Administrators\nClassifier: License :: OSI Approved :: BSD License\nClassifier: Programming Language :: Python\nClassifier: Programming Language :: Python :: 3 :: Only\nClassifier: Programming Language :: Python :: 3.8\nClassifier: Programming Language :: Python :: 3.9\nClassifier: Programming Language :: Python :: 3.10\nClassifier: Programming Language :: Python :: 3.11\nClassifier: Programming Language :: Python :: 3.12\nClassifier: Typing :: Typed\nRequires-Python: >=3.8\nRequires-Dist: babel>=2.10\nRequires-Dist: importlib-metadata>=4.8.3; python_version < '3.10'\nRequires-Dist: jinja2>=3.0.3\nRequires-Dist: json5>=0.9.0\nRequires-Dist: jsonschema>=4.18.0\nRequires-Dist: jupyter-server<3,>=1.21\nRequires-Dist: packaging>=21.3\nRequires-Dist: requests>=2.31\nProvides-Extra: docs\nRequires-Dist: autodoc-traits; extra == 'docs'\nRequires-Dist: jinja2<3.2.0; extra == 'docs'\nRequires-Dist: mistune<4; extra == 'docs'\nRequires-Dist: myst-parser; extra == 'docs'\nRequires-Dist: pydata-sphinx-theme; extra == 'docs'\nRequires-Dist: sphinx; extra == 'docs'\nRequires-Dist: sphinx-copybutton; extra == 'docs'\nRequires-Dist: sphinxcontrib-openapi>0.8; extra == 'docs'\nProvides-Extra: openapi\nRequires-Dist: openapi-core~=0.18.0; extra == 'openapi'\nRequires-Dist: ruamel-yaml; extra == 'openapi'\nProvides-Extra: test\nRequires-Dist: hatch; extra == 'test'\nRequires-Dist: ipykernel; extra == 'test'\nRequires-Dist: openapi-core~=0.18.0; extra == 'test'\nRequires-Dist: openapi-spec-validator<0.8.0,>=0.6.0; extra == 'test'\nRequires-Dist: pytest-console-scripts; extra == 'test'\nRequires-Dist: pytest-cov; extra == 'test'\nRequires-Dist: pytest-jupyter[server]>=0.6.2; extra == 'test'\nRequires-Dist: pytest-timeout; extra == 'test'\nRequires-Dist: pytest<8,>=7.0; extra == 'test'\nRequires-Dist: requests-mock; extra == 'test'\nRequires-Dist: ruamel-yaml; extra == 'test'\nRequires-Dist: sphinxcontrib-spelling; extra == 'test'\nRequires-Dist: strict-rfc3339; extra == 'test'\nRequires-Dist: werkzeug; extra == 'test'\nDescription-Content-Type: text/markdown\n\n# jupyterlab server\n\n[![Build Status](https://github.com/jupyterlab/jupyterlab_server/workflows/Tests/badge.svg?branch=master)](https://github.com/jupyterlab/jupyterlab_server/actions?query=branch%3Amaster+workflow%3A%22Tests%22)\n[![Documentation Status](https://readthedocs.org/projects/jupyterlab-server/badge/?version=stable)](http://jupyterlab-server.readthedocs.io/en/stable/)\n\n## Motivation\n\nJupyterLab Server sits between JupyterLab and Jupyter Server, and provides a\nset of REST API handlers and utilities that are used by JupyterLab. It is a separate project in order to\naccommodate creating JupyterLab-like applications from a more limited scope.\n\n## Install\n\n`pip install jupyterlab_server`\n\nTo include optional `openapi` dependencies, use:\n\n`pip install jupyterlab_server[openapi]`\n\nTo include optional `pytest_plugin` dependencies, use:\n\n`pip install jupyterlab_server[test]`\n\n## Usage\n\nSee the full documentation for [API docs](https://jupyterlab-server.readthedocs.io/en/stable/api/index.html) and [REST endpoint descriptions](https://jupyterlab-server.readthedocs.io/en/stable/api/rest.html).\n\n## Extending the Application\n\nSubclass the `LabServerApp` and provide additional traits and handlers as appropriate for your application.\n\n## Contribution\n\nPlease see `CONTRIBUTING.md` for details.\n
.venv\Lib\site-packages\jupyterlab_server-2.27.3.dist-info\METADATA
METADATA
Other
5,891
0.95
0.032
0.057692
node-utils
517
2023-07-31T03:09:54.506423
GPL-3.0
false
d6f0488fddcf70bb1f06bbc22c5e6ac1
jupyterlab_server-2.27.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4\njupyterlab_server-2.27.3.dist-info/METADATA,sha256=EJlj2B-2Gw9jyN-qHmH-clgq0mKQZRYpBjZ9NntLtqo,5891\njupyterlab_server-2.27.3.dist-info/RECORD,,\njupyterlab_server-2.27.3.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87\njupyterlab_server-2.27.3.dist-info/licenses/LICENSE,sha256=uF10-h8a761tg-3KEjbyCvKz7ylh0pC0wBJD5V_ScZg,1519\njupyterlab_server/__init__.py,sha256=F4i2sKYDKqoI3b3Z0ugGd5d8vubhCUkw5OBR6CqaH44,924\njupyterlab_server/__main__.py,sha256=oqhYtyuIH0L_u1etDwIg8OrtM-k4gKWk4B9q1Zrx9hU,248\njupyterlab_server/__pycache__/__init__.cpython-313.pyc,,\njupyterlab_server/__pycache__/__main__.cpython-313.pyc,,\njupyterlab_server/__pycache__/_version.cpython-313.pyc,,\njupyterlab_server/__pycache__/app.cpython-313.pyc,,\njupyterlab_server/__pycache__/config.cpython-313.pyc,,\njupyterlab_server/__pycache__/handlers.cpython-313.pyc,,\njupyterlab_server/__pycache__/licenses_app.cpython-313.pyc,,\njupyterlab_server/__pycache__/licenses_handler.cpython-313.pyc,,\njupyterlab_server/__pycache__/listings_handler.cpython-313.pyc,,\njupyterlab_server/__pycache__/process.cpython-313.pyc,,\njupyterlab_server/__pycache__/process_app.cpython-313.pyc,,\njupyterlab_server/__pycache__/pytest_plugin.cpython-313.pyc,,\njupyterlab_server/__pycache__/server.cpython-313.pyc,,\njupyterlab_server/__pycache__/settings_handler.cpython-313.pyc,,\njupyterlab_server/__pycache__/settings_utils.cpython-313.pyc,,\njupyterlab_server/__pycache__/spec.cpython-313.pyc,,\njupyterlab_server/__pycache__/test_utils.cpython-313.pyc,,\njupyterlab_server/__pycache__/themes_handler.cpython-313.pyc,,\njupyterlab_server/__pycache__/translation_utils.cpython-313.pyc,,\njupyterlab_server/__pycache__/translations_handler.cpython-313.pyc,,\njupyterlab_server/__pycache__/workspaces_app.cpython-313.pyc,,\njupyterlab_server/__pycache__/workspaces_handler.cpython-313.pyc,,\njupyterlab_server/_version.py,sha256=jIuKqGMwko3EDI10jJrLUXw2EKGnarGZ_eWtu9vr3fs,535\njupyterlab_server/app.py,sha256=X8OUtpRnfkmiMPmmHERC1ZxrH0dLmpgp1IMT__uH0qo,4753\njupyterlab_server/config.py,sha256=T337OUfQYS-c6RQcY6d5JxBhOoXsnySZN_ego7t-_WQ,14297\njupyterlab_server/handlers.py,sha256=dIQDotcf1JmTFbndl1rXSl0bUtm8gV8sxtmLNz76wEw,13897\njupyterlab_server/licenses_app.py,sha256=790WfYVTmFH-ZxaFpmVTY5d8yfrU411tpXzVc5F8hWY,2963\njupyterlab_server/licenses_handler.py,sha256=fvu36r6JPh3ZsTrlmz97iZKfOsNCyXqeK_IVIyryM1A,10529\njupyterlab_server/listings_handler.py,sha256=JQSqbrZ8_CCa81BI2Su9N7HCxkXrG8h_rigiRydH-dM,3676\njupyterlab_server/process.py,sha256=c9kxTE7Kp8hHMfxM_s4424UhXnPEohVLJaQ6n-QAzic,9484\njupyterlab_server/process_app.py,sha256=2s73TMbf1iop0fmL2nP82qhfX1GG71LvWJmsEy5TLXY,1715\njupyterlab_server/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0\njupyterlab_server/pytest_plugin.py,sha256=zjMOJbZrA_RKPyPs61iKGLgg-z4nZNwEm4Rji-7ypLw,4844\njupyterlab_server/rest-api.yml,sha256=zFMBThBIug6UgQNjKTGvI7SOyATqMDKfajiVSU4NDzk,9794\njupyterlab_server/server.py,sha256=UAdde62PWITfJzjWXgXYD6PakIokZPZAsRkRP5bBTFE,663\njupyterlab_server/settings_handler.py,sha256=Y38metOLGj2GXHCvldEKI_bFOGrDS-IE_Rpw6JPPox8,3705\njupyterlab_server/settings_utils.py,sha256=GzQTfMbf-tzRAoZWAMJDOGJ2BMwkuFHUdvC67Tm5p0Y,17628\njupyterlab_server/spec.py,sha256=_H2GSQGpSHpKvLKeQKgA6t8lXT8D4_XwXApDYWlp2iE,825\njupyterlab_server/templates/403.html,sha256=sNPTuoGccQqBeQRRFab-dl_RlGZyY2Kk9ASoWXmug5M,323\njupyterlab_server/templates/error.html,sha256=DhqbLkfmWNSRGJB1pk3ElLvqV_3dfLl3HsWh52dI5PE,1219\njupyterlab_server/templates/index.html,sha256=Vyj0eD7yU6ryqPw2EPpws_wjHSGx3xP9P6FWaKFXqCg,1407\njupyterlab_server/test_data/app-settings/overrides.json,sha256=SEkLKCys0usnq_vyAfSn7UdgqjYRo63TucAyL1veAVQ,844\njupyterlab_server/test_data/schemas/@jupyterlab/apputils-extension/themes.json,sha256=d1HpAFvLaxNhzs43YwPzjpLGRdc2XscS_LwUYKV-yqM,862\njupyterlab_server/test_data/schemas/@jupyterlab/codemirror-extension/commands.json,sha256=7oFRXsXmSfEZZfYAEoqcaawLsZaTsDmbeEtnzzJ4RUw,399\njupyterlab_server/test_data/schemas/@jupyterlab/shortcuts-extension/package.json.orig,sha256=sNDcC-mSRl8Cxd2VQaveseId6uK6MtAZLnvwSFGoq3o,77\njupyterlab_server/test_data/schemas/@jupyterlab/shortcuts-extension/plugin.json,sha256=Ey10fBOeDVg2Dt9WZb3rWM3iecCZrH2VIVSfWYSiWTY,18757\njupyterlab_server/test_data/schemas/@jupyterlab/translation-extension/plugin.json,sha256=5viReoeB56Ep-yBcDdgsxKqqb234QdAJuHj0StDh97s,399\njupyterlab_server/test_data/schemas/@jupyterlab/unicode-extension/plugin.json,sha256=0uhKHBNESbzNMZE9fceQqGhfUMlKVCCtzATk0wPWLU4,962\njupyterlab_server/test_data/workspaces/foo-2c26.jupyterlab-workspace,sha256=QZPp-pxzhwhd1S8Vm7JFv-8cjvAWfB-B1nVek_71n5s,40\njupyterlab_server/test_data/workspaces/foo-92dd.jupyterlab-workspace,sha256=LzlXkruqE1RiN0CHK10ePMtK-5tnjUVwpYlt_9LlFw4,43\njupyterlab_server/test_utils.py,sha256=965jRufORwInzeMvEL7qio6-nSupSEex1VmGFwHhAWQ,6794\njupyterlab_server/themes_handler.py,sha256=8_eiIk2lyW76S44IO0XRdHHoihKyiJgjbGTlZlT3-JU,3560\njupyterlab_server/translation_utils.py,sha256=u0CRWZTPx9bjl2lvr0tEtc91o82LslAqui4aJhs_3wA,23009\njupyterlab_server/translations_handler.py,sha256=E7m2q21sSZBLzgZPM_zbHqlMFws5z3IoVVFPvnzfTZU,2191\njupyterlab_server/workspaces_app.py,sha256=H98AQsq7f5XVypO0vXXwudpfKdmhA1SVS2VeYrd40MA,6296\njupyterlab_server/workspaces_handler.py,sha256=aQNiJ8CCk07sTg7zPfpqT2hVj2Zb80VEL4Bm9YF3SIY,8151\n
.venv\Lib\site-packages\jupyterlab_server-2.27.3.dist-info\RECORD
RECORD
Other
5,425
0.7
0
0
awesome-app
618
2024-01-09T17:17:18.340001
BSD-3-Clause
false
5db31ff7771c07b8d5a40138c9f5b925
Wheel-Version: 1.0\nGenerator: hatchling 1.25.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n
.venv\Lib\site-packages\jupyterlab_server-2.27.3.dist-info\WHEEL
WHEEL
Other
87
0.5
0
0
vue-tools
635
2023-11-11T08:38:46.054803
GPL-3.0
false
52adfa0c417902ee8f0c3d1ca2372ac3
Copyright (c) 2015-2017, Project Jupyter Contributors\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n
.venv\Lib\site-packages\jupyterlab_server-2.27.3.dist-info\licenses\LICENSE
LICENSE
Other
1,519
0.7
0
0
vue-tools
774
2025-01-03T20:53:12.187967
Apache-2.0
false
16b24abb4aef09551533365c88c785cf
*.suo\n*.user\n.DS_Store\nnode_modules\ntypings/tsd.d.ts\nnpm-debug.log\ntest/build\ntest/coverage\nlib\ndist\nbuild\ndocs\nexample/*.js\nstatic/\n
.venv\Lib\site-packages\jupyterlab_widgets\.gitignore
.gitignore
Other
133
0.8
0
0.142857
node-utils
13
2024-08-08T13:06:22.461150
GPL-3.0
false
fe5121760325afcfbdb0f0cfebe2c91b
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\n__version__ = '3.0.15'\n
.venv\Lib\site-packages\jupyterlab_widgets\_version.py
_version.py
Python
125
0.8
0
0.666667
node-utils
592
2024-09-10T13:24:14.024826
GPL-3.0
false
b55d26c6227c90ef4212b8844e988fa3
# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom ._version import __version__\n\n\ndef _jupyter_labextension_paths():\n import sys\n from pathlib import Path\n\n labext_name = '@jupyter-widgets/jupyterlab-manager'\n here = Path(__file__).parent.resolve()\n src_prefix = here.parent / 'labextension'\n\n if not src_prefix.exists():\n src_prefix = Path(sys.prefix) / f'share/jupyter/labextensions/{labext_name}'\n\n return [{'src': str(src_prefix), 'dest': labext_name}]\n\n__all__ = ['_jupyter_labextension_paths', '__version__']\n
.venv\Lib\site-packages\jupyterlab_widgets\__init__.py
__init__.py
Python
599
0.95
0.1
0.153846
python-kit
600
2025-03-31T05:56:47.762278
Apache-2.0
false
30283957d612f196641eaa4bbe5ca92e
\n\n
.venv\Lib\site-packages\jupyterlab_widgets\__pycache__\_version.cpython-313.pyc
_version.cpython-313.pyc
Other
222
0.7
0
0
react-lib
807
2024-01-13T02:05:10.560626
GPL-3.0
false
e0fbc3664740777804865c45177a4aad
\n\n
.venv\Lib\site-packages\jupyterlab_widgets\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
967
0.8
0
0
python-kit
382
2025-05-03T00:24:34.155194
GPL-3.0
false
7d9e674110a702d72c5fcaf7bf3b38d5
pip\n
.venv\Lib\site-packages\jupyterlab_widgets-3.0.15.dist-info\INSTALLER
INSTALLER
Other
4
0.5
0
0
vue-tools
219
2024-01-04T10:42:26.530421
BSD-3-Clause
false
365c9bfeb7d89244f2ce01c1de44cb85
Metadata-Version: 2.4\nName: jupyterlab_widgets\nVersion: 3.0.15\nSummary: Jupyter interactive widgets for JupyterLab\nProject-URL: Homepage, https://github.com/jupyter-widgets/ipywidgets\nAuthor-email: Jupyter Development Team <jupyter@googlegroups.com>\nLicense: Copyright (c) 2015 Project Jupyter Contributors\n All rights reserved.\n \n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are met:\n \n 1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n \n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n \n 3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\n AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n \n ------------------------------------------------------------------------------\n \n This package bundles several JavaScript npm packages in the\n jupyterlab_widgets/static directory. Their licenses (as packaged in their\n distributions in the node_modules package installation directory) are copied\n below.\n \n ------------------------------------------------------------------------------\n From css-loader/LICENSE:\n \n Copyright JS Foundation and other contributors\n \n Permission is hereby granted, free of charge, to any person obtaining\n a copy of this software and associated documentation files (the\n 'Software'), to deal in the Software without restriction, including\n without limitation the rights to use, copy, modify, merge, publish,\n distribute, sublicense, and/or sell copies of the Software, and to\n permit persons to whom the Software is furnished to do so, subject to\n the following conditions:\n \n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n \n ------------------------------------------------------------------------------\n From style-loader/LICENSE:\n \n Copyright JS Foundation and other contributors\n \n Permission is hereby granted, free of charge, to any person obtaining\n a copy of this software and associated documentation files (the\n 'Software'), to deal in the Software without restriction, including\n without limitation the rights to use, copy, modify, merge, publish,\n distribute, sublicense, and/or sell copies of the Software, and to\n permit persons to whom the Software is furnished to do so, subject to\n the following conditions:\n \n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n \n ------------------------------------------------------------------------------\n From backbone/backbone.js\n \n // (c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n // Backbone may be freely distributed under the MIT license.\n // For all details and documentation:\n // http://backbonejs.org\n \n ------------------------------------------------------------------------------\n From base-64/LICENSE\n \n The MIT License (MIT)\n \n Copyright (c) 2014 Jameson Little\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the "Software"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in\n all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n THE SOFTWARE.\n \n ------------------------------------------------------------------------------\n From lodash/LICENSE\n \n Copyright OpenJS Foundation and other contributors <https://openjsf.org/>\n \n Based on Underscore.js, copyright Jeremy Ashkenas,\n DocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>\n \n This software consists of voluntary contributions made by many\n individuals. For exact contribution history, see the revision history\n available at https://github.com/lodash/lodash\n \n The following license applies to all parts of this software except as\n documented below:\n \n ====\n \n Permission is hereby granted, free of charge, to any person obtaining\n a copy of this software and associated documentation files (the\n "Software"), to deal in the Software without restriction, including\n without limitation the rights to use, copy, modify, merge, publish,\n distribute, sublicense, and/or sell copies of the Software, and to\n permit persons to whom the Software is furnished to do so, subject to\n the following conditions:\n \n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n \n ====\n \n Copyright and related rights for sample code are waived via CC0. Sample\n code is defined as all source code displayed within the prose of the\n documentation.\n \n CC0: http://creativecommons.org/publicdomain/zero/1.0/\n \n ====\n \n Files located in the node_modules and vendor directories are externally\n maintained libraries used by this software which have their own\n licenses; we recommend you read them, as their terms may differ from the\n terms above.\n \n ------------------------------------------------------------------------------\n From d3-format/LICENSE:\n \n Copyright 2010-2015 Mike Bostock\n All rights reserved.\n \n Redistribution and use in source and binary forms, with or without modification,\n are permitted provided that the following conditions are met:\n \n * Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n \n * Neither the name of the author nor the names of contributors may be used to\n endorse or promote products derived from this software without specific prior\n written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND\n ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n \n ------------------------------------------------------------------------------\n From noUISlider/LICENSE.md (https://github.com/leongersen/noUiSlider/blob/eca62f9e56aaf02f0841b36e7993adf8db3721d5/LICENSE.md)\n \n MIT License\n \n Copyright (c) 2019 Léon Gersen\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the "Software"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n \n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n \n ------------------------------------------------------------------\n From jquery/LICENSE.txt\n \n Copyright JS Foundation and other contributors, https://js.foundation/\n \n Permission is hereby granted, free of charge, to any person obtaining\n a copy of this software and associated documentation files (the\n "Software"), to deal in the Software without restriction, including\n without limitation the rights to use, copy, modify, merge, publish,\n distribute, sublicense, and/or sell copies of the Software, and to\n permit persons to whom the Software is furnished to do so, subject to\n the following conditions:\n \n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n \n ------------------------------------------------------------------\n From semver/LICENSE:\n \n The ISC License\n \n Copyright (c) Isaac Z. Schlueter and Contributors\n \n Permission to use, copy, modify, and/or distribute this software for any\n purpose with or without fee is hereby granted, provided that the above\n copyright notice and this permission notice appear in all copies.\n \n THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR\n IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n \n ------------------------------------------------------------------\n From underscore/LICENSE\n \n Copyright (c) 2009-2018 Jeremy Ashkenas, DocumentCloud and Investigative\n Reporters & Editors\n \n Permission is hereby granted, free of charge, to any person\n obtaining a copy of this software and associated documentation\n files (the "Software"), to deal in the Software without\n restriction, including without limitation the rights to use,\n copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following\n conditions:\n \n The above copyright notice and this permission notice shall be\n included in all copies or substantial portions of the Software.\n \n THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\n WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n OTHER DEALINGS IN THE SOFTWARE.\nLicense-File: LICENSE\nKeywords: Interactive,Interpreter,Jupyter,JupyterLab,JupyterLab3,Shell,Web,notebook,widgets\nClassifier: Framework :: Jupyter\nClassifier: Framework :: Jupyter :: JupyterLab\nClassifier: Framework :: Jupyter :: JupyterLab :: 3\nClassifier: Framework :: Jupyter :: JupyterLab :: Extensions\nClassifier: Framework :: Jupyter :: JupyterLab :: Extensions :: Prebuilt\nClassifier: Intended Audience :: Developers\nClassifier: Intended Audience :: Science/Research\nClassifier: Intended Audience :: System Administrators\nClassifier: License :: OSI Approved :: BSD License\nClassifier: Programming Language :: Python\nClassifier: Programming Language :: Python :: 3\nClassifier: Programming Language :: Python :: 3 :: Only\nClassifier: Programming Language :: Python :: 3.9\nClassifier: Programming Language :: Python :: 3.10\nClassifier: Programming Language :: Python :: 3.11\nClassifier: Programming Language :: Python :: 3.12\nClassifier: Programming Language :: Python :: 3.13\nRequires-Python: >=3.7\nDescription-Content-Type: text/markdown\n\n# Jupyter Widgets JupyterLab Extension\n\nA JupyterLab 3.0 extension for Jupyter/IPython widgets.\n\n## Installation\n\nTo enable ipywidgets support in JupyterLab 3.x:\n\n```bash\npip install jupyterlab_widgets\n```\n\n### Version compatibility\n\nPrior to JupyterLab 3.0, use the appropriate command from the following list\nto install a compatible JupyterLab extension.\n\n- For JupyterLab 0.30, use `jupyter labextension install @jupyter-widgets/jupyterlab-manager@0.31`\n- For JupyterLab 0.31rc1, use `jupyter labextension install @jupyter-widgets/jupyterlab-manager@0.32`\n- For JupyterLab 0.31rc2, use `jupyter labextension install @jupyter-widgets/jupyterlab-manager@0.33`\n- For JupyterLab 0.31.x, use `jupyter labextension install @jupyter-widgets/jupyterlab-manager@0.34`\n- For JupyterLab 0.32.x, use `jupyter labextension install @jupyter-widgets/jupyterlab-manager@0.35`\n- For JupyterLab 0.33.x, use `jupyter labextension install @jupyter-widgets/jupyterlab-manager@0.36`\n- For JupyterLab 0.34.x, use `jupyter labextension install @jupyter-widgets/jupyterlab-manager@0.37`\n- For JupyterLab 0.35.x, use `jupyter labextension install @jupyter-widgets/jupyterlab-manager@0.38`\n- For JupyterLab 1.0.x and 1.1.x, use `jupyter labextension install @jupyter-widgets/jupyterlab-manager@1.0`\n- For JupyterLab 1.2.x, use `jupyter labextension install @jupyter-widgets/jupyterlab-manager@1.1`\n- For JupyterLab 2.x, use `jupyter labextension install @jupyter-widgets/jupyterlab-manager@2`\n\n## Contributing\n\n### Development install\n\nNote: You will need Node.js to build the extension package.\n\nThe `jlpm` command is JupyterLab's pinned version of\n[yarn](https://yarnpkg.com/) that is installed with JupyterLab. You may use\n`yarn` or `npm` in lieu of `jlpm` below.\n\n```bash\n# Clone the repo to your local environment\n# Change directory to the jupyterlab_widgets directory\n# Install package in development mode\npip install -e .\n# Link your development version of the extension with JupyterLab\njupyter labextension develop . --overwrite\n# Rebuild extension Typescript source after making changes\njlpm build\n```\n\nYou can watch the source directory and run JupyterLab at the same time in different terminals to watch for changes in the extension's source and automatically rebuild the extension.\n\n```bash\n# Watch the source directory in one terminal, automatically rebuilding when needed\njlpm watch\n# Run JupyterLab in another terminal\njupyter lab\n```\n\nWith the watch command running, every saved change will immediately be built locally and available in your running JupyterLab. Refresh JupyterLab to load the change in your browser (you may need to wait several seconds for the extension to be rebuilt).\n\n### Uninstall\n\n```bash\npip uninstall jupyterlab_widgets\n```\n
.venv\Lib\site-packages\jupyterlab_widgets-3.0.15.dist-info\METADATA
METADATA
Other
20,220
0.8
0.015544
0.066445
awesome-app
303
2025-01-18T21:17:58.989685
BSD-3-Clause
false
205716da93f7dd217152d592b19b7067
../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/install.json,sha256=e65KcDNtdaA4aZgF1mLHIhwaoIzpH9LmUueG4iJYmI0,197\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/package.json,sha256=vmebfycAy9ffbvozQULkX7ZwWimcOH7gX3pG2PctTHE,3551\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/schemas/@jupyter-widgets/jupyterlab-manager/package.json.orig,sha256=AutseUNp-aBQ8RYYCqF3JRkR5it3VCclwc0DGJPTdyI,3435\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/schemas/@jupyter-widgets/jupyterlab-manager/plugin.json,sha256=IWNBmBm-GTATCrzha5m-Kh0Gt6H4KzGsnzcuSigjx2A,375\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/static/327.d242f1a99504b2d5b629.js,sha256=0kLxqZUEstW2KXamPv9dXHfuOcvuAIAeerfJy4MuzXk,11590\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/static/420.23ab95819c045f6c36bc.js,sha256=I6uVgZwEX2w2vIVl6Wqh61Pl47O9zChT-Y2jNH4HpTg,580\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/static/439.b350310d057b43cdd50f.js,sha256=mWbmC0obk3jy02OcN5Qi02OBbqGcXicDplksSRXFjqw,185630\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/static/439.b350310d057b43cdd50f.js.LICENSE.txt,sha256=1J-1y3fy9iL3n7_uSe7E09q1FXCtEZ0FQkKs0FNbmNc,160\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/static/446.f8696ce72124c78273da.js,sha256=-Gls5yEkx4Jz2hQ07bMBMM24_843lmVYjXcGHsPtMAA,87945\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/static/586.085510630436c2e4273f.js,sha256=CFUQYwQ2wuQnP_hH_wAzGGfW5ujBo7F3_QNaEJEn5-E,111815\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/static/647.8458d9c331000024a14a.js,sha256=hFjZwzEAACShSmBFnPAoKVe9o28Z2La_FSpLpCf4cds,24389\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/static/651.fe40a967a60b543cf15c.js,sha256=Pw5N9MX-Yb4rrumVJXyicIznWzlBigSVrU7WJq2oMG0,87247\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/static/651.fe40a967a60b543cf15c.js.LICENSE.txt,sha256=ksdo1_7QX-XguRBhrddYKKuxB-rCvhJLqHvo4vo2WMY,218\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/static/701.043aefe0b66133629348.js,sha256=BDrv4LZhM2KTSBZeRdvrhvcwF_glz8c3G1_owWY1z40,190\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/static/722.53e4a64671c3c48de007.js,sha256=U-SmRnHDxI3gBw5kJviXDDcqSjdaGM8shUiYojPOEzc,26228\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/static/727.b26a6f3871012a0fd66a.js,sha256=smpvOHEBKg_Wam9uUS3SHbepjOcgTwIqxa692D_KTa8,38426\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/static/898.db11fb1a7e18acb58b5b.js,sha256=2xH7Gn4YrLWLW3uuwstqqUg_O6iBBq1SyzL3NIoHZ2U,60100\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/static/remoteEntry.35b6c65bd99dab37b910.js,sha256=NbbGW9mdqze5EBda_dw8nivqOtpMnxDXgM6I3OjUWaQ,11004\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/static/style.js,sha256=-CQt0ZTPaCTvrRiLcznxflAbfvIKlOVzjOos-muaXQ8,118\n../../share/jupyter/labextensions/@jupyter-widgets/jupyterlab-manager/static/third-party-licenses.json,sha256=rAEtxqfQ91D1yZL60D4LaDq1y5tR-5HE0ih2wdIEZoY,32961\njupyterlab_widgets-3.0.15.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4\njupyterlab_widgets-3.0.15.dist-info/METADATA,sha256=r1mULk-x6c8IvdnuuCZrC0RFhIp9v4fxSS5_uZsK0-A,20220\njupyterlab_widgets-3.0.15.dist-info/RECORD,,\njupyterlab_widgets-3.0.15.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87\njupyterlab_widgets-3.0.15.dist-info/licenses/LICENSE,sha256=GelTR_59wHd_oxLCLPzXb9GhXUbhzeaPEublOd3WtCE,13847\njupyterlab_widgets/.gitignore,sha256=S2QjpxOOTH6e5WAEFonNaOkYs9twSX9Ye9Uzf6LGpYk,133\njupyterlab_widgets/__init__.py,sha256=H8juS5_tHMAByEpG7ysoOMfzDcO9nC9Rl-nkonYRCrE,599\njupyterlab_widgets/__pycache__/__init__.cpython-313.pyc,,\njupyterlab_widgets/__pycache__/_version.cpython-313.pyc,,\njupyterlab_widgets/_version.py,sha256=ol5XwAaHr8UR9VUK543LLs1nI0UrDnbBTdcirnqclGQ,125\n
.venv\Lib\site-packages\jupyterlab_widgets-3.0.15.dist-info\RECORD
RECORD
Other
4,096
0.7
0
0
vue-tools
47
2024-09-21T14:01:28.764210
MIT
false
c759e85552a6ad92b618b6b6fbb1e111
Wheel-Version: 1.0\nGenerator: hatchling 1.27.0\nRoot-Is-Purelib: true\nTag: py3-none-any\n
.venv\Lib\site-packages\jupyterlab_widgets-3.0.15.dist-info\WHEEL
WHEEL
Other
87
0.5
0
0
awesome-app
73
2023-10-01T23:56:23.482085
GPL-3.0
false
e2fcb0ad9ea59332c808928b4b439e7a
Copyright (c) 2015 Project Jupyter Contributors\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n3. Neither the name of the copyright holder nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n------------------------------------------------------------------------------\n\nThis package bundles several JavaScript npm packages in the\njupyterlab_widgets/static directory. Their licenses (as packaged in their\ndistributions in the node_modules package installation directory) are copied\nbelow.\n\n------------------------------------------------------------------------------\nFrom css-loader/LICENSE:\n\nCopyright JS Foundation and other contributors\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n------------------------------------------------------------------------------\nFrom style-loader/LICENSE:\n\nCopyright JS Foundation and other contributors\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n'Software'), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\nTORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\nSOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n------------------------------------------------------------------------------\nFrom backbone/backbone.js\n\n// (c) 2010-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n// Backbone may be freely distributed under the MIT license.\n// For all details and documentation:\n// http://backbonejs.org\n\n------------------------------------------------------------------------------\nFrom base-64/LICENSE\n\nThe MIT License (MIT)\n\nCopyright (c) 2014 Jameson Little\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\n------------------------------------------------------------------------------\nFrom lodash/LICENSE\n\nCopyright OpenJS Foundation and other contributors <https://openjsf.org/>\n\nBased on Underscore.js, copyright Jeremy Ashkenas,\nDocumentCloud and Investigative Reporters & Editors <http://underscorejs.org/>\n\nThis software consists of voluntary contributions made by many\nindividuals. For exact contribution history, see the revision history\navailable at https://github.com/lodash/lodash\n\nThe following license applies to all parts of this software except as\ndocumented below:\n\n====\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n"Software"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n====\n\nCopyright and related rights for sample code are waived via CC0. Sample\ncode is defined as all source code displayed within the prose of the\ndocumentation.\n\nCC0: http://creativecommons.org/publicdomain/zero/1.0/\n\n====\n\nFiles located in the node_modules and vendor directories are externally\nmaintained libraries used by this software which have their own\nlicenses; we recommend you read them, as their terms may differ from the\nterms above.\n\n------------------------------------------------------------------------------\nFrom d3-format/LICENSE:\n\nCopyright 2010-2015 Mike Bostock\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\n* Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n\n* Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and/or other materials provided with the distribution.\n\n* Neither the name of the author nor the names of contributors may be used to\n endorse or promote products derived from this software without specific prior\n written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n------------------------------------------------------------------------------\nFrom noUISlider/LICENSE.md (https://github.com/leongersen/noUiSlider/blob/eca62f9e56aaf02f0841b36e7993adf8db3721d5/LICENSE.md)\n\nMIT License\n\nCopyright (c) 2019 Léon Gersen\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n------------------------------------------------------------------\nFrom jquery/LICENSE.txt\n\nCopyright JS Foundation and other contributors, https://js.foundation/\n\nPermission is hereby granted, free of charge, to any person obtaining\na copy of this software and associated documentation files (the\n"Software"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to\npermit persons to whom the Software is furnished to do so, subject to\nthe following conditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\nLIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\nWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n------------------------------------------------------------------\nFrom semver/LICENSE:\n\nThe ISC License\n\nCopyright (c) Isaac Z. Schlueter and Contributors\n\nPermission to use, copy, modify, and/or distribute this software for any\npurpose with or without fee is hereby granted, provided that the above\ncopyright notice and this permission notice appear in all copies.\n\nTHE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\nWITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\nANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR\nIN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n------------------------------------------------------------------\nFrom underscore/LICENSE\n\nCopyright (c) 2009-2018 Jeremy Ashkenas, DocumentCloud and Investigative\nReporters & Editors\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the "Software"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n
.venv\Lib\site-packages\jupyterlab_widgets-3.0.15.dist-info\licenses\LICENSE
LICENSE
Other
13,847
0.8
0.006849
0.031111
vue-tools
568
2024-12-31T05:19:42.567445
Apache-2.0
false
46c4b25eb11307c56dc6205528a80fb0
"""Adapters for Jupyter msg spec versions."""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nimport json\nimport re\nfrom typing import Any, Dict, List, Tuple\n\nfrom ._version import protocol_version_info\n\n\ndef code_to_line(code: str, cursor_pos: int) -> Tuple[str, int]:\n """Turn a multiline code block and cursor position into a single line\n and new cursor position.\n\n For adapting ``complete_`` and ``object_info_request``.\n """\n if not code:\n return "", 0\n for line in code.splitlines(True):\n n = len(line)\n if cursor_pos > n:\n cursor_pos -= n\n else:\n break\n return line, cursor_pos\n\n\n_match_bracket = re.compile(r"\([^\(\)]+\)", re.UNICODE)\n_end_bracket = re.compile(r"\([^\(]*$", re.UNICODE)\n_identifier = re.compile(r"[a-z_][0-9a-z._]*", re.I | re.UNICODE)\n\n\ndef extract_oname_v4(code: str, cursor_pos: int) -> str:\n """Reimplement token-finding logic from IPython 2.x javascript\n\n for adapting object_info_request from v5 to v4\n """\n\n line, _ = code_to_line(code, cursor_pos)\n\n oldline = line\n line = _match_bracket.sub("", line)\n while oldline != line:\n oldline = line\n line = _match_bracket.sub("", line)\n\n # remove everything after last open bracket\n line = _end_bracket.sub("", line)\n matches = _identifier.findall(line)\n if matches:\n return matches[-1]\n else:\n return ""\n\n\nclass Adapter:\n """Base class for adapting messages\n\n Override message_type(msg) methods to create adapters.\n """\n\n msg_type_map: Dict[str, str] = {}\n\n def update_header(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Update the header."""\n return msg\n\n def update_metadata(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Update the metadata."""\n return msg\n\n def update_msg_type(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Update the message type."""\n header = msg["header"]\n msg_type = header["msg_type"]\n if msg_type in self.msg_type_map:\n msg["msg_type"] = header["msg_type"] = self.msg_type_map[msg_type]\n return msg\n\n def handle_reply_status_error(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """This will be called *instead of* the regular handler\n\n on any reply with status != ok\n """\n return msg\n\n def __call__(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n msg = self.update_header(msg)\n msg = self.update_metadata(msg)\n msg = self.update_msg_type(msg)\n header = msg["header"]\n\n handler = getattr(self, header["msg_type"], None)\n if handler is None:\n return msg\n\n # handle status=error replies separately (no change, at present)\n if msg["content"].get("status", None) in {"error", "aborted"}:\n return self.handle_reply_status_error(msg)\n return handler(msg)\n\n\ndef _version_str_to_list(version: str) -> List[int]:\n """convert a version string to a list of ints\n\n non-int segments are excluded\n """\n v = []\n for part in version.split("."):\n try:\n v.append(int(part))\n except ValueError:\n pass\n return v\n\n\nclass V5toV4(Adapter):\n """Adapt msg protocol v5 to v4"""\n\n version = "4.1"\n\n msg_type_map = {\n "execute_result": "pyout",\n "execute_input": "pyin",\n "error": "pyerr",\n "inspect_request": "object_info_request",\n "inspect_reply": "object_info_reply",\n }\n\n def update_header(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Update the header."""\n msg["header"].pop("version", None)\n msg["parent_header"].pop("version", None)\n return msg\n\n # shell channel\n\n def kernel_info_reply(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle a kernel info reply."""\n v4c = {}\n content = msg["content"]\n for key in ("language_version", "protocol_version"):\n if key in content:\n v4c[key] = _version_str_to_list(content[key])\n if content.get("implementation", "") == "ipython" and "implementation_version" in content:\n v4c["ipython_version"] = _version_str_to_list(content["implementation_version"])\n language_info = content.get("language_info", {})\n language = language_info.get("name", "")\n v4c.setdefault("language", language)\n if "version" in language_info:\n v4c.setdefault("language_version", _version_str_to_list(language_info["version"]))\n msg["content"] = v4c\n return msg\n\n def execute_request(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle an execute request."""\n content = msg["content"]\n content.setdefault("user_variables", [])\n return msg\n\n def execute_reply(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle an execute reply."""\n content = msg["content"]\n content.setdefault("user_variables", {})\n # TODO: handle payloads\n return msg\n\n def complete_request(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle a complete request."""\n content = msg["content"]\n code = content["code"]\n cursor_pos = content["cursor_pos"]\n line, cursor_pos = code_to_line(code, cursor_pos)\n\n new_content = msg["content"] = {}\n new_content["text"] = ""\n new_content["line"] = line\n new_content["block"] = None\n new_content["cursor_pos"] = cursor_pos\n return msg\n\n def complete_reply(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle a complete reply."""\n content = msg["content"]\n cursor_start = content.pop("cursor_start")\n cursor_end = content.pop("cursor_end")\n match_len = cursor_end - cursor_start\n content["matched_text"] = content["matches"][0][:match_len]\n content.pop("metadata", None)\n return msg\n\n def object_info_request(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle an object info request."""\n content = msg["content"]\n code = content["code"]\n cursor_pos = content["cursor_pos"]\n line, _ = code_to_line(code, cursor_pos)\n\n new_content = msg["content"] = {}\n new_content["oname"] = extract_oname_v4(code, cursor_pos)\n new_content["detail_level"] = content["detail_level"]\n return msg\n\n def object_info_reply(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """inspect_reply can't be easily backward compatible"""\n msg["content"] = {"found": False, "oname": "unknown"}\n return msg\n\n # iopub channel\n\n def stream(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle a stream message."""\n content = msg["content"]\n content["data"] = content.pop("text")\n return msg\n\n def display_data(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle a display data message."""\n content = msg["content"]\n content.setdefault("source", "display")\n data = content["data"]\n if "application/json" in data:\n try:\n data["application/json"] = json.dumps(data["application/json"])\n except Exception:\n # warn?\n pass\n return msg\n\n # stdin channel\n\n def input_request(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle an input request."""\n msg["content"].pop("password", None)\n return msg\n\n\nclass V4toV5(Adapter):\n """Convert msg spec V4 to V5"""\n\n version = "5.0"\n\n # invert message renames above\n msg_type_map = {v: k for k, v in V5toV4.msg_type_map.items()}\n\n def update_header(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Update the header."""\n msg["header"]["version"] = self.version\n if msg["parent_header"]:\n msg["parent_header"]["version"] = self.version\n return msg\n\n # shell channel\n\n def kernel_info_reply(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle a kernel info reply."""\n content = msg["content"]\n for key in ("protocol_version", "ipython_version"):\n if key in content:\n content[key] = ".".join(map(str, content[key]))\n\n content.setdefault("protocol_version", "4.1")\n\n if content["language"].startswith("python") and "ipython_version" in content:\n content["implementation"] = "ipython"\n content["implementation_version"] = content.pop("ipython_version")\n\n language = content.pop("language")\n language_info = content.setdefault("language_info", {})\n language_info.setdefault("name", language)\n if "language_version" in content:\n language_version = ".".join(map(str, content.pop("language_version")))\n language_info.setdefault("version", language_version)\n\n content["banner"] = ""\n return msg\n\n def execute_request(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle an execute request."""\n content = msg["content"]\n user_variables = content.pop("user_variables", [])\n user_expressions = content.setdefault("user_expressions", {})\n for v in user_variables:\n user_expressions[v] = v\n return msg\n\n def execute_reply(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle an execute reply."""\n content = msg["content"]\n user_expressions = content.setdefault("user_expressions", {})\n user_variables = content.pop("user_variables", {})\n if user_variables:\n user_expressions.update(user_variables)\n\n # Pager payloads became a mime bundle\n for payload in content.get("payload", []):\n if payload.get("source", None) == "page" and ("text" in payload):\n if "data" not in payload:\n payload["data"] = {}\n payload["data"]["text/plain"] = payload.pop("text")\n\n return msg\n\n def complete_request(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle a complete request."""\n old_content = msg["content"]\n\n new_content = msg["content"] = {}\n new_content["code"] = old_content["line"]\n new_content["cursor_pos"] = old_content["cursor_pos"]\n return msg\n\n def complete_reply(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle a complete reply."""\n # complete_reply needs more context than we have to get cursor_start and end.\n # use special end=null to indicate current cursor position and negative offset\n # for start relative to the cursor.\n # start=None indicates that start == end (accounts for no -0).\n content = msg["content"]\n new_content = msg["content"] = {"status": "ok"}\n new_content["matches"] = content["matches"]\n if content["matched_text"]:\n new_content["cursor_start"] = -len(content["matched_text"])\n else:\n # no -0, use None to indicate that start == end\n new_content["cursor_start"] = None\n new_content["cursor_end"] = None\n new_content["metadata"] = {}\n return msg\n\n def inspect_request(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle an inspect request."""\n content = msg["content"]\n name = content["oname"]\n\n new_content = msg["content"] = {}\n new_content["code"] = name\n new_content["cursor_pos"] = len(name)\n new_content["detail_level"] = content["detail_level"]\n return msg\n\n def inspect_reply(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """inspect_reply can't be easily backward compatible"""\n content = msg["content"]\n new_content = msg["content"] = {"status": "ok"}\n found = new_content["found"] = content["found"]\n new_content["data"] = data = {}\n new_content["metadata"] = {}\n if found:\n lines = []\n for key in ("call_def", "init_definition", "definition"):\n if content.get(key, False):\n lines.append(content[key])\n break\n for key in ("call_docstring", "init_docstring", "docstring"):\n if content.get(key, False):\n lines.append(content[key])\n break\n if not lines:\n lines.append("<empty docstring>")\n data["text/plain"] = "\n".join(lines)\n return msg\n\n # iopub channel\n\n def stream(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle a stream message."""\n content = msg["content"]\n content["text"] = content.pop("data")\n return msg\n\n def display_data(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle display data."""\n content = msg["content"]\n content.pop("source", None)\n data = content["data"]\n if "application/json" in data:\n try:\n data["application/json"] = json.loads(data["application/json"])\n except Exception:\n # warn?\n pass\n return msg\n\n # stdin channel\n\n def input_request(self, msg: Dict[str, Any]) -> Dict[str, Any]:\n """Handle an input request."""\n msg["content"].setdefault("password", False)\n return msg\n\n\ndef adapt(msg: Dict[str, Any], to_version: int = protocol_version_info[0]) -> Dict[str, Any]:\n """Adapt a single message to a target version\n\n Parameters\n ----------\n\n msg : dict\n A Jupyter message.\n to_version : int, optional\n The target major version.\n If unspecified, adapt to the current version.\n\n Returns\n -------\n\n msg : dict\n A Jupyter message appropriate in the new version.\n """\n from .session import utcnow\n\n header = msg["header"]\n if "date" not in header:\n header["date"] = utcnow()\n if "version" in header:\n from_version = int(header["version"].split(".")[0])\n else:\n # assume last version before adding the key to the header\n from_version = 4\n adapter = adapters.get((from_version, to_version), None)\n if adapter is None:\n return msg\n return adapter(msg)\n\n\n# one adapter per major version from,to\nadapters = {\n (5, 4): V5toV4(),\n (4, 5): V4toV5(),\n}\n
.venv\Lib\site-packages\jupyter_client\adapter.py
adapter.py
Python
14,381
0.95
0.183295
0.063037
react-lib
357
2024-10-08T20:44:13.078797
BSD-3-Clause
false
a54a6e822702f044cd609db99664ec0e
"""Base classes to manage a Client's interaction with a running kernel"""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nimport asyncio\nimport atexit\nimport time\nimport typing as t\nfrom queue import Empty\nfrom threading import Event, Thread\n\nimport zmq.asyncio\nfrom jupyter_core.utils import ensure_async\n\nfrom ._version import protocol_version_info\nfrom .channelsabc import HBChannelABC\nfrom .session import Session\n\n# import ZMQError in top-level namespace, to avoid ugly attribute-error messages\n# during garbage collection of threads at exit\n\n# -----------------------------------------------------------------------------\n# Constants and exceptions\n# -----------------------------------------------------------------------------\n\nmajor_protocol_version = protocol_version_info[0]\n\n\nclass InvalidPortNumber(Exception): # noqa\n """An exception raised for an invalid port number."""\n\n pass\n\n\nclass HBChannel(Thread):\n """The heartbeat channel which monitors the kernel heartbeat.\n\n Note that the heartbeat channel is paused by default. As long as you start\n this channel, the kernel manager will ensure that it is paused and un-paused\n as appropriate.\n """\n\n session = None\n socket = None\n address = None\n _exiting = False\n\n time_to_dead: float = 1.0\n _running = None\n _pause = None\n _beating = None\n\n def __init__(\n self,\n context: t.Optional[zmq.Context] = None,\n session: t.Optional[Session] = None,\n address: t.Union[t.Tuple[str, int], str] = "",\n ) -> None:\n """Create the heartbeat monitor thread.\n\n Parameters\n ----------\n context : :class:`zmq.Context`\n The ZMQ context to use.\n session : :class:`session.Session`\n The session to use.\n address : zmq url\n Standard (ip, port) tuple that the kernel is listening on.\n """\n super().__init__()\n self.daemon = True\n\n self.context = context\n self.session = session\n if isinstance(address, tuple):\n if address[1] == 0:\n message = "The port number for a channel cannot be 0."\n raise InvalidPortNumber(message)\n address_str = "tcp://%s:%i" % address\n else:\n address_str = address\n self.address = address_str\n\n # running is False until `.start()` is called\n self._running = False\n self._exit = Event()\n # don't start paused\n self._pause = False\n self.poller = zmq.Poller()\n\n @staticmethod\n @atexit.register\n def _notice_exit() -> None:\n # Class definitions can be torn down during interpreter shutdown.\n # We only need to set _exiting flag if this hasn't happened.\n if HBChannel is not None:\n HBChannel._exiting = True\n\n def _create_socket(self) -> None:\n if self.socket is not None:\n # close previous socket, before opening a new one\n self.poller.unregister(self.socket) # type:ignore[unreachable]\n self.socket.close()\n assert self.context is not None\n self.socket = self.context.socket(zmq.REQ)\n self.socket.linger = 1000\n assert self.address is not None\n self.socket.connect(self.address)\n\n self.poller.register(self.socket, zmq.POLLIN)\n\n async def _async_run(self) -> None:\n """The thread's main activity. Call start() instead."""\n self._create_socket()\n self._running = True\n self._beating = True\n assert self.socket is not None\n\n while self._running:\n if self._pause:\n # just sleep, and skip the rest of the loop\n self._exit.wait(self.time_to_dead)\n continue\n\n since_last_heartbeat = 0.0\n # no need to catch EFSM here, because the previous event was\n # either a recv or connect, which cannot be followed by EFSM)\n await ensure_async(self.socket.send(b"ping"))\n request_time = time.time()\n # Wait until timeout\n self._exit.wait(self.time_to_dead)\n # poll(0) means return immediately (see http://api.zeromq.org/2-1:zmq-poll)\n self._beating = bool(self.poller.poll(0))\n if self._beating:\n # the poll above guarantees we have something to recv\n await ensure_async(self.socket.recv())\n continue\n elif self._running:\n # nothing was received within the time limit, signal heart failure\n since_last_heartbeat = time.time() - request_time\n self.call_handlers(since_last_heartbeat)\n # and close/reopen the socket, because the REQ/REP cycle has been broken\n self._create_socket()\n continue\n\n def run(self) -> None:\n """Run the heartbeat thread."""\n loop = asyncio.new_event_loop()\n asyncio.set_event_loop(loop)\n loop.run_until_complete(self._async_run())\n loop.close()\n\n def pause(self) -> None:\n """Pause the heartbeat."""\n self._pause = True\n\n def unpause(self) -> None:\n """Unpause the heartbeat."""\n self._pause = False\n\n def is_beating(self) -> bool:\n """Is the heartbeat running and responsive (and not paused)."""\n if self.is_alive() and not self._pause and self._beating: # noqa\n return True\n else:\n return False\n\n def stop(self) -> None:\n """Stop the channel's event loop and join its thread."""\n self._running = False\n self._exit.set()\n self.join()\n self.close()\n\n def close(self) -> None:\n """Close the heartbeat thread."""\n if self.socket is not None:\n try:\n self.socket.close(linger=0)\n except Exception:\n pass\n self.socket = None\n\n def call_handlers(self, since_last_heartbeat: float) -> None:\n """This method is called in the ioloop thread when a message arrives.\n\n Subclasses should override this method to handle incoming messages.\n It is important to remember that this method is called in the thread\n so that some logic must be done to ensure that the application level\n handlers are called in the application thread.\n """\n pass\n\n\nHBChannelABC.register(HBChannel)\n\n\nclass ZMQSocketChannel:\n """A ZMQ socket wrapper"""\n\n def __init__(self, socket: zmq.Socket, session: Session, loop: t.Any = None) -> None:\n """Create a channel.\n\n Parameters\n ----------\n socket : :class:`zmq.Socket`\n The ZMQ socket to use.\n session : :class:`session.Session`\n The session to use.\n loop\n Unused here, for other implementations\n """\n super().__init__()\n\n self.socket: t.Optional[zmq.Socket] = socket\n self.session = session\n\n def _recv(self, **kwargs: t.Any) -> t.Dict[str, t.Any]:\n assert self.socket is not None\n msg = self.socket.recv_multipart(**kwargs)\n ident, smsg = self.session.feed_identities(msg)\n return self.session.deserialize(smsg)\n\n def get_msg(self, timeout: t.Optional[float] = None) -> t.Dict[str, t.Any]:\n """Gets a message if there is one that is ready."""\n assert self.socket is not None\n timeout_ms = None if timeout is None else int(timeout * 1000) # seconds to ms\n ready = self.socket.poll(timeout_ms)\n if ready:\n res = self._recv()\n return res\n else:\n raise Empty\n\n def get_msgs(self) -> t.List[t.Dict[str, t.Any]]:\n """Get all messages that are currently ready."""\n msgs = []\n while True:\n try:\n msgs.append(self.get_msg())\n except Empty:\n break\n return msgs\n\n def msg_ready(self) -> bool:\n """Is there a message that has been received?"""\n assert self.socket is not None\n return bool(self.socket.poll(timeout=0))\n\n def close(self) -> None:\n """Close the socket channel."""\n if self.socket is not None:\n try:\n self.socket.close(linger=0)\n except Exception:\n pass\n self.socket = None\n\n stop = close\n\n def is_alive(self) -> bool:\n """Test whether the channel is alive."""\n return self.socket is not None\n\n def send(self, msg: t.Dict[str, t.Any]) -> None:\n """Pass a message to the ZMQ socket to send"""\n assert self.socket is not None\n self.session.send(self.socket, msg)\n\n def start(self) -> None:\n """Start the socket channel."""\n pass\n\n\nclass AsyncZMQSocketChannel(ZMQSocketChannel):\n """A ZMQ socket in an async API"""\n\n socket: zmq.asyncio.Socket\n\n def __init__(self, socket: zmq.asyncio.Socket, session: Session, loop: t.Any = None) -> None:\n """Create a channel.\n\n Parameters\n ----------\n socket : :class:`zmq.asyncio.Socket`\n The ZMQ socket to use.\n session : :class:`session.Session`\n The session to use.\n loop\n Unused here, for other implementations\n """\n if not isinstance(socket, zmq.asyncio.Socket):\n msg = "Socket must be asyncio" # type:ignore[unreachable]\n raise ValueError(msg)\n super().__init__(socket, session)\n\n async def _recv(self, **kwargs: t.Any) -> t.Dict[str, t.Any]: # type:ignore[override]\n assert self.socket is not None\n msg = await self.socket.recv_multipart(**kwargs)\n _, smsg = self.session.feed_identities(msg)\n return self.session.deserialize(smsg)\n\n async def get_msg( # type:ignore[override]\n self, timeout: t.Optional[float] = None\n ) -> t.Dict[str, t.Any]:\n """Gets a message if there is one that is ready."""\n assert self.socket is not None\n timeout_ms = None if timeout is None else int(timeout * 1000) # seconds to ms\n ready = await self.socket.poll(timeout_ms)\n if ready:\n res = await self._recv()\n return res\n else:\n raise Empty\n\n async def get_msgs(self) -> t.List[t.Dict[str, t.Any]]: # type:ignore[override]\n """Get all messages that are currently ready."""\n msgs = []\n while True:\n try:\n msgs.append(await self.get_msg())\n except Empty:\n break\n return msgs\n\n async def msg_ready(self) -> bool: # type:ignore[override]\n """Is there a message that has been received?"""\n assert self.socket is not None\n return bool(await self.socket.poll(timeout=0))\n
.venv\Lib\site-packages\jupyter_client\channels.py
channels.py
Python
10,835
0.95
0.195122
0.073529
node-utils
620
2024-06-06T01:10:19.018569
GPL-3.0
false
0eef122b29398611b796a0933b03405a
"""Abstract base classes for kernel client channels"""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nimport abc\n\n\nclass ChannelABC(metaclass=abc.ABCMeta):\n """A base class for all channel ABCs."""\n\n @abc.abstractmethod\n def start(self) -> None:\n """Start the channel."""\n pass\n\n @abc.abstractmethod\n def stop(self) -> None:\n """Stop the channel."""\n pass\n\n @abc.abstractmethod\n def is_alive(self) -> bool:\n """Test whether the channel is alive."""\n pass\n\n\nclass HBChannelABC(ChannelABC):\n """HBChannel ABC.\n\n The docstrings for this class can be found in the base implementation:\n\n `jupyter_client.channels.HBChannel`\n """\n\n @abc.abstractproperty\n def time_to_dead(self) -> float:\n pass\n\n @abc.abstractmethod\n def pause(self) -> None:\n """Pause the heartbeat channel."""\n pass\n\n @abc.abstractmethod\n def unpause(self) -> None:\n """Unpause the heartbeat channel."""\n pass\n\n @abc.abstractmethod\n def is_beating(self) -> bool:\n """Test whether the channel is beating."""\n pass\n
.venv\Lib\site-packages\jupyter_client\channelsabc.py
channelsabc.py
Python
1,177
0.95
0.27451
0.052632
react-lib
659
2024-03-08T20:10:35.311489
MIT
false
1be0b9f91b28fb5da4ebae0ca07a5289
"""Base class to manage the interaction with a running kernel"""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nimport asyncio\nimport inspect\nimport sys\nimport time\nimport typing as t\nfrom functools import partial\nfrom getpass import getpass\nfrom queue import Empty\n\nimport zmq.asyncio\nfrom jupyter_core.utils import ensure_async\nfrom traitlets import Any, Bool, Instance, Type\n\nfrom .channels import major_protocol_version\nfrom .channelsabc import ChannelABC, HBChannelABC\nfrom .clientabc import KernelClientABC\nfrom .connect import ConnectionFileMixin\nfrom .session import Session\n\n# some utilities to validate message structure, these might get moved elsewhere\n# if they prove to have more generic utility\n\n\ndef validate_string_dict(dct: t.Dict[str, str]) -> None:\n """Validate that the input is a dict with string keys and values.\n\n Raises ValueError if not."""\n for k, v in dct.items():\n if not isinstance(k, str):\n raise ValueError("key %r in dict must be a string" % k)\n if not isinstance(v, str):\n raise ValueError("value %r in dict must be a string" % v)\n\n\ndef reqrep(wrapped: t.Callable, meth: t.Callable, channel: str = "shell") -> t.Callable:\n wrapped = wrapped(meth, channel)\n if not meth.__doc__:\n # python -OO removes docstrings,\n # so don't bother building the wrapped docstring\n return wrapped\n\n basedoc, _ = meth.__doc__.split("Returns\n", 1)\n parts = [basedoc.strip()]\n if "Parameters" not in basedoc:\n parts.append(\n """\n Parameters\n ----------\n """\n )\n parts.append(\n """\n reply: bool (default: False)\n Whether to wait for and return reply\n timeout: float or None (default: None)\n Timeout to use when waiting for a reply\n\n Returns\n -------\n msg_id: str\n The msg_id of the request sent, if reply=False (default)\n reply: dict\n The reply message for this request, if reply=True\n """\n )\n wrapped.__doc__ = "\n".join(parts)\n return wrapped\n\n\nclass KernelClient(ConnectionFileMixin):\n """Communicates with a single kernel on any host via zmq channels.\n\n There are five channels associated with each kernel:\n\n * shell: for request/reply calls to the kernel.\n * iopub: for the kernel to publish results to frontends.\n * hb: for monitoring the kernel's heartbeat.\n * stdin: for frontends to reply to raw_input calls in the kernel.\n * control: for kernel management calls to the kernel.\n\n The messages that can be sent on these channels are exposed as methods of the\n client (KernelClient.execute, complete, history, etc.). These methods only\n send the message, they don't wait for a reply. To get results, use e.g.\n :meth:`get_shell_msg` to fetch messages from the shell channel.\n """\n\n # The PyZMQ Context to use for communication with the kernel.\n context = Instance(zmq.Context)\n\n _created_context = Bool(False)\n\n def _context_default(self) -> zmq.Context:\n self._created_context = True\n return zmq.Context()\n\n # The classes to use for the various channels\n shell_channel_class = Type(ChannelABC)\n iopub_channel_class = Type(ChannelABC)\n stdin_channel_class = Type(ChannelABC)\n hb_channel_class = Type(HBChannelABC)\n control_channel_class = Type(ChannelABC)\n\n # Protected traits\n _shell_channel = Any()\n _iopub_channel = Any()\n _stdin_channel = Any()\n _hb_channel = Any()\n _control_channel = Any()\n\n # flag for whether execute requests should be allowed to call raw_input:\n allow_stdin: bool = True\n\n def __del__(self) -> None:\n """Handle garbage collection. Destroy context if applicable."""\n if (\n self._created_context\n and self.context is not None # type:ignore[redundant-expr]\n and not self.context.closed\n ):\n if self.channels_running:\n if self.log:\n self.log.warning("Could not destroy zmq context for %s", self)\n else:\n if self.log:\n self.log.debug("Destroying zmq context for %s", self)\n self.context.destroy()\n try:\n super_del = super().__del__ # type:ignore[misc]\n except AttributeError:\n pass\n else:\n super_del()\n\n # --------------------------------------------------------------------------\n # Channel proxy methods\n # --------------------------------------------------------------------------\n\n async def _async_get_shell_msg(self, *args: t.Any, **kwargs: t.Any) -> t.Dict[str, t.Any]:\n """Get a message from the shell channel"""\n return await ensure_async(self.shell_channel.get_msg(*args, **kwargs))\n\n async def _async_get_iopub_msg(self, *args: t.Any, **kwargs: t.Any) -> t.Dict[str, t.Any]:\n """Get a message from the iopub channel"""\n return await ensure_async(self.iopub_channel.get_msg(*args, **kwargs))\n\n async def _async_get_stdin_msg(self, *args: t.Any, **kwargs: t.Any) -> t.Dict[str, t.Any]:\n """Get a message from the stdin channel"""\n return await ensure_async(self.stdin_channel.get_msg(*args, **kwargs))\n\n async def _async_get_control_msg(self, *args: t.Any, **kwargs: t.Any) -> t.Dict[str, t.Any]:\n """Get a message from the control channel"""\n return await ensure_async(self.control_channel.get_msg(*args, **kwargs))\n\n async def _async_wait_for_ready(self, timeout: t.Optional[float] = None) -> None:\n """Waits for a response when a client is blocked\n\n - Sets future time for timeout\n - Blocks on shell channel until a message is received\n - Exit if the kernel has died\n - If client times out before receiving a message from the kernel, send RuntimeError\n - Flush the IOPub channel\n """\n if timeout is None:\n timeout = float("inf")\n abs_timeout = time.time() + timeout\n\n from .manager import KernelManager\n\n if not isinstance(self.parent, KernelManager):\n # This Client was not created by a KernelManager,\n # so wait for kernel to become responsive to heartbeats\n # before checking for kernel_info reply\n while not await self._async_is_alive():\n if time.time() > abs_timeout:\n raise RuntimeError(\n "Kernel didn't respond to heartbeats in %d seconds and timed out" % timeout\n )\n await asyncio.sleep(0.2)\n\n # Wait for kernel info reply on shell channel\n while True:\n self.kernel_info()\n try:\n msg = await ensure_async(self.shell_channel.get_msg(timeout=1))\n except Empty:\n pass\n else:\n if msg["msg_type"] == "kernel_info_reply":\n # Checking that IOPub is connected. If it is not connected, start over.\n try:\n await ensure_async(self.iopub_channel.get_msg(timeout=0.2))\n except Empty:\n pass\n else:\n self._handle_kernel_info_reply(msg)\n break\n\n if not await self._async_is_alive():\n msg = "Kernel died before replying to kernel_info"\n raise RuntimeError(msg)\n\n # Check if current time is ready check time plus timeout\n if time.time() > abs_timeout:\n raise RuntimeError("Kernel didn't respond in %d seconds" % timeout)\n\n # Flush IOPub channel\n while True:\n try:\n msg = await ensure_async(self.iopub_channel.get_msg(timeout=0.2))\n except Empty:\n break\n\n async def _async_recv_reply(\n self, msg_id: str, timeout: t.Optional[float] = None, channel: str = "shell"\n ) -> t.Dict[str, t.Any]:\n """Receive and return the reply for a given request"""\n if timeout is not None:\n deadline = time.monotonic() + timeout\n while True:\n if timeout is not None:\n timeout = max(0, deadline - time.monotonic())\n try:\n if channel == "control":\n reply = await self._async_get_control_msg(timeout=timeout)\n else:\n reply = await self._async_get_shell_msg(timeout=timeout)\n except Empty as e:\n msg = "Timeout waiting for reply"\n raise TimeoutError(msg) from e\n if reply["parent_header"].get("msg_id") != msg_id:\n # not my reply, someone may have forgotten to retrieve theirs\n continue\n return reply\n\n async def _stdin_hook_default(self, msg: t.Dict[str, t.Any]) -> None:\n """Handle an input request"""\n content = msg["content"]\n prompt = getpass if content.get("password", False) else input\n\n try:\n raw_data = prompt(content["prompt"]) # type:ignore[operator]\n except EOFError:\n # turn EOFError into EOF character\n raw_data = "\x04"\n except KeyboardInterrupt:\n sys.stdout.write("\n")\n return\n\n # only send stdin reply if there *was not* another request\n # or execution finished while we were reading.\n if not (await self.stdin_channel.msg_ready() or await self.shell_channel.msg_ready()):\n self.input(raw_data)\n\n def _output_hook_default(self, msg: t.Dict[str, t.Any]) -> None:\n """Default hook for redisplaying plain-text output"""\n msg_type = msg["header"]["msg_type"]\n content = msg["content"]\n if msg_type == "stream":\n stream = getattr(sys, content["name"])\n stream.write(content["text"])\n elif msg_type in ("display_data", "execute_result"):\n sys.stdout.write(content["data"].get("text/plain", ""))\n elif msg_type == "error":\n sys.stderr.write("\n".join(content["traceback"]))\n\n def _output_hook_kernel(\n self,\n session: Session,\n socket: zmq.sugar.socket.Socket,\n parent_header: t.Any,\n msg: t.Dict[str, t.Any],\n ) -> None:\n """Output hook when running inside an IPython kernel\n\n adds rich output support.\n """\n msg_type = msg["header"]["msg_type"]\n if msg_type in ("display_data", "execute_result", "error"):\n session.send(socket, msg_type, msg["content"], parent=parent_header)\n else:\n self._output_hook_default(msg)\n\n # --------------------------------------------------------------------------\n # Channel management methods\n # --------------------------------------------------------------------------\n\n def start_channels(\n self,\n shell: bool = True,\n iopub: bool = True,\n stdin: bool = True,\n hb: bool = True,\n control: bool = True,\n ) -> None:\n """Starts the channels for this kernel.\n\n This will create the channels if they do not exist and then start\n them (their activity runs in a thread). If port numbers of 0 are\n being used (random ports) then you must first call\n :meth:`start_kernel`. If the channels have been stopped and you\n call this, :class:`RuntimeError` will be raised.\n """\n if iopub:\n self.iopub_channel.start()\n if shell:\n self.shell_channel.start()\n if stdin:\n self.stdin_channel.start()\n self.allow_stdin = True\n else:\n self.allow_stdin = False\n if hb:\n self.hb_channel.start()\n if control:\n self.control_channel.start()\n\n def stop_channels(self) -> None:\n """Stops all the running channels for this kernel.\n\n This stops their event loops and joins their threads.\n """\n if self.shell_channel.is_alive():\n self.shell_channel.stop()\n if self.iopub_channel.is_alive():\n self.iopub_channel.stop()\n if self.stdin_channel.is_alive():\n self.stdin_channel.stop()\n if self.hb_channel.is_alive():\n self.hb_channel.stop()\n if self.control_channel.is_alive():\n self.control_channel.stop()\n\n @property\n def channels_running(self) -> bool:\n """Are any of the channels created and running?"""\n return (\n (self._shell_channel and self.shell_channel.is_alive())\n or (self._iopub_channel and self.iopub_channel.is_alive())\n or (self._stdin_channel and self.stdin_channel.is_alive())\n or (self._hb_channel and self.hb_channel.is_alive())\n or (self._control_channel and self.control_channel.is_alive())\n )\n\n ioloop = None # Overridden in subclasses that use pyzmq event loop\n\n @property\n def shell_channel(self) -> t.Any:\n """Get the shell channel object for this kernel."""\n if self._shell_channel is None:\n url = self._make_url("shell")\n self.log.debug("connecting shell channel to %s", url)\n socket = self.connect_shell(identity=self.session.bsession)\n self._shell_channel = self.shell_channel_class( # type:ignore[call-arg,abstract]\n socket, self.session, self.ioloop\n )\n return self._shell_channel\n\n @property\n def iopub_channel(self) -> t.Any:\n """Get the iopub channel object for this kernel."""\n if self._iopub_channel is None:\n url = self._make_url("iopub")\n self.log.debug("connecting iopub channel to %s", url)\n socket = self.connect_iopub()\n self._iopub_channel = self.iopub_channel_class( # type:ignore[call-arg,abstract]\n socket, self.session, self.ioloop\n )\n return self._iopub_channel\n\n @property\n def stdin_channel(self) -> t.Any:\n """Get the stdin channel object for this kernel."""\n if self._stdin_channel is None:\n url = self._make_url("stdin")\n self.log.debug("connecting stdin channel to %s", url)\n socket = self.connect_stdin(identity=self.session.bsession)\n self._stdin_channel = self.stdin_channel_class( # type:ignore[call-arg,abstract]\n socket, self.session, self.ioloop\n )\n return self._stdin_channel\n\n @property\n def hb_channel(self) -> t.Any:\n """Get the hb channel object for this kernel."""\n if self._hb_channel is None:\n url = self._make_url("hb")\n self.log.debug("connecting heartbeat channel to %s", url)\n self._hb_channel = self.hb_channel_class( # type:ignore[call-arg,abstract]\n self.context, self.session, url\n )\n return self._hb_channel\n\n @property\n def control_channel(self) -> t.Any:\n """Get the control channel object for this kernel."""\n if self._control_channel is None:\n url = self._make_url("control")\n self.log.debug("connecting control channel to %s", url)\n socket = self.connect_control(identity=self.session.bsession)\n self._control_channel = self.control_channel_class( # type:ignore[call-arg,abstract]\n socket, self.session, self.ioloop\n )\n return self._control_channel\n\n async def _async_is_alive(self) -> bool:\n """Is the kernel process still running?"""\n from .manager import KernelManager\n\n if isinstance(self.parent, KernelManager):\n # This KernelClient was created by a KernelManager,\n # we can ask the parent KernelManager:\n return await self.parent._async_is_alive()\n if self._hb_channel is not None:\n # We don't have access to the KernelManager,\n # so we use the heartbeat.\n return self._hb_channel.is_beating()\n # no heartbeat and not local, we can't tell if it's running,\n # so naively return True\n return True\n\n async def _async_execute_interactive(\n self,\n code: str,\n silent: bool = False,\n store_history: bool = True,\n user_expressions: t.Optional[t.Dict[str, t.Any]] = None,\n allow_stdin: t.Optional[bool] = None,\n stop_on_error: bool = True,\n timeout: t.Optional[float] = None,\n output_hook: t.Optional[t.Callable] = None,\n stdin_hook: t.Optional[t.Callable] = None,\n ) -> t.Dict[str, t.Any]:\n """Execute code in the kernel interactively\n\n Output will be redisplayed, and stdin prompts will be relayed as well.\n If an IPython kernel is detected, rich output will be displayed.\n\n You can pass a custom output_hook callable that will be called\n with every IOPub message that is produced instead of the default redisplay.\n\n .. versionadded:: 5.0\n\n Parameters\n ----------\n code : str\n A string of code in the kernel's language.\n\n silent : bool, optional (default False)\n If set, the kernel will execute the code as quietly possible, and\n will force store_history to be False.\n\n store_history : bool, optional (default True)\n If set, the kernel will store command history. This is forced\n to be False if silent is True.\n\n user_expressions : dict, optional\n A dict mapping names to expressions to be evaluated in the user's\n dict. The expression values are returned as strings formatted using\n :func:`repr`.\n\n allow_stdin : bool, optional (default self.allow_stdin)\n Flag for whether the kernel can send stdin requests to frontends.\n\n Some frontends (e.g. the Notebook) do not support stdin requests.\n If raw_input is called from code executed from such a frontend, a\n StdinNotImplementedError will be raised.\n\n stop_on_error: bool, optional (default True)\n Flag whether to abort the execution queue, if an exception is encountered.\n\n timeout: float or None (default: None)\n Timeout to use when waiting for a reply\n\n output_hook: callable(msg)\n Function to be called with output messages.\n If not specified, output will be redisplayed.\n\n stdin_hook: callable(msg)\n Function or awaitable to be called with stdin_request messages.\n If not specified, input/getpass will be called.\n\n Returns\n -------\n reply: dict\n The reply message for this request\n """\n if not self.iopub_channel.is_alive():\n emsg = "IOPub channel must be running to receive output"\n raise RuntimeError(emsg)\n if allow_stdin is None:\n allow_stdin = self.allow_stdin\n if allow_stdin and not self.stdin_channel.is_alive():\n emsg = "stdin channel must be running to allow input"\n raise RuntimeError(emsg)\n msg_id = await ensure_async(\n self.execute(\n code,\n silent=silent,\n store_history=store_history,\n user_expressions=user_expressions,\n allow_stdin=allow_stdin,\n stop_on_error=stop_on_error,\n )\n )\n if stdin_hook is None:\n stdin_hook = self._stdin_hook_default\n # detect IPython kernel\n if output_hook is None and "IPython" in sys.modules:\n from IPython import get_ipython\n\n ip = get_ipython() # type:ignore[no-untyped-call]\n in_kernel = getattr(ip, "kernel", False)\n if in_kernel:\n output_hook = partial(\n self._output_hook_kernel,\n ip.display_pub.session,\n ip.display_pub.pub_socket,\n ip.display_pub.parent_header,\n )\n if output_hook is None:\n # default: redisplay plain-text outputs\n output_hook = self._output_hook_default\n\n # set deadline based on timeout\n if timeout is not None:\n deadline = time.monotonic() + timeout\n else:\n timeout_ms = None\n\n poller = zmq.asyncio.Poller()\n iopub_socket = self.iopub_channel.socket\n poller.register(iopub_socket, zmq.POLLIN)\n if allow_stdin:\n stdin_socket = self.stdin_channel.socket\n poller.register(stdin_socket, zmq.POLLIN)\n else:\n stdin_socket = None\n\n # wait for output and redisplay it\n while True:\n if timeout is not None:\n timeout = max(0, deadline - time.monotonic())\n timeout_ms = int(1000 * timeout)\n events = dict(await poller.poll(timeout_ms))\n if not events:\n emsg = "Timeout waiting for output"\n raise TimeoutError(emsg)\n if stdin_socket in events:\n req = await ensure_async(self.stdin_channel.get_msg(timeout=0))\n res = stdin_hook(req)\n if inspect.isawaitable(res):\n await res\n continue\n if iopub_socket not in events:\n continue\n\n msg = await ensure_async(self.iopub_channel.get_msg(timeout=0))\n\n if msg["parent_header"].get("msg_id") != msg_id:\n # not from my request\n continue\n output_hook(msg)\n\n # stop on idle\n if (\n msg["header"]["msg_type"] == "status"\n and msg["content"]["execution_state"] == "idle"\n ):\n break\n\n # output is done, get the reply\n if timeout is not None:\n timeout = max(0, deadline - time.monotonic())\n return await self._async_recv_reply(msg_id, timeout=timeout)\n\n # Methods to send specific messages on channels\n def execute(\n self,\n code: str,\n silent: bool = False,\n store_history: bool = True,\n user_expressions: t.Optional[t.Dict[str, t.Any]] = None,\n allow_stdin: t.Optional[bool] = None,\n stop_on_error: bool = True,\n ) -> str:\n """Execute code in the kernel.\n\n Parameters\n ----------\n code : str\n A string of code in the kernel's language.\n\n silent : bool, optional (default False)\n If set, the kernel will execute the code as quietly possible, and\n will force store_history to be False.\n\n store_history : bool, optional (default True)\n If set, the kernel will store command history. This is forced\n to be False if silent is True.\n\n user_expressions : dict, optional\n A dict mapping names to expressions to be evaluated in the user's\n dict. The expression values are returned as strings formatted using\n :func:`repr`.\n\n allow_stdin : bool, optional (default self.allow_stdin)\n Flag for whether the kernel can send stdin requests to frontends.\n\n Some frontends (e.g. the Notebook) do not support stdin requests.\n If raw_input is called from code executed from such a frontend, a\n StdinNotImplementedError will be raised.\n\n stop_on_error: bool, optional (default True)\n Flag whether to abort the execution queue, if an exception is encountered.\n\n Returns\n -------\n The msg_id of the message sent.\n """\n if user_expressions is None:\n user_expressions = {}\n if allow_stdin is None:\n allow_stdin = self.allow_stdin\n\n # Don't waste network traffic if inputs are invalid\n if not isinstance(code, str):\n raise ValueError("code %r must be a string" % code)\n validate_string_dict(user_expressions)\n\n # Create class for content/msg creation. Related to, but possibly\n # not in Session.\n content = {\n "code": code,\n "silent": silent,\n "store_history": store_history,\n "user_expressions": user_expressions,\n "allow_stdin": allow_stdin,\n "stop_on_error": stop_on_error,\n }\n msg = self.session.msg("execute_request", content)\n self.shell_channel.send(msg)\n return msg["header"]["msg_id"]\n\n def complete(self, code: str, cursor_pos: t.Optional[int] = None) -> str:\n """Tab complete text in the kernel's namespace.\n\n Parameters\n ----------\n code : str\n The context in which completion is requested.\n Can be anything between a variable name and an entire cell.\n cursor_pos : int, optional\n The position of the cursor in the block of code where the completion was requested.\n Default: ``len(code)``\n\n Returns\n -------\n The msg_id of the message sent.\n """\n if cursor_pos is None:\n cursor_pos = len(code)\n content = {"code": code, "cursor_pos": cursor_pos}\n msg = self.session.msg("complete_request", content)\n self.shell_channel.send(msg)\n return msg["header"]["msg_id"]\n\n def inspect(self, code: str, cursor_pos: t.Optional[int] = None, detail_level: int = 0) -> str:\n """Get metadata information about an object in the kernel's namespace.\n\n It is up to the kernel to determine the appropriate object to inspect.\n\n Parameters\n ----------\n code : str\n The context in which info is requested.\n Can be anything between a variable name and an entire cell.\n cursor_pos : int, optional\n The position of the cursor in the block of code where the info was requested.\n Default: ``len(code)``\n detail_level : int, optional\n The level of detail for the introspection (0-2)\n\n Returns\n -------\n The msg_id of the message sent.\n """\n if cursor_pos is None:\n cursor_pos = len(code)\n content = {\n "code": code,\n "cursor_pos": cursor_pos,\n "detail_level": detail_level,\n }\n msg = self.session.msg("inspect_request", content)\n self.shell_channel.send(msg)\n return msg["header"]["msg_id"]\n\n def history(\n self,\n raw: bool = True,\n output: bool = False,\n hist_access_type: str = "range",\n **kwargs: t.Any,\n ) -> str:\n """Get entries from the kernel's history list.\n\n Parameters\n ----------\n raw : bool\n If True, return the raw input.\n output : bool\n If True, then return the output as well.\n hist_access_type : str\n 'range' (fill in session, start and stop params), 'tail' (fill in n)\n or 'search' (fill in pattern param).\n\n session : int\n For a range request, the session from which to get lines. Session\n numbers are positive integers; negative ones count back from the\n current session.\n start : int\n The first line number of a history range.\n stop : int\n The final (excluded) line number of a history range.\n\n n : int\n The number of lines of history to get for a tail request.\n\n pattern : str\n The glob-syntax pattern for a search request.\n\n Returns\n -------\n The ID of the message sent.\n """\n if hist_access_type == "range":\n kwargs.setdefault("session", 0)\n kwargs.setdefault("start", 0)\n content = dict(raw=raw, output=output, hist_access_type=hist_access_type, **kwargs)\n msg = self.session.msg("history_request", content)\n self.shell_channel.send(msg)\n return msg["header"]["msg_id"]\n\n def kernel_info(self) -> str:\n """Request kernel info\n\n Returns\n -------\n The msg_id of the message sent\n """\n msg = self.session.msg("kernel_info_request")\n self.shell_channel.send(msg)\n return msg["header"]["msg_id"]\n\n def comm_info(self, target_name: t.Optional[str] = None) -> str:\n """Request comm info\n\n Returns\n -------\n The msg_id of the message sent\n """\n content = {} if target_name is None else {"target_name": target_name}\n msg = self.session.msg("comm_info_request", content)\n self.shell_channel.send(msg)\n return msg["header"]["msg_id"]\n\n def _handle_kernel_info_reply(self, msg: t.Dict[str, t.Any]) -> None:\n """handle kernel info reply\n\n sets protocol adaptation version. This might\n be run from a separate thread.\n """\n adapt_version = int(msg["content"]["protocol_version"].split(".")[0])\n if adapt_version != major_protocol_version:\n self.session.adapt_version = adapt_version\n\n def is_complete(self, code: str) -> str:\n """Ask the kernel whether some code is complete and ready to execute.\n\n Returns\n -------\n The ID of the message sent.\n """\n msg = self.session.msg("is_complete_request", {"code": code})\n self.shell_channel.send(msg)\n return msg["header"]["msg_id"]\n\n def input(self, string: str) -> None:\n """Send a string of raw input to the kernel.\n\n This should only be called in response to the kernel sending an\n ``input_request`` message on the stdin channel.\n\n Returns\n -------\n The ID of the message sent.\n """\n content = {"value": string}\n msg = self.session.msg("input_reply", content)\n self.stdin_channel.send(msg)\n\n def shutdown(self, restart: bool = False) -> str:\n """Request an immediate kernel shutdown on the control channel.\n\n Upon receipt of the (empty) reply, client code can safely assume that\n the kernel has shut down and it's safe to forcefully terminate it if\n it's still alive.\n\n The kernel will send the reply via a function registered with Python's\n atexit module, ensuring it's truly done as the kernel is done with all\n normal operation.\n\n Returns\n -------\n The msg_id of the message sent\n """\n # Send quit message to kernel. Once we implement kernel-side setattr,\n # this should probably be done that way, but for now this will do.\n msg = self.session.msg("shutdown_request", {"restart": restart})\n self.control_channel.send(msg)\n return msg["header"]["msg_id"]\n\n\nKernelClientABC.register(KernelClient)\n
.venv\Lib\site-packages\jupyter_client\client.py
client.py
Python
30,848
0.95
0.206771
0.07355
react-lib
916
2024-01-06T10:48:51.956944
GPL-3.0
false
770579fe44bea44cf65bb163a610de4c
"""Abstract base class for kernel clients"""\n# -----------------------------------------------------------------------------\n# Copyright (c) The Jupyter Development Team\n#\n# Distributed under the terms of the BSD License. The full license is in\n# the file COPYING, distributed as part of this software.\n# -----------------------------------------------------------------------------\n# -----------------------------------------------------------------------------\n# Imports\n# -----------------------------------------------------------------------------\nfrom __future__ import annotations\n\nimport abc\nfrom typing import TYPE_CHECKING, Any\n\nif TYPE_CHECKING:\n from .channelsabc import ChannelABC\n\n# -----------------------------------------------------------------------------\n# Main kernel client class\n# -----------------------------------------------------------------------------\n\n\nclass KernelClientABC(metaclass=abc.ABCMeta):\n """KernelManager ABC.\n\n The docstrings for this class can be found in the base implementation:\n\n `jupyter_client.client.KernelClient`\n """\n\n @abc.abstractproperty\n def kernel(self) -> Any:\n pass\n\n @abc.abstractproperty\n def shell_channel_class(self) -> type[ChannelABC]:\n pass\n\n @abc.abstractproperty\n def iopub_channel_class(self) -> type[ChannelABC]:\n pass\n\n @abc.abstractproperty\n def hb_channel_class(self) -> type[ChannelABC]:\n pass\n\n @abc.abstractproperty\n def stdin_channel_class(self) -> type[ChannelABC]:\n pass\n\n @abc.abstractproperty\n def control_channel_class(self) -> type[ChannelABC]:\n pass\n\n # --------------------------------------------------------------------------\n # Channel management methods\n # --------------------------------------------------------------------------\n\n @abc.abstractmethod\n def start_channels(\n self,\n shell: bool = True,\n iopub: bool = True,\n stdin: bool = True,\n hb: bool = True,\n control: bool = True,\n ) -> None:\n """Start the channels for the client."""\n pass\n\n @abc.abstractmethod\n def stop_channels(self) -> None:\n """Stop the channels for the client."""\n pass\n\n @abc.abstractproperty\n def channels_running(self) -> bool:\n """Get whether the channels are running."""\n pass\n\n @abc.abstractproperty\n def shell_channel(self) -> ChannelABC:\n pass\n\n @abc.abstractproperty\n def iopub_channel(self) -> ChannelABC:\n pass\n\n @abc.abstractproperty\n def stdin_channel(self) -> ChannelABC:\n pass\n\n @abc.abstractproperty\n def hb_channel(self) -> ChannelABC:\n pass\n\n @abc.abstractproperty\n def control_channel(self) -> ChannelABC:\n pass\n
.venv\Lib\site-packages\jupyter_client\clientabc.py
clientabc.py
Python
2,776
0.95
0.23
0.192308
python-kit
323
2025-04-13T03:17:19.338307
GPL-3.0
false
5e730640ea09a34b2b2b16b25d36313c
"""Utilities for connecting to jupyter kernels\n\nThe :class:`ConnectionFileMixin` class in this module encapsulates the logic\nrelated to writing and reading connections files.\n"""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport errno\nimport glob\nimport json\nimport os\nimport socket\nimport stat\nimport tempfile\nimport warnings\nfrom getpass import getpass\nfrom typing import TYPE_CHECKING, Any, Dict, Union, cast\n\nimport zmq\nfrom jupyter_core.paths import jupyter_data_dir, jupyter_runtime_dir, secure_write\nfrom traitlets import Bool, CaselessStrEnum, Instance, Integer, Type, Unicode, observe\nfrom traitlets.config import LoggingConfigurable, SingletonConfigurable\n\nfrom .localinterfaces import localhost\nfrom .utils import _filefind\n\nif TYPE_CHECKING:\n from jupyter_client import BlockingKernelClient\n\n from .session import Session\n\n# Define custom type for kernel connection info\nKernelConnectionInfo = Dict[str, Union[int, str, bytes]]\n\n\ndef write_connection_file(\n fname: str | None = None,\n shell_port: int = 0,\n iopub_port: int = 0,\n stdin_port: int = 0,\n hb_port: int = 0,\n control_port: int = 0,\n ip: str = "",\n key: bytes = b"",\n transport: str = "tcp",\n signature_scheme: str = "hmac-sha256",\n kernel_name: str = "",\n **kwargs: Any,\n) -> tuple[str, KernelConnectionInfo]:\n """Generates a JSON config file, including the selection of random ports.\n\n Parameters\n ----------\n\n fname : unicode\n The path to the file to write\n\n shell_port : int, optional\n The port to use for ROUTER (shell) channel.\n\n iopub_port : int, optional\n The port to use for the SUB channel.\n\n stdin_port : int, optional\n The port to use for the ROUTER (raw input) channel.\n\n control_port : int, optional\n The port to use for the ROUTER (control) channel.\n\n hb_port : int, optional\n The port to use for the heartbeat REP channel.\n\n ip : str, optional\n The ip address the kernel will bind to.\n\n key : str, optional\n The Session key used for message authentication.\n\n signature_scheme : str, optional\n The scheme used for message authentication.\n This has the form 'digest-hash', where 'digest'\n is the scheme used for digests, and 'hash' is the name of the hash function\n used by the digest scheme.\n Currently, 'hmac' is the only supported digest scheme,\n and 'sha256' is the default hash function.\n\n kernel_name : str, optional\n The name of the kernel currently connected to.\n """\n if not ip:\n ip = localhost()\n # default to temporary connector file\n if not fname:\n fd, fname = tempfile.mkstemp(".json")\n os.close(fd)\n\n # Find open ports as necessary.\n\n ports: list[int] = []\n sockets: list[socket.socket] = []\n ports_needed = (\n int(shell_port <= 0)\n + int(iopub_port <= 0)\n + int(stdin_port <= 0)\n + int(control_port <= 0)\n + int(hb_port <= 0)\n )\n if transport == "tcp":\n for _ in range(ports_needed):\n sock = socket.socket()\n # struct.pack('ii', (0,0)) is 8 null bytes\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, b"\0" * 8)\n sock.bind((ip, 0))\n sockets.append(sock)\n for sock in sockets:\n port = sock.getsockname()[1]\n sock.close()\n ports.append(port)\n else:\n N = 1\n for _ in range(ports_needed):\n while os.path.exists(f"{ip}-{N!s}"):\n N += 1\n ports.append(N)\n N += 1\n if shell_port <= 0:\n shell_port = ports.pop(0)\n if iopub_port <= 0:\n iopub_port = ports.pop(0)\n if stdin_port <= 0:\n stdin_port = ports.pop(0)\n if control_port <= 0:\n control_port = ports.pop(0)\n if hb_port <= 0:\n hb_port = ports.pop(0)\n\n cfg: KernelConnectionInfo = {\n "shell_port": shell_port,\n "iopub_port": iopub_port,\n "stdin_port": stdin_port,\n "control_port": control_port,\n "hb_port": hb_port,\n }\n cfg["ip"] = ip\n cfg["key"] = key.decode()\n cfg["transport"] = transport\n cfg["signature_scheme"] = signature_scheme\n cfg["kernel_name"] = kernel_name\n cfg.update(kwargs)\n\n # Only ever write this file as user read/writeable\n # This would otherwise introduce a vulnerability as a file has secrets\n # which would let others execute arbitrary code as you\n with secure_write(fname) as f:\n f.write(json.dumps(cfg, indent=2))\n\n if hasattr(stat, "S_ISVTX"):\n # set the sticky bit on the parent directory of the file\n # to ensure only owner can remove it\n runtime_dir = os.path.dirname(fname)\n if runtime_dir:\n permissions = os.stat(runtime_dir).st_mode\n new_permissions = permissions | stat.S_ISVTX\n if new_permissions != permissions:\n try:\n os.chmod(runtime_dir, new_permissions)\n except OSError as e:\n if e.errno == errno.EPERM:\n # suppress permission errors setting sticky bit on runtime_dir,\n # which we may not own.\n pass\n return fname, cfg\n\n\ndef find_connection_file(\n filename: str = "kernel-*.json",\n path: str | list[str] | None = None,\n profile: str | None = None,\n) -> str:\n """find a connection file, and return its absolute path.\n\n The current working directory and optional search path\n will be searched for the file if it is not given by absolute path.\n\n If the argument does not match an existing file, it will be interpreted as a\n fileglob, and the matching file in the profile's security dir with\n the latest access time will be used.\n\n Parameters\n ----------\n filename : str\n The connection file or fileglob to search for.\n path : str or list of strs[optional]\n Paths in which to search for connection files.\n\n Returns\n -------\n str : The absolute path of the connection file.\n """\n if profile is not None:\n warnings.warn(\n "Jupyter has no profiles. profile=%s has been ignored." % profile, stacklevel=2\n )\n if path is None:\n path = [".", jupyter_runtime_dir()]\n if isinstance(path, str):\n path = [path]\n\n try:\n # first, try explicit name\n return _filefind(filename, path)\n except OSError:\n pass\n\n # not found by full name\n\n if "*" in filename:\n # given as a glob already\n pat = filename\n else:\n # accept any substring match\n pat = "*%s*" % filename\n\n matches = []\n for p in path:\n matches.extend(glob.glob(os.path.join(p, pat)))\n\n matches = [os.path.abspath(m) for m in matches]\n if not matches:\n msg = f"Could not find {filename!r} in {path!r}"\n raise OSError(msg)\n elif len(matches) == 1:\n return matches[0]\n else:\n # get most recent match, by access time:\n return sorted(matches, key=lambda f: os.stat(f).st_atime)[-1]\n\n\ndef tunnel_to_kernel(\n connection_info: str | KernelConnectionInfo,\n sshserver: str,\n sshkey: str | None = None,\n) -> tuple[Any, ...]:\n """tunnel connections to a kernel via ssh\n\n This will open five SSH tunnels from localhost on this machine to the\n ports associated with the kernel. They can be either direct\n localhost-localhost tunnels, or if an intermediate server is necessary,\n the kernel must be listening on a public IP.\n\n Parameters\n ----------\n connection_info : dict or str (path)\n Either a connection dict, or the path to a JSON connection file\n sshserver : str\n The ssh sever to use to tunnel to the kernel. Can be a full\n `user@server:port` string. ssh config aliases are respected.\n sshkey : str [optional]\n Path to file containing ssh key to use for authentication.\n Only necessary if your ssh config does not already associate\n a keyfile with the host.\n\n Returns\n -------\n\n (shell, iopub, stdin, hb, control) : ints\n The five ports on localhost that have been forwarded to the kernel.\n """\n from .ssh import tunnel\n\n if isinstance(connection_info, str):\n # it's a path, unpack it\n with open(connection_info) as f:\n connection_info = json.loads(f.read())\n\n cf = cast(Dict[str, Any], connection_info)\n\n lports = tunnel.select_random_ports(5)\n rports = (\n cf["shell_port"],\n cf["iopub_port"],\n cf["stdin_port"],\n cf["hb_port"],\n cf["control_port"],\n )\n\n remote_ip = cf["ip"]\n\n if tunnel.try_passwordless_ssh(sshserver, sshkey):\n password: bool | str = False\n else:\n password = getpass("SSH Password for %s: " % sshserver)\n\n for lp, rp in zip(lports, rports):\n tunnel.ssh_tunnel(lp, rp, sshserver, remote_ip, sshkey, password)\n\n return tuple(lports)\n\n\n# -----------------------------------------------------------------------------\n# Mixin for classes that work with connection files\n# -----------------------------------------------------------------------------\n\nchannel_socket_types = {\n "hb": zmq.REQ,\n "shell": zmq.DEALER,\n "iopub": zmq.SUB,\n "stdin": zmq.DEALER,\n "control": zmq.DEALER,\n}\n\nport_names = ["%s_port" % channel for channel in ("shell", "stdin", "iopub", "hb", "control")]\n\n\nclass ConnectionFileMixin(LoggingConfigurable):\n """Mixin for configurable classes that work with connection files"""\n\n data_dir: str | Unicode = Unicode()\n\n def _data_dir_default(self) -> str:\n return jupyter_data_dir()\n\n # The addresses for the communication channels\n connection_file = Unicode(\n "",\n config=True,\n help="""JSON file in which to store connection info [default: kernel-<pid>.json]\n\n This file will contain the IP, ports, and authentication key needed to connect\n clients to this kernel. By default, this file will be created in the security dir\n of the current profile, but can be specified by absolute path.\n """,\n )\n _connection_file_written = Bool(False)\n\n transport = CaselessStrEnum(["tcp", "ipc"], default_value="tcp", config=True)\n kernel_name: str | Unicode = Unicode()\n\n context = Instance(zmq.Context)\n\n ip = Unicode(\n config=True,\n help="""Set the kernel\'s IP address [default localhost].\n If the IP address is something other than localhost, then\n Consoles on other machines will be able to connect\n to the Kernel, so be careful!""",\n )\n\n def _ip_default(self) -> str:\n if self.transport == "ipc":\n if self.connection_file:\n return os.path.splitext(self.connection_file)[0] + "-ipc"\n else:\n return "kernel-ipc"\n else:\n return localhost()\n\n @observe("ip")\n def _ip_changed(self, change: Any) -> None:\n if change["new"] == "*":\n self.ip = "0.0.0.0" # noqa\n\n # protected traits\n\n hb_port = Integer(0, config=True, help="set the heartbeat port [default: random]")\n shell_port = Integer(0, config=True, help="set the shell (ROUTER) port [default: random]")\n iopub_port = Integer(0, config=True, help="set the iopub (PUB) port [default: random]")\n stdin_port = Integer(0, config=True, help="set the stdin (ROUTER) port [default: random]")\n control_port = Integer(0, config=True, help="set the control (ROUTER) port [default: random]")\n\n # names of the ports with random assignment\n _random_port_names: list[str] | None = None\n\n @property\n def ports(self) -> list[int]:\n return [getattr(self, name) for name in port_names]\n\n # The Session to use for communication with the kernel.\n session = Instance("jupyter_client.session.Session")\n\n def _session_default(self) -> Session:\n from .session import Session\n\n return Session(parent=self)\n\n # --------------------------------------------------------------------------\n # Connection and ipc file management\n # --------------------------------------------------------------------------\n\n def get_connection_info(self, session: bool = False) -> KernelConnectionInfo:\n """Return the connection info as a dict\n\n Parameters\n ----------\n session : bool [default: False]\n If True, return our session object will be included in the connection info.\n If False (default), the configuration parameters of our session object will be included,\n rather than the session object itself.\n\n Returns\n -------\n connect_info : dict\n dictionary of connection information.\n """\n info = {\n "transport": self.transport,\n "ip": self.ip,\n "shell_port": self.shell_port,\n "iopub_port": self.iopub_port,\n "stdin_port": self.stdin_port,\n "hb_port": self.hb_port,\n "control_port": self.control_port,\n }\n if session:\n # add *clone* of my session,\n # so that state such as digest_history is not shared.\n info["session"] = self.session.clone()\n else:\n # add session info\n info.update(\n {\n "signature_scheme": self.session.signature_scheme,\n "key": self.session.key,\n }\n )\n return info\n\n # factory for blocking clients\n blocking_class = Type(klass=object, default_value="jupyter_client.BlockingKernelClient")\n\n def blocking_client(self) -> BlockingKernelClient:\n """Make a blocking client connected to my kernel"""\n info = self.get_connection_info()\n bc = self.blocking_class(parent=self) # type:ignore[operator]\n bc.load_connection_info(info)\n return bc\n\n def cleanup_connection_file(self) -> None:\n """Cleanup connection file *if we wrote it*\n\n Will not raise if the connection file was already removed somehow.\n """\n if self._connection_file_written:\n # cleanup connection files on full shutdown of kernel we started\n self._connection_file_written = False\n try:\n os.remove(self.connection_file)\n except (OSError, AttributeError):\n pass\n\n def cleanup_ipc_files(self) -> None:\n """Cleanup ipc files if we wrote them."""\n if self.transport != "ipc":\n return\n for port in self.ports:\n ipcfile = "%s-%i" % (self.ip, port)\n try:\n os.remove(ipcfile)\n except OSError:\n pass\n\n def _record_random_port_names(self) -> None:\n """Records which of the ports are randomly assigned.\n\n Records on first invocation, if the transport is tcp.\n Does nothing on later invocations."""\n\n if self.transport != "tcp":\n return\n if self._random_port_names is not None:\n return\n\n self._random_port_names = []\n for name in port_names:\n if getattr(self, name) <= 0:\n self._random_port_names.append(name)\n\n def cleanup_random_ports(self) -> None:\n """Forgets randomly assigned port numbers and cleans up the connection file.\n\n Does nothing if no port numbers have been randomly assigned.\n In particular, does nothing unless the transport is tcp.\n """\n\n if not self._random_port_names:\n return\n\n for name in self._random_port_names:\n setattr(self, name, 0)\n\n self.cleanup_connection_file()\n\n def write_connection_file(self, **kwargs: Any) -> None:\n """Write connection info to JSON dict in self.connection_file."""\n if self._connection_file_written and os.path.exists(self.connection_file):\n return\n\n self.connection_file, cfg = write_connection_file(\n self.connection_file,\n transport=self.transport,\n ip=self.ip,\n key=self.session.key,\n stdin_port=self.stdin_port,\n iopub_port=self.iopub_port,\n shell_port=self.shell_port,\n hb_port=self.hb_port,\n control_port=self.control_port,\n signature_scheme=self.session.signature_scheme,\n kernel_name=self.kernel_name,\n **kwargs,\n )\n # write_connection_file also sets default ports:\n self._record_random_port_names()\n for name in port_names:\n setattr(self, name, cfg[name])\n\n self._connection_file_written = True\n\n def load_connection_file(self, connection_file: str | None = None) -> None:\n """Load connection info from JSON dict in self.connection_file.\n\n Parameters\n ----------\n connection_file: unicode, optional\n Path to connection file to load.\n If unspecified, use self.connection_file\n """\n if connection_file is None:\n connection_file = self.connection_file\n self.log.debug("Loading connection file %s", connection_file)\n with open(connection_file) as f:\n info = json.load(f)\n self.load_connection_info(info)\n\n def load_connection_info(self, info: KernelConnectionInfo) -> None:\n """Load connection info from a dict containing connection info.\n\n Typically this data comes from a connection file\n and is called by load_connection_file.\n\n Parameters\n ----------\n info: dict\n Dictionary containing connection_info.\n See the connection_file spec for details.\n """\n self.transport = info.get("transport", self.transport)\n self.ip = info.get("ip", self._ip_default()) # type:ignore[assignment]\n\n self._record_random_port_names()\n for name in port_names:\n if getattr(self, name) == 0 and name in info:\n # not overridden by config or cl_args\n setattr(self, name, info[name])\n\n if "key" in info:\n key = info["key"]\n if isinstance(key, str):\n key = key.encode()\n assert isinstance(key, bytes)\n\n self.session.key = key\n if "signature_scheme" in info:\n self.session.signature_scheme = info["signature_scheme"]\n\n def _reconcile_connection_info(self, info: KernelConnectionInfo) -> None:\n """Reconciles the connection information returned from the Provisioner.\n\n Because some provisioners (like derivations of LocalProvisioner) may have already\n written the connection file, this method needs to ensure that, if the connection\n file exists, its contents match that of what was returned by the provisioner. If\n the file does exist and its contents do not match, the file will be replaced with\n the provisioner information (which is considered the truth).\n\n If the file does not exist, the connection information in 'info' is loaded into the\n KernelManager and written to the file.\n """\n # Prevent over-writing a file that has already been written with the same\n # info. This is to prevent a race condition where the process has\n # already been launched but has not yet read the connection file - as is\n # the case with LocalProvisioners.\n file_exists: bool = False\n if os.path.exists(self.connection_file):\n with open(self.connection_file) as f:\n file_info = json.load(f)\n # Prior to the following comparison, we need to adjust the value of "key" to\n # be bytes, otherwise the comparison below will fail.\n file_info["key"] = file_info["key"].encode()\n if not self._equal_connections(info, file_info):\n os.remove(self.connection_file) # Contents mismatch - remove the file\n self._connection_file_written = False\n else:\n file_exists = True\n\n if not file_exists:\n # Load the connection info and write out file, clearing existing\n # port-based attributes so they will be reloaded\n for name in port_names:\n setattr(self, name, 0)\n self.load_connection_info(info)\n self.write_connection_file()\n\n # Ensure what is in KernelManager is what we expect.\n km_info = self.get_connection_info()\n if not self._equal_connections(info, km_info):\n msg = (\n "KernelManager's connection information already exists and does not match "\n "the expected values returned from provisioner!"\n )\n raise ValueError(msg)\n\n @staticmethod\n def _equal_connections(conn1: KernelConnectionInfo, conn2: KernelConnectionInfo) -> bool:\n """Compares pertinent keys of connection info data. Returns True if equivalent, False otherwise."""\n\n pertinent_keys = [\n "key",\n "ip",\n "stdin_port",\n "iopub_port",\n "shell_port",\n "control_port",\n "hb_port",\n "transport",\n "signature_scheme",\n ]\n\n return all(conn1.get(key) == conn2.get(key) for key in pertinent_keys)\n\n # --------------------------------------------------------------------------\n # Creating connected sockets\n # --------------------------------------------------------------------------\n\n def _make_url(self, channel: str) -> str:\n """Make a ZeroMQ URL for a given channel."""\n transport = self.transport\n ip = self.ip\n port = getattr(self, "%s_port" % channel)\n\n if transport == "tcp":\n return "tcp://%s:%i" % (ip, port)\n else:\n return f"{transport}://{ip}-{port}"\n\n def _create_connected_socket(\n self, channel: str, identity: bytes | None = None\n ) -> zmq.sugar.socket.Socket:\n """Create a zmq Socket and connect it to the kernel."""\n url = self._make_url(channel)\n socket_type = channel_socket_types[channel]\n self.log.debug("Connecting to: %s", url)\n sock = self.context.socket(socket_type)\n # set linger to 1s to prevent hangs at exit\n sock.linger = 1000\n if identity:\n sock.identity = identity\n sock.connect(url)\n return sock\n\n def connect_iopub(self, identity: bytes | None = None) -> zmq.sugar.socket.Socket:\n """return zmq Socket connected to the IOPub channel"""\n sock = self._create_connected_socket("iopub", identity=identity)\n sock.setsockopt(zmq.SUBSCRIBE, b"")\n return sock\n\n def connect_shell(self, identity: bytes | None = None) -> zmq.sugar.socket.Socket:\n """return zmq Socket connected to the Shell channel"""\n return self._create_connected_socket("shell", identity=identity)\n\n def connect_stdin(self, identity: bytes | None = None) -> zmq.sugar.socket.Socket:\n """return zmq Socket connected to the StdIn channel"""\n return self._create_connected_socket("stdin", identity=identity)\n\n def connect_hb(self, identity: bytes | None = None) -> zmq.sugar.socket.Socket:\n """return zmq Socket connected to the Heartbeat channel"""\n return self._create_connected_socket("hb", identity=identity)\n\n def connect_control(self, identity: bytes | None = None) -> zmq.sugar.socket.Socket:\n """return zmq Socket connected to the Control channel"""\n return self._create_connected_socket("control", identity=identity)\n\n\nclass LocalPortCache(SingletonConfigurable):\n """\n Used to keep track of local ports in order to prevent race conditions that\n can occur between port acquisition and usage by the kernel. All locally-\n provisioned kernels should use this mechanism to limit the possibility of\n race conditions. Note that this does not preclude other applications from\n acquiring a cached but unused port, thereby re-introducing the issue this\n class is attempting to resolve (minimize).\n See: https://github.com/jupyter/jupyter_client/issues/487\n """\n\n def __init__(self, **kwargs: Any) -> None:\n super().__init__(**kwargs)\n self.currently_used_ports: set[int] = set()\n\n def find_available_port(self, ip: str) -> int:\n while True:\n tmp_sock = socket.socket()\n tmp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, b"\0" * 8)\n tmp_sock.bind((ip, 0))\n port = tmp_sock.getsockname()[1]\n tmp_sock.close()\n\n # This is a workaround for https://github.com/jupyter/jupyter_client/issues/487\n # We prevent two kernels to have the same ports.\n if port not in self.currently_used_ports:\n self.currently_used_ports.add(port)\n return port\n\n def return_port(self, port: int) -> None:\n if port in self.currently_used_ports: # Tolerate uncached ports\n self.currently_used_ports.remove(port)\n\n\n__all__ = [\n "write_connection_file",\n "find_connection_file",\n "tunnel_to_kernel",\n "KernelConnectionInfo",\n "LocalPortCache",\n]\n
.venv\Lib\site-packages\jupyter_client\connect.py
connect.py
Python
25,340
0.95
0.186207
0.088333
vue-tools
874
2023-11-12T19:44:01.539876
MIT
false
42d231133ad090b19aceca1d190a4f73
""" A minimal application base mixin for all ZMQ based IPython frontends.\n\nThis is not a complete console app, as subprocess will not be able to receive\ninput, there is no real readline support, among other limitations. This is a\nrefactoring of what used to be the IPython/qt/console/qtconsoleapp.py\n"""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nimport atexit\nimport os\nimport signal\nimport sys\nimport typing as t\nimport uuid\nimport warnings\n\nfrom jupyter_core.application import base_aliases, base_flags\nfrom traitlets import CBool, CUnicode, Dict, List, Type, Unicode\nfrom traitlets.config.application import boolean_flag\n\nfrom . import KernelManager, connect, find_connection_file, tunnel_to_kernel\nfrom .blocking import BlockingKernelClient\nfrom .connect import KernelConnectionInfo\nfrom .kernelspec import NoSuchKernel\nfrom .localinterfaces import localhost\nfrom .restarter import KernelRestarter\nfrom .session import Session\nfrom .utils import _filefind\n\nConnectionFileMixin = connect.ConnectionFileMixin\n\n# -----------------------------------------------------------------------------\n# Aliases and Flags\n# -----------------------------------------------------------------------------\n\nflags: dict = {}\nflags.update(base_flags)\n# the flags that are specific to the frontend\n# these must be scrubbed before being passed to the kernel,\n# or it will raise an error on unrecognized flags\napp_flags: dict = {\n "existing": (\n {"JupyterConsoleApp": {"existing": "kernel*.json"}},\n "Connect to an existing kernel. If no argument specified, guess most recent",\n ),\n}\napp_flags.update(\n boolean_flag(\n "confirm-exit",\n "JupyterConsoleApp.confirm_exit",\n """Set to display confirmation dialog on exit. You can always use 'exit' or\n 'quit', to force a direct exit without any confirmation. This can also\n be set in the config file by setting\n `c.JupyterConsoleApp.confirm_exit`.\n """,\n """Don't prompt the user when exiting. This will terminate the kernel\n if it is owned by the frontend, and leave it alive if it is external.\n This can also be set in the config file by setting\n `c.JupyterConsoleApp.confirm_exit`.\n """,\n )\n)\nflags.update(app_flags)\n\naliases: dict = {}\naliases.update(base_aliases)\n\n# also scrub aliases from the frontend\napp_aliases: dict = {\n "ip": "JupyterConsoleApp.ip",\n "transport": "JupyterConsoleApp.transport",\n "hb": "JupyterConsoleApp.hb_port",\n "shell": "JupyterConsoleApp.shell_port",\n "iopub": "JupyterConsoleApp.iopub_port",\n "stdin": "JupyterConsoleApp.stdin_port",\n "control": "JupyterConsoleApp.control_port",\n "existing": "JupyterConsoleApp.existing",\n "f": "JupyterConsoleApp.connection_file",\n "kernel": "JupyterConsoleApp.kernel_name",\n "ssh": "JupyterConsoleApp.sshserver",\n "sshkey": "JupyterConsoleApp.sshkey",\n}\naliases.update(app_aliases)\n\n# -----------------------------------------------------------------------------\n# Classes\n# -----------------------------------------------------------------------------\n\nclasses: t.List[t.Type[t.Any]] = [KernelManager, KernelRestarter, Session]\n\n\nclass JupyterConsoleApp(ConnectionFileMixin):\n """The base Jupyter console application."""\n\n name: t.Union[str, Unicode] = "jupyter-console-mixin"\n\n description: t.Union[str, Unicode] = """\n The Jupyter Console Mixin.\n\n This class contains the common portions of console client (QtConsole,\n ZMQ-based terminal console, etc). It is not a full console, in that\n launched terminal subprocesses will not be able to accept input.\n\n The Console using this mixing supports various extra features beyond\n the single-process Terminal IPython shell, such as connecting to\n existing kernel, via:\n\n jupyter console <appname> --existing\n\n as well as tunnel via SSH\n\n """\n\n classes = classes\n flags = Dict(flags)\n aliases = Dict(aliases)\n kernel_manager_class = Type(\n default_value=KernelManager,\n config=True,\n help="The kernel manager class to use.",\n )\n kernel_client_class = BlockingKernelClient\n\n kernel_argv = List(Unicode())\n\n # connection info:\n\n sshserver = Unicode("", config=True, help="""The SSH server to use to connect to the kernel.""")\n sshkey = Unicode(\n "",\n config=True,\n help="""Path to the ssh key to use for logging in to the ssh server.""",\n )\n\n def _connection_file_default(self) -> str:\n return "kernel-%i.json" % os.getpid()\n\n existing = CUnicode("", config=True, help="""Connect to an already running kernel""")\n\n kernel_name = Unicode(\n "python", config=True, help="""The name of the default kernel to start."""\n )\n\n confirm_exit = CBool(\n True,\n config=True,\n help="""\n Set to display confirmation dialog on exit. You can always use 'exit' or 'quit',\n to force a direct exit without any confirmation.""",\n )\n\n def build_kernel_argv(self, argv: object = None) -> None:\n """build argv to be passed to kernel subprocess\n\n Override in subclasses if any args should be passed to the kernel\n """\n self.kernel_argv = self.extra_args # type:ignore[attr-defined]\n\n def init_connection_file(self) -> None:\n """find the connection file, and load the info if found.\n\n The current working directory and the current profile's security\n directory will be searched for the file if it is not given by\n absolute path.\n\n When attempting to connect to an existing kernel and the `--existing`\n argument does not match an existing file, it will be interpreted as a\n fileglob, and the matching file in the current profile's security dir\n with the latest access time will be used.\n\n After this method is called, self.connection_file contains the *full path*\n to the connection file, never just its name.\n """\n runtime_dir = self.runtime_dir # type:ignore[attr-defined]\n if self.existing:\n try:\n cf = find_connection_file(self.existing, [".", runtime_dir])\n except Exception:\n self.log.critical(\n "Could not find existing kernel connection file %s", self.existing\n )\n self.exit(1) # type:ignore[attr-defined]\n self.log.debug("Connecting to existing kernel: %s", cf)\n self.connection_file = cf\n else:\n # not existing, check if we are going to write the file\n # and ensure that self.connection_file is a full path, not just the shortname\n try:\n cf = find_connection_file(self.connection_file, [runtime_dir])\n except Exception:\n # file might not exist\n if self.connection_file == os.path.basename(self.connection_file):\n # just shortname, put it in security dir\n cf = os.path.join(runtime_dir, self.connection_file)\n else:\n cf = self.connection_file\n self.connection_file = cf\n try:\n self.connection_file = _filefind(self.connection_file, [".", runtime_dir])\n except OSError:\n self.log.debug("Connection File not found: %s", self.connection_file)\n return\n\n # should load_connection_file only be used for existing?\n # as it is now, this allows reusing ports if an existing\n # file is requested\n try:\n self.load_connection_file()\n except Exception:\n self.log.error(\n "Failed to load connection file: %r",\n self.connection_file,\n exc_info=True,\n )\n self.exit(1) # type:ignore[attr-defined]\n\n def init_ssh(self) -> None:\n """set up ssh tunnels, if needed."""\n if not self.existing or (not self.sshserver and not self.sshkey):\n return\n self.load_connection_file()\n\n transport = self.transport\n ip = self.ip\n\n if transport != "tcp":\n self.log.error("Can only use ssh tunnels with TCP sockets, not %s", transport)\n sys.exit(-1)\n\n if self.sshkey and not self.sshserver:\n # specifying just the key implies that we are connecting directly\n self.sshserver = ip\n ip = localhost()\n\n # build connection dict for tunnels:\n info: KernelConnectionInfo = {\n "ip": ip,\n "shell_port": self.shell_port,\n "iopub_port": self.iopub_port,\n "stdin_port": self.stdin_port,\n "hb_port": self.hb_port,\n "control_port": self.control_port,\n }\n\n self.log.info("Forwarding connections to %s via %s", ip, self.sshserver)\n\n # tunnels return a new set of ports, which will be on localhost:\n self.ip = localhost()\n try:\n newports = tunnel_to_kernel(info, self.sshserver, self.sshkey)\n except: # noqa\n # even catch KeyboardInterrupt\n self.log.error("Could not setup tunnels", exc_info=True)\n self.exit(1) # type:ignore[attr-defined]\n\n (\n self.shell_port,\n self.iopub_port,\n self.stdin_port,\n self.hb_port,\n self.control_port,\n ) = newports\n\n cf = self.connection_file\n root, ext = os.path.splitext(cf)\n self.connection_file = root + "-ssh" + ext\n self.write_connection_file() # write the new connection file\n self.log.info("To connect another client via this tunnel, use:")\n self.log.info("--existing %s", os.path.basename(self.connection_file))\n\n def _new_connection_file(self) -> str:\n cf = ""\n while not cf:\n # we don't need a 128b id to distinguish kernels, use more readable\n # 48b node segment (12 hex chars). Users running more than 32k simultaneous\n # kernels can subclass.\n ident = str(uuid.uuid4()).split("-")[-1]\n runtime_dir = self.runtime_dir # type:ignore[attr-defined]\n cf = os.path.join(runtime_dir, "kernel-%s.json" % ident)\n # only keep if it's actually new. Protect against unlikely collision\n # in 48b random search space\n cf = cf if not os.path.exists(cf) else ""\n return cf\n\n def init_kernel_manager(self) -> None:\n """Initialize the kernel manager."""\n # Don't let Qt or ZMQ swallow KeyboardInterupts.\n if self.existing:\n self.kernel_manager = None\n return\n signal.signal(signal.SIGINT, signal.SIG_DFL)\n\n # Create a KernelManager and start a kernel.\n try:\n self.kernel_manager = self.kernel_manager_class(\n ip=self.ip,\n session=self.session,\n transport=self.transport,\n shell_port=self.shell_port,\n iopub_port=self.iopub_port,\n stdin_port=self.stdin_port,\n hb_port=self.hb_port,\n control_port=self.control_port,\n connection_file=self.connection_file,\n kernel_name=self.kernel_name,\n parent=self,\n data_dir=self.data_dir,\n )\n except NoSuchKernel:\n self.log.critical("Could not find kernel %s", self.kernel_name)\n self.exit(1) # type:ignore[attr-defined]\n\n self.kernel_manager = t.cast(KernelManager, self.kernel_manager)\n self.kernel_manager.client_factory = self.kernel_client_class\n kwargs = {}\n kwargs["extra_arguments"] = self.kernel_argv\n self.kernel_manager.start_kernel(**kwargs)\n atexit.register(self.kernel_manager.cleanup_ipc_files)\n\n if self.sshserver:\n # ssh, write new connection file\n self.kernel_manager.write_connection_file()\n\n # in case KM defaults / ssh writing changes things:\n km = self.kernel_manager\n self.shell_port = km.shell_port\n self.iopub_port = km.iopub_port\n self.stdin_port = km.stdin_port\n self.hb_port = km.hb_port\n self.control_port = km.control_port\n self.connection_file = km.connection_file\n\n atexit.register(self.kernel_manager.cleanup_connection_file)\n\n def init_kernel_client(self) -> None:\n """Initialize the kernel client."""\n if self.kernel_manager is not None:\n self.kernel_client = self.kernel_manager.client()\n else:\n self.kernel_client = self.kernel_client_class(\n session=self.session,\n ip=self.ip,\n transport=self.transport,\n shell_port=self.shell_port,\n iopub_port=self.iopub_port,\n stdin_port=self.stdin_port,\n hb_port=self.hb_port,\n control_port=self.control_port,\n connection_file=self.connection_file,\n parent=self,\n )\n\n self.kernel_client.start_channels()\n\n def initialize(self, argv: object = None) -> None:\n """\n Classes which mix this class in should call:\n JupyterConsoleApp.initialize(self,argv)\n """\n if getattr(self, "_dispatching", False):\n return\n self.init_connection_file()\n self.init_ssh()\n self.init_kernel_manager()\n self.init_kernel_client()\n\n\nclass IPythonConsoleApp(JupyterConsoleApp):\n """An app to manage an ipython console."""\n\n def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n """Initialize the app."""\n warnings.warn("IPythonConsoleApp is deprecated. Use JupyterConsoleApp", stacklevel=2)\n super().__init__(*args, **kwargs)\n
.venv\Lib\site-packages\jupyter_client\consoleapp.py
consoleapp.py
Python
13,913
0.95
0.122995
0.103774
awesome-app
350
2024-10-11T01:11:18.724544
MIT
false
fc79d5122f7a8aed67df5a5f64dbbba8
"""Utilities to manipulate JSON objects."""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nimport math\nimport numbers\nimport re\nimport types\nimport warnings\nfrom binascii import b2a_base64\nfrom collections.abc import Iterable\nfrom datetime import datetime\nfrom typing import Any, Optional, Union\n\nfrom dateutil.parser import isoparse as _dateutil_parse\nfrom dateutil.tz import tzlocal\n\nnext_attr_name = "__next__" # Not sure what downstream library uses this, but left it to be safe\n\n# -----------------------------------------------------------------------------\n# Globals and constants\n# -----------------------------------------------------------------------------\n\n# timestamp formats\nISO8601 = "%Y-%m-%dT%H:%M:%S.%f"\nISO8601_PAT = re.compile(\n r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(\.\d{1,6})?(Z|([\+\-]\d{2}:?\d{2}))?$"\n)\n\n# holy crap, strptime is not threadsafe.\n# Calling it once at import seems to help.\ndatetime.strptime("2000-01-01", "%Y-%m-%d") # noqa\n\n# -----------------------------------------------------------------------------\n# Classes and functions\n# -----------------------------------------------------------------------------\n\n\ndef _ensure_tzinfo(dt: datetime) -> datetime:\n """Ensure a datetime object has tzinfo\n\n If no tzinfo is present, add tzlocal\n """\n if not dt.tzinfo:\n # No more naïve datetime objects!\n warnings.warn(\n "Interpreting naive datetime as local %s. Please add timezone info to timestamps." % dt,\n DeprecationWarning,\n stacklevel=4,\n )\n dt = dt.replace(tzinfo=tzlocal())\n return dt\n\n\ndef parse_date(s: Optional[str]) -> Optional[Union[str, datetime]]:\n """parse an ISO8601 date string\n\n If it is None or not a valid ISO8601 timestamp,\n it will be returned unmodified.\n Otherwise, it will return a datetime object.\n """\n if s is None:\n return s\n m = ISO8601_PAT.match(s)\n if m:\n dt = _dateutil_parse(s)\n return _ensure_tzinfo(dt)\n return s\n\n\ndef extract_dates(obj: Any) -> Any:\n """extract ISO8601 dates from unpacked JSON"""\n if isinstance(obj, dict):\n new_obj = {} # don't clobber\n for k, v in obj.items():\n new_obj[k] = extract_dates(v)\n obj = new_obj\n elif isinstance(obj, (list, tuple)):\n obj = [extract_dates(o) for o in obj]\n elif isinstance(obj, str):\n obj = parse_date(obj)\n return obj\n\n\ndef squash_dates(obj: Any) -> Any:\n """squash datetime objects into ISO8601 strings"""\n if isinstance(obj, dict):\n obj = dict(obj) # don't clobber\n for k, v in obj.items():\n obj[k] = squash_dates(v)\n elif isinstance(obj, (list, tuple)):\n obj = [squash_dates(o) for o in obj]\n elif isinstance(obj, datetime):\n obj = obj.isoformat()\n return obj\n\n\ndef date_default(obj: Any) -> Any:\n """DEPRECATED: Use jupyter_client.jsonutil.json_default"""\n warnings.warn(\n "date_default is deprecated since jupyter_client 7.0.0."\n " Use jupyter_client.jsonutil.json_default.",\n stacklevel=2,\n )\n return json_default(obj)\n\n\ndef json_default(obj: Any) -> Any:\n """default function for packing objects in JSON."""\n if isinstance(obj, datetime):\n obj = _ensure_tzinfo(obj)\n return obj.isoformat().replace("+00:00", "Z")\n\n if isinstance(obj, bytes):\n return b2a_base64(obj, newline=False).decode("ascii")\n\n if isinstance(obj, Iterable):\n return list(obj)\n\n if isinstance(obj, numbers.Integral):\n return int(obj)\n\n if isinstance(obj, numbers.Real):\n return float(obj)\n\n raise TypeError("%r is not JSON serializable" % obj)\n\n\n# Copy of the old ipykernel's json_clean\n# This is temporary, it should be removed when we deprecate support for\n# non-valid JSON messages\ndef json_clean(obj: Any) -> Any:\n # types that are 'atomic' and ok in json as-is.\n atomic_ok = (str, type(None))\n\n # containers that we need to convert into lists\n container_to_list = (tuple, set, types.GeneratorType)\n\n # Since bools are a subtype of Integrals, which are a subtype of Reals,\n # we have to check them in that order.\n\n if isinstance(obj, bool):\n return obj\n\n if isinstance(obj, numbers.Integral):\n # cast int to int, in case subclasses override __str__ (e.g. boost enum, #4598)\n return int(obj)\n\n if isinstance(obj, numbers.Real):\n # cast out-of-range floats to their reprs\n if math.isnan(obj) or math.isinf(obj):\n return repr(obj)\n return float(obj)\n\n if isinstance(obj, atomic_ok):\n return obj\n\n if isinstance(obj, bytes):\n # unanmbiguous binary data is base64-encoded\n # (this probably should have happened upstream)\n return b2a_base64(obj, newline=False).decode("ascii")\n\n if isinstance(obj, container_to_list) or (\n hasattr(obj, "__iter__") and hasattr(obj, next_attr_name)\n ):\n obj = list(obj)\n\n if isinstance(obj, list):\n return [json_clean(x) for x in obj]\n\n if isinstance(obj, dict):\n # First, validate that the dict won't lose data in conversion due to\n # key collisions after stringification. This can happen with keys like\n # True and 'true' or 1 and '1', which collide in JSON.\n nkeys = len(obj)\n nkeys_collapsed = len(set(map(str, obj)))\n if nkeys != nkeys_collapsed:\n msg = (\n "dict cannot be safely converted to JSON: "\n "key collision would lead to dropped values"\n )\n raise ValueError(msg)\n # If all OK, proceed by making the new dict that will be json-safe\n out = {}\n for k, v in obj.items():\n out[str(k)] = json_clean(v)\n return out\n\n if isinstance(obj, datetime):\n return obj.strftime(ISO8601)\n\n # we don't understand it, it's probably an unserializable object\n raise ValueError("Can't clean for JSON: %r" % obj)\n
.venv\Lib\site-packages\jupyter_client\jsonutil.py
jsonutil.py
Python
6,039
0.95
0.197917
0.183007
vue-tools
215
2024-12-15T23:39:24.522386
MIT
false
730578326e54965d243698ca1c0f3994
"""An application to launch a kernel by name in a local subprocess."""\nimport os\nimport signal\nimport typing as t\nimport uuid\n\nfrom jupyter_core.application import JupyterApp, base_flags\nfrom tornado.ioloop import IOLoop\nfrom traitlets import Unicode\n\nfrom . import __version__\nfrom .kernelspec import NATIVE_KERNEL_NAME, KernelSpecManager\nfrom .manager import KernelManager\n\n\nclass KernelApp(JupyterApp):\n """Launch a kernel by name in a local subprocess."""\n\n version = __version__\n description = "Run a kernel locally in a subprocess"\n\n classes = [KernelManager, KernelSpecManager]\n\n aliases = {\n "kernel": "KernelApp.kernel_name",\n "ip": "KernelManager.ip",\n }\n flags = {"debug": base_flags["debug"]}\n\n kernel_name = Unicode(NATIVE_KERNEL_NAME, help="The name of a kernel type to start").tag(\n config=True\n )\n\n def initialize(self, argv: t.Union[str, t.Sequence[str], None] = None) -> None:\n """Initialize the application."""\n super().initialize(argv)\n\n cf_basename = "kernel-%s.json" % uuid.uuid4()\n self.config.setdefault("KernelManager", {}).setdefault(\n "connection_file", os.path.join(self.runtime_dir, cf_basename)\n )\n self.km = KernelManager(kernel_name=self.kernel_name, config=self.config)\n\n self.loop = IOLoop.current()\n self.loop.add_callback(self._record_started)\n\n def setup_signals(self) -> None:\n """Shutdown on SIGTERM or SIGINT (Ctrl-C)"""\n if os.name == "nt":\n return\n\n def shutdown_handler(signo: int, frame: t.Any) -> None:\n self.loop.add_callback_from_signal(self.shutdown, signo)\n\n for sig in [signal.SIGTERM, signal.SIGINT]:\n signal.signal(sig, shutdown_handler)\n\n def shutdown(self, signo: int) -> None:\n """Shut down the application."""\n self.log.info("Shutting down on signal %d", signo)\n self.km.shutdown_kernel()\n self.loop.stop()\n\n def log_connection_info(self) -> None:\n """Log the connection info for the kernel."""\n cf = self.km.connection_file\n self.log.info("Connection file: %s", cf)\n self.log.info("To connect a client: --existing %s", os.path.basename(cf))\n\n def _record_started(self) -> None:\n """For tests, create a file to indicate that we've started\n\n Do not rely on this except in our own tests!\n """\n fn = os.environ.get("JUPYTER_CLIENT_TEST_RECORD_STARTUP_PRIVATE")\n if fn is not None:\n with open(fn, "wb"):\n pass\n\n def start(self) -> None:\n """Start the application."""\n self.log.info("Starting kernel %r", self.kernel_name)\n try:\n self.km.start_kernel()\n self.log_connection_info()\n self.setup_signals()\n self.loop.start()\n finally:\n self.km.cleanup_resources()\n\n\nmain = KernelApp.launch_instance\n
.venv\Lib\site-packages\jupyter_client\kernelapp.py
kernelapp.py
Python
2,941
0.85
0.141304
0
node-utils
221
2024-06-12T00:41:31.998929
Apache-2.0
false
a9782e204c61beb195aa7b4aee5fef50
"""Tools for managing kernel specs"""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport json\nimport os\nimport re\nimport shutil\nimport typing as t\nimport warnings\n\nfrom jupyter_core.paths import SYSTEM_JUPYTER_PATH, jupyter_data_dir, jupyter_path\nfrom traitlets import Bool, CaselessStrEnum, Dict, HasTraits, List, Set, Type, Unicode, observe\nfrom traitlets.config import LoggingConfigurable\n\nfrom .provisioning import KernelProvisionerFactory as KPF # noqa\n\npjoin = os.path.join\n\nNATIVE_KERNEL_NAME = "python3"\n\n\nclass KernelSpec(HasTraits):\n """A kernel spec model object."""\n\n argv: List[str] = List()\n name = Unicode()\n mimetype = Unicode()\n display_name = Unicode()\n language = Unicode()\n env = Dict()\n resource_dir = Unicode()\n interrupt_mode = CaselessStrEnum(["message", "signal"], default_value="signal")\n metadata = Dict()\n\n @classmethod\n def from_resource_dir(cls: type[KernelSpec], resource_dir: str) -> KernelSpec:\n """Create a KernelSpec object by reading kernel.json\n\n Pass the path to the *directory* containing kernel.json.\n """\n kernel_file = pjoin(resource_dir, "kernel.json")\n with open(kernel_file, encoding="utf-8") as f:\n kernel_dict = json.load(f)\n return cls(resource_dir=resource_dir, **kernel_dict)\n\n def to_dict(self) -> dict[str, t.Any]:\n """Convert the kernel spec to a dict."""\n d = {\n "argv": self.argv,\n "env": self.env,\n "display_name": self.display_name,\n "language": self.language,\n "interrupt_mode": self.interrupt_mode,\n "metadata": self.metadata,\n }\n\n return d\n\n def to_json(self) -> str:\n """Serialise this kernelspec to a JSON object.\n\n Returns a string.\n """\n return json.dumps(self.to_dict())\n\n\n_kernel_name_pat = re.compile(r"^[a-z0-9._\-]+$", re.IGNORECASE)\n\n\ndef _is_valid_kernel_name(name: str) -> t.Any:\n """Check that a kernel name is valid."""\n # quote is not unicode-safe on Python 2\n return _kernel_name_pat.match(name)\n\n\n_kernel_name_description = (\n "Kernel names can only contain ASCII letters and numbers and these separators:"\n " - . _ (hyphen, period, and underscore)."\n)\n\n\ndef _is_kernel_dir(path: str) -> bool:\n """Is ``path`` a kernel directory?"""\n return os.path.isdir(path) and os.path.isfile(pjoin(path, "kernel.json"))\n\n\ndef _list_kernels_in(dir: str | None) -> dict[str, str]:\n """Return a mapping of kernel names to resource directories from dir.\n\n If dir is None or does not exist, returns an empty dict.\n """\n if dir is None or not os.path.isdir(dir):\n return {}\n kernels = {}\n for f in os.listdir(dir):\n path = pjoin(dir, f)\n if not _is_kernel_dir(path):\n continue\n key = f.lower()\n if not _is_valid_kernel_name(key):\n warnings.warn(\n f"Invalid kernelspec directory name ({_kernel_name_description}): {path}",\n stacklevel=3,\n )\n kernels[key] = path\n return kernels\n\n\nclass NoSuchKernel(KeyError): # noqa\n """An error raised when there is no kernel of a give name."""\n\n def __init__(self, name: str) -> None:\n """Initialize the error."""\n self.name = name\n\n def __str__(self) -> str:\n return f"No such kernel named {self.name}"\n\n\nclass KernelSpecManager(LoggingConfigurable):\n """A manager for kernel specs."""\n\n kernel_spec_class = Type(\n KernelSpec,\n config=True,\n help="""The kernel spec class. This is configurable to allow\n subclassing of the KernelSpecManager for customized behavior.\n """,\n )\n\n ensure_native_kernel = Bool(\n True,\n config=True,\n help="""If there is no Python kernelspec registered and the IPython\n kernel is available, ensure it is added to the spec list.\n """,\n )\n\n data_dir = Unicode()\n\n def _data_dir_default(self) -> str:\n return jupyter_data_dir()\n\n user_kernel_dir = Unicode()\n\n def _user_kernel_dir_default(self) -> str:\n return pjoin(self.data_dir, "kernels")\n\n whitelist = Set(\n config=True,\n help="""Deprecated, use `KernelSpecManager.allowed_kernelspecs`\n """,\n )\n allowed_kernelspecs = Set(\n config=True,\n help="""List of allowed kernel names.\n\n By default, all installed kernels are allowed.\n """,\n )\n kernel_dirs: List[str] = List(\n help="List of kernel directories to search. Later ones take priority over earlier."\n )\n\n _deprecated_aliases = {\n "whitelist": ("allowed_kernelspecs", "7.0"),\n }\n\n # Method copied from\n # https://github.com/jupyterhub/jupyterhub/blob/d1a85e53dccfc7b1dd81b0c1985d158cc6b61820/jupyterhub/auth.py#L143-L161\n @observe(*list(_deprecated_aliases))\n def _deprecated_trait(self, change: t.Any) -> None:\n """observer for deprecated traits"""\n old_attr = change.name\n new_attr, version = self._deprecated_aliases[old_attr]\n new_value = getattr(self, new_attr)\n if new_value != change.new:\n # only warn if different\n # protects backward-compatible config from warnings\n # if they set the same value under both names\n self.log.warning(\n f"{self.__class__.__name__}.{old_attr} is deprecated in jupyter_client "\n f"{version}, use {self.__class__.__name__}.{new_attr} instead"\n )\n setattr(self, new_attr, change.new)\n\n def _kernel_dirs_default(self) -> list[str]:\n dirs = jupyter_path("kernels")\n # At some point, we should stop adding .ipython/kernels to the path,\n # but the cost to keeping it is very small.\n try:\n # this should always be valid on IPython 3+\n from IPython.paths import get_ipython_dir\n\n dirs.append(os.path.join(get_ipython_dir(), "kernels"))\n except ModuleNotFoundError:\n pass\n return dirs\n\n def find_kernel_specs(self) -> dict[str, str]:\n """Returns a dict mapping kernel names to resource directories."""\n d = {}\n for kernel_dir in self.kernel_dirs:\n kernels = _list_kernels_in(kernel_dir)\n for kname, spec in kernels.items():\n if kname not in d:\n self.log.debug("Found kernel %s in %s", kname, kernel_dir)\n d[kname] = spec\n\n if self.ensure_native_kernel and NATIVE_KERNEL_NAME not in d:\n try:\n from ipykernel.kernelspec import RESOURCES\n\n self.log.debug(\n "Native kernel (%s) available from %s",\n NATIVE_KERNEL_NAME,\n RESOURCES,\n )\n d[NATIVE_KERNEL_NAME] = RESOURCES\n except ImportError:\n self.log.warning("Native kernel (%s) is not available", NATIVE_KERNEL_NAME)\n\n if self.allowed_kernelspecs:\n # filter if there's an allow list\n d = {name: spec for name, spec in d.items() if name in self.allowed_kernelspecs}\n return d\n # TODO: Caching?\n\n def _get_kernel_spec_by_name(self, kernel_name: str, resource_dir: str) -> KernelSpec:\n """Returns a :class:`KernelSpec` instance for a given kernel_name\n and resource_dir.\n """\n kspec = None\n if kernel_name == NATIVE_KERNEL_NAME:\n try:\n from ipykernel.kernelspec import RESOURCES, get_kernel_dict\n except ImportError:\n # It should be impossible to reach this, but let's play it safe\n pass\n else:\n if resource_dir == RESOURCES:\n kdict = get_kernel_dict()\n kspec = self.kernel_spec_class(resource_dir=resource_dir, **kdict)\n if not kspec:\n kspec = self.kernel_spec_class.from_resource_dir(resource_dir)\n\n if not KPF.instance(parent=self.parent).is_provisioner_available(kspec):\n raise NoSuchKernel(kernel_name)\n\n return kspec\n\n def _find_spec_directory(self, kernel_name: str) -> str | None:\n """Find the resource directory of a named kernel spec"""\n for kernel_dir in [kd for kd in self.kernel_dirs if os.path.isdir(kd)]:\n files = os.listdir(kernel_dir)\n for f in files:\n path = pjoin(kernel_dir, f)\n if f.lower() == kernel_name and _is_kernel_dir(path):\n return path\n\n if kernel_name == NATIVE_KERNEL_NAME:\n try:\n from ipykernel.kernelspec import RESOURCES\n except ImportError:\n pass\n else:\n return RESOURCES\n return None\n\n def get_kernel_spec(self, kernel_name: str) -> KernelSpec:\n """Returns a :class:`KernelSpec` instance for the given kernel_name.\n\n Raises :exc:`NoSuchKernel` if the given kernel name is not found.\n """\n if not _is_valid_kernel_name(kernel_name):\n self.log.warning(\n f"Kernelspec name {kernel_name} is invalid: {_kernel_name_description}"\n )\n\n resource_dir = self._find_spec_directory(kernel_name.lower())\n if resource_dir is None:\n self.log.warning("Kernelspec name %s cannot be found!", kernel_name)\n raise NoSuchKernel(kernel_name)\n\n return self._get_kernel_spec_by_name(kernel_name, resource_dir)\n\n def get_all_specs(self) -> dict[str, t.Any]:\n """Returns a dict mapping kernel names to kernelspecs.\n\n Returns a dict of the form::\n\n {\n 'kernel_name': {\n 'resource_dir': '/path/to/kernel_name',\n 'spec': {"the spec itself": ...}\n },\n ...\n }\n """\n d = self.find_kernel_specs()\n res = {}\n for kname, resource_dir in d.items():\n try:\n if self.__class__ is KernelSpecManager:\n spec = self._get_kernel_spec_by_name(kname, resource_dir)\n else:\n # avoid calling private methods in subclasses,\n # which may have overridden find_kernel_specs\n # and get_kernel_spec, but not the newer get_all_specs\n spec = self.get_kernel_spec(kname)\n\n res[kname] = {"resource_dir": resource_dir, "spec": spec.to_dict()}\n except NoSuchKernel:\n pass # The appropriate warning has already been logged\n except Exception:\n self.log.warning("Error loading kernelspec %r", kname, exc_info=True)\n return res\n\n def remove_kernel_spec(self, name: str) -> str:\n """Remove a kernel spec directory by name.\n\n Returns the path that was deleted.\n """\n save_native = self.ensure_native_kernel\n try:\n self.ensure_native_kernel = False\n specs = self.find_kernel_specs()\n finally:\n self.ensure_native_kernel = save_native\n spec_dir = specs[name]\n self.log.debug("Removing %s", spec_dir)\n if os.path.islink(spec_dir):\n os.remove(spec_dir)\n else:\n shutil.rmtree(spec_dir)\n return spec_dir\n\n def _get_destination_dir(\n self, kernel_name: str, user: bool = False, prefix: str | None = None\n ) -> str:\n if user:\n return os.path.join(self.user_kernel_dir, kernel_name)\n elif prefix:\n return os.path.join(os.path.abspath(prefix), "share", "jupyter", "kernels", kernel_name)\n else:\n return os.path.join(SYSTEM_JUPYTER_PATH[0], "kernels", kernel_name)\n\n def install_kernel_spec(\n self,\n source_dir: str,\n kernel_name: str | None = None,\n user: bool = False,\n replace: bool | None = None,\n prefix: str | None = None,\n ) -> str:\n """Install a kernel spec by copying its directory.\n\n If ``kernel_name`` is not given, the basename of ``source_dir`` will\n be used.\n\n If ``user`` is False, it will attempt to install into the systemwide\n kernel registry. If the process does not have appropriate permissions,\n an :exc:`OSError` will be raised.\n\n If ``prefix`` is given, the kernelspec will be installed to\n PREFIX/share/jupyter/kernels/KERNEL_NAME. This can be sys.prefix\n for installation inside virtual or conda envs.\n """\n source_dir = source_dir.rstrip("/\\")\n if not kernel_name:\n kernel_name = os.path.basename(source_dir)\n kernel_name = kernel_name.lower()\n if not _is_valid_kernel_name(kernel_name):\n msg = f"Invalid kernel name {kernel_name!r}. {_kernel_name_description}"\n raise ValueError(msg)\n\n if user and prefix:\n msg = "Can't specify both user and prefix. Please choose one or the other."\n raise ValueError(msg)\n\n if replace is not None:\n warnings.warn(\n "replace is ignored. Installing a kernelspec always replaces an existing "\n "installation",\n DeprecationWarning,\n stacklevel=2,\n )\n\n destination = self._get_destination_dir(kernel_name, user=user, prefix=prefix)\n self.log.debug("Installing kernelspec in %s", destination)\n\n kernel_dir = os.path.dirname(destination)\n if kernel_dir not in self.kernel_dirs:\n self.log.warning(\n "Installing to %s, which is not in %s. The kernelspec may not be found.",\n kernel_dir,\n self.kernel_dirs,\n )\n\n if os.path.isdir(destination):\n self.log.info("Removing existing kernelspec in %s", destination)\n shutil.rmtree(destination)\n\n shutil.copytree(source_dir, destination)\n self.log.info("Installed kernelspec %s in %s", kernel_name, destination)\n return destination\n\n def install_native_kernel_spec(self, user: bool = False) -> None:\n """DEPRECATED: Use ipykernel.kernelspec.install"""\n warnings.warn(\n "install_native_kernel_spec is deprecated. Use ipykernel.kernelspec import install.",\n stacklevel=2,\n )\n from ipykernel.kernelspec import install\n\n install(self, user=user)\n\n\ndef find_kernel_specs() -> dict[str, str]:\n """Returns a dict mapping kernel names to resource directories."""\n return KernelSpecManager().find_kernel_specs()\n\n\ndef get_kernel_spec(kernel_name: str) -> KernelSpec:\n """Returns a :class:`KernelSpec` instance for the given kernel_name.\n\n Raises KeyError if the given kernel name is not found.\n """\n return KernelSpecManager().get_kernel_spec(kernel_name)\n\n\ndef install_kernel_spec(\n source_dir: str,\n kernel_name: str | None = None,\n user: bool = False,\n replace: bool | None = False,\n prefix: str | None = None,\n) -> str:\n """Install a kernel spec in a given directory."""\n return KernelSpecManager().install_kernel_spec(source_dir, kernel_name, user, replace, prefix)\n\n\ninstall_kernel_spec.__doc__ = KernelSpecManager.install_kernel_spec.__doc__\n\n\ndef install_native_kernel_spec(user: bool = False) -> None:\n """Install the native kernel spec."""\n KernelSpecManager().install_native_kernel_spec(user=user)\n\n\ninstall_native_kernel_spec.__doc__ = KernelSpecManager.install_native_kernel_spec.__doc__\n
.venv\Lib\site-packages\jupyter_client\kernelspec.py
kernelspec.py
Python
15,663
0.95
0.187638
0.046575
python-kit
120
2024-02-02T11:07:19.736654
Apache-2.0
false
a23d0a87e0baecc2eb9d89f041bbca64
"""Apps for managing kernel specs."""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport errno\nimport json\nimport os.path\nimport sys\nimport typing as t\n\nfrom jupyter_core.application import JupyterApp, base_aliases, base_flags\nfrom traitlets import Bool, Dict, Instance, List, Unicode\nfrom traitlets.config.application import Application\n\nfrom . import __version__\nfrom .kernelspec import KernelSpecManager\nfrom .provisioning.factory import KernelProvisionerFactory\n\n\nclass ListKernelSpecs(JupyterApp):\n """An app to list kernel specs."""\n\n version = __version__\n description = """List installed kernel specifications."""\n kernel_spec_manager = Instance(KernelSpecManager)\n json_output = Bool(\n False,\n help="output spec name and location as machine-readable json.",\n config=True,\n )\n\n flags = {\n "json": (\n {"ListKernelSpecs": {"json_output": True}},\n "output spec name and location as machine-readable json.",\n ),\n "debug": base_flags["debug"],\n }\n\n def _kernel_spec_manager_default(self) -> KernelSpecManager:\n return KernelSpecManager(parent=self, data_dir=self.data_dir)\n\n def start(self) -> dict[str, t.Any] | None: # type:ignore[override]\n """Start the application."""\n paths = self.kernel_spec_manager.find_kernel_specs()\n specs = self.kernel_spec_manager.get_all_specs()\n if not self.json_output:\n if not specs:\n print("No kernels available")\n return None\n # pad to width of longest kernel name\n name_len = len(sorted(paths, key=lambda name: len(name))[-1])\n\n def path_key(item: t.Any) -> t.Any:\n """sort key function for Jupyter path priority"""\n path = item[1]\n for idx, prefix in enumerate(self.jupyter_path):\n if path.startswith(prefix):\n return (idx, path)\n # not in jupyter path, artificially added to the front\n return (-1, path)\n\n print("Available kernels:")\n for kernelname, path in sorted(paths.items(), key=path_key):\n print(f" {kernelname.ljust(name_len)} {path}")\n else:\n print(json.dumps({"kernelspecs": specs}, indent=2))\n return specs\n\n\nclass InstallKernelSpec(JupyterApp):\n """An app to install a kernel spec."""\n\n version = __version__\n description = """Install a kernel specification directory.\n\n Given a SOURCE DIRECTORY containing a kernel spec,\n jupyter will copy that directory into one of the Jupyter kernel directories.\n The default is to install kernelspecs for all users.\n `--user` can be specified to install a kernel only for the current user.\n """\n examples = """\n jupyter kernelspec install /path/to/my_kernel --user\n """\n usage = "jupyter kernelspec install SOURCE_DIR [--options]"\n kernel_spec_manager = Instance(KernelSpecManager)\n\n def _kernel_spec_manager_default(self) -> KernelSpecManager:\n return KernelSpecManager(data_dir=self.data_dir)\n\n sourcedir = Unicode()\n kernel_name = Unicode("", config=True, help="Install the kernel spec with this name")\n\n def _kernel_name_default(self) -> str:\n return os.path.basename(self.sourcedir)\n\n user = Bool(\n False,\n config=True,\n help="""\n Try to install the kernel spec to the per-user directory instead of\n the system or environment directory.\n """,\n )\n prefix = Unicode(\n "",\n config=True,\n help="""Specify a prefix to install to, e.g. an env.\n The kernelspec will be installed in PREFIX/share/jupyter/kernels/\n """,\n )\n replace = Bool(False, config=True, help="Replace any existing kernel spec with this name.")\n\n aliases = {\n "name": "InstallKernelSpec.kernel_name",\n "prefix": "InstallKernelSpec.prefix",\n }\n aliases.update(base_aliases)\n\n flags = {\n "user": (\n {"InstallKernelSpec": {"user": True}},\n "Install to the per-user kernel registry",\n ),\n "replace": (\n {"InstallKernelSpec": {"replace": True}},\n "Replace any existing kernel spec with this name.",\n ),\n "sys-prefix": (\n {"InstallKernelSpec": {"prefix": sys.prefix}},\n "Install to Python's sys.prefix. Useful in conda/virtual environments.",\n ),\n "debug": base_flags["debug"],\n }\n\n def parse_command_line(self, argv: None | list[str]) -> None: # type:ignore[override]\n """Parse the command line args."""\n super().parse_command_line(argv)\n # accept positional arg as profile name\n if self.extra_args:\n self.sourcedir = self.extra_args[0]\n else:\n print("No source directory specified.", file=sys.stderr)\n self.exit(1)\n\n def start(self) -> None:\n """Start the application."""\n if self.user and self.prefix:\n self.exit("Can't specify both user and prefix. Please choose one or the other.")\n try:\n self.kernel_spec_manager.install_kernel_spec(\n self.sourcedir,\n kernel_name=self.kernel_name,\n user=self.user,\n prefix=self.prefix,\n replace=self.replace,\n )\n except OSError as e:\n if e.errno == errno.EACCES:\n print(e, file=sys.stderr)\n if not self.user:\n print("Perhaps you want to install with `sudo` or `--user`?", file=sys.stderr)\n self.exit(1)\n elif e.errno == errno.EEXIST:\n print(f"A kernel spec is already present at {e.filename}", file=sys.stderr)\n self.exit(1)\n raise\n\n\nclass RemoveKernelSpec(JupyterApp):\n """An app to remove a kernel spec."""\n\n version = __version__\n description = """Remove one or more Jupyter kernelspecs by name."""\n examples = """jupyter kernelspec remove python2 [my_kernel ...]"""\n\n force = Bool(False, config=True, help="""Force removal, don't prompt for confirmation.""")\n spec_names = List(Unicode())\n\n kernel_spec_manager = Instance(KernelSpecManager)\n\n def _kernel_spec_manager_default(self) -> KernelSpecManager:\n return KernelSpecManager(data_dir=self.data_dir, parent=self)\n\n flags = {\n "f": ({"RemoveKernelSpec": {"force": True}}, force.help),\n }\n flags.update(JupyterApp.flags)\n\n def parse_command_line(self, argv: list[str] | None) -> None: # type:ignore[override]\n """Parse the command line args."""\n super().parse_command_line(argv)\n # accept positional arg as profile name\n if self.extra_args:\n self.spec_names = sorted(set(self.extra_args)) # remove duplicates\n else:\n self.exit("No kernelspec specified.")\n\n def start(self) -> None:\n """Start the application."""\n self.kernel_spec_manager.ensure_native_kernel = False\n spec_paths = self.kernel_spec_manager.find_kernel_specs()\n missing = set(self.spec_names).difference(set(spec_paths))\n if missing:\n self.exit("Couldn't find kernel spec(s): %s" % ", ".join(missing))\n\n if not (self.force or self.answer_yes):\n print("Kernel specs to remove:")\n for name in self.spec_names:\n path = spec_paths.get(name, name)\n print(f" {name.ljust(20)}\t{path.ljust(20)}")\n answer = input("Remove %i kernel specs [y/N]: " % len(self.spec_names))\n if not answer.lower().startswith("y"):\n return\n\n for kernel_name in self.spec_names:\n try:\n path = self.kernel_spec_manager.remove_kernel_spec(kernel_name)\n except OSError as e:\n if e.errno == errno.EACCES:\n print(e, file=sys.stderr)\n print("Perhaps you want sudo?", file=sys.stderr)\n self.exit(1)\n else:\n raise\n print(f"Removed {path}")\n\n\nclass InstallNativeKernelSpec(JupyterApp):\n """An app to install the native kernel spec."""\n\n version = __version__\n description = """[DEPRECATED] Install the IPython kernel spec directory for this Python."""\n kernel_spec_manager = Instance(KernelSpecManager)\n\n def _kernel_spec_manager_default(self) -> KernelSpecManager: # pragma: no cover\n return KernelSpecManager(data_dir=self.data_dir)\n\n user = Bool(\n False,\n config=True,\n help="""\n Try to install the kernel spec to the per-user directory instead of\n the system or environment directory.\n """,\n )\n\n flags = {\n "user": (\n {"InstallNativeKernelSpec": {"user": True}},\n "Install to the per-user kernel registry",\n ),\n "debug": base_flags["debug"],\n }\n\n def start(self) -> None: # pragma: no cover\n """Start the application."""\n self.log.warning(\n "`jupyter kernelspec install-self` is DEPRECATED as of 4.0."\n " You probably want `ipython kernel install` to install the IPython kernelspec."\n )\n try:\n from ipykernel import kernelspec\n except ModuleNotFoundError:\n print("ipykernel not available, can't install its spec.", file=sys.stderr)\n self.exit(1)\n try:\n kernelspec.install(self.kernel_spec_manager, user=self.user)\n except OSError as e:\n if e.errno == errno.EACCES:\n print(e, file=sys.stderr)\n if not self.user:\n print(\n "Perhaps you want to install with `sudo` or `--user`?",\n file=sys.stderr,\n )\n self.exit(1)\n self.exit(e) # type:ignore[arg-type]\n\n\nclass ListProvisioners(JupyterApp):\n """An app to list provisioners."""\n\n version = __version__\n description = """List available provisioners for use in kernel specifications."""\n\n def start(self) -> None:\n """Start the application."""\n kfp = KernelProvisionerFactory.instance(parent=self)\n print("Available kernel provisioners:")\n provisioners = kfp.get_provisioner_entries()\n\n # pad to width of longest kernel name\n name_len = len(sorted(provisioners, key=lambda name: len(name))[-1])\n\n for name in sorted(provisioners):\n print(f" {name.ljust(name_len)} {provisioners[name]}")\n\n\nclass KernelSpecApp(Application):\n """An app to manage kernel specs."""\n\n version = __version__\n name = "jupyter kernelspec"\n description = """Manage Jupyter kernel specifications."""\n\n subcommands = Dict(\n {\n "list": (ListKernelSpecs, ListKernelSpecs.description.splitlines()[0]),\n "install": (\n InstallKernelSpec,\n InstallKernelSpec.description.splitlines()[0],\n ),\n "uninstall": (RemoveKernelSpec, "Alias for remove"),\n "remove": (RemoveKernelSpec, RemoveKernelSpec.description.splitlines()[0]),\n "install-self": (\n InstallNativeKernelSpec,\n InstallNativeKernelSpec.description.splitlines()[0],\n ),\n "provisioners": (ListProvisioners, ListProvisioners.description.splitlines()[0]),\n }\n )\n\n aliases = {}\n flags = {}\n\n def start(self) -> None:\n """Start the application."""\n if self.subapp is None:\n print("No subcommand specified. Must specify one of: %s" % list(self.subcommands))\n print()\n self.print_description()\n self.print_subcommands()\n self.exit(1)\n else:\n return self.subapp.start()\n\n\nif __name__ == "__main__":\n KernelSpecApp.launch_instance()\n
.venv\Lib\site-packages\jupyter_client\kernelspecapp.py
kernelspecapp.py
Python
12,048
0.95
0.158358
0.024476
python-kit
549
2023-12-04T09:04:19.449257
GPL-3.0
false
94f819124753d1d07f2af39397b55382
"""Utilities for launching kernels"""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nimport os\nimport sys\nimport warnings\nfrom subprocess import PIPE, Popen\nfrom typing import Any, Dict, List, Optional\n\nfrom traitlets.log import get_logger\n\n\ndef launch_kernel(\n cmd: List[str],\n stdin: Optional[int] = None,\n stdout: Optional[int] = None,\n stderr: Optional[int] = None,\n env: Optional[Dict[str, str]] = None,\n independent: bool = False,\n cwd: Optional[str] = None,\n **kw: Any,\n) -> Popen:\n """Launches a localhost kernel, binding to the specified ports.\n\n Parameters\n ----------\n cmd : Popen list,\n A string of Python code that imports and executes a kernel entry point.\n\n stdin, stdout, stderr : optional (default None)\n Standards streams, as defined in subprocess.Popen.\n\n env: dict, optional\n Environment variables passed to the kernel\n\n independent : bool, optional (default False)\n If set, the kernel process is guaranteed to survive if this process\n dies. If not set, an effort is made to ensure that the kernel is killed\n when this process dies. Note that in this case it is still good practice\n to kill kernels manually before exiting.\n\n cwd : path, optional\n The working dir of the kernel process (default: cwd of this process).\n\n **kw: optional\n Additional arguments for Popen\n\n Returns\n -------\n\n Popen instance for the kernel subprocess\n """\n\n # Popen will fail (sometimes with a deadlock) if stdin, stdout, and stderr\n # are invalid. Unfortunately, there is in general no way to detect whether\n # they are valid. The following two blocks redirect them to (temporary)\n # pipes in certain important cases.\n\n # If this process has been backgrounded, our stdin is invalid. Since there\n # is no compelling reason for the kernel to inherit our stdin anyway, we'll\n # place this one safe and always redirect.\n redirect_in = True\n _stdin = PIPE if stdin is None else stdin\n\n # If this process in running on pythonw, we know that stdin, stdout, and\n # stderr are all invalid.\n redirect_out = sys.executable.endswith("pythonw.exe")\n if redirect_out:\n blackhole = open(os.devnull, "w") # noqa\n _stdout = blackhole if stdout is None else stdout\n _stderr = blackhole if stderr is None else stderr\n else:\n _stdout, _stderr = stdout, stderr\n\n env = env if (env is not None) else os.environ.copy()\n\n kwargs = kw.copy()\n main_args = {\n "stdin": _stdin,\n "stdout": _stdout,\n "stderr": _stderr,\n "cwd": cwd,\n "env": env,\n }\n kwargs.update(main_args)\n\n # Spawn a kernel.\n if sys.platform == "win32":\n if cwd:\n kwargs["cwd"] = cwd\n\n from .win_interrupt import create_interrupt_event\n\n # Create a Win32 event for interrupting the kernel\n # and store it in an environment variable.\n interrupt_event = create_interrupt_event()\n env["JPY_INTERRUPT_EVENT"] = str(interrupt_event)\n # deprecated old env name:\n env["IPY_INTERRUPT_EVENT"] = env["JPY_INTERRUPT_EVENT"]\n\n try:\n from _winapi import (\n CREATE_NEW_PROCESS_GROUP,\n DUPLICATE_SAME_ACCESS,\n DuplicateHandle,\n GetCurrentProcess,\n )\n except: # noqa\n from _subprocess import (\n CREATE_NEW_PROCESS_GROUP,\n DUPLICATE_SAME_ACCESS,\n DuplicateHandle,\n GetCurrentProcess,\n )\n\n # create a handle on the parent to be inherited\n if independent:\n kwargs["creationflags"] = CREATE_NEW_PROCESS_GROUP\n else:\n pid = GetCurrentProcess()\n handle = DuplicateHandle(\n pid,\n pid,\n pid,\n 0,\n True,\n DUPLICATE_SAME_ACCESS, # Inheritable by new processes.\n )\n env["JPY_PARENT_PID"] = str(int(handle))\n\n # Prevent creating new console window on pythonw\n if redirect_out:\n kwargs["creationflags"] = (\n kwargs.setdefault("creationflags", 0) | 0x08000000\n ) # CREATE_NO_WINDOW\n\n # Avoid closing the above parent and interrupt handles.\n # close_fds is True by default on Python >=3.7\n # or when no stream is captured on Python <3.7\n # (we always capture stdin, so this is already False by default on <3.7)\n kwargs["close_fds"] = False\n else:\n # Create a new session.\n # This makes it easier to interrupt the kernel,\n # because we want to interrupt the whole process group.\n # We don't use setpgrp, which is known to cause problems for kernels starting\n # certain interactive subprocesses, such as bash -i.\n kwargs["start_new_session"] = True\n if not independent:\n env["JPY_PARENT_PID"] = str(os.getpid())\n\n try:\n # Allow to use ~/ in the command or its arguments\n cmd = [os.path.expanduser(s) for s in cmd]\n proc = Popen(cmd, **kwargs) # noqa\n except Exception as ex:\n try:\n msg = "Failed to run command:\n{}\n PATH={!r}\n with kwargs:\n{!r}\n"\n # exclude environment variables,\n # which may contain access tokens and the like.\n without_env = {key: value for key, value in kwargs.items() if key != "env"}\n msg = msg.format(cmd, env.get("PATH", os.defpath), without_env)\n get_logger().error(msg)\n except Exception as ex2: # Don't let a formatting/logger issue lead to the wrong exception\n warnings.warn(f"Failed to run command: '{cmd}' due to exception: {ex}", stacklevel=2)\n warnings.warn(\n f"The following exception occurred handling the previous failure: {ex2}",\n stacklevel=2,\n )\n raise ex\n\n if sys.platform == "win32":\n # Attach the interrupt event to the Popen object so it can be used later.\n proc.win32_interrupt_event = interrupt_event\n\n # Clean up pipes created to work around Popen bug.\n if redirect_in and stdin is None:\n assert proc.stdin is not None\n proc.stdin.close()\n\n return proc\n\n\n__all__ = [\n "launch_kernel",\n]\n
.venv\Lib\site-packages\jupyter_client\launcher.py
launcher.py
Python
6,443
0.95
0.145161
0.210191
vue-tools
270
2025-04-16T16:39:31.930727
GPL-3.0
false
090e1ba022bec0556a5a24cf649e10b2
"""Utilities for identifying local IP addresses."""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport os\nimport re\nimport socket\nimport subprocess\nfrom subprocess import PIPE, Popen\nfrom typing import Any, Callable, Iterable, Sequence\nfrom warnings import warn\n\nLOCAL_IPS: list = []\nPUBLIC_IPS: list = []\n\nLOCALHOST: str = ""\n\n\ndef _uniq_stable(elems: Iterable) -> list:\n """uniq_stable(elems) -> list\n\n Return from an iterable, a list of all the unique elements in the input,\n maintaining the order in which they first appear.\n """\n seen = set()\n value = []\n for x in elems:\n if x not in seen:\n value.append(x)\n seen.add(x)\n return value\n\n\ndef _get_output(cmd: str | Sequence[str]) -> str:\n """Get output of a command, raising IOError if it fails"""\n startupinfo = None\n if os.name == "nt":\n startupinfo = subprocess.STARTUPINFO() # type:ignore[attr-defined]\n startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW # type:ignore[attr-defined]\n p = Popen(cmd, stdout=PIPE, stderr=PIPE, startupinfo=startupinfo) # noqa\n stdout, stderr = p.communicate()\n if p.returncode:\n msg = "Failed to run {}: {}".format(cmd, stderr.decode("utf8", "replace"))\n raise OSError(msg)\n return stdout.decode("utf8", "replace")\n\n\ndef _only_once(f: Callable) -> Callable:\n """decorator to only run a function once"""\n f.called = False # type:ignore[attr-defined]\n\n def wrapped(**kwargs: Any) -> Any:\n if f.called: # type:ignore[attr-defined]\n return\n ret = f(**kwargs)\n f.called = True # type:ignore[attr-defined]\n return ret\n\n return wrapped\n\n\ndef _requires_ips(f: Callable) -> Callable:\n """decorator to ensure load_ips has been run before f"""\n\n def ips_loaded(*args: Any, **kwargs: Any) -> Any:\n _load_ips()\n return f(*args, **kwargs)\n\n return ips_loaded\n\n\n# subprocess-parsing ip finders\nclass NoIPAddresses(Exception): # noqa\n pass\n\n\ndef _populate_from_list(addrs: Sequence[str] | None) -> None:\n """populate local and public IPs from flat list of all IPs"""\n if not addrs:\n raise NoIPAddresses\n\n global LOCALHOST\n public_ips = []\n local_ips = []\n\n for ip in addrs:\n local_ips.append(ip)\n if not ip.startswith("127."):\n public_ips.append(ip)\n elif not LOCALHOST:\n LOCALHOST = ip\n\n if not LOCALHOST or LOCALHOST == "127.0.0.1":\n LOCALHOST = "127.0.0.1"\n local_ips.insert(0, LOCALHOST)\n\n local_ips.extend(["0.0.0.0", ""]) # noqa\n\n LOCAL_IPS[:] = _uniq_stable(local_ips)\n PUBLIC_IPS[:] = _uniq_stable(public_ips)\n\n\n_ifconfig_ipv4_pat = re.compile(r"inet\b.*?(\d+\.\d+\.\d+\.\d+)", re.IGNORECASE)\n\n\ndef _load_ips_ifconfig() -> None:\n """load ip addresses from `ifconfig` output (posix)"""\n\n try:\n out = _get_output("ifconfig")\n except OSError:\n # no ifconfig, it's usually in /sbin and /sbin is not on everyone's PATH\n out = _get_output("/sbin/ifconfig")\n\n lines = out.splitlines()\n addrs = []\n for line in lines:\n m = _ifconfig_ipv4_pat.match(line.strip())\n if m:\n addrs.append(m.group(1))\n _populate_from_list(addrs)\n\n\ndef _load_ips_ip() -> None:\n """load ip addresses from `ip addr` output (Linux)"""\n out = _get_output(["ip", "-f", "inet", "addr"])\n\n lines = out.splitlines()\n addrs = []\n for line in lines:\n blocks = line.lower().split()\n if (len(blocks) >= 2) and (blocks[0] == "inet"):\n addrs.append(blocks[1].split("/")[0])\n _populate_from_list(addrs)\n\n\n_ipconfig_ipv4_pat = re.compile(r"ipv4.*?(\d+\.\d+\.\d+\.\d+)$", re.IGNORECASE)\n\n\ndef _load_ips_ipconfig() -> None:\n """load ip addresses from `ipconfig` output (Windows)"""\n out = _get_output("ipconfig")\n\n lines = out.splitlines()\n addrs = []\n for line in lines:\n m = _ipconfig_ipv4_pat.match(line.strip())\n if m:\n addrs.append(m.group(1))\n _populate_from_list(addrs)\n\n\ndef _load_ips_psutil() -> None:\n """load ip addresses with netifaces"""\n import psutil\n\n global LOCALHOST\n local_ips = []\n public_ips = []\n\n # dict of iface_name: address_list, eg\n # {"lo": [snicaddr(family=<AddressFamily.AF_INET>, address="127.0.0.1",\n # ...), snicaddr(family=<AddressFamily.AF_INET6>, ...)]}\n for iface, ifaddresses in psutil.net_if_addrs().items():\n for address_data in ifaddresses:\n if address_data.family == socket.AF_INET:\n addr = address_data.address\n if not (iface.startswith("lo") or addr.startswith("127.")):\n public_ips.append(addr)\n elif not LOCALHOST:\n LOCALHOST = addr\n local_ips.append(addr)\n if not LOCALHOST:\n # we never found a loopback interface (can this ever happen?), assume common default\n LOCALHOST = "127.0.0.1"\n local_ips.insert(0, LOCALHOST)\n local_ips.extend(["0.0.0.0", ""]) # noqa\n LOCAL_IPS[:] = _uniq_stable(local_ips)\n PUBLIC_IPS[:] = _uniq_stable(public_ips)\n\n\ndef _load_ips_netifaces() -> None:\n """load ip addresses with netifaces"""\n import netifaces # type: ignore[import-not-found]\n\n global LOCALHOST\n local_ips = []\n public_ips = []\n\n # list of iface names, 'lo0', 'eth0', etc.\n for iface in netifaces.interfaces():\n # list of ipv4 addrinfo dicts\n ipv4s = netifaces.ifaddresses(iface).get(netifaces.AF_INET, [])\n for entry in ipv4s:\n addr = entry.get("addr")\n if not addr:\n continue\n if not (iface.startswith("lo") or addr.startswith("127.")):\n public_ips.append(addr)\n elif not LOCALHOST:\n LOCALHOST = addr\n local_ips.append(addr)\n if not LOCALHOST:\n # we never found a loopback interface (can this ever happen?), assume common default\n LOCALHOST = "127.0.0.1"\n local_ips.insert(0, LOCALHOST)\n local_ips.extend(["0.0.0.0", ""]) # noqa\n LOCAL_IPS[:] = _uniq_stable(local_ips)\n PUBLIC_IPS[:] = _uniq_stable(public_ips)\n\n\ndef _load_ips_gethostbyname() -> None:\n """load ip addresses with socket.gethostbyname_ex\n\n This can be slow.\n """\n global LOCALHOST\n try:\n LOCAL_IPS[:] = socket.gethostbyname_ex("localhost")[2]\n except OSError:\n # assume common default\n LOCAL_IPS[:] = ["127.0.0.1"]\n\n try:\n hostname = socket.gethostname()\n PUBLIC_IPS[:] = socket.gethostbyname_ex(hostname)[2]\n # try hostname.local, in case hostname has been short-circuited to loopback\n if not hostname.endswith(".local") and all(ip.startswith("127") for ip in PUBLIC_IPS):\n PUBLIC_IPS[:] = socket.gethostbyname_ex(socket.gethostname() + ".local")[2]\n except OSError:\n pass\n finally:\n PUBLIC_IPS[:] = _uniq_stable(PUBLIC_IPS)\n LOCAL_IPS.extend(PUBLIC_IPS)\n\n # include all-interface aliases: 0.0.0.0 and ''\n LOCAL_IPS.extend(["0.0.0.0", ""]) # noqa\n\n LOCAL_IPS[:] = _uniq_stable(LOCAL_IPS)\n\n LOCALHOST = LOCAL_IPS[0]\n\n\ndef _load_ips_dumb() -> None:\n """Fallback in case of unexpected failure"""\n global LOCALHOST\n LOCALHOST = "127.0.0.1"\n LOCAL_IPS[:] = [LOCALHOST, "0.0.0.0", ""] # noqa\n PUBLIC_IPS[:] = []\n\n\n@_only_once\ndef _load_ips(suppress_exceptions: bool = True) -> None:\n """load the IPs that point to this machine\n\n This function will only ever be called once.\n\n If will use psutil to do it quickly if available.\n If not, it will use netifaces to do it quickly if available.\n Then it will fallback on parsing the output of ifconfig / ip addr / ipconfig, as appropriate.\n Finally, it will fallback on socket.gethostbyname_ex, which can be slow.\n """\n\n try:\n # first priority, use psutil\n try:\n return _load_ips_psutil()\n except ImportError:\n pass\n\n # second priority, use netifaces\n try:\n return _load_ips_netifaces()\n except ImportError:\n pass\n\n # second priority, parse subprocess output (how reliable is this?)\n\n if os.name == "nt":\n try:\n return _load_ips_ipconfig()\n except (OSError, NoIPAddresses):\n pass\n else:\n try:\n return _load_ips_ip()\n except (OSError, NoIPAddresses):\n pass\n try:\n return _load_ips_ifconfig()\n except (OSError, NoIPAddresses):\n pass\n\n # lowest priority, use gethostbyname\n\n return _load_ips_gethostbyname()\n except Exception as e:\n if not suppress_exceptions:\n raise\n # unexpected error shouldn't crash, load dumb default values instead.\n warn("Unexpected error discovering local network interfaces: %s" % e, stacklevel=2)\n _load_ips_dumb()\n\n\n@_requires_ips\ndef local_ips() -> list[str]:\n """return the IP addresses that point to this machine"""\n return LOCAL_IPS\n\n\n@_requires_ips\ndef public_ips() -> list[str]:\n """return the IP addresses for this machine that are visible to other machines"""\n return PUBLIC_IPS\n\n\n@_requires_ips\ndef localhost() -> str:\n """return ip for localhost (almost always 127.0.0.1)"""\n return LOCALHOST\n\n\n@_requires_ips\ndef is_local_ip(ip: str) -> bool:\n """does `ip` point to this machine?"""\n return ip in LOCAL_IPS\n\n\n@_requires_ips\ndef is_public_ip(ip: str) -> bool:\n """is `ip` a publicly visible address?"""\n return ip in PUBLIC_IPS\n
.venv\Lib\site-packages\jupyter_client\localinterfaces.py
localinterfaces.py
Python
9,733
0.95
0.204204
0.07393
node-utils
655
2025-03-31T14:54:33.501242
GPL-3.0
false
51e0a2da13d79e3baf16c10d60af7d93
"""Base class to manage a running kernel"""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nimport asyncio\nimport functools\nimport os\nimport re\nimport signal\nimport sys\nimport typing as t\nimport uuid\nimport warnings\nfrom asyncio.futures import Future\nfrom concurrent.futures import Future as CFuture\nfrom contextlib import contextmanager\nfrom enum import Enum\n\nimport zmq\nfrom jupyter_core.utils import run_sync\nfrom traitlets import (\n Any,\n Bool,\n Dict,\n DottedObjectName,\n Float,\n Instance,\n Type,\n Unicode,\n default,\n observe,\n observe_compat,\n)\nfrom traitlets.utils.importstring import import_item\n\nfrom . import kernelspec\nfrom .asynchronous import AsyncKernelClient\nfrom .blocking import BlockingKernelClient\nfrom .client import KernelClient\nfrom .connect import ConnectionFileMixin\nfrom .managerabc import KernelManagerABC\nfrom .provisioning import KernelProvisionerBase\nfrom .provisioning import KernelProvisionerFactory as KPF # noqa\n\n\nclass _ShutdownStatus(Enum):\n """\n\n This is so far used only for testing in order to track the internal state of\n the shutdown logic, and verifying which path is taken for which\n missbehavior.\n\n """\n\n Unset = None\n ShutdownRequest = "ShutdownRequest"\n SigtermRequest = "SigtermRequest"\n SigkillRequest = "SigkillRequest"\n\n\nF = t.TypeVar("F", bound=t.Callable[..., t.Any])\n\n\ndef _get_future() -> t.Union[Future, CFuture]:\n """Get an appropriate Future object"""\n try:\n asyncio.get_running_loop()\n return Future()\n except RuntimeError:\n # No event loop running, use concurrent future\n return CFuture()\n\n\ndef in_pending_state(method: F) -> F:\n """Sets the kernel to a pending state by\n creating a fresh Future for the KernelManager's `ready`\n attribute. Once the method is finished, set the Future's results.\n """\n\n @t.no_type_check\n @functools.wraps(method)\n async def wrapper(self: t.Any, *args: t.Any, **kwargs: t.Any) -> t.Any:\n """Create a future for the decorated method."""\n if self._attempted_start or not self._ready:\n self._ready = _get_future()\n try:\n # call wrapped method, await, and set the result or exception.\n out = await method(self, *args, **kwargs)\n # Add a small sleep to ensure tests can capture the state before done\n await asyncio.sleep(0.01)\n if self.owns_kernel:\n self._ready.set_result(None)\n return out\n except Exception as e:\n self._ready.set_exception(e)\n self.log.exception(self._ready.exception())\n raise e\n\n return t.cast(F, wrapper)\n\n\nclass KernelManager(ConnectionFileMixin):\n """Manages a single kernel in a subprocess on this host.\n\n This version starts kernels with Popen.\n """\n\n _ready: t.Optional[t.Union[Future, CFuture]]\n\n def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n """Initialize a kernel manager."""\n if args:\n warnings.warn(\n "Passing positional only arguments to "\n "`KernelManager.__init__` is deprecated since jupyter_client"\n " 8.6, and will become an error on future versions. Positional "\n " arguments have been ignored since jupyter_client 7.0",\n DeprecationWarning,\n stacklevel=2,\n )\n self._owns_kernel = kwargs.pop("owns_kernel", True)\n super().__init__(**kwargs)\n self._shutdown_status = _ShutdownStatus.Unset\n self._attempted_start = False\n self._ready = None\n\n _created_context: Bool = Bool(False)\n\n # The PyZMQ Context to use for communication with the kernel.\n context: Instance = Instance(zmq.Context)\n\n @default("context")\n def _context_default(self) -> zmq.Context:\n self._created_context = True\n return zmq.Context()\n\n # the class to create with our `client` method\n client_class: DottedObjectName = DottedObjectName(\n "jupyter_client.blocking.BlockingKernelClient"\n )\n client_factory: Type = Type(klass=KernelClient)\n\n @default("client_factory")\n def _client_factory_default(self) -> Type:\n return import_item(self.client_class)\n\n @observe("client_class")\n def _client_class_changed(self, change: t.Dict[str, DottedObjectName]) -> None:\n self.client_factory = import_item(str(change["new"]))\n\n kernel_id: t.Union[str, Unicode] = Unicode(None, allow_none=True)\n\n # The kernel provisioner with which this KernelManager is communicating.\n # This will generally be a LocalProvisioner instance unless the kernelspec\n # indicates otherwise.\n provisioner: t.Optional[KernelProvisionerBase] = None\n\n kernel_spec_manager: Instance = Instance(kernelspec.KernelSpecManager)\n\n @default("kernel_spec_manager")\n def _kernel_spec_manager_default(self) -> kernelspec.KernelSpecManager:\n return kernelspec.KernelSpecManager(data_dir=self.data_dir)\n\n @observe("kernel_spec_manager")\n @observe_compat\n def _kernel_spec_manager_changed(self, change: t.Dict[str, Instance]) -> None:\n self._kernel_spec = None\n\n shutdown_wait_time: Float = Float(\n 5.0,\n config=True,\n help="Time to wait for a kernel to terminate before killing it, "\n "in seconds. When a shutdown request is initiated, the kernel "\n "will be immediately sent an interrupt (SIGINT), followed"\n "by a shutdown_request message, after 1/2 of `shutdown_wait_time`"\n "it will be sent a terminate (SIGTERM) request, and finally at "\n "the end of `shutdown_wait_time` will be killed (SIGKILL). terminate "\n "and kill may be equivalent on windows. Note that this value can be"\n "overridden by the in-use kernel provisioner since shutdown times may"\n "vary by provisioned environment.",\n )\n\n kernel_name: t.Union[str, Unicode] = Unicode(kernelspec.NATIVE_KERNEL_NAME)\n\n @observe("kernel_name")\n def _kernel_name_changed(self, change: t.Dict[str, str]) -> None:\n self._kernel_spec = None\n if change["new"] == "python":\n self.kernel_name = kernelspec.NATIVE_KERNEL_NAME\n\n _kernel_spec: t.Optional[kernelspec.KernelSpec] = None\n\n @property\n def kernel_spec(self) -> t.Optional[kernelspec.KernelSpec]:\n if self._kernel_spec is None and self.kernel_name != "":\n self._kernel_spec = self.kernel_spec_manager.get_kernel_spec(self.kernel_name)\n return self._kernel_spec\n\n cache_ports: Bool = Bool(\n False,\n config=True,\n help="True if the MultiKernelManager should cache ports for this KernelManager instance",\n )\n\n @default("cache_ports")\n def _default_cache_ports(self) -> bool:\n return self.transport == "tcp"\n\n @property\n def ready(self) -> t.Union[CFuture, Future]:\n """A future that resolves when the kernel process has started for the first time"""\n if not self._ready:\n self._ready = _get_future()\n return self._ready\n\n @property\n def ipykernel(self) -> bool:\n return self.kernel_name in {"python", "python2", "python3"}\n\n # Protected traits\n _launch_args: t.Optional["Dict[str, Any]"] = Dict(allow_none=True)\n _control_socket: Any = Any()\n\n _restarter: Any = Any()\n\n autorestart: Bool = Bool(\n True, config=True, help="""Should we autorestart the kernel if it dies."""\n )\n\n shutting_down: bool = False\n\n def __del__(self) -> None:\n self._close_control_socket()\n self.cleanup_connection_file()\n\n # --------------------------------------------------------------------------\n # Kernel restarter\n # --------------------------------------------------------------------------\n\n def start_restarter(self) -> None:\n """Start the kernel restarter."""\n pass\n\n def stop_restarter(self) -> None:\n """Stop the kernel restarter."""\n pass\n\n def add_restart_callback(self, callback: t.Callable, event: str = "restart") -> None:\n """Register a callback to be called when a kernel is restarted"""\n if self._restarter is None:\n return\n self._restarter.add_callback(callback, event)\n\n def remove_restart_callback(self, callback: t.Callable, event: str = "restart") -> None:\n """Unregister a callback to be called when a kernel is restarted"""\n if self._restarter is None:\n return\n self._restarter.remove_callback(callback, event)\n\n # --------------------------------------------------------------------------\n # create a Client connected to our Kernel\n # --------------------------------------------------------------------------\n\n def client(self, **kwargs: t.Any) -> BlockingKernelClient:\n """Create a client configured to connect to our kernel"""\n kw: dict = {}\n kw.update(self.get_connection_info(session=True))\n kw.update(\n {\n "connection_file": self.connection_file,\n "parent": self,\n }\n )\n\n # add kwargs last, for manual overrides\n kw.update(kwargs)\n return self.client_factory(**kw)\n\n # --------------------------------------------------------------------------\n # Kernel management\n # --------------------------------------------------------------------------\n\n def update_env(self, *, env: t.Dict[str, str]) -> None:\n """\n Allow to update the environment of a kernel manager.\n\n This will take effect only after kernel restart when the new env is\n passed to the new kernel.\n\n This is useful as some of the information of the current kernel reflect\n the state of the session that started it, and those session information\n (like the attach file path, or name), are mutable.\n\n .. version-added: 8.5\n """\n # Mypy think this is unreachable as it see _launch_args as Dict, not t.Dict\n if (\n isinstance(self._launch_args, dict)\n and "env" in self._launch_args\n and isinstance(self._launch_args["env"], dict) # type: ignore [unreachable]\n ):\n self._launch_args["env"].update(env) # type: ignore [unreachable]\n\n def format_kernel_cmd(self, extra_arguments: t.Optional[t.List[str]] = None) -> t.List[str]:\n """Replace templated args (e.g. {connection_file})"""\n extra_arguments = extra_arguments or []\n assert self.kernel_spec is not None\n cmd = self.kernel_spec.argv + extra_arguments\n\n if cmd and cmd[0] in {\n "python",\n "python%i" % sys.version_info[0],\n "python%i.%i" % sys.version_info[:2],\n }:\n # executable is 'python' or 'python3', use sys.executable.\n # These will typically be the same,\n # but if the current process is in an env\n # and has been launched by abspath without\n # activating the env, python on PATH may not be sys.executable,\n # but it should be.\n cmd[0] = sys.executable\n\n # Make sure to use the realpath for the connection_file\n # On windows, when running with the store python, the connection_file path\n # is not usable by non python kernels because the path is being rerouted when\n # inside of a store app.\n # See this bug here: https://bugs.python.org/issue41196\n ns: t.Dict[str, t.Any] = {\n "connection_file": os.path.realpath(self.connection_file),\n "prefix": sys.prefix,\n }\n\n if self.kernel_spec: # type:ignore[truthy-bool]\n ns["resource_dir"] = self.kernel_spec.resource_dir\n assert isinstance(self._launch_args, dict)\n\n ns.update(self._launch_args)\n\n pat = re.compile(r"\{([A-Za-z0-9_]+)\}")\n\n def from_ns(match: t.Any) -> t.Any:\n """Get the key out of ns if it's there, otherwise no change."""\n return ns.get(match.group(1), match.group())\n\n return [pat.sub(from_ns, arg) for arg in cmd]\n\n async def _async_launch_kernel(self, kernel_cmd: t.List[str], **kw: t.Any) -> None:\n """actually launch the kernel\n\n override in a subclass to launch kernel subprocesses differently\n Note that provisioners can now be used to customize kernel environments\n and\n """\n assert self.provisioner is not None\n connection_info = await self.provisioner.launch_kernel(kernel_cmd, **kw)\n assert self.provisioner.has_process\n # Provisioner provides the connection information. Load into kernel manager\n # and write the connection file, if not already done.\n self._reconcile_connection_info(connection_info)\n\n _launch_kernel = run_sync(_async_launch_kernel)\n\n # Control socket used for polite kernel shutdown\n\n def _connect_control_socket(self) -> None:\n if self._control_socket is None:\n self._control_socket = self._create_connected_socket("control")\n self._control_socket.linger = 100\n\n def _close_control_socket(self) -> None:\n if self._control_socket is None:\n return\n self._control_socket.close()\n self._control_socket = None\n\n async def _async_pre_start_kernel(\n self, **kw: t.Any\n ) -> t.Tuple[t.List[str], t.Dict[str, t.Any]]:\n """Prepares a kernel for startup in a separate process.\n\n If random ports (port=0) are being used, this method must be called\n before the channels are created.\n\n Parameters\n ----------\n `**kw` : optional\n keyword arguments that are passed down to build the kernel_cmd\n and launching the kernel (e.g. Popen kwargs).\n """\n self.shutting_down = False\n self.kernel_id = self.kernel_id or kw.pop("kernel_id", str(uuid.uuid4()))\n # save kwargs for use in restart\n # assigning Traitlets Dicts to Dict make mypy unhappy but is ok\n self._launch_args = kw.copy() # type:ignore [assignment]\n if self.provisioner is None: # will not be None on restarts\n self.provisioner = KPF.instance(parent=self.parent).create_provisioner_instance(\n self.kernel_id,\n self.kernel_spec,\n parent=self,\n )\n kw = await self.provisioner.pre_launch(**kw)\n kernel_cmd = kw.pop("cmd")\n return kernel_cmd, kw\n\n pre_start_kernel = run_sync(_async_pre_start_kernel)\n\n async def _async_post_start_kernel(self, **kw: t.Any) -> None:\n """Performs any post startup tasks relative to the kernel.\n\n Parameters\n ----------\n `**kw` : optional\n keyword arguments that were used in the kernel process's launch.\n """\n self.start_restarter()\n self._connect_control_socket()\n assert self.provisioner is not None\n await self.provisioner.post_launch(**kw)\n\n post_start_kernel = run_sync(_async_post_start_kernel)\n\n @in_pending_state\n async def _async_start_kernel(self, **kw: t.Any) -> None:\n """Starts a kernel on this host in a separate process.\n\n If random ports (port=0) are being used, this method must be called\n before the channels are created.\n\n Parameters\n ----------\n `**kw` : optional\n keyword arguments that are passed down to build the kernel_cmd\n and launching the kernel (e.g. Popen kwargs).\n """\n self._attempted_start = True\n kernel_cmd, kw = await self._async_pre_start_kernel(**kw)\n\n # launch the kernel subprocess\n self.log.debug("Starting kernel: %s", kernel_cmd)\n await self._async_launch_kernel(kernel_cmd, **kw)\n await self._async_post_start_kernel(**kw)\n\n start_kernel = run_sync(_async_start_kernel)\n\n async def _async_request_shutdown(self, restart: bool = False) -> None:\n """Send a shutdown request via control channel"""\n content = {"restart": restart}\n msg = self.session.msg("shutdown_request", content=content)\n # ensure control socket is connected\n self._connect_control_socket()\n self.session.send(self._control_socket, msg)\n assert self.provisioner is not None\n await self.provisioner.shutdown_requested(restart=restart)\n self._shutdown_status = _ShutdownStatus.ShutdownRequest\n\n request_shutdown = run_sync(_async_request_shutdown)\n\n async def _async_finish_shutdown(\n self,\n waittime: t.Optional[float] = None,\n pollinterval: float = 0.1,\n restart: bool = False,\n ) -> None:\n """Wait for kernel shutdown, then kill process if it doesn't shutdown.\n\n This does not send shutdown requests - use :meth:`request_shutdown`\n first.\n """\n if waittime is None:\n waittime = max(self.shutdown_wait_time, 0)\n if self.provisioner: # Allow provisioner to override\n waittime = self.provisioner.get_shutdown_wait_time(recommended=waittime)\n\n try:\n await asyncio.wait_for(\n self._async_wait(pollinterval=pollinterval), timeout=waittime / 2\n )\n except asyncio.TimeoutError:\n self.log.debug("Kernel is taking too long to finish, terminating")\n self._shutdown_status = _ShutdownStatus.SigtermRequest\n await self._async_send_kernel_sigterm()\n\n try:\n await asyncio.wait_for(\n self._async_wait(pollinterval=pollinterval), timeout=waittime / 2\n )\n except asyncio.TimeoutError:\n self.log.debug("Kernel is taking too long to finish, killing")\n self._shutdown_status = _ShutdownStatus.SigkillRequest\n await self._async_kill_kernel(restart=restart)\n else:\n # Process is no longer alive, wait and clear\n if self.has_kernel:\n assert self.provisioner is not None\n await self.provisioner.wait()\n\n finish_shutdown = run_sync(_async_finish_shutdown)\n\n async def _async_cleanup_resources(self, restart: bool = False) -> None:\n """Clean up resources when the kernel is shut down"""\n if not restart:\n self.cleanup_connection_file()\n\n self.cleanup_ipc_files()\n self._close_control_socket()\n self.session.parent = None\n\n if self._created_context and not restart:\n self.context.destroy(linger=100)\n\n if self.provisioner:\n await self.provisioner.cleanup(restart=restart)\n\n cleanup_resources = run_sync(_async_cleanup_resources)\n\n @in_pending_state\n async def _async_shutdown_kernel(self, now: bool = False, restart: bool = False) -> None:\n """Attempts to stop the kernel process cleanly.\n\n This attempts to shutdown the kernels cleanly by:\n\n 1. Sending it a shutdown message over the control channel.\n 2. If that fails, the kernel is shutdown forcibly by sending it\n a signal.\n\n Parameters\n ----------\n now : bool\n Should the kernel be forcible killed *now*. This skips the\n first, nice shutdown attempt.\n restart: bool\n Will this kernel be restarted after it is shutdown. When this\n is True, connection files will not be cleaned up.\n """\n if not self.owns_kernel:\n return\n\n self.shutting_down = True # Used by restarter to prevent race condition\n # Stop monitoring for restarting while we shutdown.\n self.stop_restarter()\n\n if self.has_kernel:\n await self._async_interrupt_kernel()\n\n if now:\n await self._async_kill_kernel()\n else:\n await self._async_request_shutdown(restart=restart)\n # Don't send any additional kernel kill messages immediately, to give\n # the kernel a chance to properly execute shutdown actions. Wait for at\n # most 1s, checking every 0.1s.\n await self._async_finish_shutdown(restart=restart)\n\n await self._async_cleanup_resources(restart=restart)\n\n shutdown_kernel = run_sync(_async_shutdown_kernel)\n\n async def _async_restart_kernel(\n self, now: bool = False, newports: bool = False, **kw: t.Any\n ) -> None:\n """Restarts a kernel with the arguments that were used to launch it.\n\n Parameters\n ----------\n now : bool, optional\n If True, the kernel is forcefully restarted *immediately*, without\n having a chance to do any cleanup action. Otherwise the kernel is\n given 1s to clean up before a forceful restart is issued.\n\n In all cases the kernel is restarted, the only difference is whether\n it is given a chance to perform a clean shutdown or not.\n\n newports : bool, optional\n If the old kernel was launched with random ports, this flag decides\n whether the same ports and connection file will be used again.\n If False, the same ports and connection file are used. This is\n the default. If True, new random port numbers are chosen and a\n new connection file is written. It is still possible that the newly\n chosen random port numbers happen to be the same as the old ones.\n\n `**kw` : optional\n Any options specified here will overwrite those used to launch the\n kernel.\n """\n if self._launch_args is None:\n msg = "Cannot restart the kernel. No previous call to 'start_kernel'."\n raise RuntimeError(msg)\n\n # Stop currently running kernel.\n await self._async_shutdown_kernel(now=now, restart=True)\n\n if newports:\n self.cleanup_random_ports()\n\n # Start new kernel.\n self._launch_args.update(kw)\n await self._async_start_kernel(**self._launch_args)\n\n restart_kernel = run_sync(_async_restart_kernel)\n\n @property\n def owns_kernel(self) -> bool:\n return self._owns_kernel\n\n @property\n def has_kernel(self) -> bool:\n """Has a kernel process been started that we are actively managing."""\n return self.provisioner is not None and self.provisioner.has_process\n\n async def _async_send_kernel_sigterm(self, restart: bool = False) -> None:\n """similar to _kill_kernel, but with sigterm (not sigkill), but do not block"""\n if self.has_kernel:\n assert self.provisioner is not None\n await self.provisioner.terminate(restart=restart)\n\n _send_kernel_sigterm = run_sync(_async_send_kernel_sigterm)\n\n async def _async_kill_kernel(self, restart: bool = False) -> None:\n """Kill the running kernel.\n\n This is a private method, callers should use shutdown_kernel(now=True).\n """\n if self.has_kernel:\n assert self.provisioner is not None\n await self.provisioner.kill(restart=restart)\n\n # Wait until the kernel terminates.\n try:\n await asyncio.wait_for(self._async_wait(), timeout=5.0)\n except asyncio.TimeoutError:\n # Wait timed out, just log warning but continue - not much more we can do.\n self.log.warning("Wait for final termination of kernel timed out - continuing...")\n pass\n else:\n # Process is no longer alive, wait and clear\n if self.has_kernel:\n await self.provisioner.wait()\n\n _kill_kernel = run_sync(_async_kill_kernel)\n\n async def _async_interrupt_kernel(self) -> None:\n """Interrupts the kernel by sending it a signal.\n\n Unlike ``signal_kernel``, this operation is well supported on all\n platforms.\n """\n if not self.has_kernel and self._ready is not None:\n if isinstance(self._ready, CFuture):\n ready = asyncio.ensure_future(t.cast(Future[t.Any], self._ready))\n else:\n ready = self._ready\n # Wait for a shutdown if one is in progress.\n if self.shutting_down:\n await ready\n # Wait for a startup.\n await ready\n\n if self.has_kernel:\n assert self.kernel_spec is not None\n interrupt_mode = self.kernel_spec.interrupt_mode\n if interrupt_mode == "signal":\n await self._async_signal_kernel(signal.SIGINT)\n\n elif interrupt_mode == "message":\n msg = self.session.msg("interrupt_request", content={})\n self._connect_control_socket()\n self.session.send(self._control_socket, msg)\n else:\n msg = "Cannot interrupt kernel. No kernel is running!"\n raise RuntimeError(msg)\n\n interrupt_kernel = run_sync(_async_interrupt_kernel)\n\n async def _async_signal_kernel(self, signum: int) -> None:\n """Sends a signal to the process group of the kernel (this\n usually includes the kernel and any subprocesses spawned by\n the kernel).\n\n Note that since only SIGTERM is supported on Windows, this function is\n only useful on Unix systems.\n """\n if self.has_kernel:\n assert self.provisioner is not None\n await self.provisioner.send_signal(signum)\n else:\n msg = "Cannot signal kernel. No kernel is running!"\n raise RuntimeError(msg)\n\n signal_kernel = run_sync(_async_signal_kernel)\n\n async def _async_is_alive(self) -> bool:\n """Is the kernel process still running?"""\n if not self.owns_kernel:\n return True\n\n if self.has_kernel:\n assert self.provisioner is not None\n ret = await self.provisioner.poll()\n if ret is None:\n return True\n return False\n\n is_alive = run_sync(_async_is_alive)\n\n async def _async_wait(self, pollinterval: float = 0.1) -> None:\n # Use busy loop at 100ms intervals, polling until the process is\n # not alive. If we find the process is no longer alive, complete\n # its cleanup via the blocking wait(). Callers are responsible for\n # issuing calls to wait() using a timeout (see _kill_kernel()).\n while await self._async_is_alive():\n await asyncio.sleep(pollinterval)\n\n\nclass AsyncKernelManager(KernelManager):\n """An async kernel manager."""\n\n # the class to create with our `client` method\n client_class: DottedObjectName = DottedObjectName(\n "jupyter_client.asynchronous.AsyncKernelClient"\n )\n client_factory: Type = Type(klass="jupyter_client.asynchronous.AsyncKernelClient")\n\n # The PyZMQ Context to use for communication with the kernel.\n context: Instance = Instance(zmq.asyncio.Context)\n\n @default("context")\n def _context_default(self) -> zmq.asyncio.Context:\n self._created_context = True\n return zmq.asyncio.Context()\n\n def client( # type:ignore[override]\n self, **kwargs: t.Any\n ) -> AsyncKernelClient:\n """Get a client for the manager."""\n return super().client(**kwargs) # type:ignore[return-value]\n\n _launch_kernel = KernelManager._async_launch_kernel # type:ignore[assignment]\n start_kernel: t.Callable[..., t.Awaitable] = KernelManager._async_start_kernel # type:ignore[assignment]\n pre_start_kernel: t.Callable[..., t.Awaitable] = KernelManager._async_pre_start_kernel # type:ignore[assignment]\n post_start_kernel: t.Callable[..., t.Awaitable] = KernelManager._async_post_start_kernel # type:ignore[assignment]\n request_shutdown: t.Callable[..., t.Awaitable] = KernelManager._async_request_shutdown # type:ignore[assignment]\n finish_shutdown: t.Callable[..., t.Awaitable] = KernelManager._async_finish_shutdown # type:ignore[assignment]\n cleanup_resources: t.Callable[..., t.Awaitable] = KernelManager._async_cleanup_resources # type:ignore[assignment]\n shutdown_kernel: t.Callable[..., t.Awaitable] = KernelManager._async_shutdown_kernel # type:ignore[assignment]\n restart_kernel: t.Callable[..., t.Awaitable] = KernelManager._async_restart_kernel # type:ignore[assignment]\n _send_kernel_sigterm = KernelManager._async_send_kernel_sigterm # type:ignore[assignment]\n _kill_kernel = KernelManager._async_kill_kernel # type:ignore[assignment]\n interrupt_kernel: t.Callable[..., t.Awaitable] = KernelManager._async_interrupt_kernel # type:ignore[assignment]\n signal_kernel: t.Callable[..., t.Awaitable] = KernelManager._async_signal_kernel # type:ignore[assignment]\n is_alive: t.Callable[..., t.Awaitable] = KernelManager._async_is_alive # type:ignore[assignment]\n\n\nKernelManagerABC.register(KernelManager)\n\n\ndef start_new_kernel(\n startup_timeout: float = 60, kernel_name: str = "python", **kwargs: t.Any\n) -> t.Tuple[KernelManager, BlockingKernelClient]:\n """Start a new kernel, and return its Manager and Client"""\n km = KernelManager(kernel_name=kernel_name)\n km.start_kernel(**kwargs)\n kc = km.client()\n kc.start_channels()\n try:\n kc.wait_for_ready(timeout=startup_timeout)\n except RuntimeError:\n kc.stop_channels()\n km.shutdown_kernel()\n raise\n\n return km, kc\n\n\nasync def start_new_async_kernel(\n startup_timeout: float = 60, kernel_name: str = "python", **kwargs: t.Any\n) -> t.Tuple[AsyncKernelManager, AsyncKernelClient]:\n """Start a new kernel, and return its Manager and Client"""\n km = AsyncKernelManager(kernel_name=kernel_name)\n await km.start_kernel(**kwargs)\n kc = km.client()\n kc.start_channels()\n try:\n await kc.wait_for_ready(timeout=startup_timeout)\n except RuntimeError:\n kc.stop_channels()\n await km.shutdown_kernel()\n raise\n\n return (km, kc)\n\n\n@contextmanager\ndef run_kernel(**kwargs: t.Any) -> t.Iterator[KernelClient]:\n """Context manager to create a kernel in a subprocess.\n\n The kernel is shut down when the context exits.\n\n Returns\n -------\n kernel_client: connected KernelClient instance\n """\n km, kc = start_new_kernel(**kwargs)\n try:\n yield kc\n finally:\n kc.stop_channels()\n km.shutdown_kernel(now=True)\n
.venv\Lib\site-packages\jupyter_client\manager.py
manager.py
Python
30,322
0.95
0.162531
0.088821
node-utils
448
2025-04-11T17:52:23.631146
BSD-3-Clause
false
39ed7bacff19948c9ba77657256fe08d
"""Abstract base class for kernel managers."""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nimport abc\nfrom typing import Any\n\n\nclass KernelManagerABC(metaclass=abc.ABCMeta):\n """KernelManager ABC.\n\n The docstrings for this class can be found in the base implementation:\n\n `jupyter_client.manager.KernelManager`\n """\n\n @abc.abstractproperty\n def kernel(self) -> Any:\n pass\n\n # --------------------------------------------------------------------------\n # Kernel management\n # --------------------------------------------------------------------------\n\n @abc.abstractmethod\n def start_kernel(self, **kw: Any) -> None:\n """Start the kernel."""\n pass\n\n @abc.abstractmethod\n def shutdown_kernel(self, now: bool = False, restart: bool = False) -> None:\n """Shut down the kernel."""\n pass\n\n @abc.abstractmethod\n def restart_kernel(self, now: bool = False, **kw: Any) -> None:\n """Restart the kernel."""\n pass\n\n @abc.abstractproperty\n def has_kernel(self) -> bool:\n pass\n\n @abc.abstractmethod\n def interrupt_kernel(self) -> None:\n """Interrupt the kernel."""\n pass\n\n @abc.abstractmethod\n def signal_kernel(self, signum: int) -> None:\n """Send a signal to the kernel."""\n pass\n\n @abc.abstractmethod\n def is_alive(self) -> bool:\n """Test whether the kernel is alive."""\n pass\n
.venv\Lib\site-packages\jupyter_client\managerabc.py
managerabc.py
Python
1,490
0.95
0.232143
0.116279
node-utils
252
2025-04-19T07:19:06.564211
Apache-2.0
false
24902c3b1309d87d1f071ea4e9a0fa31
"""A kernel manager for multiple kernels"""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport asyncio\nimport json\nimport os\nimport socket\nimport typing as t\nimport uuid\nfrom functools import wraps\nfrom pathlib import Path\n\nimport zmq\nfrom traitlets import Any, Bool, Dict, DottedObjectName, Instance, Unicode, default, observe\nfrom traitlets.config.configurable import LoggingConfigurable\nfrom traitlets.utils.importstring import import_item\n\nfrom .connect import KernelConnectionInfo\nfrom .kernelspec import NATIVE_KERNEL_NAME, KernelSpecManager\nfrom .manager import KernelManager\nfrom .utils import ensure_async, run_sync, utcnow\n\n\nclass DuplicateKernelError(Exception):\n pass\n\n\ndef kernel_method(f: t.Callable) -> t.Callable:\n """decorator for proxying MKM.method(kernel_id) to individual KMs by ID"""\n\n @wraps(f)\n def wrapped(\n self: t.Any, kernel_id: str, *args: t.Any, **kwargs: t.Any\n ) -> t.Callable | t.Awaitable:\n # get the kernel\n km = self.get_kernel(kernel_id)\n method = getattr(km, f.__name__)\n # call the kernel's method\n r = method(*args, **kwargs)\n # last thing, call anything defined in the actual class method\n # such as logging messages\n f(self, kernel_id, *args, **kwargs)\n # return the method result\n return r\n\n return wrapped\n\n\nclass MultiKernelManager(LoggingConfigurable):\n """A class for managing multiple kernels."""\n\n default_kernel_name = Unicode(\n NATIVE_KERNEL_NAME, help="The name of the default kernel to start"\n ).tag(config=True)\n\n kernel_spec_manager = Instance(KernelSpecManager, allow_none=True)\n\n kernel_manager_class = DottedObjectName(\n "jupyter_client.ioloop.IOLoopKernelManager",\n help="""The kernel manager class. This is configurable to allow\n subclassing of the KernelManager for customized behavior.\n """,\n ).tag(config=True)\n\n @observe("kernel_manager_class")\n def _kernel_manager_class_changed(self, change: t.Any) -> None:\n self.kernel_manager_factory = self._create_kernel_manager_factory()\n\n kernel_manager_factory = Any(help="this is kernel_manager_class after import")\n\n @default("kernel_manager_factory")\n def _kernel_manager_factory_default(self) -> t.Callable:\n return self._create_kernel_manager_factory()\n\n def _create_kernel_manager_factory(self) -> t.Callable:\n kernel_manager_ctor = import_item(self.kernel_manager_class)\n\n def create_kernel_manager(*args: t.Any, **kwargs: t.Any) -> KernelManager:\n if self.shared_context:\n if self.context.closed:\n # recreate context if closed\n self.context = self._context_default()\n kwargs.setdefault("context", self.context)\n km = kernel_manager_ctor(*args, **kwargs)\n return km\n\n return create_kernel_manager\n\n shared_context = Bool(\n True,\n help="Share a single zmq.Context to talk to all my kernels",\n ).tag(config=True)\n\n context = Instance("zmq.Context")\n\n _created_context = Bool(False)\n\n _pending_kernels = Dict()\n\n @property\n def _starting_kernels(self) -> dict:\n """A shim for backwards compatibility."""\n return self._pending_kernels\n\n @default("context")\n def _context_default(self) -> zmq.Context:\n self._created_context = True\n return zmq.Context()\n\n connection_dir = Unicode("")\n external_connection_dir = Unicode(None, allow_none=True)\n\n _kernels = Dict()\n\n def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(*args, **kwargs)\n self.kernel_id_to_connection_file: dict[str, Path] = {}\n\n def __del__(self) -> None:\n """Handle garbage collection. Destroy context if applicable."""\n if self._created_context and self.context and not self.context.closed:\n if self.log:\n self.log.debug("Destroying zmq context for %s", self)\n self.context.destroy()\n try:\n super_del = super().__del__ # type:ignore[misc]\n except AttributeError:\n pass\n else:\n super_del()\n\n def list_kernel_ids(self) -> list[str]:\n """Return a list of the kernel ids of the active kernels."""\n if self.external_connection_dir is not None:\n external_connection_dir = Path(self.external_connection_dir)\n if external_connection_dir.is_dir():\n connection_files = [p for p in external_connection_dir.iterdir() if p.is_file()]\n\n # remove kernels (whose connection file has disappeared) from our list\n k = list(self.kernel_id_to_connection_file.keys())\n v = list(self.kernel_id_to_connection_file.values())\n for connection_file in list(self.kernel_id_to_connection_file.values()):\n if connection_file not in connection_files:\n kernel_id = k[v.index(connection_file)]\n del self.kernel_id_to_connection_file[kernel_id]\n del self._kernels[kernel_id]\n\n # add kernels (whose connection file appeared) to our list\n for connection_file in connection_files:\n if connection_file in self.kernel_id_to_connection_file.values():\n continue\n try:\n connection_info: KernelConnectionInfo = json.loads(\n connection_file.read_text()\n )\n except Exception: # noqa: S112\n continue\n self.log.debug("Loading connection file %s", connection_file)\n if not ("kernel_name" in connection_info and "key" in connection_info):\n continue\n # it looks like a connection file\n kernel_id = self.new_kernel_id()\n self.kernel_id_to_connection_file[kernel_id] = connection_file\n km = self.kernel_manager_factory(\n parent=self,\n log=self.log,\n owns_kernel=False,\n )\n km.load_connection_info(connection_info)\n km.last_activity = utcnow()\n km.execution_state = "idle"\n km.connections = 1\n km.kernel_id = kernel_id\n km.kernel_name = connection_info["kernel_name"]\n km.ready.set_result(None)\n\n self._kernels[kernel_id] = km\n\n # Create a copy so we can iterate over kernels in operations\n # that delete keys.\n return list(self._kernels.keys())\n\n def __len__(self) -> int:\n """Return the number of running kernels."""\n return len(self.list_kernel_ids())\n\n def __contains__(self, kernel_id: str) -> bool:\n return kernel_id in self._kernels\n\n def pre_start_kernel(\n self, kernel_name: str | None, kwargs: t.Any\n ) -> tuple[KernelManager, str, str]:\n # kwargs should be mutable, passing it as a dict argument.\n kernel_id = kwargs.pop("kernel_id", self.new_kernel_id(**kwargs))\n if kernel_id in self:\n raise DuplicateKernelError("Kernel already exists: %s" % kernel_id)\n\n if kernel_name is None:\n kernel_name = self.default_kernel_name\n # kernel_manager_factory is the constructor for the KernelManager\n # subclass we are using. It can be configured as any Configurable,\n # including things like its transport and ip.\n constructor_kwargs = {}\n if self.kernel_spec_manager:\n constructor_kwargs["kernel_spec_manager"] = self.kernel_spec_manager\n km = self.kernel_manager_factory(\n connection_file=os.path.join(self.connection_dir, "kernel-%s.json" % kernel_id),\n parent=self,\n log=self.log,\n kernel_name=kernel_name,\n **constructor_kwargs,\n )\n return km, kernel_name, kernel_id\n\n def update_env(self, *, kernel_id: str, env: t.Dict[str, str]) -> None:\n """\n Allow to update the environment of the given kernel.\n\n Forward the update env request to the corresponding kernel.\n\n .. version-added: 8.5\n """\n if kernel_id in self:\n self._kernels[kernel_id].update_env(env=env)\n\n async def _add_kernel_when_ready(\n self, kernel_id: str, km: KernelManager, kernel_awaitable: t.Awaitable\n ) -> None:\n try:\n await kernel_awaitable\n self._kernels[kernel_id] = km\n self._pending_kernels.pop(kernel_id, None)\n except Exception as e:\n self.log.exception(e)\n\n async def _remove_kernel_when_ready(\n self, kernel_id: str, kernel_awaitable: t.Awaitable\n ) -> None:\n try:\n await kernel_awaitable\n self.remove_kernel(kernel_id)\n self._pending_kernels.pop(kernel_id, None)\n except Exception as e:\n self.log.exception(e)\n\n def _using_pending_kernels(self) -> bool:\n """Returns a boolean; a clearer method for determining if\n this multikernelmanager is using pending kernels or not\n """\n return getattr(self, "use_pending_kernels", False)\n\n async def _async_start_kernel(self, *, kernel_name: str | None = None, **kwargs: t.Any) -> str:\n """Start a new kernel.\n\n The caller can pick a kernel_id by passing one in as a keyword arg,\n otherwise one will be generated using new_kernel_id().\n\n The kernel ID for the newly started kernel is returned.\n """\n km, kernel_name, kernel_id = self.pre_start_kernel(kernel_name, kwargs)\n if not isinstance(km, KernelManager):\n self.log.warning( # type:ignore[unreachable]\n "Kernel manager class ({km_class}) is not an instance of 'KernelManager'!".format(\n km_class=self.kernel_manager_class.__class__\n )\n )\n kwargs["kernel_id"] = kernel_id # Make kernel_id available to manager and provisioner\n\n starter = ensure_async(km.start_kernel(**kwargs))\n task = asyncio.create_task(self._add_kernel_when_ready(kernel_id, km, starter))\n self._pending_kernels[kernel_id] = task\n # Handling a Pending Kernel\n if self._using_pending_kernels():\n # If using pending kernels, do not block\n # on the kernel start.\n self._kernels[kernel_id] = km\n else:\n await task\n # raise an exception if one occurred during kernel startup.\n if km.ready.exception():\n raise km.ready.exception() # type: ignore[misc]\n\n return kernel_id\n\n start_kernel = run_sync(_async_start_kernel)\n\n async def _async_shutdown_kernel(\n self,\n kernel_id: str,\n now: bool | None = False,\n restart: bool | None = False,\n ) -> None:\n """Shutdown a kernel by its kernel uuid.\n\n Parameters\n ==========\n kernel_id : uuid\n The id of the kernel to shutdown.\n now : bool\n Should the kernel be shutdown forcibly using a signal.\n restart : bool\n Will the kernel be restarted?\n """\n self.log.info("Kernel shutdown: %s", kernel_id)\n # If the kernel is still starting, wait for it to be ready.\n if kernel_id in self._pending_kernels:\n task = self._pending_kernels[kernel_id]\n try:\n await task\n km = self.get_kernel(kernel_id)\n await t.cast(asyncio.Future, km.ready)\n except asyncio.CancelledError:\n pass\n except Exception:\n self.remove_kernel(kernel_id)\n return\n km = self.get_kernel(kernel_id)\n # If a pending kernel raised an exception, remove it.\n if not km.ready.cancelled() and km.ready.exception():\n self.remove_kernel(kernel_id)\n return\n stopper = ensure_async(km.shutdown_kernel(now, restart))\n fut = asyncio.ensure_future(self._remove_kernel_when_ready(kernel_id, stopper))\n self._pending_kernels[kernel_id] = fut\n # Await the kernel if not using pending kernels.\n if not self._using_pending_kernels():\n await fut\n # raise an exception if one occurred during kernel shutdown.\n if km.ready.exception():\n raise km.ready.exception() # type: ignore[misc]\n\n shutdown_kernel = run_sync(_async_shutdown_kernel)\n\n @kernel_method\n def request_shutdown(self, kernel_id: str, restart: bool | None = False) -> None:\n """Ask a kernel to shut down by its kernel uuid"""\n\n @kernel_method\n def finish_shutdown(\n self,\n kernel_id: str,\n waittime: float | None = None,\n pollinterval: float | None = 0.1,\n ) -> None:\n """Wait for a kernel to finish shutting down, and kill it if it doesn't"""\n self.log.info("Kernel shutdown: %s", kernel_id)\n\n @kernel_method\n def cleanup_resources(self, kernel_id: str, restart: bool = False) -> None:\n """Clean up a kernel's resources"""\n\n def remove_kernel(self, kernel_id: str) -> KernelManager:\n """remove a kernel from our mapping.\n\n Mainly so that a kernel can be removed if it is already dead,\n without having to call shutdown_kernel.\n\n The kernel object is returned, or `None` if not found.\n """\n return self._kernels.pop(kernel_id, None)\n\n async def _async_shutdown_all(self, now: bool = False) -> None:\n """Shutdown all kernels."""\n kids = self.list_kernel_ids()\n kids += list(self._pending_kernels)\n kms = list(self._kernels.values())\n futs = [self._async_shutdown_kernel(kid, now=now) for kid in set(kids)]\n await asyncio.gather(*futs)\n # If using pending kernels, the kernels will not have been fully shut down.\n if self._using_pending_kernels():\n for km in kms:\n try:\n await km.ready\n except asyncio.CancelledError:\n self._pending_kernels[km.kernel_id].cancel()\n except Exception:\n # Will have been logged in _add_kernel_when_ready\n pass\n\n shutdown_all = run_sync(_async_shutdown_all)\n\n def interrupt_kernel(self, kernel_id: str) -> None:\n """Interrupt (SIGINT) the kernel by its uuid.\n\n Parameters\n ==========\n kernel_id : uuid\n The id of the kernel to interrupt.\n """\n kernel = self.get_kernel(kernel_id)\n if not kernel.ready.done():\n msg = "Kernel is in a pending state. Cannot interrupt."\n raise RuntimeError(msg)\n out = kernel.interrupt_kernel()\n self.log.info("Kernel interrupted: %s", kernel_id)\n return out\n\n @kernel_method\n def signal_kernel(self, kernel_id: str, signum: int) -> None:\n """Sends a signal to the kernel by its uuid.\n\n Note that since only SIGTERM is supported on Windows, this function\n is only useful on Unix systems.\n\n Parameters\n ==========\n kernel_id : uuid\n The id of the kernel to signal.\n signum : int\n Signal number to send kernel.\n """\n self.log.info("Signaled Kernel %s with %s", kernel_id, signum)\n\n async def _async_restart_kernel(self, kernel_id: str, now: bool = False) -> None:\n """Restart a kernel by its uuid, keeping the same ports.\n\n Parameters\n ==========\n kernel_id : uuid\n The id of the kernel to interrupt.\n now : bool, optional\n If True, the kernel is forcefully restarted *immediately*, without\n having a chance to do any cleanup action. Otherwise the kernel is\n given 1s to clean up before a forceful restart is issued.\n\n In all cases the kernel is restarted, the only difference is whether\n it is given a chance to perform a clean shutdown or not.\n """\n kernel = self.get_kernel(kernel_id)\n if self._using_pending_kernels() and not kernel.ready.done():\n msg = "Kernel is in a pending state. Cannot restart."\n raise RuntimeError(msg)\n await ensure_async(kernel.restart_kernel(now=now))\n self.log.info("Kernel restarted: %s", kernel_id)\n\n restart_kernel = run_sync(_async_restart_kernel)\n\n @kernel_method\n def is_alive(self, kernel_id: str) -> bool: # type:ignore[empty-body]\n """Is the kernel alive.\n\n This calls KernelManager.is_alive() which calls Popen.poll on the\n actual kernel subprocess.\n\n Parameters\n ==========\n kernel_id : uuid\n The id of the kernel.\n """\n\n def _check_kernel_id(self, kernel_id: str) -> None:\n """check that a kernel id is valid"""\n if kernel_id not in self:\n raise KeyError("Kernel with id not found: %s" % kernel_id)\n\n def get_kernel(self, kernel_id: str) -> KernelManager:\n """Get the single KernelManager object for a kernel by its uuid.\n\n Parameters\n ==========\n kernel_id : uuid\n The id of the kernel.\n """\n self._check_kernel_id(kernel_id)\n return self._kernels[kernel_id]\n\n @kernel_method\n def add_restart_callback(\n self, kernel_id: str, callback: t.Callable, event: str = "restart"\n ) -> None:\n """add a callback for the KernelRestarter"""\n\n @kernel_method\n def remove_restart_callback(\n self, kernel_id: str, callback: t.Callable, event: str = "restart"\n ) -> None:\n """remove a callback for the KernelRestarter"""\n\n @kernel_method\n def get_connection_info(self, kernel_id: str) -> dict[str, t.Any]: # type:ignore[empty-body]\n """Return a dictionary of connection data for a kernel.\n\n Parameters\n ==========\n kernel_id : uuid\n The id of the kernel.\n\n Returns\n =======\n connection_dict : dict\n A dict of the information needed to connect to a kernel.\n This includes the ip address and the integer port\n numbers of the different channels (stdin_port, iopub_port,\n shell_port, hb_port).\n """\n\n @kernel_method\n def connect_iopub( # type:ignore[empty-body]\n self, kernel_id: str, identity: bytes | None = None\n ) -> socket.socket:\n """Return a zmq Socket connected to the iopub channel.\n\n Parameters\n ==========\n kernel_id : uuid\n The id of the kernel\n identity : bytes (optional)\n The zmq identity of the socket\n\n Returns\n =======\n stream : zmq Socket or ZMQStream\n """\n\n @kernel_method\n def connect_shell( # type:ignore[empty-body]\n self, kernel_id: str, identity: bytes | None = None\n ) -> socket.socket:\n """Return a zmq Socket connected to the shell channel.\n\n Parameters\n ==========\n kernel_id : uuid\n The id of the kernel\n identity : bytes (optional)\n The zmq identity of the socket\n\n Returns\n =======\n stream : zmq Socket or ZMQStream\n """\n\n @kernel_method\n def connect_control( # type:ignore[empty-body]\n self, kernel_id: str, identity: bytes | None = None\n ) -> socket.socket:\n """Return a zmq Socket connected to the control channel.\n\n Parameters\n ==========\n kernel_id : uuid\n The id of the kernel\n identity : bytes (optional)\n The zmq identity of the socket\n\n Returns\n =======\n stream : zmq Socket or ZMQStream\n """\n\n @kernel_method\n def connect_stdin( # type:ignore[empty-body]\n self, kernel_id: str, identity: bytes | None = None\n ) -> socket.socket:\n """Return a zmq Socket connected to the stdin channel.\n\n Parameters\n ==========\n kernel_id : uuid\n The id of the kernel\n identity : bytes (optional)\n The zmq identity of the socket\n\n Returns\n =======\n stream : zmq Socket or ZMQStream\n """\n\n @kernel_method\n def connect_hb( # type:ignore[empty-body]\n self, kernel_id: str, identity: bytes | None = None\n ) -> socket.socket:\n """Return a zmq Socket connected to the hb channel.\n\n Parameters\n ==========\n kernel_id : uuid\n The id of the kernel\n identity : bytes (optional)\n The zmq identity of the socket\n\n Returns\n =======\n stream : zmq Socket or ZMQStream\n """\n\n def new_kernel_id(self, **kwargs: t.Any) -> str:\n """\n Returns the id to associate with the kernel for this request. Subclasses may override\n this method to substitute other sources of kernel ids.\n :param kwargs:\n :return: string-ized version 4 uuid\n """\n return str(uuid.uuid4())\n\n\nclass AsyncMultiKernelManager(MultiKernelManager):\n kernel_manager_class = DottedObjectName(\n "jupyter_client.ioloop.AsyncIOLoopKernelManager",\n config=True,\n help="""The kernel manager class. This is configurable to allow\n subclassing of the AsyncKernelManager for customized behavior.\n """,\n )\n\n use_pending_kernels = Bool(\n False,\n help="""Whether to make kernels available before the process has started. The\n kernel has a `.ready` future which can be awaited before connecting""",\n ).tag(config=True)\n\n context = Instance("zmq.asyncio.Context")\n\n @default("context")\n def _context_default(self) -> zmq.asyncio.Context:\n self._created_context = True\n return zmq.asyncio.Context()\n\n start_kernel: t.Callable[..., t.Awaitable] = MultiKernelManager._async_start_kernel # type:ignore[assignment]\n restart_kernel: t.Callable[..., t.Awaitable] = MultiKernelManager._async_restart_kernel # type:ignore[assignment]\n shutdown_kernel: t.Callable[..., t.Awaitable] = MultiKernelManager._async_shutdown_kernel # type:ignore[assignment]\n shutdown_all: t.Callable[..., t.Awaitable] = MultiKernelManager._async_shutdown_all # type:ignore[assignment]\n
.venv\Lib\site-packages\jupyter_client\multikernelmanager.py
multikernelmanager.py
Python
22,601
0.95
0.179487
0.053846
python-kit
179
2025-01-09T20:10:55.421944
GPL-3.0
false
98b8de1d2abe0ebc5f3dd152f036ed0d
"""A basic kernel monitor with autorestarting.\n\nThis watches a kernel's state using KernelManager.is_alive and auto\nrestarts the kernel if it dies.\n\nIt is an incomplete base class, and must be subclassed.\n"""\n# Copyright (c) Jupyter Development Team.\n# Distributed under the terms of the Modified BSD License.\nfrom __future__ import annotations\n\nimport time\nimport typing as t\n\nfrom traitlets import Bool, Dict, Float, Instance, Integer, default\nfrom traitlets.config.configurable import LoggingConfigurable\n\n\nclass KernelRestarter(LoggingConfigurable):\n """Monitor and autorestart a kernel."""\n\n kernel_manager = Instance("jupyter_client.KernelManager")\n\n debug = Bool(\n False,\n config=True,\n help="""Whether to include every poll event in debugging output.\n\n Has to be set explicitly, because there will be *a lot* of output.\n """,\n )\n\n time_to_dead = Float(3.0, config=True, help="""Kernel heartbeat interval in seconds.""")\n\n stable_start_time = Float(\n 10.0,\n config=True,\n help="""The time in seconds to consider the kernel to have completed a stable start up.""",\n )\n\n restart_limit = Integer(\n 5,\n config=True,\n help="""The number of consecutive autorestarts before the kernel is presumed dead.""",\n )\n\n random_ports_until_alive = Bool(\n True,\n config=True,\n help="""Whether to choose new random ports when restarting before the kernel is alive.""",\n )\n _restarting = Bool(False)\n _restart_count = Integer(0)\n _initial_startup = Bool(True)\n _last_dead = Float()\n\n @default("_last_dead")\n def _default_last_dead(self) -> float:\n return time.time()\n\n callbacks = Dict()\n\n def _callbacks_default(self) -> dict[str, list]:\n return {"restart": [], "dead": []}\n\n def start(self) -> None:\n """Start the polling of the kernel."""\n msg = "Must be implemented in a subclass"\n raise NotImplementedError(msg)\n\n def stop(self) -> None:\n """Stop the kernel polling."""\n msg = "Must be implemented in a subclass"\n raise NotImplementedError(msg)\n\n def add_callback(self, f: t.Callable[..., t.Any], event: str = "restart") -> None:\n """register a callback to fire on a particular event\n\n Possible values for event:\n\n 'restart' (default): kernel has died, and will be restarted.\n 'dead': restart has failed, kernel will be left dead.\n\n """\n self.callbacks[event].append(f)\n\n def remove_callback(self, f: t.Callable[..., t.Any], event: str = "restart") -> None:\n """unregister a callback to fire on a particular event\n\n Possible values for event:\n\n 'restart' (default): kernel has died, and will be restarted.\n 'dead': restart has failed, kernel will be left dead.\n\n """\n try:\n self.callbacks[event].remove(f)\n except ValueError:\n pass\n\n def _fire_callbacks(self, event: t.Any) -> None:\n """fire our callbacks for a particular event"""\n for callback in self.callbacks[event]:\n try:\n callback()\n except Exception:\n self.log.error(\n "KernelRestarter: %s callback %r failed",\n event,\n callback,\n exc_info=True,\n )\n\n def poll(self) -> None:\n if self.debug:\n self.log.debug("Polling kernel...")\n if self.kernel_manager.shutting_down:\n self.log.debug("Kernel shutdown in progress...")\n return\n now = time.time()\n if not self.kernel_manager.is_alive():\n self._last_dead = now\n if self._restarting:\n self._restart_count += 1\n else:\n self._restart_count = 1\n\n if self._restart_count > self.restart_limit:\n self.log.warning("KernelRestarter: restart failed")\n self._fire_callbacks("dead")\n self._restarting = False\n self._restart_count = 0\n self.stop()\n else:\n newports = self.random_ports_until_alive and self._initial_startup\n self.log.info(\n "KernelRestarter: restarting kernel (%i/%i), %s random ports",\n self._restart_count,\n self.restart_limit,\n "new" if newports else "keep",\n )\n self._fire_callbacks("restart")\n self.kernel_manager.restart_kernel(now=True, newports=newports)\n self._restarting = True\n else:\n # Since `is_alive` only tests that the kernel process is alive, it does not\n # indicate that the kernel has successfully completed startup. To solve this\n # correctly, we would need to wait for a kernel info reply, but it is not\n # necessarily appropriate to start a kernel client + channels in the\n # restarter. Therefore, we use "has been alive continuously for X time" as a\n # heuristic for a stable start up.\n # See https://github.com/jupyter/jupyter_client/pull/717 for details.\n stable_start_time = self.stable_start_time\n if self.kernel_manager.provisioner:\n stable_start_time = self.kernel_manager.provisioner.get_stable_start_time(\n recommended=stable_start_time\n )\n if self._initial_startup and now - self._last_dead >= stable_start_time:\n self._initial_startup = False\n if self._restarting and now - self._last_dead >= stable_start_time:\n self.log.debug("KernelRestarter: restart apparently succeeded")\n self._restarting = False\n
.venv\Lib\site-packages\jupyter_client\restarter.py
restarter.py
Python
5,852
0.95
0.185185
0.067669
python-kit
912
2023-12-01T15:54:05.923921
GPL-3.0
false
709d75ce6a22f8aa163f7b1168430f25