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
\n\n
.venv\Lib\site-packages\IPython\core\__pycache__\pylabtools.cpython-313.pyc
pylabtools.cpython-313.pyc
Other
16,363
0.95
0.052863
0.005051
node-utils
952
2024-07-26T10:14:40.621307
Apache-2.0
false
8fa1d52e142852d8a868ca24ff7fc3ef
\n\n
.venv\Lib\site-packages\IPython\core\__pycache__\release.cpython-313.pyc
release.cpython-313.pyc
Other
855
0.7
0.1
0
python-kit
383
2024-10-26T21:12:43.640307
Apache-2.0
false
d39c4ea64fa0326198e379e8b4c8b107
\n\n
.venv\Lib\site-packages\IPython\core\__pycache__\shellapp.cpython-313.pyc
shellapp.cpython-313.pyc
Other
24,072
0.95
0.042308
0.008584
python-kit
828
2025-01-20T20:40:54.453969
Apache-2.0
false
3b60e57784ca3541eda77f177b943737
\n\n
.venv\Lib\site-packages\IPython\core\__pycache__\splitinput.cpython-313.pyc
splitinput.cpython-313.pyc
Other
4,920
0.95
0.130952
0.042857
python-kit
118
2024-06-20T09:12:40.862338
GPL-3.0
false
83a0eb6d5a0704ba9cb6f4dba46c1201
\n\n
.venv\Lib\site-packages\IPython\core\__pycache__\tbtools.cpython-313.pyc
tbtools.cpython-313.pyc
Other
20,537
0.8
0.018116
0.004032
node-utils
629
2025-05-22T08:18:18.287802
GPL-3.0
false
2acfa9b4efc8fc220858c3ff7bc6512d
\n\n
.venv\Lib\site-packages\IPython\core\__pycache__\tips.cpython-313.pyc
tips.cpython-313.pyc
Other
4,160
0.95
0.142857
0
awesome-app
617
2024-10-23T21:38:32.336227
Apache-2.0
false
b14f02a35509cc97ea52a4655955cce9
\n\n
.venv\Lib\site-packages\IPython\core\__pycache__\ultratb.cpython-313.pyc
ultratb.cpython-313.pyc
Other
47,227
0.95
0.050654
0.012844
python-kit
334
2024-02-29T05:26:30.468094
GPL-3.0
false
6c22c02a900c30a691be308d4ec9843a
\n\n
.venv\Lib\site-packages\IPython\core\__pycache__\usage.cpython-313.pyc
usage.cpython-313.pyc
Other
13,507
0.95
0.108025
0.064655
python-kit
841
2024-01-10T08:12:22.653811
MIT
false
2a3c7be7259c557d42de40f7035fc456
\n\n
.venv\Lib\site-packages\IPython\core\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
187
0.7
0
0
python-kit
212
2025-02-05T12:57:01.642883
Apache-2.0
false
109fb524c8f0e4c5d3e65a35190b1efe
# -*- coding: utf-8 -*-\n"""\n%store magic for lightweight persistence.\n\nStores variables, aliases and macros in IPython's database.\n\nTo automatically restore stored variables at startup, add this to your\n:file:`ipython_config.py` file::\n\n c.StoreMagics.autorestore = True\n"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport inspect, os, sys, textwrap\n\nfrom IPython.core.error import UsageError\nfrom IPython.core.magic import Magics, magics_class, line_magic\nfrom IPython.testing.skipdoctest import skip_doctest\nfrom traitlets import Bool\n\n\ndef restore_aliases(ip, alias=None):\n staliases = ip.db.get('stored_aliases', {})\n if alias is None:\n for k,v in staliases.items():\n # print("restore alias",k,v) # dbg\n #self.alias_table[k] = v\n ip.alias_manager.define_alias(k,v)\n else:\n ip.alias_manager.define_alias(alias, staliases[alias])\n\n\ndef refresh_variables(ip):\n db = ip.db\n for key in db.keys('autorestore/*'):\n # strip autorestore\n justkey = os.path.basename(key)\n try:\n obj = db[key]\n except KeyError:\n print("Unable to restore variable '%s', ignoring (use %%store -d to forget!)" % justkey)\n print("The error was:", sys.exc_info()[0])\n else:\n # print("restored",justkey,"=",obj) # dbg\n ip.user_ns[justkey] = obj\n\n\ndef restore_dhist(ip):\n ip.user_ns['_dh'] = ip.db.get('dhist',[])\n\n\ndef restore_data(ip):\n refresh_variables(ip)\n restore_aliases(ip)\n restore_dhist(ip)\n\n\n@magics_class\nclass StoreMagics(Magics):\n """Lightweight persistence for python variables.\n\n Provides the %store magic."""\n\n autorestore = Bool(False, help=\n """If True, any %store-d variables will be automatically restored\n when IPython starts.\n """\n ).tag(config=True)\n\n def __init__(self, shell):\n super(StoreMagics, self).__init__(shell=shell)\n self.shell.configurables.append(self)\n if self.autorestore:\n restore_data(self.shell)\n\n @skip_doctest\n @line_magic\n def store(self, parameter_s=''):\n """Lightweight persistence for python variables.\n\n Example::\n\n In [1]: l = ['hello',10,'world']\n In [2]: %store l\n Stored 'l' (list)\n In [3]: exit\n\n (IPython session is closed and started again...)\n\n ville@badger:~$ ipython\n In [1]: l\n NameError: name 'l' is not defined\n In [2]: %store -r\n In [3]: l\n Out[3]: ['hello', 10, 'world']\n\n Usage:\n\n * ``%store`` - Show list of all variables and their current\n values\n * ``%store spam bar`` - Store the *current* value of the variables spam\n and bar to disk\n * ``%store -d spam`` - Remove the variable and its value from storage\n * ``%store -z`` - Remove all variables from storage\n * ``%store -r`` - Refresh all variables, aliases and directory history\n from store (overwrite current vals)\n * ``%store -r spam bar`` - Refresh specified variables and aliases from store\n (delete current val)\n * ``%store foo >a.txt`` - Store value of foo to new file a.txt\n * ``%store foo >>a.txt`` - Append value of foo to file a.txt\n\n It should be noted that if you change the value of a variable, you\n need to %store it again if you want to persist the new value.\n\n Note also that the variables will need to be pickleable; most basic\n python types can be safely %store'd.\n\n Also aliases can be %store'd across sessions.\n To remove an alias from the storage, use the %unalias magic.\n """\n\n opts,argsl = self.parse_options(parameter_s,'drz',mode='string')\n args = argsl.split()\n ip = self.shell\n db = ip.db\n # delete\n if 'd' in opts:\n try:\n todel = args[0]\n except IndexError as e:\n raise UsageError('You must provide the variable to forget') from e\n else:\n try:\n del db['autorestore/' + todel]\n except BaseException as e:\n raise UsageError("Can't delete variable '%s'" % todel) from e\n # reset\n elif 'z' in opts:\n for k in db.keys('autorestore/*'):\n del db[k]\n\n elif 'r' in opts:\n if args:\n for arg in args:\n try:\n obj = db["autorestore/" + arg]\n except KeyError:\n try:\n restore_aliases(ip, alias=arg)\n except KeyError:\n print("no stored variable or alias %s" % arg)\n else:\n ip.user_ns[arg] = obj\n else:\n restore_data(ip)\n\n # run without arguments -> list variables & values\n elif not args:\n vars = db.keys('autorestore/*')\n vars.sort()\n if vars:\n size = max(map(len, vars))\n else:\n size = 0\n\n print('Stored variables and their in-db values:')\n fmt = '%-'+str(size)+'s -> %s'\n get = db.get\n for var in vars:\n justkey = os.path.basename(var)\n # print 30 first characters from every var\n print(fmt % (justkey, repr(get(var, '<unavailable>'))[:50]))\n\n # default action - store the variable\n else:\n # %store foo >file.txt or >>file.txt\n if len(args) > 1 and args[1].startswith(">"):\n fnam = os.path.expanduser(args[1].lstrip(">").lstrip())\n if args[1].startswith(">>"):\n fil = open(fnam, "a", encoding="utf-8")\n else:\n fil = open(fnam, "w", encoding="utf-8")\n with fil:\n obj = ip.ev(args[0])\n print("Writing '%s' (%s) to file '%s'." % (args[0],\n obj.__class__.__name__, fnam))\n\n if not isinstance (obj, str):\n from pprint import pprint\n pprint(obj, fil)\n else:\n fil.write(obj)\n if not obj.endswith('\n'):\n fil.write('\n')\n\n return\n\n # %store foo\n for arg in args:\n try:\n obj = ip.user_ns[arg]\n except KeyError:\n # it might be an alias\n name = arg\n try:\n cmd = ip.alias_manager.retrieve_alias(name)\n except ValueError as e:\n raise UsageError("Unknown variable '%s'" % name) from e\n\n staliases = db.get('stored_aliases',{})\n staliases[name] = cmd\n db['stored_aliases'] = staliases\n print("Alias stored: %s (%s)" % (name, cmd))\n return\n\n else:\n modname = getattr(inspect.getmodule(obj), '__name__', '')\n if modname == '__main__':\n print(textwrap.dedent("""\\n Warning:%s is %s\n Proper storage of interactively declared classes (or instances\n of those classes) is not possible! Only instances\n of classes in real modules on file system can be %%store'd.\n """ % (arg, obj) ))\n return\n #pickled = pickle.dumps(obj)\n db[ 'autorestore/' + arg ] = obj\n print("Stored '%s' (%s)" % (arg, obj.__class__.__name__))\n\n\ndef load_ipython_extension(ip):\n """Load the extension in IPython."""\n ip.register_magics(StoreMagics)\n\n
.venv\Lib\site-packages\IPython\extensions\storemagic.py
storemagic.py
Python
8,168
0.95
0.152542
0.123711
awesome-app
883
2023-08-17T09:46:56.880759
GPL-3.0
false
a327c075d0c6b382877a65d7e92b6a9b
# -*- coding: utf-8 -*-\n"""This directory is meant for IPython extensions."""\n
.venv\Lib\site-packages\IPython\extensions\__init__.py
__init__.py
Python
78
0.6
0.5
0.5
awesome-app
592
2025-02-04T17:49:36.909287
MIT
false
23d2cb54131f0dfc5f9c5155fc142226
from __future__ import annotations\nimport ctypes\nimport sys\nfrom typing import Any\n\nNOT_FOUND: object = object()\n_MAX_FIELD_SEARCH_OFFSET = 50\n\nif sys.maxsize > 2**32:\n WORD_TYPE: type[ctypes.c_int32] | type[ctypes.c_int64] = ctypes.c_int64\n WORD_N_BYTES = 8\nelse:\n WORD_TYPE = ctypes.c_int32\n WORD_N_BYTES = 4\n\n\nclass DeduperReloaderPatchingMixin:\n @staticmethod\n def infer_field_offset(\n obj: object,\n field: str,\n ) -> int:\n field_value = getattr(obj, field, NOT_FOUND)\n if field_value is NOT_FOUND:\n return -1\n obj_addr = ctypes.c_void_p.from_buffer(ctypes.py_object(obj)).value\n field_addr = ctypes.c_void_p.from_buffer(ctypes.py_object(field_value)).value\n if obj_addr is None or field_addr is None:\n return -1\n ret = -1\n for offset in range(1, _MAX_FIELD_SEARCH_OFFSET):\n if (\n ctypes.cast(\n obj_addr + WORD_N_BYTES * offset, ctypes.POINTER(WORD_TYPE)\n ).contents.value\n == field_addr\n ):\n ret = offset\n break\n return ret\n\n @classmethod\n def try_write_readonly_attr(\n cls,\n obj: object,\n field: str,\n new_value: object,\n offset: int | None = None,\n ) -> None:\n prev_value = getattr(obj, field, NOT_FOUND)\n if prev_value is NOT_FOUND:\n return\n if offset is None:\n offset = cls.infer_field_offset(obj, field)\n if offset == -1:\n return\n obj_addr = ctypes.c_void_p.from_buffer(ctypes.py_object(obj)).value\n new_value_addr = ctypes.c_void_p.from_buffer(ctypes.py_object(new_value)).value\n if obj_addr is None or new_value_addr is None:\n return\n if prev_value is not None:\n ctypes.pythonapi.Py_DecRef(ctypes.py_object(prev_value))\n if new_value is not None:\n ctypes.pythonapi.Py_IncRef(ctypes.py_object(new_value))\n ctypes.cast(\n obj_addr + WORD_N_BYTES * offset, ctypes.POINTER(WORD_TYPE)\n ).contents.value = new_value_addr\n\n @classmethod\n def try_patch_readonly_attr(\n cls,\n old: object,\n new: object,\n field: str,\n new_is_value: bool = False,\n offset: int = -1,\n ) -> None:\n\n old_value = getattr(old, field, NOT_FOUND)\n new_value = new if new_is_value else getattr(new, field, NOT_FOUND)\n if old_value is NOT_FOUND or new_value is NOT_FOUND:\n return\n elif old_value is new_value:\n return\n elif old_value is not None and offset < 0:\n offset = cls.infer_field_offset(old, field)\n elif offset < 0:\n assert not new_is_value\n assert new_value is not None\n offset = cls.infer_field_offset(new, field)\n cls.try_write_readonly_attr(old, field, new_value, offset=offset)\n\n @classmethod\n def try_patch_attr(\n cls,\n old: object,\n new: object,\n field: str,\n new_is_value: bool = False,\n offset: int = -1,\n ) -> None:\n try:\n setattr(old, field, new if new_is_value else getattr(new, field))\n except (AttributeError, TypeError, ValueError):\n cls.try_patch_readonly_attr(old, new, field, new_is_value, offset)\n\n @classmethod\n def patch_function(\n cls, to_patch_to: Any, to_patch_from: Any, is_method: bool\n ) -> None:\n new_freevars = []\n new_closure = []\n for i, v in enumerate(to_patch_to.__code__.co_freevars):\n if v not in to_patch_from.__code__.co_freevars or v == "__class__":\n new_freevars.append(v)\n new_closure.append(to_patch_to.__closure__[i])\n for i, v in enumerate(to_patch_from.__code__.co_freevars):\n if v not in new_freevars:\n new_freevars.append(v)\n new_closure.append(to_patch_from.__closure__[i])\n code_with_new_freevars = to_patch_from.__code__.replace(\n co_freevars=tuple(new_freevars)\n )\n # lambdas may complain if there is more than one freevar\n cls.try_patch_attr(\n to_patch_to, code_with_new_freevars, "__code__", new_is_value=True\n )\n offset = -1\n if to_patch_to.__closure__ is None and to_patch_from.__closure__ is not None:\n offset = cls.infer_field_offset(to_patch_from, "__closure__")\n cls.try_patch_readonly_attr(\n to_patch_to,\n tuple(new_closure) or None,\n "__closure__",\n new_is_value=True,\n offset=offset,\n )\n for attr in ("__defaults__", "__kwdefaults__", "__doc__", "__dict__"):\n cls.try_patch_attr(to_patch_to, to_patch_from, attr)\n if is_method:\n cls.try_patch_readonly_attr(to_patch_to, to_patch_from, "__self__")\n
.venv\Lib\site-packages\IPython\extensions\deduperreload\deduperreload_patching.py
deduperreload_patching.py
Python
4,934
0.95
0.205674
0.007576
node-utils
328
2025-02-05T15:10:31.518008
Apache-2.0
false
941f2a2085a7d42bbb8b5bc4799a8dbc
\n\n
.venv\Lib\site-packages\IPython\extensions\deduperreload\__pycache__\deduperreload.cpython-313.pyc
deduperreload.cpython-313.pyc
Other
32,031
0.95
0.111524
0.007813
vue-tools
531
2024-11-11T16:57:06.591593
MIT
false
8f7353913d20daebb7e952024ac23656
\n\n
.venv\Lib\site-packages\IPython\extensions\deduperreload\__pycache__\deduperreload_patching.cpython-313.pyc
deduperreload_patching.cpython-313.pyc
Other
6,978
0.95
0
0.016393
vue-tools
409
2024-03-15T00:48:24.637713
GPL-3.0
false
bbc003b97d97bac95eba2c4093232670
\n\n
.venv\Lib\site-packages\IPython\extensions\deduperreload\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
207
0.7
0
0
awesome-app
966
2023-11-16T14:24:17.039862
GPL-3.0
false
548983ace3279513305069152363d630
\n\n
.venv\Lib\site-packages\IPython\extensions\__pycache__\autoreload.cpython-313.pyc
autoreload.cpython-313.pyc
Other
33,900
0.95
0.06747
0
python-kit
77
2023-10-15T03:06:28.819919
BSD-3-Clause
false
6eb6c1eab32116e1987cb0b00e6b6084
\n\n
.venv\Lib\site-packages\IPython\extensions\__pycache__\storemagic.cpython-313.pyc
storemagic.cpython-313.pyc
Other
10,012
0.8
0.039063
0.072072
awesome-app
812
2023-11-23T06:42:37.757886
MIT
false
8b454548ca5fc19e2d3ec3daf7eaa432
\n\n
.venv\Lib\site-packages\IPython\extensions\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
255
0.7
0.5
0
awesome-app
651
2024-09-06T09:03:42.404746
BSD-3-Clause
false
92934fbf602fabcaa063dc01cf83e054
"""\nThis module contains factory functions that attempt\nto return Qt submodules from the various python Qt bindings.\n\nIt also protects against double-importing Qt with different\nbindings, which is unstable and likely to crash\n\nThis is used primarily by qt and qt_for_kernel, and shouldn't\nbe accessed directly from the outside\n"""\n\nimport importlib.abc\nimport sys\nimport os\nimport types\nfrom functools import partial, lru_cache\nimport operator\n\n# ### Available APIs.\n# Qt6\nQT_API_PYQT6 = "pyqt6"\nQT_API_PYSIDE6 = "pyside6"\n\n# Qt5\nQT_API_PYQT5 = 'pyqt5'\nQT_API_PYSIDE2 = 'pyside2'\n\n# Qt4\n# NOTE: Here for legacy matplotlib compatibility, but not really supported on the IPython side.\nQT_API_PYQT = "pyqt" # Force version 2\nQT_API_PYQTv1 = "pyqtv1" # Force version 2\nQT_API_PYSIDE = "pyside"\n\nQT_API_PYQT_DEFAULT = "pyqtdefault" # use system default for version 1 vs. 2\n\napi_to_module = {\n # Qt6\n QT_API_PYQT6: "PyQt6",\n QT_API_PYSIDE6: "PySide6",\n # Qt5\n QT_API_PYQT5: "PyQt5",\n QT_API_PYSIDE2: "PySide2",\n # Qt4\n QT_API_PYSIDE: "PySide",\n QT_API_PYQT: "PyQt4",\n QT_API_PYQTv1: "PyQt4",\n # default\n QT_API_PYQT_DEFAULT: "PyQt6",\n}\n\n\nclass ImportDenier(importlib.abc.MetaPathFinder):\n """Import Hook that will guard against bad Qt imports\n once IPython commits to a specific binding\n """\n\n def __init__(self):\n self.__forbidden = set()\n\n def forbid(self, module_name):\n sys.modules.pop(module_name, None)\n self.__forbidden.add(module_name)\n\n def find_spec(self, fullname, path, target=None):\n if path:\n return\n if fullname in self.__forbidden:\n raise ImportError(\n """\n Importing %s disabled by IPython, which has\n already imported an Incompatible QT Binding: %s\n """\n % (fullname, loaded_api())\n )\n\n\nID = ImportDenier()\nsys.meta_path.insert(0, ID)\n\n\ndef commit_api(api):\n """Commit to a particular API, and trigger ImportErrors on subsequent\n dangerous imports"""\n modules = set(api_to_module.values())\n\n modules.remove(api_to_module[api])\n for mod in modules:\n ID.forbid(mod)\n\n\ndef loaded_api():\n """Return which API is loaded, if any\n\n If this returns anything besides None,\n importing any other Qt binding is unsafe.\n\n Returns\n -------\n None, 'pyside6', 'pyqt6', 'pyside2', 'pyside', 'pyqt', 'pyqt5', 'pyqtv1'\n """\n if sys.modules.get("PyQt6.QtCore"):\n return QT_API_PYQT6\n elif sys.modules.get("PySide6.QtCore"):\n return QT_API_PYSIDE6\n elif sys.modules.get("PyQt5.QtCore"):\n return QT_API_PYQT5\n elif sys.modules.get("PySide2.QtCore"):\n return QT_API_PYSIDE2\n elif sys.modules.get("PyQt4.QtCore"):\n if qtapi_version() == 2:\n return QT_API_PYQT\n else:\n return QT_API_PYQTv1\n elif sys.modules.get("PySide.QtCore"):\n return QT_API_PYSIDE\n\n return None\n\n\ndef has_binding(api):\n """Safely check for PyQt4/5, PySide or PySide2, without importing submodules\n\n Parameters\n ----------\n api : str [ 'pyqtv1' | 'pyqt' | 'pyqt5' | 'pyside' | 'pyside2' | 'pyqtdefault']\n Which module to check for\n\n Returns\n -------\n True if the relevant module appears to be importable\n """\n module_name = api_to_module[api]\n from importlib.util import find_spec\n\n required = ['QtCore', 'QtGui', 'QtSvg']\n if api in (QT_API_PYQT5, QT_API_PYSIDE2, QT_API_PYQT6, QT_API_PYSIDE6):\n # QT5 requires QtWidgets too\n required.append('QtWidgets')\n\n for submod in required:\n try:\n spec = find_spec('%s.%s' % (module_name, submod))\n except ImportError:\n # Package (e.g. PyQt5) not found\n return False\n else:\n if spec is None:\n # Submodule (e.g. PyQt5.QtCore) not found\n return False\n\n if api == QT_API_PYSIDE:\n # We can also safely check PySide version\n import PySide\n\n return PySide.__version_info__ >= (1, 0, 3)\n\n return True\n\n\ndef qtapi_version():\n """Return which QString API has been set, if any\n\n Returns\n -------\n The QString API version (1 or 2), or None if not set\n """\n try:\n import sip\n except ImportError:\n # as of PyQt5 5.11, sip is no longer available as a top-level\n # module and needs to be imported from the PyQt5 namespace\n try:\n from PyQt5 import sip\n except ImportError:\n return\n try:\n return sip.getapi('QString')\n except ValueError:\n return\n\n\ndef can_import(api):\n """Safely query whether an API is importable, without importing it"""\n if not has_binding(api):\n return False\n\n current = loaded_api()\n if api == QT_API_PYQT_DEFAULT:\n return current in [QT_API_PYQT6, None]\n else:\n return current in [api, None]\n\n\ndef import_pyqt4(version=2):\n """\n Import PyQt4\n\n Parameters\n ----------\n version : 1, 2, or None\n Which QString/QVariant API to use. Set to None to use the system\n default\n ImportErrors raised within this function are non-recoverable\n """\n # The new-style string API (version=2) automatically\n # converts QStrings to Unicode Python strings. Also, automatically unpacks\n # QVariants to their underlying objects.\n import sip\n\n if version is not None:\n sip.setapi('QString', version)\n sip.setapi('QVariant', version)\n\n from PyQt4 import QtGui, QtCore, QtSvg\n\n if QtCore.PYQT_VERSION < 0x040700:\n raise ImportError("IPython requires PyQt4 >= 4.7, found %s" %\n QtCore.PYQT_VERSION_STR)\n\n # Alias PyQt-specific functions for PySide compatibility.\n QtCore.Signal = QtCore.pyqtSignal\n QtCore.Slot = QtCore.pyqtSlot\n\n # query for the API version (in case version == None)\n version = sip.getapi('QString')\n api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT\n return QtCore, QtGui, QtSvg, api\n\n\ndef import_pyqt5():\n """\n Import PyQt5\n\n ImportErrors raised within this function are non-recoverable\n """\n\n from PyQt5 import QtCore, QtSvg, QtWidgets, QtGui\n\n # Alias PyQt-specific functions for PySide compatibility.\n QtCore.Signal = QtCore.pyqtSignal\n QtCore.Slot = QtCore.pyqtSlot\n\n # Join QtGui and QtWidgets for Qt4 compatibility.\n QtGuiCompat = types.ModuleType('QtGuiCompat')\n QtGuiCompat.__dict__.update(QtGui.__dict__)\n QtGuiCompat.__dict__.update(QtWidgets.__dict__)\n\n api = QT_API_PYQT5\n return QtCore, QtGuiCompat, QtSvg, api\n\n\ndef import_pyqt6():\n """\n Import PyQt6\n\n ImportErrors raised within this function are non-recoverable\n """\n\n from PyQt6 import QtCore, QtSvg, QtWidgets, QtGui\n\n # Alias PyQt-specific functions for PySide compatibility.\n QtCore.Signal = QtCore.pyqtSignal\n QtCore.Slot = QtCore.pyqtSlot\n\n # Join QtGui and QtWidgets for Qt4 compatibility.\n QtGuiCompat = types.ModuleType("QtGuiCompat")\n QtGuiCompat.__dict__.update(QtGui.__dict__)\n QtGuiCompat.__dict__.update(QtWidgets.__dict__)\n\n api = QT_API_PYQT6\n return QtCore, QtGuiCompat, QtSvg, api\n\n\ndef import_pyside():\n """\n Import PySide\n\n ImportErrors raised within this function are non-recoverable\n """\n from PySide import QtGui, QtCore, QtSvg\n return QtCore, QtGui, QtSvg, QT_API_PYSIDE\n\ndef import_pyside2():\n """\n Import PySide2\n\n ImportErrors raised within this function are non-recoverable\n """\n from PySide2 import QtGui, QtCore, QtSvg, QtWidgets, QtPrintSupport\n\n # Join QtGui and QtWidgets for Qt4 compatibility.\n QtGuiCompat = types.ModuleType('QtGuiCompat')\n QtGuiCompat.__dict__.update(QtGui.__dict__)\n QtGuiCompat.__dict__.update(QtWidgets.__dict__)\n QtGuiCompat.__dict__.update(QtPrintSupport.__dict__)\n\n return QtCore, QtGuiCompat, QtSvg, QT_API_PYSIDE2\n\n\ndef import_pyside6():\n """\n Import PySide6\n\n ImportErrors raised within this function are non-recoverable\n """\n\n def get_attrs(module):\n return {\n name: getattr(module, name)\n for name in dir(module)\n if not name.startswith("_")\n }\n\n from PySide6 import QtGui, QtCore, QtSvg, QtWidgets, QtPrintSupport\n\n # Join QtGui and QtWidgets for Qt4 compatibility.\n QtGuiCompat = types.ModuleType("QtGuiCompat")\n QtGuiCompat.__dict__.update(QtGui.__dict__)\n if QtCore.__version_info__ < (6, 7):\n QtGuiCompat.__dict__.update(QtWidgets.__dict__)\n QtGuiCompat.__dict__.update(QtPrintSupport.__dict__)\n else:\n QtGuiCompat.__dict__.update(get_attrs(QtWidgets))\n QtGuiCompat.__dict__.update(get_attrs(QtPrintSupport))\n\n return QtCore, QtGuiCompat, QtSvg, QT_API_PYSIDE6\n\n\ndef load_qt(api_options):\n """\n Attempt to import Qt, given a preference list\n of permissible bindings\n\n It is safe to call this function multiple times.\n\n Parameters\n ----------\n api_options : List of strings\n The order of APIs to try. Valid items are 'pyside', 'pyside2',\n 'pyqt', 'pyqt5', 'pyqtv1' and 'pyqtdefault'\n\n Returns\n -------\n A tuple of QtCore, QtGui, QtSvg, QT_API\n The first three are the Qt modules. The last is the\n string indicating which module was loaded.\n\n Raises\n ------\n ImportError, if it isn't possible to import any requested\n bindings (either because they aren't installed, or because\n an incompatible library has already been installed)\n """\n loaders = {\n # Qt6\n QT_API_PYQT6: import_pyqt6,\n QT_API_PYSIDE6: import_pyside6,\n # Qt5\n QT_API_PYQT5: import_pyqt5,\n QT_API_PYSIDE2: import_pyside2,\n # Qt4\n QT_API_PYSIDE: import_pyside,\n QT_API_PYQT: import_pyqt4,\n QT_API_PYQTv1: partial(import_pyqt4, version=1),\n # default\n QT_API_PYQT_DEFAULT: import_pyqt6,\n }\n\n for api in api_options:\n\n if api not in loaders:\n raise RuntimeError(\n "Invalid Qt API %r, valid values are: %s" %\n (api, ", ".join(["%r" % k for k in loaders.keys()])))\n\n if not can_import(api):\n continue\n\n #cannot safely recover from an ImportError during this\n result = loaders[api]()\n api = result[-1] # changed if api = QT_API_PYQT_DEFAULT\n commit_api(api)\n return result\n else:\n # Clear the environment variable since it doesn't work.\n if "QT_API" in os.environ:\n del os.environ["QT_API"]\n\n raise ImportError(\n """\n Could not load requested Qt binding. Please ensure that\n PyQt4 >= 4.7, PyQt5, PyQt6, PySide >= 1.0.3, PySide2, or\n PySide6 is available, and only one is imported per session.\n\n Currently-imported Qt library: %r\n PyQt5 available (requires QtCore, QtGui, QtSvg, QtWidgets): %s\n PyQt6 available (requires QtCore, QtGui, QtSvg, QtWidgets): %s\n PySide2 installed: %s\n PySide6 installed: %s\n Tried to load: %r\n """\n % (\n loaded_api(),\n has_binding(QT_API_PYQT5),\n has_binding(QT_API_PYQT6),\n has_binding(QT_API_PYSIDE2),\n has_binding(QT_API_PYSIDE6),\n api_options,\n )\n )\n\n\ndef enum_factory(QT_API, QtCore):\n """Construct an enum helper to account for PyQt5 <-> PyQt6 changes."""\n\n @lru_cache(None)\n def _enum(name):\n # foo.bar.Enum.Entry (PyQt6) <=> foo.bar.Entry (non-PyQt6).\n return operator.attrgetter(\n name if QT_API == QT_API_PYQT6 else name.rpartition(".")[0]\n )(sys.modules[QtCore.__package__])\n\n return _enum\n
.venv\Lib\site-packages\IPython\external\qt_loaders.py
qt_loaders.py
Python
11,863
0.95
0.172577
0.099099
python-kit
505
2024-06-07T18:50:19.522209
MIT
false
be69091ad28e28852a64d7fc3801f3d9
"""\nThis package contains all third-party modules bundled with IPython.\n"""\n\nfrom typing import List\n\n__all__: List[str] = []\n
.venv\Lib\site-packages\IPython\external\__init__.py
__init__.py
Python
126
0.85
0
0
python-kit
395
2025-01-07T05:58:36.481624
Apache-2.0
false
a82fcdd726ca2549f9f365bedb8e3171
\n\n
.venv\Lib\site-packages\IPython\external\__pycache__\pickleshare.cpython-313.pyc
pickleshare.cpython-313.pyc
Other
15,054
0.95
0.076923
0
vue-tools
354
2024-01-19T09:27:36.857973
BSD-3-Clause
false
fb222b9fde7a2154a00b240f2b55c0bb
\n\n
.venv\Lib\site-packages\IPython\external\__pycache__\qt_for_kernel.cpython-313.pyc
qt_for_kernel.cpython-313.pyc
Other
3,725
0.95
0.109589
0.016129
python-kit
871
2023-08-19T02:14:24.878614
BSD-3-Clause
false
543ab316b2c4697f230b33c103ef3e0d
\n\n
.venv\Lib\site-packages\IPython\external\__pycache__\qt_loaders.cpython-313.pyc
qt_loaders.cpython-313.pyc
Other
14,195
0.95
0.086022
0.006211
python-kit
221
2024-10-02T14:30:59.096785
BSD-3-Clause
false
ecb19f07117592b87db78f306d5049c5
\n\n
.venv\Lib\site-packages\IPython\external\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
392
0.7
0
0
node-utils
225
2024-02-08T12:34:21.597102
Apache-2.0
false
528bc1e46bee9703269af17c66aa9c8a
# -*- coding: utf-8 -*-\n"""\nProvides a reload() function that acts recursively.\n\nPython's normal :func:`python:reload` function only reloads the module that it's\npassed. The :func:`reload` function in this module also reloads everything\nimported from that module, which is useful when you're changing files deep\ninside a package.\n\nTo use this as your default reload function, type this::\n\n import builtins\n from IPython.lib import deepreload\n builtins.reload = deepreload.reload\n\nA reference to the original :func:`python:reload` is stored in this module as\n:data:`original_reload`, so you can restore it later.\n\nThis code is almost entirely based on knee.py, which is a Python\nre-implementation of hierarchical module import.\n"""\n#*****************************************************************************\n# Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu>\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\nimport builtins as builtin_mod\nfrom contextlib import contextmanager\nimport importlib\nimport sys\n\nfrom types import ModuleType\nfrom warnings import warn\nimport types\n\noriginal_import = builtin_mod.__import__\n\n@contextmanager\ndef replace_import_hook(new_import):\n saved_import = builtin_mod.__import__\n builtin_mod.__import__ = new_import\n try:\n yield\n finally:\n builtin_mod.__import__ = saved_import\n\ndef get_parent(globals, level):\n """\n parent, name = get_parent(globals, level)\n\n Return the package that an import is being performed in. If globals comes\n from the module foo.bar.bat (not itself a package), this returns the\n sys.modules entry for foo.bar. If globals is from a package's __init__.py,\n the package's entry in sys.modules is returned.\n\n If globals doesn't come from a package or a module in a package, or a\n corresponding entry is not found in sys.modules, None is returned.\n """\n orig_level = level\n\n if not level or not isinstance(globals, dict):\n return None, ''\n\n pkgname = globals.get('__package__', None)\n\n if pkgname is not None:\n # __package__ is set, so use it\n if not hasattr(pkgname, 'rindex'):\n raise ValueError('__package__ set to non-string')\n if len(pkgname) == 0:\n if level > 0:\n raise ValueError('Attempted relative import in non-package')\n return None, ''\n name = pkgname\n else:\n # __package__ not set, so figure it out and set it\n if '__name__' not in globals:\n return None, ''\n modname = globals['__name__']\n\n if '__path__' in globals:\n # __path__ is set, so modname is already the package name\n globals['__package__'] = name = modname\n else:\n # Normal module, so work out the package name if any\n lastdot = modname.rfind('.')\n if lastdot < 0 < level:\n raise ValueError("Attempted relative import in non-package")\n if lastdot < 0:\n globals['__package__'] = None\n return None, ''\n globals['__package__'] = name = modname[:lastdot]\n\n dot = len(name)\n for x in range(level, 1, -1):\n try:\n dot = name.rindex('.', 0, dot)\n except ValueError as e:\n raise ValueError("attempted relative import beyond top-level "\n "package") from e\n name = name[:dot]\n\n try:\n parent = sys.modules[name]\n except BaseException as e:\n if orig_level < 1:\n warn("Parent module '%.200s' not found while handling absolute "\n "import" % name)\n parent = None\n else:\n raise SystemError("Parent module '%.200s' not loaded, cannot "\n "perform relative import" % name) from e\n\n # We expect, but can't guarantee, if parent != None, that:\n # - parent.__name__ == name\n # - parent.__dict__ is globals\n # If this is violated... Who cares?\n return parent, name\n\ndef load_next(mod, altmod, name, buf):\n """\n mod, name, buf = load_next(mod, altmod, name, buf)\n\n altmod is either None or same as mod\n """\n\n if len(name) == 0:\n # completely empty module name should only happen in\n # 'from . import' (or '__import__("")')\n return mod, None, buf\n\n dot = name.find('.')\n if dot == 0:\n raise ValueError('Empty module name')\n\n if dot < 0:\n subname = name\n next = None\n else:\n subname = name[:dot]\n next = name[dot+1:]\n\n if buf != '':\n buf += '.'\n buf += subname\n\n result = import_submodule(mod, subname, buf)\n if result is None and mod != altmod:\n result = import_submodule(altmod, subname, subname)\n if result is not None:\n buf = subname\n\n if result is None:\n raise ImportError("No module named %.200s" % name)\n\n return result, next, buf\n\n\n# Need to keep track of what we've already reloaded to prevent cyclic evil\nfound_now = {}\n\ndef import_submodule(mod, subname, fullname):\n """m = import_submodule(mod, subname, fullname)"""\n # Require:\n # if mod == None: subname == fullname\n # else: mod.__name__ + "." + subname == fullname\n\n global found_now\n if fullname in found_now and fullname in sys.modules:\n m = sys.modules[fullname]\n else:\n print('Reloading', fullname)\n found_now[fullname] = 1\n oldm = sys.modules.get(fullname, None)\n try:\n if oldm is not None:\n m = importlib.reload(oldm)\n else:\n m = importlib.import_module(subname, mod)\n except:\n # load_module probably removed name from modules because of\n # the error. Put back the original module object.\n if oldm:\n sys.modules[fullname] = oldm\n raise\n\n add_submodule(mod, m, fullname, subname)\n\n return m\n\ndef add_submodule(mod, submod, fullname, subname):\n """mod.{subname} = submod"""\n if mod is None:\n return #Nothing to do here.\n\n if submod is None:\n submod = sys.modules[fullname]\n\n setattr(mod, subname, submod)\n\n return\n\ndef ensure_fromlist(mod, fromlist, buf, recursive):\n """Handle 'from module import a, b, c' imports."""\n if not hasattr(mod, '__path__'):\n return\n for item in fromlist:\n if not hasattr(item, 'rindex'):\n raise TypeError("Item in ``from list'' not a string")\n if item == '*':\n if recursive:\n continue # avoid endless recursion\n try:\n all = mod.__all__\n except AttributeError:\n pass\n else:\n ret = ensure_fromlist(mod, all, buf, 1)\n if not ret:\n return 0\n elif not hasattr(mod, item):\n import_submodule(mod, item, buf + '.' + item)\n\ndef deep_import_hook(name, globals=None, locals=None, fromlist=None, level=-1):\n """Replacement for __import__()"""\n parent, buf = get_parent(globals, level)\n\n head, name, buf = load_next(parent, None if level < 0 else parent, name, buf)\n\n tail = head\n while name:\n tail, name, buf = load_next(tail, tail, name, buf)\n\n # If tail is None, both get_parent and load_next found\n # an empty module name: someone called __import__("") or\n # doctored faulty bytecode\n if tail is None:\n raise ValueError('Empty module name')\n\n if not fromlist:\n return head\n\n ensure_fromlist(tail, fromlist, buf, 0)\n return tail\n\nmodules_reloading = {}\n\ndef deep_reload_hook(m):\n """Replacement for reload()."""\n # Hardcode this one as it would raise a NotImplementedError from the\n # bowels of Python and screw up the import machinery after.\n # unlike other imports the `exclude` list already in place is not enough.\n\n if m is types:\n return m\n if not isinstance(m, ModuleType):\n raise TypeError("reload() argument must be module")\n\n name = m.__name__\n\n if name not in sys.modules:\n raise ImportError("reload(): module %.200s not in sys.modules" % name)\n\n global modules_reloading\n try:\n return modules_reloading[name]\n except:\n modules_reloading[name] = m\n\n try:\n newm = importlib.reload(m)\n except:\n sys.modules[name] = m\n raise\n finally:\n modules_reloading.clear()\n return newm\n\n# Save the original hooks\noriginal_reload = importlib.reload\n\n# Replacement for reload()\ndef reload(\n module,\n exclude=(\n *sys.builtin_module_names,\n "sys",\n "os.path",\n "builtins",\n "__main__",\n "numpy",\n "numpy._globals",\n ),\n):\n """Recursively reload all modules used in the given module. Optionally\n takes a list of modules to exclude from reloading. The default exclude\n list contains modules listed in sys.builtin_module_names with additional\n sys, os.path, builtins and __main__, to prevent, e.g., resetting\n display, exception, and io hooks.\n """\n global found_now\n for i in exclude:\n found_now[i] = 1\n try:\n with replace_import_hook(deep_import_hook):\n return deep_reload_hook(module)\n finally:\n found_now = {}\n
.venv\Lib\site-packages\IPython\lib\deepreload.py
deepreload.py
Python
9,431
0.95
0.212903
0.125
awesome-app
530
2025-04-08T04:48:42.394140
GPL-3.0
false
545db3f468f974c4fefd27c7a864d9db
# coding: utf-8\n"""\nSupport for creating GUI apps and starting event loops.\n\nIPython's GUI integration allows interactive plotting and GUI usage in IPython\nsession. IPython has two different types of GUI integration:\n\n1. The terminal based IPython supports GUI event loops through Python's\n PyOS_InputHook. PyOS_InputHook is a hook that Python calls periodically\n whenever raw_input is waiting for a user to type code. We implement GUI\n support in the terminal by setting PyOS_InputHook to a function that\n iterates the event loop for a short while. It is important to note that\n in this situation, the real GUI event loop is NOT run in the normal\n manner, so you can't use the normal means to detect that it is running.\n2. In the two process IPython kernel/frontend, the GUI event loop is run in\n the kernel. In this case, the event loop is run in the normal manner by\n calling the function or method of the GUI toolkit that starts the event\n loop.\n\nIn addition to starting the GUI event loops in one of these two ways, IPython\nwill *always* create an appropriate GUI application object when GUi\nintegration is enabled.\n\nIf you want your GUI apps to run in IPython you need to do two things:\n\n1. Test to see if there is already an existing main application object. If\n there is, you should use it. If there is not an existing application object\n you should create one.\n2. Test to see if the GUI event loop is running. If it is, you should not\n start it. If the event loop is not running you may start it.\n\nThis module contains functions for each toolkit that perform these things\nin a consistent manner. Because of how PyOS_InputHook runs the event loop\nyou cannot detect if the event loop is running using the traditional calls\n(such as ``wx.GetApp.IsMainLoopRunning()`` in wxPython). If PyOS_InputHook is\nset These methods will return a false negative. That is, they will say the\nevent loop is not running, when is actually is. To work around this limitation\nwe proposed the following informal protocol:\n\n* Whenever someone starts the event loop, they *must* set the ``_in_event_loop``\n attribute of the main application object to ``True``. This should be done\n regardless of how the event loop is actually run.\n* Whenever someone stops the event loop, they *must* set the ``_in_event_loop``\n attribute of the main application object to ``False``.\n* If you want to see if the event loop is running, you *must* use ``hasattr``\n to see if ``_in_event_loop`` attribute has been set. If it is set, you\n *must* use its value. If it has not been set, you can query the toolkit\n in the normal manner.\n* If you want GUI support and no one else has created an application or\n started the event loop you *must* do this. We don't want projects to\n attempt to defer these things to someone else if they themselves need it.\n\nThe functions below implement this logic for each GUI toolkit. If you need\nto create custom application subclasses, you will likely have to modify this\ncode for your own purposes. This code can be copied into your own project\nso you don't have to depend on IPython.\n\n"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nfrom IPython.core.getipython import get_ipython\n\n#-----------------------------------------------------------------------------\n# wx\n#-----------------------------------------------------------------------------\n\ndef get_app_wx(*args, **kwargs):\n """Create a new wx app or return an exiting one."""\n import wx\n app = wx.GetApp()\n if app is None:\n if 'redirect' not in kwargs:\n kwargs['redirect'] = False\n app = wx.PySimpleApp(*args, **kwargs)\n return app\n\ndef is_event_loop_running_wx(app=None):\n """Is the wx event loop running."""\n # New way: check attribute on shell instance\n ip = get_ipython()\n if ip is not None:\n if ip.active_eventloop and ip.active_eventloop == 'wx':\n return True\n # Fall through to checking the application, because Wx has a native way\n # to check if the event loop is running, unlike Qt.\n\n # Old way: check Wx application\n if app is None:\n app = get_app_wx()\n if hasattr(app, '_in_event_loop'):\n return app._in_event_loop\n else:\n return app.IsMainLoopRunning()\n\ndef start_event_loop_wx(app=None):\n """Start the wx event loop in a consistent manner."""\n if app is None:\n app = get_app_wx()\n if not is_event_loop_running_wx(app):\n app._in_event_loop = True\n app.MainLoop()\n app._in_event_loop = False\n else:\n app._in_event_loop = True\n\n#-----------------------------------------------------------------------------\n# Qt\n#-----------------------------------------------------------------------------\n\ndef get_app_qt4(*args, **kwargs):\n """Create a new Qt app or return an existing one."""\n from IPython.external.qt_for_kernel import QtGui\n app = QtGui.QApplication.instance()\n if app is None:\n if not args:\n args = ([""],)\n app = QtGui.QApplication(*args, **kwargs)\n return app\n\ndef is_event_loop_running_qt4(app=None):\n """Is the qt event loop running."""\n # New way: check attribute on shell instance\n ip = get_ipython()\n if ip is not None:\n return ip.active_eventloop and ip.active_eventloop.startswith('qt')\n\n # Old way: check attribute on QApplication singleton\n if app is None:\n app = get_app_qt4([""])\n if hasattr(app, '_in_event_loop'):\n return app._in_event_loop\n else:\n # Does qt provide a other way to detect this?\n return False\n\ndef start_event_loop_qt4(app=None):\n """Start the qt event loop in a consistent manner."""\n if app is None:\n app = get_app_qt4([""])\n if not is_event_loop_running_qt4(app):\n app._in_event_loop = True\n app.exec_()\n app._in_event_loop = False\n else:\n app._in_event_loop = True\n\n#-----------------------------------------------------------------------------\n# Tk\n#-----------------------------------------------------------------------------\n\n#-----------------------------------------------------------------------------\n# gtk\n#-----------------------------------------------------------------------------\n
.venv\Lib\site-packages\IPython\lib\guisupport.py
guisupport.py
Python
6,300
0.95
0.23871
0.204545
node-utils
104
2024-02-13T21:36:35.567585
BSD-3-Clause
false
d71a3768fbb9886f3cfc8636f1de283f
# -*- coding: utf-8 -*-\n"""\nThe IPython lexers are now a separate package, ipython-pygments-lexers.\n\nImporting from here is deprecated and may break in the future.\n"""\n# -----------------------------------------------------------------------------\n# Copyright (c) 2013, the IPython Development Team.\n#\n# Distributed under the terms of the Modified BSD License.\n#\n# The full license is in the file COPYING.txt, distributed with this software.\n# -----------------------------------------------------------------------------\n\nfrom ipython_pygments_lexers import (\n IPythonLexer,\n IPython3Lexer,\n IPythonPartialTracebackLexer,\n IPythonTracebackLexer,\n IPythonConsoleLexer,\n IPyLexer,\n)\n\n\n__all__ = [\n "IPython3Lexer",\n "IPythonLexer",\n "IPythonPartialTracebackLexer",\n "IPythonTracebackLexer",\n "IPythonConsoleLexer",\n "IPyLexer",\n]\n
.venv\Lib\site-packages\IPython\lib\lexers.py
lexers.py
Python
865
0.95
0
0.285714
awesome-app
751
2025-03-08T11:44:13.543044
GPL-3.0
false
b1d835b94ee94c984552a1420f606509
"""\nPython advanced pretty printer. This pretty printer is intended to\nreplace the old `pprint` python module which does not allow developers\nto provide their own pretty print callbacks.\n\nThis module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.\n\n\nExample Usage\n-------------\n\nTo directly print the representation of an object use `pprint`::\n\n from pretty import pprint\n pprint(complex_object)\n\nTo get a string of the output use `pretty`::\n\n from pretty import pretty\n string = pretty(complex_object)\n\n\nExtending\n---------\n\nThe pretty library allows developers to add pretty printing rules for their\nown objects. This process is straightforward. All you have to do is to\nadd a `_repr_pretty_` method to your object and call the methods on the\npretty printer passed::\n\n class MyObject(object):\n\n def _repr_pretty_(self, p, cycle):\n ...\n\nHere's an example for a class with a simple constructor::\n\n class MySimpleObject:\n\n def __init__(self, a, b, *, c=None):\n self.a = a\n self.b = b\n self.c = c\n\n def _repr_pretty_(self, p, cycle):\n ctor = CallExpression.factory(self.__class__.__name__)\n if self.c is None:\n p.pretty(ctor(a, b))\n else:\n p.pretty(ctor(a, b, c=c))\n\nHere is an example implementation of a `_repr_pretty_` method for a list\nsubclass::\n\n class MyList(list):\n\n def _repr_pretty_(self, p, cycle):\n if cycle:\n p.text('MyList(...)')\n else:\n with p.group(8, 'MyList([', '])'):\n for idx, item in enumerate(self):\n if idx:\n p.text(',')\n p.breakable()\n p.pretty(item)\n\nThe `cycle` parameter is `True` if pretty detected a cycle. You *have* to\nreact to that or the result is an infinite loop. `p.text()` just adds\nnon breaking text to the output, `p.breakable()` either adds a whitespace\nor breaks here. If you pass it an argument it's used instead of the\ndefault space. `p.pretty` prettyprints another object using the pretty print\nmethod.\n\nThe first parameter to the `group` function specifies the extra indentation\nof the next line. In this example the next item will either be on the same\nline (if the items are short enough) or aligned with the right edge of the\nopening bracket of `MyList`.\n\nIf you just want to indent something you can use the group function\nwithout open / close parameters. You can also use this code::\n\n with p.indent(2):\n ...\n\nInheritance diagram:\n\n.. inheritance-diagram:: IPython.lib.pretty\n :parts: 3\n\n:copyright: 2007 by Armin Ronacher.\n Portions (c) 2009 by Robert Kern.\n:license: BSD License.\n"""\n\nfrom contextlib import contextmanager\nimport datetime\nimport os\nimport re\nimport sys\nimport types\nfrom collections import deque\nfrom inspect import signature\nfrom io import StringIO\nfrom warnings import warn\n\nfrom IPython.utils.decorators import undoc\nfrom IPython.utils.py3compat import PYPY\n\nfrom typing import Dict\n\n__all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',\n 'for_type', 'for_type_by_name', 'RawText', 'RawStringLiteral', 'CallExpression']\n\n\nMAX_SEQ_LENGTH = 1000\n_re_pattern_type = type(re.compile(''))\n\ndef _safe_getattr(obj, attr, default=None):\n """Safe version of getattr.\n\n Same as getattr, but will return ``default`` on any Exception,\n rather than raising.\n """\n try:\n return getattr(obj, attr, default)\n except Exception:\n return default\n\ndef _sorted_for_pprint(items):\n """\n Sort the given items for pretty printing. Since some predictable\n sorting is better than no sorting at all, we sort on the string\n representation if normal sorting fails.\n """\n items = list(items)\n try:\n return sorted(items)\n except Exception:\n try:\n return sorted(items, key=str)\n except Exception:\n return items\n\ndef pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):\n """\n Pretty print the object's representation.\n """\n stream = StringIO()\n printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)\n printer.pretty(obj)\n printer.flush()\n return stream.getvalue()\n\n\ndef pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):\n """\n Like `pretty` but print to stdout.\n """\n printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)\n printer.pretty(obj)\n printer.flush()\n sys.stdout.write(newline)\n sys.stdout.flush()\n\nclass _PrettyPrinterBase:\n\n @contextmanager\n def indent(self, indent):\n """with statement support for indenting/dedenting."""\n self.indentation += indent\n try:\n yield\n finally:\n self.indentation -= indent\n\n @contextmanager\n def group(self, indent=0, open='', close=''):\n """like begin_group / end_group but for the with statement."""\n self.begin_group(indent, open)\n try:\n yield\n finally:\n self.end_group(indent, close)\n\nclass PrettyPrinter(_PrettyPrinterBase):\n """\n Baseclass for the `RepresentationPrinter` prettyprinter that is used to\n generate pretty reprs of objects. Contrary to the `RepresentationPrinter`\n this printer knows nothing about the default pprinters or the `_repr_pretty_`\n callback method.\n """\n\n def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):\n self.output = output\n self.max_width = max_width\n self.newline = newline\n self.max_seq_length = max_seq_length\n self.output_width = 0\n self.buffer_width = 0\n self.buffer = deque()\n\n root_group = Group(0)\n self.group_stack = [root_group]\n self.group_queue = GroupQueue(root_group)\n self.indentation = 0\n\n def _break_one_group(self, group):\n while group.breakables:\n x = self.buffer.popleft()\n self.output_width = x.output(self.output, self.output_width)\n self.buffer_width -= x.width\n while self.buffer and isinstance(self.buffer[0], Text):\n x = self.buffer.popleft()\n self.output_width = x.output(self.output, self.output_width)\n self.buffer_width -= x.width\n\n def _break_outer_groups(self):\n while self.max_width < self.output_width + self.buffer_width:\n group = self.group_queue.deq()\n if not group:\n return\n self._break_one_group(group)\n\n def text(self, obj):\n """Add literal text to the output."""\n width = len(obj)\n if self.buffer:\n text = self.buffer[-1]\n if not isinstance(text, Text):\n text = Text()\n self.buffer.append(text)\n text.add(obj, width)\n self.buffer_width += width\n self._break_outer_groups()\n else:\n self.output.write(obj)\n self.output_width += width\n\n def breakable(self, sep=' '):\n """\n Add a breakable separator to the output. This does not mean that it\n will automatically break here. If no breaking on this position takes\n place the `sep` is inserted which default to one space.\n """\n width = len(sep)\n group = self.group_stack[-1]\n if group.want_break:\n self.flush()\n self.output.write(self.newline)\n self.output.write(' ' * self.indentation)\n self.output_width = self.indentation\n self.buffer_width = 0\n else:\n self.buffer.append(Breakable(sep, width, self))\n self.buffer_width += width\n self._break_outer_groups()\n\n def break_(self):\n """\n Explicitly insert a newline into the output, maintaining correct indentation.\n """\n group = self.group_queue.deq()\n if group:\n self._break_one_group(group)\n self.flush()\n self.output.write(self.newline)\n self.output.write(' ' * self.indentation)\n self.output_width = self.indentation\n self.buffer_width = 0\n\n\n def begin_group(self, indent=0, open=''):\n """\n Begin a group.\n The first parameter specifies the indentation for the next line (usually\n the width of the opening text), the second the opening text. All\n parameters are optional.\n """\n if open:\n self.text(open)\n group = Group(self.group_stack[-1].depth + 1)\n self.group_stack.append(group)\n self.group_queue.enq(group)\n self.indentation += indent\n\n def _enumerate(self, seq):\n """like enumerate, but with an upper limit on the number of items"""\n for idx, x in enumerate(seq):\n if self.max_seq_length and idx >= self.max_seq_length:\n self.text(',')\n self.breakable()\n self.text('...')\n return\n yield idx, x\n\n def end_group(self, dedent=0, close=''):\n """End a group. See `begin_group` for more details."""\n self.indentation -= dedent\n group = self.group_stack.pop()\n if not group.breakables:\n self.group_queue.remove(group)\n if close:\n self.text(close)\n\n def flush(self):\n """Flush data that is left in the buffer."""\n for data in self.buffer:\n self.output_width += data.output(self.output, self.output_width)\n self.buffer.clear()\n self.buffer_width = 0\n\n\ndef _get_mro(obj_class):\n """ Get a reasonable method resolution order of a class and its superclasses\n for both old-style and new-style classes.\n """\n if not hasattr(obj_class, '__mro__'):\n # Old-style class. Mix in object to make a fake new-style class.\n try:\n obj_class = type(obj_class.__name__, (obj_class, object), {})\n except TypeError:\n # Old-style extension type that does not descend from object.\n # FIXME: try to construct a more thorough MRO.\n mro = [obj_class]\n else:\n mro = obj_class.__mro__[1:-1]\n else:\n mro = obj_class.__mro__\n return mro\n\n\nclass RepresentationPrinter(PrettyPrinter):\n """\n Special pretty printer that has a `pretty` method that calls the pretty\n printer for a python object.\n\n This class stores processing data on `self` so you must *never* use\n this class in a threaded environment. Always lock it or reinstanciate\n it.\n\n Instances also have a verbose flag callbacks can access to control their\n output. For example the default instance repr prints all attributes and\n methods that are not prefixed by an underscore if the printer is in\n verbose mode.\n """\n\n def __init__(self, output, verbose=False, max_width=79, newline='\n',\n singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,\n max_seq_length=MAX_SEQ_LENGTH):\n\n PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)\n self.verbose = verbose\n self.stack = []\n if singleton_pprinters is None:\n singleton_pprinters = _singleton_pprinters.copy()\n self.singleton_pprinters = singleton_pprinters\n if type_pprinters is None:\n type_pprinters = _type_pprinters.copy()\n self.type_pprinters = type_pprinters\n if deferred_pprinters is None:\n deferred_pprinters = _deferred_type_pprinters.copy()\n self.deferred_pprinters = deferred_pprinters\n\n def pretty(self, obj):\n """Pretty print the given object."""\n obj_id = id(obj)\n cycle = obj_id in self.stack\n self.stack.append(obj_id)\n self.begin_group()\n try:\n obj_class = _safe_getattr(obj, '__class__', None) or type(obj)\n # First try to find registered singleton printers for the type.\n try:\n printer = self.singleton_pprinters[obj_id]\n except (TypeError, KeyError):\n pass\n else:\n return printer(obj, self, cycle)\n # Next walk the mro and check for either:\n # 1) a registered printer\n # 2) a _repr_pretty_ method\n for cls in _get_mro(obj_class):\n if cls in self.type_pprinters:\n # printer registered in self.type_pprinters\n return self.type_pprinters[cls](obj, self, cycle)\n else:\n # deferred printer\n printer = self._in_deferred_types(cls)\n if printer is not None:\n return printer(obj, self, cycle)\n else:\n # Finally look for special method names.\n # Some objects automatically create any requested\n # attribute. Try to ignore most of them by checking for\n # callability.\n if '_repr_pretty_' in cls.__dict__:\n meth = cls._repr_pretty_\n if callable(meth):\n return meth(obj, self, cycle)\n if (\n cls is not object\n # check if cls defines __repr__\n and "__repr__" in cls.__dict__\n # check if __repr__ is callable.\n # Note: we need to test getattr(cls, '__repr__')\n # instead of cls.__dict__['__repr__']\n # in order to work with descriptors like partialmethod,\n and callable(_safe_getattr(cls, "__repr__", None))\n ):\n return _repr_pprint(obj, self, cycle)\n\n return _default_pprint(obj, self, cycle)\n finally:\n self.end_group()\n self.stack.pop()\n\n def _in_deferred_types(self, cls):\n """\n Check if the given class is specified in the deferred type registry.\n\n Returns the printer from the registry if it exists, and None if the\n class is not in the registry. Successful matches will be moved to the\n regular type registry for future use.\n """\n mod = _safe_getattr(cls, '__module__', None)\n name = _safe_getattr(cls, '__name__', None)\n key = (mod, name)\n printer = None\n if key in self.deferred_pprinters:\n # Move the printer over to the regular registry.\n printer = self.deferred_pprinters.pop(key)\n self.type_pprinters[cls] = printer\n return printer\n\n\nclass Printable:\n\n def output(self, stream, output_width):\n return output_width\n\n\nclass Text(Printable):\n\n def __init__(self):\n self.objs = []\n self.width = 0\n\n def output(self, stream, output_width):\n for obj in self.objs:\n stream.write(obj)\n return output_width + self.width\n\n def add(self, obj, width):\n self.objs.append(obj)\n self.width += width\n\n\nclass Breakable(Printable):\n\n def __init__(self, seq, width, pretty):\n self.obj = seq\n self.width = width\n self.pretty = pretty\n self.indentation = pretty.indentation\n self.group = pretty.group_stack[-1]\n self.group.breakables.append(self)\n\n def output(self, stream, output_width):\n self.group.breakables.popleft()\n if self.group.want_break:\n stream.write(self.pretty.newline)\n stream.write(' ' * self.indentation)\n return self.indentation\n if not self.group.breakables:\n self.pretty.group_queue.remove(self.group)\n stream.write(self.obj)\n return output_width + self.width\n\n\nclass Group(Printable):\n\n def __init__(self, depth):\n self.depth = depth\n self.breakables = deque()\n self.want_break = False\n\n\nclass GroupQueue:\n\n def __init__(self, *groups):\n self.queue = []\n for group in groups:\n self.enq(group)\n\n def enq(self, group):\n depth = group.depth\n while depth > len(self.queue) - 1:\n self.queue.append([])\n self.queue[depth].append(group)\n\n def deq(self):\n for stack in self.queue:\n for idx, group in enumerate(reversed(stack)):\n if group.breakables:\n del stack[idx]\n group.want_break = True\n return group\n for group in stack:\n group.want_break = True\n del stack[:]\n\n def remove(self, group):\n try:\n self.queue[group.depth].remove(group)\n except ValueError:\n pass\n\n\nclass RawText:\n """ Object such that ``p.pretty(RawText(value))`` is the same as ``p.text(value)``.\n\n An example usage of this would be to show a list as binary numbers, using\n ``p.pretty([RawText(bin(i)) for i in integers])``.\n """\n def __init__(self, value):\n self.value = value\n\n def _repr_pretty_(self, p, cycle):\n p.text(self.value)\n\n\nclass CallExpression:\n """ Object which emits a line-wrapped call expression in the form `__name(*args, **kwargs)` """\n def __init__(__self, __name, *args, **kwargs):\n # dunders are to avoid clashes with kwargs, as python's name managing\n # will kick in.\n self = __self\n self.name = __name\n self.args = args\n self.kwargs = kwargs\n\n @classmethod\n def factory(cls, name):\n def inner(*args, **kwargs):\n return cls(name, *args, **kwargs)\n return inner\n\n def _repr_pretty_(self, p, cycle):\n # dunders are to avoid clashes with kwargs, as python's name managing\n # will kick in.\n\n started = False\n def new_item():\n nonlocal started\n if started:\n p.text(",")\n p.breakable()\n started = True\n\n prefix = self.name + "("\n with p.group(len(prefix), prefix, ")"):\n for arg in self.args:\n new_item()\n p.pretty(arg)\n for arg_name, arg in self.kwargs.items():\n new_item()\n arg_prefix = arg_name + "="\n with p.group(len(arg_prefix), arg_prefix):\n p.pretty(arg)\n\n\nclass RawStringLiteral:\n """ Wrapper that shows a string with a `r` prefix """\n def __init__(self, value):\n self.value = value\n\n def _repr_pretty_(self, p, cycle):\n base_repr = repr(self.value)\n if base_repr[:1] in 'uU':\n base_repr = base_repr[1:]\n prefix = 'ur'\n else:\n prefix = 'r'\n base_repr = prefix + base_repr.replace('\\\\', '\\')\n p.text(base_repr)\n\n\ndef _default_pprint(obj, p, cycle):\n """\n The default print function. Used if an object does not provide one and\n it's none of the builtin objects.\n """\n klass = _safe_getattr(obj, '__class__', None) or type(obj)\n if _safe_getattr(klass, '__repr__', None) is not object.__repr__:\n # A user-provided repr. Find newlines and replace them with p.break_()\n _repr_pprint(obj, p, cycle)\n return\n p.begin_group(1, '<')\n p.pretty(klass)\n p.text(' at 0x%x' % id(obj))\n if cycle:\n p.text(' ...')\n elif p.verbose:\n first = True\n for key in dir(obj):\n if not key.startswith('_'):\n try:\n value = getattr(obj, key)\n except AttributeError:\n continue\n if isinstance(value, types.MethodType):\n continue\n if not first:\n p.text(',')\n p.breakable()\n p.text(key)\n p.text('=')\n step = len(key) + 1\n p.indentation += step\n p.pretty(value)\n p.indentation -= step\n first = False\n p.end_group(1, '>')\n\n\ndef _seq_pprinter_factory(start, end):\n """\n Factory that returns a pprint function useful for sequences. Used by\n the default pprint for tuples and lists.\n """\n def inner(obj, p, cycle):\n if cycle:\n return p.text(start + '...' + end)\n step = len(start)\n p.begin_group(step, start)\n for idx, x in p._enumerate(obj):\n if idx:\n p.text(',')\n p.breakable()\n p.pretty(x)\n if len(obj) == 1 and isinstance(obj, tuple):\n # Special case for 1-item tuples.\n p.text(',')\n p.end_group(step, end)\n return inner\n\n\ndef _set_pprinter_factory(start, end):\n """\n Factory that returns a pprint function useful for sets and frozensets.\n """\n def inner(obj, p, cycle):\n if cycle:\n return p.text(start + '...' + end)\n if len(obj) == 0:\n # Special case.\n p.text(type(obj).__name__ + '()')\n else:\n step = len(start)\n p.begin_group(step, start)\n # Like dictionary keys, we will try to sort the items if there aren't too many\n if not (p.max_seq_length and len(obj) >= p.max_seq_length):\n items = _sorted_for_pprint(obj)\n else:\n items = obj\n for idx, x in p._enumerate(items):\n if idx:\n p.text(',')\n p.breakable()\n p.pretty(x)\n p.end_group(step, end)\n return inner\n\n\ndef _dict_pprinter_factory(start, end):\n """\n Factory that returns a pprint function used by the default pprint of\n dicts and dict proxies.\n """\n def inner(obj, p, cycle):\n if cycle:\n return p.text('{...}')\n step = len(start)\n p.begin_group(step, start)\n keys = obj.keys()\n for idx, key in p._enumerate(keys):\n if idx:\n p.text(',')\n p.breakable()\n p.pretty(key)\n p.text(': ')\n p.pretty(obj[key])\n p.end_group(step, end)\n return inner\n\n\ndef _super_pprint(obj, p, cycle):\n """The pprint for the super type."""\n p.begin_group(8, '<super: ')\n p.pretty(obj.__thisclass__)\n p.text(',')\n p.breakable()\n if PYPY: # In PyPy, super() objects don't have __self__ attributes\n dself = obj.__repr__.__self__\n p.pretty(None if dself is obj else dself)\n else:\n p.pretty(obj.__self__)\n p.end_group(8, '>')\n\n\n\nclass _ReFlags:\n def __init__(self, value):\n self.value = value\n\n def _repr_pretty_(self, p, cycle):\n done_one = False\n for flag in (\n "IGNORECASE",\n "LOCALE",\n "MULTILINE",\n "DOTALL",\n "UNICODE",\n "VERBOSE",\n "DEBUG",\n ):\n if self.value & getattr(re, flag):\n if done_one:\n p.text('|')\n p.text('re.' + flag)\n done_one = True\n\n\ndef _re_pattern_pprint(obj, p, cycle):\n """The pprint function for regular expression patterns."""\n re_compile = CallExpression.factory('re.compile')\n if obj.flags:\n p.pretty(re_compile(RawStringLiteral(obj.pattern), _ReFlags(obj.flags)))\n else:\n p.pretty(re_compile(RawStringLiteral(obj.pattern)))\n\n\ndef _types_simplenamespace_pprint(obj, p, cycle):\n """The pprint function for types.SimpleNamespace."""\n namespace = CallExpression.factory('namespace')\n if cycle:\n p.pretty(namespace(RawText("...")))\n else:\n p.pretty(namespace(**obj.__dict__))\n\n\ndef _type_pprint(obj, p, cycle):\n """The pprint for classes and types."""\n # Heap allocated types might not have the module attribute,\n # and others may set it to None.\n\n # Checks for a __repr__ override in the metaclass. Can't compare the\n # type(obj).__repr__ directly because in PyPy the representation function\n # inherited from type isn't the same type.__repr__\n if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:\n _repr_pprint(obj, p, cycle)\n return\n\n mod = _safe_getattr(obj, '__module__', None)\n try:\n name = obj.__qualname__\n if not isinstance(name, str):\n # This can happen if the type implements __qualname__ as a property\n # or other descriptor in Python 2.\n raise Exception("Try __name__")\n except Exception:\n name = obj.__name__\n if not isinstance(name, str):\n name = '<unknown type>'\n\n if mod in (None, '__builtin__', 'builtins', 'exceptions'):\n p.text(name)\n else:\n p.text(mod + '.' + name)\n\n\ndef _repr_pprint(obj, p, cycle):\n """A pprint that just redirects to the normal repr function."""\n # Find newlines and replace them with p.break_()\n output = repr(obj)\n lines = output.splitlines()\n with p.group():\n for idx, output_line in enumerate(lines):\n if idx:\n p.break_()\n p.text(output_line)\n\n\ndef _function_pprint(obj, p, cycle):\n """Base pprint for all functions and builtin functions."""\n name = _safe_getattr(obj, '__qualname__', obj.__name__)\n mod = obj.__module__\n if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):\n name = mod + '.' + name\n try:\n func_def = name + str(signature(obj))\n except ValueError:\n func_def = name\n p.text('<function %s>' % func_def)\n\n\ndef _exception_pprint(obj, p, cycle):\n """Base pprint for all exceptions."""\n name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)\n if obj.__class__.__module__ not in ('exceptions', 'builtins'):\n name = '%s.%s' % (obj.__class__.__module__, name)\n\n p.pretty(CallExpression(name, *getattr(obj, 'args', ())))\n\n\n#: the exception base\n_exception_base: type\ntry:\n _exception_base = BaseException\nexcept NameError:\n _exception_base = Exception\n\n\n#: printers for builtin types\n_type_pprinters = {\n int: _repr_pprint,\n float: _repr_pprint,\n str: _repr_pprint,\n tuple: _seq_pprinter_factory('(', ')'),\n list: _seq_pprinter_factory('[', ']'),\n dict: _dict_pprinter_factory('{', '}'),\n set: _set_pprinter_factory('{', '}'),\n frozenset: _set_pprinter_factory('frozenset({', '})'),\n super: _super_pprint,\n _re_pattern_type: _re_pattern_pprint,\n type: _type_pprint,\n types.FunctionType: _function_pprint,\n types.BuiltinFunctionType: _function_pprint,\n types.MethodType: _repr_pprint,\n types.SimpleNamespace: _types_simplenamespace_pprint,\n datetime.datetime: _repr_pprint,\n datetime.timedelta: _repr_pprint,\n _exception_base: _exception_pprint\n}\n\n# render os.environ like a dict\n_env_type = type(os.environ)\n# future-proof in case os.environ becomes a plain dict?\nif _env_type is not dict:\n _type_pprinters[_env_type] = _dict_pprinter_factory('environ{', '}')\n\n_type_pprinters[types.MappingProxyType] = _dict_pprinter_factory("mappingproxy({", "})")\n_type_pprinters[slice] = _repr_pprint\n\n_type_pprinters[range] = _repr_pprint\n_type_pprinters[bytes] = _repr_pprint\n\n#: printers for types specified by name\n_deferred_type_pprinters: Dict = {}\n\n\ndef for_type(typ, func):\n """\n Add a pretty printer for a given type.\n """\n oldfunc = _type_pprinters.get(typ, None)\n if func is not None:\n # To support easy restoration of old pprinters, we need to ignore Nones.\n _type_pprinters[typ] = func\n return oldfunc\n\ndef for_type_by_name(type_module, type_name, func):\n """\n Add a pretty printer for a type specified by the module and name of a type\n rather than the type object itself.\n """\n key = (type_module, type_name)\n oldfunc = _deferred_type_pprinters.get(key, None)\n if func is not None:\n # To support easy restoration of old pprinters, we need to ignore Nones.\n _deferred_type_pprinters[key] = func\n return oldfunc\n\n\n#: printers for the default singletons\n_singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,\n NotImplemented]), _repr_pprint)\n\n\ndef _defaultdict_pprint(obj, p, cycle):\n cls_ctor = CallExpression.factory(obj.__class__.__name__)\n if cycle:\n p.pretty(cls_ctor(RawText("...")))\n else:\n p.pretty(cls_ctor(obj.default_factory, dict(obj)))\n\ndef _ordereddict_pprint(obj, p, cycle):\n cls_ctor = CallExpression.factory(obj.__class__.__name__)\n if cycle:\n p.pretty(cls_ctor(RawText("...")))\n elif len(obj):\n p.pretty(cls_ctor(list(obj.items())))\n else:\n p.pretty(cls_ctor())\n\ndef _deque_pprint(obj, p, cycle):\n cls_ctor = CallExpression.factory(obj.__class__.__name__)\n if cycle:\n p.pretty(cls_ctor(RawText("...")))\n elif obj.maxlen is not None:\n p.pretty(cls_ctor(list(obj), maxlen=obj.maxlen))\n else:\n p.pretty(cls_ctor(list(obj)))\n\ndef _counter_pprint(obj, p, cycle):\n cls_ctor = CallExpression.factory(obj.__class__.__name__)\n if cycle:\n p.pretty(cls_ctor(RawText("...")))\n elif len(obj):\n p.pretty(cls_ctor(dict(obj.most_common())))\n else:\n p.pretty(cls_ctor())\n\n\ndef _userlist_pprint(obj, p, cycle):\n cls_ctor = CallExpression.factory(obj.__class__.__name__)\n if cycle:\n p.pretty(cls_ctor(RawText("...")))\n else:\n p.pretty(cls_ctor(obj.data))\n\n\nfor_type_by_name('collections', 'defaultdict', _defaultdict_pprint)\nfor_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)\nfor_type_by_name('collections', 'deque', _deque_pprint)\nfor_type_by_name('collections', 'Counter', _counter_pprint)\nfor_type_by_name("collections", "UserList", _userlist_pprint)\n\nif __name__ == '__main__':\n from random import randrange\n\n class Foo:\n def __init__(self):\n self.foo = 1\n self.bar = re.compile(r'\s+')\n self.blub = dict.fromkeys(range(30), randrange(1, 40))\n self.hehe = 23424.234234\n self.list = ["blub", "blah", self]\n\n def get_foo(self):\n print("foo")\n\n pprint(Foo(), verbose=True)\n
.venv\Lib\site-packages\IPython\lib\pretty.py
pretty.py
Python
30,721
0.95
0.263103
0.053885
vue-tools
823
2023-08-29T12:59:46.956271
GPL-3.0
false
5f57e771d8f2b2a46887cf7ad3e63b3e
# encoding: utf-8\n"""\nExtra capabilities for IPython\n"""\n\n# -----------------------------------------------------------------------------\n# Copyright (C) 2008-2011 The IPython 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
.venv\Lib\site-packages\IPython\lib\__init__.py
__init__.py
Python
411
0.8
0.090909
0.7
python-kit
799
2024-06-13T02:34:15.063192
GPL-3.0
false
eaa66a9a23cd5dee96abbf7e40cf19fe
\n\n
.venv\Lib\site-packages\IPython\lib\__pycache__\backgroundjobs.cpython-313.pyc
backgroundjobs.cpython-313.pyc
Other
21,143
0.95
0.119342
0
python-kit
585
2024-08-28T15:17:05.032914
MIT
false
bbac9cca5a2820e548394a3dcc3ec551
\n\n
.venv\Lib\site-packages\IPython\lib\__pycache__\clipboard.cpython-313.pyc
clipboard.cpython-313.pyc
Other
5,010
0.95
0.018519
0
react-lib
475
2025-05-15T04:43:04.085825
MIT
false
0bc363ad11ae7ccdaf5fe30895e31957
\n\n
.venv\Lib\site-packages\IPython\lib\__pycache__\deepreload.cpython-313.pyc
deepreload.cpython-313.pyc
Other
9,256
0.95
0.062992
0.008547
vue-tools
793
2024-11-05T05:49:37.951305
BSD-3-Clause
false
17200e96d6e6a43ff208889dc0be26d7
\n\n
.venv\Lib\site-packages\IPython\lib\__pycache__\demo.cpython-313.pyc
demo.cpython-313.pyc
Other
29,274
0.95
0.08776
0.056548
vue-tools
876
2024-01-30T09:54:40.775356
GPL-3.0
false
1adad0fc4ab5f3a241b32e436331dac7
\n\n
.venv\Lib\site-packages\IPython\lib\__pycache__\display.cpython-313.pyc
display.cpython-313.pyc
Other
28,809
0.95
0.111399
0.018237
awesome-app
543
2025-02-26T16:57:02.339571
Apache-2.0
false
6394a790681934f828a57bf6bf8bb85f
\n\n
.venv\Lib\site-packages\IPython\lib\__pycache__\editorhooks.cpython-313.pyc
editorhooks.cpython-313.pyc
Other
4,935
0.8
0.058824
0
node-utils
606
2023-09-17T15:42:43.366333
Apache-2.0
false
27447cd062ec39ef26869a326f71c252
\n\n
.venv\Lib\site-packages\IPython\lib\__pycache__\guisupport.cpython-313.pyc
guisupport.cpython-313.pyc
Other
6,012
0.95
0.172414
0.066667
react-lib
165
2024-12-29T05:31:05.263901
Apache-2.0
false
86824d48c723f7ae82db9d293f993e45
\n\n
.venv\Lib\site-packages\IPython\lib\__pycache__\latextools.cpython-313.pyc
latextools.cpython-313.pyc
Other
10,414
0.8
0.061224
0
vue-tools
313
2023-10-08T00:23:30.634936
MIT
false
214af12b2110d65aa9b28c6082b57adb
\n\n
.venv\Lib\site-packages\IPython\lib\__pycache__\lexers.cpython-313.pyc
lexers.cpython-313.pyc
Other
611
0.7
0
0
awesome-app
587
2025-01-26T11:01:18.534681
Apache-2.0
false
902ee3cd3676d80965ebba01a2c1beea
\n\n
.venv\Lib\site-packages\IPython\lib\__pycache__\pretty.cpython-313.pyc
pretty.cpython-313.pyc
Other
44,500
0.95
0.141827
0
node-utils
584
2024-04-16T02:47:59.757254
Apache-2.0
false
32744974f2e2d25d5cdf3098bb200ad6
\n\n
.venv\Lib\site-packages\IPython\lib\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
235
0.7
0.2
0
node-utils
833
2025-05-14T13:21:59.391285
GPL-3.0
false
5570f3e0c71a4085a85fd28db3cf2d04
"""\nreST directive for syntax-highlighting ipython interactive sessions.\n\n"""\n\nfrom sphinx import highlighting\nfrom ipython_pygments_lexers import IPyLexer\n\n\ndef setup(app):\n """Setup as a sphinx extension."""\n\n # This is only a lexer, so adding it below to pygments appears sufficient.\n # But if somebody knows what the right API usage should be to do that via\n # sphinx, by all means fix it here. At least having this setup.py\n # suppresses the sphinx warning we'd get without it.\n metadata = {"parallel_read_safe": True, "parallel_write_safe": True}\n return metadata\n\n\n# Register the extension as a valid pygments lexer.\n# Alternatively, we could register the lexer with pygments instead. This would\n# require using setuptools entrypoints: http://pygments.org/docs/plugins\n\nipy3 = IPyLexer()\n\nhighlighting.lexers["ipython"] = ipy3\nhighlighting.lexers["ipython3"] = ipy3\n
.venv\Lib\site-packages\IPython\sphinxext\ipython_console_highlighting.py
ipython_console_highlighting.py
Python
895
0.95
0.107143
0.368421
awesome-app
324
2024-04-01T14:36:36.350329
Apache-2.0
false
312cecbd7f3e1fa09304061d14d21772
\n\n
.venv\Lib\site-packages\IPython\sphinxext\__pycache__\custom_doctests.cpython-313.pyc
custom_doctests.cpython-313.pyc
Other
4,806
0.95
0.04918
0
react-lib
848
2025-03-23T05:22:29.647061
GPL-3.0
true
2a6380ea9d6607dfe5287364db3c9a4e
\n\n
.venv\Lib\site-packages\IPython\sphinxext\__pycache__\ipython_console_highlighting.cpython-313.pyc
ipython_console_highlighting.cpython-313.pyc
Other
769
0.7
0.111111
0
awesome-app
161
2024-10-30T15:09:47.939693
BSD-3-Clause
false
53154ee06681e48f58133571130d69d0
\n\n
.venv\Lib\site-packages\IPython\sphinxext\__pycache__\ipython_directive.cpython-313.pyc
ipython_directive.cpython-313.pyc
Other
40,666
0.95
0.025105
0.021127
node-utils
502
2024-02-21T04:48:24.504979
MIT
false
482212f7a589886e8cf30de10a94e312
\n\n
.venv\Lib\site-packages\IPython\sphinxext\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
192
0.7
0
0
python-kit
894
2025-03-16T18:34:04.177056
Apache-2.0
false
86419d4e4021ecebcdd3e1adb81adc4d
import asyncio\nimport os\nimport sys\n\nfrom IPython.core.debugger import Pdb\nfrom IPython.core.completer import IPCompleter\nfrom .ptutils import IPythonPTCompleter\nfrom .shortcuts import create_ipython_shortcuts\nfrom . import embed\n\nfrom pathlib import Path\nfrom pygments.token import Token\nfrom prompt_toolkit.application import create_app_session\nfrom prompt_toolkit.shortcuts.prompt import PromptSession\nfrom prompt_toolkit.enums import EditingMode\nfrom prompt_toolkit.formatted_text import PygmentsTokens\nfrom prompt_toolkit.history import InMemoryHistory, FileHistory\nfrom concurrent.futures import ThreadPoolExecutor\n\n# we want to avoid ptk as much as possible when using subprocesses\n# as it uses cursor positioning requests, deletes color ....\n_use_simple_prompt = "IPY_TEST_SIMPLE_PROMPT" in os.environ\n\n\nclass TerminalPdb(Pdb):\n """Standalone IPython debugger."""\n\n def __init__(self, *args, pt_session_options=None, **kwargs):\n Pdb.__init__(self, *args, **kwargs)\n self._ptcomp = None\n self.pt_init(pt_session_options)\n self.thread_executor = ThreadPoolExecutor(1)\n\n def pt_init(self, pt_session_options=None):\n """Initialize the prompt session and the prompt loop\n and store them in self.pt_app and self.pt_loop.\n\n Additional keyword arguments for the PromptSession class\n can be specified in pt_session_options.\n """\n if pt_session_options is None:\n pt_session_options = {}\n\n def get_prompt_tokens():\n return [(Token.Prompt, self.prompt)]\n\n if self._ptcomp is None:\n compl = IPCompleter(\n shell=self.shell, namespace={}, global_namespace={}, parent=self.shell\n )\n # add a completer for all the do_ methods\n methods_names = [m[3:] for m in dir(self) if m.startswith("do_")]\n\n def gen_comp(self, text):\n return [m for m in methods_names if m.startswith(text)]\n import types\n newcomp = types.MethodType(gen_comp, compl)\n compl.custom_matchers.insert(0, newcomp)\n # end add completer.\n\n self._ptcomp = IPythonPTCompleter(compl)\n\n # setup history only when we start pdb\n if self.shell.debugger_history is None:\n if self.shell.debugger_history_file is not None:\n p = Path(self.shell.debugger_history_file).expanduser()\n if not p.exists():\n p.touch()\n self.debugger_history = FileHistory(os.path.expanduser(str(p)))\n else:\n self.debugger_history = InMemoryHistory()\n else:\n self.debugger_history = self.shell.debugger_history\n\n options = dict(\n message=(lambda: PygmentsTokens(get_prompt_tokens())),\n editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),\n key_bindings=create_ipython_shortcuts(self.shell),\n history=self.debugger_history,\n completer=self._ptcomp,\n enable_history_search=True,\n mouse_support=self.shell.mouse_support,\n complete_style=self.shell.pt_complete_style,\n style=getattr(self.shell, "style", None),\n color_depth=self.shell.color_depth,\n )\n\n options.update(pt_session_options)\n if not _use_simple_prompt:\n self.pt_loop = asyncio.new_event_loop()\n self.pt_app = PromptSession(**options)\n\n def _prompt(self):\n """\n In case other prompt_toolkit apps have to run in parallel to this one (e.g. in madbg),\n create_app_session must be used to prevent mixing up between them. According to the prompt_toolkit docs:\n\n > If you need multiple applications running at the same time, you have to create a separate\n > `AppSession` using a `with create_app_session():` block.\n """\n with create_app_session():\n return self.pt_app.prompt()\n\n def cmdloop(self, intro=None):\n """Repeatedly issue a prompt, accept input, parse an initial prefix\n off the received input, and dispatch to action methods, passing them\n the remainder of the line as argument.\n\n override the same methods from cmd.Cmd to provide prompt toolkit replacement.\n """\n if not self.use_rawinput:\n raise ValueError('Sorry ipdb does not support use_rawinput=False')\n\n # In order to make sure that prompt, which uses asyncio doesn't\n # interfere with applications in which it's used, we always run the\n # prompt itself in a different thread (we can't start an event loop\n # within an event loop). This new thread won't have any event loop\n # running, and here we run our prompt-loop.\n self.preloop()\n\n try:\n if intro is not None:\n self.intro = intro\n if self.intro:\n print(self.intro, file=self.stdout)\n stop = None\n while not stop:\n if self.cmdqueue:\n line = self.cmdqueue.pop(0)\n else:\n self._ptcomp.ipy_completer.namespace = self.curframe_locals\n self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals\n\n # Run the prompt in a different thread.\n if not _use_simple_prompt:\n try:\n line = self.thread_executor.submit(self._prompt).result()\n except EOFError:\n line = "EOF"\n else:\n line = input("ipdb> ")\n\n line = self.precmd(line)\n stop = self.onecmd(line)\n stop = self.postcmd(stop, line)\n self.postloop()\n except Exception:\n raise\n\n def do_interact(self, arg):\n ipshell = embed.InteractiveShellEmbed(\n config=self.shell.config,\n banner1="*interactive*",\n exit_msg="*exiting interactive console...*",\n )\n global_ns = self.curframe.f_globals\n ipshell(\n module=sys.modules.get(global_ns["__name__"], None),\n local_ns=self.curframe_locals,\n )\n\n\ndef set_trace(frame=None):\n """\n Start debugging from `frame`.\n\n If frame is not specified, debugging starts from caller's frame.\n """\n TerminalPdb().set_trace(frame or sys._getframe().f_back)\n\n\nif __name__ == '__main__':\n import pdb\n # IPython.core.debugger.Pdb.trace_dispatch shall not catch\n # bdb.BdbQuit. When started through __main__ and an exception\n # happened after hitting "c", this is needed in order to\n # be able to quit the debugging session (see #9950).\n old_trace_dispatch = pdb.Pdb.trace_dispatch\n pdb.Pdb = TerminalPdb # type: ignore\n pdb.Pdb.trace_dispatch = old_trace_dispatch # type: ignore\n pdb.main()\n
.venv\Lib\site-packages\IPython\terminal\debugger.py
debugger.py
Python
6,937
0.95
0.176796
0.098684
node-utils
240
2025-04-25T09:26:44.804890
GPL-3.0
false
37e2f7f70005a744b8aad03ca316a796
"""Terminal input and output prompts."""\n\nfrom pygments.token import Token\nimport sys\n\nfrom IPython.core.displayhook import DisplayHook\n\nfrom prompt_toolkit.formatted_text import fragment_list_width, PygmentsTokens\nfrom prompt_toolkit.shortcuts import print_formatted_text\nfrom prompt_toolkit.enums import EditingMode\n\n\nclass Prompts:\n def __init__(self, shell):\n self.shell = shell\n\n def vi_mode(self):\n if (getattr(self.shell.pt_app, 'editing_mode', None) == EditingMode.VI\n and self.shell.prompt_includes_vi_mode):\n mode = str(self.shell.pt_app.app.vi_state.input_mode)\n if mode.startswith('InputMode.'):\n mode = mode[10:13].lower()\n elif mode.startswith('vi-'):\n mode = mode[3:6]\n return '['+mode+'] '\n return ''\n\n def current_line(self) -> int:\n if self.shell.pt_app is not None:\n return self.shell.pt_app.default_buffer.document.cursor_position_row or 0\n return 0\n\n def in_prompt_tokens(self):\n return [\n (Token.Prompt.Mode, self.vi_mode()),\n (\n Token.Prompt.LineNumber,\n self.shell.prompt_line_number_format.format(\n line=1, rel_line=-self.current_line()\n ),\n ),\n (Token.Prompt, "In ["),\n (Token.PromptNum, str(self.shell.execution_count)),\n (Token.Prompt, ']: '),\n ]\n\n def _width(self):\n return fragment_list_width(self.in_prompt_tokens())\n\n def continuation_prompt_tokens(\n self,\n width: int | None = None,\n *,\n lineno: int | None = None,\n wrap_count: int | None = None,\n ):\n if width is None:\n width = self._width()\n line = lineno + 1 if lineno is not None else 0\n if wrap_count:\n return [\n (\n Token.Prompt.Wrap,\n # (" " * (width - 2)) + "\N{HORIZONTAL ELLIPSIS} ",\n (" " * (width - 2)) + "\N{VERTICAL ELLIPSIS} ",\n ),\n ]\n prefix = " " * len(\n self.vi_mode()\n ) + self.shell.prompt_line_number_format.format(\n line=line, rel_line=line - self.current_line() - 1\n )\n return [\n (\n getattr(Token.Prompt.Continuation, f"L{lineno}"),\n prefix + (" " * (width - len(prefix) - 5)) + "...:",\n ),\n (Token.Prompt.Padding, " "),\n ]\n\n def rewrite_prompt_tokens(self):\n width = self._width()\n return [\n (Token.Prompt, ('-' * (width - 2)) + '> '),\n ]\n\n def out_prompt_tokens(self):\n return [\n (Token.OutPrompt, 'Out['),\n (Token.OutPromptNum, str(self.shell.execution_count)),\n (Token.OutPrompt, ']: '),\n ]\n\nclass ClassicPrompts(Prompts):\n def in_prompt_tokens(self):\n return [\n (Token.Prompt, '>>> '),\n ]\n\n def continuation_prompt_tokens(self, width=None):\n return [(Token.Prompt.Continuation, "... ")]\n\n def rewrite_prompt_tokens(self):\n return []\n\n def out_prompt_tokens(self):\n return []\n\nclass RichPromptDisplayHook(DisplayHook):\n """Subclass of base display hook using coloured prompt"""\n def write_output_prompt(self):\n sys.stdout.write(self.shell.separate_out)\n # If we're not displaying a prompt, it effectively ends with a newline,\n # because the output will be left-aligned.\n self.prompt_end_newline = True\n\n if self.do_full_cache:\n tokens = self.shell.prompts.out_prompt_tokens()\n prompt_txt = "".join(s for _, s in tokens)\n if prompt_txt and not prompt_txt.endswith("\n"):\n # Ask for a newline before multiline output\n self.prompt_end_newline = False\n\n if self.shell.pt_app:\n print_formatted_text(PygmentsTokens(tokens),\n style=self.shell.pt_app.app.style, end='',\n )\n else:\n sys.stdout.write(prompt_txt)\n\n def write_format_data(self, format_dict, md_dict=None) -> None:\n assert self.shell is not None\n if self.shell.mime_renderers:\n\n for mime, handler in self.shell.mime_renderers.items():\n if mime in format_dict:\n handler(format_dict[mime], None)\n return\n \n super().write_format_data(format_dict, md_dict)\n\n
.venv\Lib\site-packages\IPython\terminal\prompts.py
prompts.py
Python
4,555
0.95
0.219858
0.042373
python-kit
372
2024-07-14T14:23:23.098969
GPL-3.0
false
4fb4ea1dc789d83a75532550def2d4b7
"""prompt-toolkit utilities\n\nEverything in this module is a private API,\nnot to be used outside IPython.\n"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport unicodedata\nfrom wcwidth import wcwidth\n\nfrom IPython.core.completer import (\n provisionalcompleter, cursor_to_position,\n _deduplicate_completions)\nfrom prompt_toolkit.completion import Completer, Completion\nfrom prompt_toolkit.lexers import Lexer\nfrom prompt_toolkit.lexers import PygmentsLexer\nfrom prompt_toolkit.patch_stdout import patch_stdout\nfrom IPython.core.getipython import get_ipython\n\n\nimport pygments.lexers as pygments_lexers\nimport os\nimport sys\nimport traceback\n\n_completion_sentinel = object()\n\n\ndef _elide_point(string: str, *, min_elide) -> str:\n """\n If a string is long enough, and has at least 3 dots,\n replace the middle part with ellipses.\n\n If a string naming a file is long enough, and has at least 3 slashes,\n replace the middle part with ellipses.\n\n If three consecutive dots, or two consecutive dots are encountered these are\n replaced by the equivalents HORIZONTAL ELLIPSIS or TWO DOT LEADER unicode\n equivalents\n """\n string = string.replace('...','\N{HORIZONTAL ELLIPSIS}')\n string = string.replace('..','\N{TWO DOT LEADER}')\n if len(string) < min_elide:\n return string\n\n object_parts = string.split('.')\n file_parts = string.split(os.sep)\n if file_parts[-1] == '':\n file_parts.pop()\n\n if len(object_parts) > 3:\n return "{}.{}\N{HORIZONTAL ELLIPSIS}{}.{}".format(\n object_parts[0],\n object_parts[1][:1],\n object_parts[-2][-1:],\n object_parts[-1],\n )\n\n elif len(file_parts) > 3:\n return ("{}" + os.sep + "{}\N{HORIZONTAL ELLIPSIS}{}" + os.sep + "{}").format(\n file_parts[0], file_parts[1][:1], file_parts[-2][-1:], file_parts[-1]\n )\n\n return string\n\n\ndef _elide_typed(string: str, typed: str, *, min_elide: int) -> str:\n """\n Elide the middle of a long string if the beginning has already been typed.\n """\n\n if len(string) < min_elide:\n return string\n cut_how_much = len(typed)-3\n if cut_how_much < 7:\n return string\n if string.startswith(typed) and len(string)> len(typed):\n return f"{string[:3]}\N{HORIZONTAL ELLIPSIS}{string[cut_how_much:]}"\n return string\n\n\ndef _elide(string: str, typed: str, min_elide) -> str:\n return _elide_typed(\n _elide_point(string, min_elide=min_elide),\n typed, min_elide=min_elide)\n\n\n\ndef _adjust_completion_text_based_on_context(text, body, offset):\n if text.endswith('=') and len(body) > offset and body[offset] == '=':\n return text[:-1]\n else:\n return text\n\n\nclass IPythonPTCompleter(Completer):\n """Adaptor to provide IPython completions to prompt_toolkit"""\n def __init__(self, ipy_completer=None, shell=None):\n if shell is None and ipy_completer is None:\n raise TypeError("Please pass shell=an InteractiveShell instance.")\n self._ipy_completer = ipy_completer\n self.shell = shell\n\n @property\n def ipy_completer(self):\n if self._ipy_completer:\n return self._ipy_completer\n else:\n return self.shell.Completer\n\n def get_completions(self, document, complete_event):\n if not document.current_line.strip():\n return\n # Some bits of our completion system may print stuff (e.g. if a module\n # is imported). This context manager ensures that doesn't interfere with\n # the prompt.\n\n with patch_stdout(), provisionalcompleter():\n body = document.text\n cursor_row = document.cursor_position_row\n cursor_col = document.cursor_position_col\n cursor_position = document.cursor_position\n offset = cursor_to_position(body, cursor_row, cursor_col)\n try:\n yield from self._get_completions(body, offset, cursor_position, self.ipy_completer)\n except Exception as e:\n try:\n exc_type, exc_value, exc_tb = sys.exc_info()\n traceback.print_exception(exc_type, exc_value, exc_tb)\n except AttributeError:\n print('Unrecoverable Error in completions')\n\n def _get_completions(self, body, offset, cursor_position, ipyc):\n """\n Private equivalent of get_completions() use only for unit_testing.\n """\n debug = getattr(ipyc, 'debug', False)\n completions = _deduplicate_completions(\n body, ipyc.completions(body, offset))\n for c in completions:\n if not c.text:\n # Guard against completion machinery giving us an empty string.\n continue\n text = unicodedata.normalize('NFC', c.text)\n # When the first character of the completion has a zero length,\n # then it's probably a decomposed unicode character. E.g. caused by\n # the "\dot" completion. Try to compose again with the previous\n # character.\n if wcwidth(text[0]) == 0:\n if cursor_position + c.start > 0:\n char_before = body[c.start - 1]\n fixed_text = unicodedata.normalize(\n 'NFC', char_before + text)\n\n # Yield the modified completion instead, if this worked.\n if wcwidth(text[0:1]) == 1:\n yield Completion(fixed_text, start_position=c.start - offset - 1)\n continue\n\n # TODO: Use Jedi to determine meta_text\n # (Jedi currently has a bug that results in incorrect information.)\n # meta_text = ''\n # yield Completion(m, start_position=start_pos,\n # display_meta=meta_text)\n display_text = c.text\n\n adjusted_text = _adjust_completion_text_based_on_context(\n c.text, body, offset\n )\n min_elide = 30 if self.shell is None else self.shell.min_elide\n if c.type == "function":\n yield Completion(\n adjusted_text,\n start_position=c.start - offset,\n display=_elide(\n display_text + "()",\n body[c.start : c.end],\n min_elide=min_elide,\n ),\n display_meta=c.type + c.signature,\n )\n else:\n yield Completion(\n adjusted_text,\n start_position=c.start - offset,\n display=_elide(\n display_text,\n body[c.start : c.end],\n min_elide=min_elide,\n ),\n display_meta=c.type,\n )\n\n\nclass IPythonPTLexer(Lexer):\n """\n Wrapper around PythonLexer and BashLexer.\n """\n def __init__(self):\n l = pygments_lexers\n self.python_lexer = PygmentsLexer(l.Python3Lexer)\n self.shell_lexer = PygmentsLexer(l.BashLexer)\n\n self.magic_lexers = {\n 'HTML': PygmentsLexer(l.HtmlLexer),\n 'html': PygmentsLexer(l.HtmlLexer),\n 'javascript': PygmentsLexer(l.JavascriptLexer),\n 'js': PygmentsLexer(l.JavascriptLexer),\n 'perl': PygmentsLexer(l.PerlLexer),\n 'ruby': PygmentsLexer(l.RubyLexer),\n 'latex': PygmentsLexer(l.TexLexer),\n }\n\n def lex_document(self, document):\n text = document.text.lstrip()\n\n lexer = self.python_lexer\n\n if text.startswith('!') or text.startswith('%%bash'):\n lexer = self.shell_lexer\n\n elif text.startswith('%%'):\n for magic, l in self.magic_lexers.items():\n if text.startswith('%%' + magic):\n lexer = l\n break\n\n return lexer.lex_document(document)\n
.venv\Lib\site-packages\IPython\terminal\ptutils.py
ptutils.py
Python
8,067
0.95
0.169565
0.084211
python-kit
527
2024-10-25T04:03:43.554597
MIT
false
7c14e44dd794a144e64be59f9d7ac4c8
"""\nInputhook for running the original asyncio event loop while we're waiting for\ninput.\n\nBy default, in IPython, we run the prompt with a different asyncio event loop,\nbecause otherwise we risk that people are freezing the prompt by scheduling bad\ncoroutines. E.g., a coroutine that does a while/true and never yield back\ncontrol to the loop. We can't cancel that.\n\nHowever, sometimes we want the asyncio loop to keep running while waiting for\na prompt.\n\nThe following example will print the numbers from 1 to 10 above the prompt,\nwhile we are waiting for input. (This works also because we use\nprompt_toolkit`s `patch_stdout`)::\n\n In [1]: import asyncio\n\n In [2]: %gui asyncio\n\n In [3]: async def f():\n ...: for i in range(10):\n ...: await asyncio.sleep(1)\n ...: print(i)\n\n\n In [4]: asyncio.ensure_future(f())\n\n"""\n\n\ndef inputhook(context):\n """\n Inputhook for asyncio event loop integration.\n """\n # For prompt_toolkit 3.0, this input hook literally doesn't do anything.\n # The event loop integration here is implemented in `interactiveshell.py`\n # by running the prompt itself in the current asyncio loop. The main reason\n # for this is that nesting asyncio event loops is unreliable.\n return\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\asyncio.py
asyncio.py
Python
1,271
0.95
0.325
0.137931
node-utils
576
2024-04-08T21:06:59.213773
MIT
false
0bb992dce0d6bdb10fa5f9255e402797
"""GLUT Input hook for interactive use with prompt_toolkit\n"""\n\n\n# GLUT is quite an old library and it is difficult to ensure proper\n# integration within IPython since original GLUT does not allow to handle\n# events one by one. Instead, it requires for the mainloop to be entered\n# and never returned (there is not even a function to exit he\n# mainloop). Fortunately, there are alternatives such as freeglut\n# (available for linux and windows) and the OSX implementation gives\n# access to a glutCheckLoop() function that blocks itself until a new\n# event is received. This means we have to setup the idle callback to\n# ensure we got at least one event that will unblock the function.\n#\n# Furthermore, it is not possible to install these handlers without a window\n# being first created. We choose to make this window invisible. This means that\n# display mode options are set at this level and user won't be able to change\n# them later without modifying the code. This should probably be made available\n# via IPython options system.\n\nimport sys\nimport time\nimport signal\nimport OpenGL.GLUT as glut\nimport OpenGL.platform as platform\nfrom timeit import default_timer as clock\n\n# Frame per second : 60\n# Should probably be an IPython option\nglut_fps = 60\n\n# Display mode : double buffeed + rgba + depth\n# Should probably be an IPython option\nglut_display_mode = (glut.GLUT_DOUBLE |\n glut.GLUT_RGBA |\n glut.GLUT_DEPTH)\n\nglutMainLoopEvent = None\nif sys.platform == 'darwin':\n try:\n glutCheckLoop = platform.createBaseFunction(\n 'glutCheckLoop', dll=platform.GLUT, resultType=None,\n argTypes=[],\n doc='glutCheckLoop( ) -> None',\n argNames=(),\n )\n except AttributeError as e:\n raise RuntimeError(\n '''Your glut implementation does not allow interactive sessions. '''\n '''Consider installing freeglut.''') from e\n glutMainLoopEvent = glutCheckLoop\nelif glut.HAVE_FREEGLUT:\n glutMainLoopEvent = glut.glutMainLoopEvent\nelse:\n raise RuntimeError(\n '''Your glut implementation does not allow interactive sessions. '''\n '''Consider installing freeglut.''')\n\n\ndef glut_display():\n # Dummy display function\n pass\n\ndef glut_idle():\n # Dummy idle function\n pass\n\ndef glut_close():\n # Close function only hides the current window\n glut.glutHideWindow()\n glutMainLoopEvent()\n\ndef glut_int_handler(signum, frame):\n # Catch sigint and print the defaultipyt message\n signal.signal(signal.SIGINT, signal.default_int_handler)\n print('\nKeyboardInterrupt')\n # Need to reprint the prompt at this stage\n\n# Initialisation code\nglut.glutInit( sys.argv )\nglut.glutInitDisplayMode( glut_display_mode )\n# This is specific to freeglut\nif bool(glut.glutSetOption):\n glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,\n glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )\nglut.glutCreateWindow( b'ipython' )\nglut.glutReshapeWindow( 1, 1 )\nglut.glutHideWindow( )\nglut.glutWMCloseFunc( glut_close )\nglut.glutDisplayFunc( glut_display )\nglut.glutIdleFunc( glut_idle )\n\n\ndef inputhook(context):\n """Run the pyglet event loop by processing pending events only.\n\n This keeps processing pending events until stdin is ready. After\n processing all pending events, a call to time.sleep is inserted. This is\n needed, otherwise, CPU usage is at 100%. This sleep time should be tuned\n though for best performance.\n """\n # We need to protect against a user pressing Control-C when IPython is\n # idle and this is running. We trap KeyboardInterrupt and pass.\n\n signal.signal(signal.SIGINT, glut_int_handler)\n\n try:\n t = clock()\n\n # Make sure the default window is set after a window has been closed\n if glut.glutGetWindow() == 0:\n glut.glutSetWindow( 1 )\n glutMainLoopEvent()\n return 0\n\n while not context.input_is_ready():\n glutMainLoopEvent()\n # We need to sleep at this point to keep the idle CPU load\n # low. However, if sleep to long, GUI response is poor. As\n # a compromise, we watch how often GUI events are being processed\n # and switch between a short and long sleep time. Here are some\n # stats useful in helping to tune this.\n # time CPU load\n # 0.001 13%\n # 0.005 3%\n # 0.01 1.5%\n # 0.05 0.5%\n used_time = clock() - t\n if used_time > 10.0:\n # print('Sleep for 1 s') # dbg\n time.sleep(1.0)\n elif used_time > 0.1:\n # Few GUI events coming in, so we can sleep longer\n # print('Sleep for 0.05 s') # dbg\n time.sleep(0.05)\n else:\n # Many GUI events coming in, so sleep only very little\n time.sleep(0.001)\n except KeyboardInterrupt:\n pass\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\glut.py
glut.py
Python
4,999
0.95
0.185714
0.355372
vue-tools
865
2023-07-29T21:43:07.739848
BSD-3-Clause
false
7a097f2ac6626eb7ded6f2c9f121eff9
"""prompt_toolkit input hook for GTK 3"""\n\nfrom gi.repository import Gtk, GLib\n\n\ndef _main_quit(*args, **kwargs):\n Gtk.main_quit()\n return False\n\n\ndef inputhook(context):\n GLib.io_add_watch(context.fileno(), GLib.PRIORITY_DEFAULT, GLib.IO_IN, _main_quit)\n Gtk.main()\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\gtk3.py
gtk3.py
Python
279
0.85
0.230769
0
vue-tools
611
2025-07-03T18:15:12.477480
BSD-3-Clause
false
ac932eaf16d991a2fbd9f0c18397fc26
"""\nprompt_toolkit input hook for GTK 4.\n"""\n\nfrom gi.repository import GLib\n\n\nclass _InputHook:\n def __init__(self, context):\n self._quit = False\n GLib.io_add_watch(\n context.fileno(), GLib.PRIORITY_DEFAULT, GLib.IO_IN, self.quit\n )\n\n def quit(self, *args, **kwargs):\n self._quit = True\n return False\n\n def run(self):\n context = GLib.MainContext.default()\n while not self._quit:\n context.iteration(True)\n\n\ndef inputhook(context):\n hook = _InputHook(context)\n hook.run()\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\gtk4.py
gtk4.py
Python
557
0.85
0.259259
0
awesome-app
722
2024-11-01T20:22:57.367260
BSD-3-Clause
false
d087594f1893eda9a751732b51822ac4
"""Inputhook for OS X\n\nCalls NSApp / CoreFoundation APIs via ctypes.\n"""\n\n# obj-c boilerplate from appnope, used under BSD 2-clause\n\nimport ctypes\nimport ctypes.util\nfrom threading import Event\n\nobjc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("objc")) # type: ignore\n\nvoid_p = ctypes.c_void_p\n\nobjc.objc_getClass.restype = void_p\nobjc.sel_registerName.restype = void_p\nobjc.objc_msgSend.restype = void_p\nobjc.objc_msgSend.argtypes = [void_p, void_p]\n\nmsg = objc.objc_msgSend\n\ndef _utf8(s):\n """ensure utf8 bytes"""\n if not isinstance(s, bytes):\n s = s.encode('utf8')\n return s\n\ndef n(name):\n """create a selector name (for ObjC methods)"""\n return objc.sel_registerName(_utf8(name))\n\ndef C(classname):\n """get an ObjC Class by name"""\n return objc.objc_getClass(_utf8(classname))\n\n# end obj-c boilerplate from appnope\n\n# CoreFoundation C-API calls we will use:\nCoreFoundation = ctypes.cdll.LoadLibrary(ctypes.util.find_library("CoreFoundation")) # type: ignore\n\nCFFileDescriptorCreate = CoreFoundation.CFFileDescriptorCreate\nCFFileDescriptorCreate.restype = void_p\nCFFileDescriptorCreate.argtypes = [void_p, ctypes.c_int, ctypes.c_bool, void_p, void_p]\n\nCFFileDescriptorGetNativeDescriptor = CoreFoundation.CFFileDescriptorGetNativeDescriptor\nCFFileDescriptorGetNativeDescriptor.restype = ctypes.c_int\nCFFileDescriptorGetNativeDescriptor.argtypes = [void_p]\n\nCFFileDescriptorEnableCallBacks = CoreFoundation.CFFileDescriptorEnableCallBacks\nCFFileDescriptorEnableCallBacks.restype = None\nCFFileDescriptorEnableCallBacks.argtypes = [void_p, ctypes.c_ulong]\n\nCFFileDescriptorCreateRunLoopSource = CoreFoundation.CFFileDescriptorCreateRunLoopSource\nCFFileDescriptorCreateRunLoopSource.restype = void_p\nCFFileDescriptorCreateRunLoopSource.argtypes = [void_p, void_p, void_p]\n\nCFRunLoopGetCurrent = CoreFoundation.CFRunLoopGetCurrent\nCFRunLoopGetCurrent.restype = void_p\n\nCFRunLoopAddSource = CoreFoundation.CFRunLoopAddSource\nCFRunLoopAddSource.restype = None\nCFRunLoopAddSource.argtypes = [void_p, void_p, void_p]\n\nCFRelease = CoreFoundation.CFRelease\nCFRelease.restype = None\nCFRelease.argtypes = [void_p]\n\nCFFileDescriptorInvalidate = CoreFoundation.CFFileDescriptorInvalidate\nCFFileDescriptorInvalidate.restype = None\nCFFileDescriptorInvalidate.argtypes = [void_p]\n\n# From CFFileDescriptor.h\nkCFFileDescriptorReadCallBack = 1\nkCFRunLoopCommonModes = void_p.in_dll(CoreFoundation, 'kCFRunLoopCommonModes')\n\n\ndef _NSApp():\n """Return the global NSApplication instance (NSApp)"""\n objc.objc_msgSend.argtypes = [void_p, void_p]\n return msg(C('NSApplication'), n('sharedApplication'))\n\n\ndef _wake(NSApp):\n """Wake the Application"""\n objc.objc_msgSend.argtypes = [\n void_p,\n void_p,\n void_p,\n void_p,\n void_p,\n void_p,\n void_p,\n void_p,\n void_p,\n void_p,\n void_p,\n ]\n event = msg(\n C("NSEvent"),\n n(\n "otherEventWithType:location:modifierFlags:"\n "timestamp:windowNumber:context:subtype:data1:data2:"\n ),\n 15, # Type\n 0, # location\n 0, # flags\n 0, # timestamp\n 0, # window\n None, # context\n 0, # subtype\n 0, # data1\n 0, # data2\n )\n objc.objc_msgSend.argtypes = [void_p, void_p, void_p, void_p]\n msg(NSApp, n('postEvent:atStart:'), void_p(event), True)\n\n\ndef _input_callback(fdref, flags, info):\n """Callback to fire when there's input to be read"""\n CFFileDescriptorInvalidate(fdref)\n CFRelease(fdref)\n NSApp = _NSApp()\n objc.objc_msgSend.argtypes = [void_p, void_p, void_p]\n msg(NSApp, n('stop:'), NSApp)\n _wake(NSApp)\n\n_c_callback_func_type = ctypes.CFUNCTYPE(None, void_p, void_p, void_p)\n_c_input_callback = _c_callback_func_type(_input_callback)\n\n\ndef _stop_on_read(fd):\n """Register callback to stop eventloop when there's data on fd"""\n fdref = CFFileDescriptorCreate(None, fd, False, _c_input_callback, None)\n CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack)\n source = CFFileDescriptorCreateRunLoopSource(None, fdref, 0)\n loop = CFRunLoopGetCurrent()\n CFRunLoopAddSource(loop, source, kCFRunLoopCommonModes)\n CFRelease(source)\n\n\ndef inputhook(context):\n """Inputhook for Cocoa (NSApp)"""\n NSApp = _NSApp()\n _stop_on_read(context.fileno())\n objc.objc_msgSend.argtypes = [void_p, void_p]\n msg(NSApp, n('run'))\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\osx.py
osx.py
Python
4,448
0.95
0.081633
0.034783
awesome-app
385
2025-07-06T14:58:51.756330
MIT
false
cf7b031b4badd1ba02435d5d252de5c3
"""Enable pyglet to be used interactively with prompt_toolkit"""\n\nimport sys\nimport time\nfrom timeit import default_timer as clock\nimport pyglet\n\n# On linux only, window.flip() has a bug that causes an AttributeError on\n# window close. For details, see:\n# http://groups.google.com/group/pyglet-users/browse_thread/thread/47c1aab9aa4a3d23/c22f9e819826799e?#c22f9e819826799e\n\nif sys.platform.startswith("linux"):\n\n def flip(window):\n try:\n window.flip()\n except AttributeError:\n pass\nelse:\n\n def flip(window):\n window.flip()\n\n\ndef inputhook(context):\n """Run the pyglet event loop by processing pending events only.\n\n This keeps processing pending events until stdin is ready. After\n processing all pending events, a call to time.sleep is inserted. This is\n needed, otherwise, CPU usage is at 100%. This sleep time should be tuned\n though for best performance.\n """\n # We need to protect against a user pressing Control-C when IPython is\n # idle and this is running. We trap KeyboardInterrupt and pass.\n try:\n t = clock()\n while not context.input_is_ready():\n pyglet.clock.tick()\n for window in pyglet.app.windows:\n window.switch_to()\n window.dispatch_events()\n window.dispatch_event("on_draw")\n flip(window)\n\n # We need to sleep at this point to keep the idle CPU load\n # low. However, if sleep to long, GUI response is poor. As\n # a compromise, we watch how often GUI events are being processed\n # and switch between a short and long sleep time. Here are some\n # stats useful in helping to tune this.\n # time CPU load\n # 0.001 13%\n # 0.005 3%\n # 0.01 1.5%\n # 0.05 0.5%\n used_time = clock() - t\n if used_time > 10.0:\n # print('Sleep for 1 s') # dbg\n time.sleep(1.0)\n elif used_time > 0.1:\n # Few GUI events coming in, so we can sleep longer\n # print('Sleep for 0.05 s') # dbg\n time.sleep(0.05)\n else:\n # Many GUI events coming in, so sleep only very little\n time.sleep(0.001)\n except KeyboardInterrupt:\n pass\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\pyglet.py
pyglet.py
Python
2,371
0.95
0.208955
0.327586
vue-tools
201
2024-09-09T02:27:43.901388
BSD-3-Clause
false
714e01595189e9352e3cb34398653d6d
"""Enable wxPython to be used interactively in prompt_toolkit\n"""\n\nimport sys\nimport signal\nimport time\nfrom timeit import default_timer as clock\nimport wx\n\n\ndef ignore_keyboardinterrupts(func):\n """Decorator which causes KeyboardInterrupt exceptions to be ignored during\n execution of the decorated function.\n\n This is used by the inputhook functions to handle the event where the user\n presses CTRL+C while IPython is idle, and the inputhook loop is running. In\n this case, we want to ignore interrupts.\n """\n def wrapper(*args, **kwargs):\n try:\n func(*args, **kwargs)\n except KeyboardInterrupt:\n pass\n return wrapper\n\n\n@ignore_keyboardinterrupts\ndef inputhook_wx1(context):\n """Run the wx event loop by processing pending events only.\n\n This approach seems to work, but its performance is not great as it\n relies on having PyOS_InputHook called regularly.\n """\n app = wx.GetApp()\n if app is not None:\n assert wx.Thread_IsMain()\n\n # Make a temporary event loop and process system events until\n # there are no more waiting, then allow idle events (which\n # will also deal with pending or posted wx events.)\n evtloop = wx.EventLoop()\n ea = wx.EventLoopActivator(evtloop)\n while evtloop.Pending():\n evtloop.Dispatch()\n app.ProcessIdle()\n del ea\n return 0\n\n\nclass EventLoopTimer(wx.Timer):\n\n def __init__(self, func):\n self.func = func\n wx.Timer.__init__(self)\n\n def Notify(self):\n self.func()\n\n\nclass EventLoopRunner:\n\n def Run(self, time, input_is_ready):\n self.input_is_ready = input_is_ready\n self.evtloop = wx.EventLoop()\n self.timer = EventLoopTimer(self.check_stdin)\n self.timer.Start(time)\n self.evtloop.Run()\n\n def check_stdin(self):\n if self.input_is_ready():\n self.timer.Stop()\n self.evtloop.Exit()\n\n\n@ignore_keyboardinterrupts\ndef inputhook_wx2(context):\n """Run the wx event loop, polling for stdin.\n\n This version runs the wx eventloop for an undetermined amount of time,\n during which it periodically checks to see if anything is ready on\n stdin. If anything is ready on stdin, the event loop exits.\n\n The argument to elr.Run controls how often the event loop looks at stdin.\n This determines the responsiveness at the keyboard. A setting of 1000\n enables a user to type at most 1 char per second. I have found that a\n setting of 10 gives good keyboard response. We can shorten it further,\n but eventually performance would suffer from calling select/kbhit too\n often.\n """\n app = wx.GetApp()\n if app is not None:\n assert wx.Thread_IsMain()\n elr = EventLoopRunner()\n # As this time is made shorter, keyboard response improves, but idle\n # CPU load goes up. 10 ms seems like a good compromise.\n elr.Run(time=10, # CHANGE time here to control polling interval\n input_is_ready=context.input_is_ready)\n return 0\n\n\n@ignore_keyboardinterrupts\ndef inputhook_wx3(context):\n """Run the wx event loop by processing pending events only.\n\n This is like inputhook_wx1, but it keeps processing pending events\n until stdin is ready. After processing all pending events, a call to\n time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%.\n This sleep time should be tuned though for best performance.\n """\n app = wx.GetApp()\n if app is not None:\n assert wx.Thread_IsMain()\n\n # The import of wx on Linux sets the handler for signal.SIGINT\n # to 0. This is a bug in wx or gtk. We fix by just setting it\n # back to the Python default.\n if not callable(signal.getsignal(signal.SIGINT)):\n signal.signal(signal.SIGINT, signal.default_int_handler)\n\n evtloop = wx.EventLoop()\n ea = wx.EventLoopActivator(evtloop)\n t = clock()\n while not context.input_is_ready():\n while evtloop.Pending():\n t = clock()\n evtloop.Dispatch()\n app.ProcessIdle()\n # We need to sleep at this point to keep the idle CPU load\n # low. However, if sleep to long, GUI response is poor. As\n # a compromise, we watch how often GUI events are being processed\n # and switch between a short and long sleep time. Here are some\n # stats useful in helping to tune this.\n # time CPU load\n # 0.001 13%\n # 0.005 3%\n # 0.01 1.5%\n # 0.05 0.5%\n used_time = clock() - t\n if used_time > 10.0:\n # print('Sleep for 1 s') # dbg\n time.sleep(1.0)\n elif used_time > 0.1:\n # Few GUI events coming in, so we can sleep longer\n # print('Sleep for 0.05 s') # dbg\n time.sleep(0.05)\n else:\n # Many GUI events coming in, so sleep only very little\n time.sleep(0.001)\n del ea\n return 0\n\n\n@ignore_keyboardinterrupts\ndef inputhook_wxphoenix(context):\n """Run the wx event loop until the user provides more input.\n\n This input hook is suitable for use with wxPython >= 4 (a.k.a. Phoenix).\n\n It uses the same approach to that used in\n ipykernel.eventloops.loop_wx. The wx.MainLoop is executed, and a wx.Timer\n is used to periodically poll the context for input. As soon as input is\n ready, the wx.MainLoop is stopped.\n """\n\n app = wx.GetApp()\n\n if app is None:\n return\n\n if context.input_is_ready():\n return\n\n assert wx.IsMainThread()\n\n # Wx uses milliseconds\n poll_interval = 100\n\n # Use a wx.Timer to periodically check whether input is ready - as soon as\n # it is, we exit the main loop\n timer = wx.Timer()\n\n def poll(ev):\n if context.input_is_ready():\n timer.Stop()\n app.ExitMainLoop()\n\n timer.Start(poll_interval)\n timer.Bind(wx.EVT_TIMER, poll)\n\n # The import of wx on Linux sets the handler for signal.SIGINT to 0. This\n # is a bug in wx or gtk. We fix by just setting it back to the Python\n # default.\n if not callable(signal.getsignal(signal.SIGINT)):\n signal.signal(signal.SIGINT, signal.default_int_handler)\n\n # The SetExitOnFrameDelete call allows us to run the wx mainloop without\n # having a frame open.\n app.SetExitOnFrameDelete(False)\n app.MainLoop()\n\n\n# Get the major wx version number to figure out what input hook we should use.\nmajor_version = 3\n\ntry:\n major_version = int(wx.__version__[0])\nexcept Exception:\n pass\n\n# Use the phoenix hook on all platforms for wxpython >= 4\nif major_version >= 4:\n inputhook = inputhook_wxphoenix\n# On OSX, evtloop.Pending() always returns True, regardless of there being\n# any events pending. As such we can't use implementations 1 or 3 of the\n# inputhook as those depend on a pending/dispatch loop.\nelif sys.platform == 'darwin':\n inputhook = inputhook_wx2\nelse:\n inputhook = inputhook_wx3\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\wx.py
wx.py
Python
7,126
0.95
0.200913
0.198864
awesome-app
258
2024-04-04T06:40:16.972197
BSD-3-Clause
false
277f8f23302e80c6a4a98d3edfe9dab9
import importlib\nimport os\nfrom typing import Tuple, Callable\n\naliases = {\n 'qt4': 'qt',\n 'gtk2': 'gtk',\n}\n\nbackends = [\n "qt",\n "qt5",\n "qt6",\n "gtk",\n "gtk2",\n "gtk3",\n "gtk4",\n "tk",\n "wx",\n "pyglet",\n "glut",\n "osx",\n "asyncio",\n]\n\nregistered = {}\n\ndef register(name, inputhook):\n """Register the function *inputhook* as an event loop integration."""\n registered[name] = inputhook\n\n\nclass UnknownBackend(KeyError):\n def __init__(self, name):\n self.name = name\n\n def __str__(self):\n return ("No event loop integration for {!r}. "\n "Supported event loops are: {}").format(self.name,\n ', '.join(backends + sorted(registered)))\n\n\ndef set_qt_api(gui):\n """Sets the `QT_API` environment variable if it isn't already set."""\n\n qt_api = os.environ.get("QT_API", None)\n\n from IPython.external.qt_loaders import (\n QT_API_PYQT,\n QT_API_PYQT5,\n QT_API_PYQT6,\n QT_API_PYSIDE,\n QT_API_PYSIDE2,\n QT_API_PYSIDE6,\n QT_API_PYQTv1,\n loaded_api,\n )\n\n loaded = loaded_api()\n\n qt_env2gui = {\n QT_API_PYSIDE: "qt4",\n QT_API_PYQTv1: "qt4",\n QT_API_PYQT: "qt4",\n QT_API_PYSIDE2: "qt5",\n QT_API_PYQT5: "qt5",\n QT_API_PYSIDE6: "qt6",\n QT_API_PYQT6: "qt6",\n }\n if loaded is not None and gui != "qt":\n if qt_env2gui[loaded] != gui:\n print(\n f"Cannot switch Qt versions for this session; will use {qt_env2gui[loaded]}."\n )\n return qt_env2gui[loaded]\n\n if qt_api is not None and gui != "qt":\n if qt_env2gui[qt_api] != gui:\n print(\n f'Request for "{gui}" will be ignored because `QT_API` '\n f'environment variable is set to "{qt_api}"'\n )\n return qt_env2gui[qt_api]\n else:\n if gui == "qt5":\n try:\n import PyQt5 # noqa\n\n os.environ["QT_API"] = "pyqt5"\n except ImportError:\n try:\n import PySide2 # noqa\n\n os.environ["QT_API"] = "pyside2"\n except ImportError:\n os.environ["QT_API"] = "pyqt5"\n elif gui == "qt6":\n try:\n import PyQt6 # noqa\n\n os.environ["QT_API"] = "pyqt6"\n except ImportError:\n try:\n import PySide6 # noqa\n\n os.environ["QT_API"] = "pyside6"\n except ImportError:\n os.environ["QT_API"] = "pyqt6"\n elif gui == "qt":\n # Don't set QT_API; let IPython logic choose the version.\n if "QT_API" in os.environ.keys():\n del os.environ["QT_API"]\n else:\n print(f'Unrecognized Qt version: {gui}. Should be "qt5", "qt6", or "qt".')\n return\n\n # Import it now so we can figure out which version it is.\n from IPython.external.qt_for_kernel import QT_API\n\n return qt_env2gui[QT_API]\n\n\ndef get_inputhook_name_and_func(gui: str) -> Tuple[str, Callable]:\n if gui in registered:\n return gui, registered[gui]\n\n if gui not in backends:\n raise UnknownBackend(gui)\n\n if gui in aliases:\n return get_inputhook_name_and_func(aliases[gui])\n\n gui_mod = gui\n if gui.startswith("qt"):\n gui = set_qt_api(gui)\n gui_mod = "qt"\n\n mod = importlib.import_module("IPython.terminal.pt_inputhooks." + gui_mod)\n return gui, mod.inputhook\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\__init__.py
__init__.py
Python
3,606
0.95
0.18705
0.017699
react-lib
639
2025-06-12T15:35:06.476974
GPL-3.0
false
9021ca15d34a69f5aeb6acd509ba908d
\n\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\__pycache__\asyncio.cpython-313.pyc
asyncio.cpython-313.pyc
Other
1,246
0.85
0.34375
0
awesome-app
117
2023-12-23T05:04:24.052685
Apache-2.0
false
e9086b95a97637de6458d61da4bb2369
\n\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\__pycache__\glut.cpython-313.pyc
glut.cpython-313.pyc
Other
4,290
0.8
0.040816
0
node-utils
882
2024-04-04T10:04:33.690299
MIT
false
0b84793679a3d4327086dc446adc4f58
\n\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\__pycache__\gtk.cpython-313.pyc
gtk.cpython-313.pyc
Other
1,257
0.7
0.1
0
node-utils
360
2023-09-26T00:38:57.772460
MIT
false
9264ca5d5523a37a739996bc998d3709
\n\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\__pycache__\gtk3.cpython-313.pyc
gtk3.cpython-313.pyc
Other
899
0.8
0.111111
0
awesome-app
172
2024-09-06T11:39:09.391424
GPL-3.0
false
22b65d1243ceb013ca04879e5b68f05d
\n\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\__pycache__\gtk4.cpython-313.pyc
gtk4.cpython-313.pyc
Other
1,662
0.8
0.071429
0
react-lib
491
2024-08-04T20:26:59.884663
BSD-3-Clause
false
fcb4a5e5c4b06f18a5ea41364c874918
\n\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\__pycache__\osx.cpython-313.pyc
osx.cpython-313.pyc
Other
5,691
0.8
0.050847
0
node-utils
950
2024-01-08T03:36:33.716773
GPL-3.0
false
fbac7d84ff966068d00d45a386fe3e5c
\n\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\__pycache__\pyglet.cpython-313.pyc
pyglet.cpython-313.pyc
Other
2,292
0.8
0.030303
0
python-kit
594
2025-04-08T23:21:53.817499
BSD-3-Clause
false
ac84a4a28abab2a9bb0f7a9a291ade1c
\n\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\__pycache__\qt.cpython-313.pyc
qt.cpython-313.pyc
Other
4,054
0.95
0
0.051282
vue-tools
760
2024-05-09T03:23:00.102261
MIT
false
5d79e285c36f8d1d0f98cdcdb0d60639
\n\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\__pycache__\tk.cpython-313.pyc
tk.cpython-313.pyc
Other
2,926
0.8
0.151515
0
awesome-app
273
2025-02-24T18:59:46.727240
BSD-3-Clause
false
7909c042c1fb95c57820ba407a072261
\n\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\__pycache__\wx.cpython-313.pyc
wx.cpython-313.pyc
Other
8,660
0.95
0.071429
0
node-utils
569
2024-04-03T10:22:56.739025
GPL-3.0
false
eea4b102ac3b204bd695502d3fe85e04
\n\n
.venv\Lib\site-packages\IPython\terminal\pt_inputhooks\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
4,556
0.95
0.095238
0
awesome-app
657
2023-11-01T01:26:40.708904
Apache-2.0
false
cba0963e5b619366f05b0e715f27e110
"""\nUtilities function for keybinding with prompt toolkit.\n\nThis will be bound to specific key press and filter modes,\nlike whether we are in edit mode, and whether the completer is open.\n"""\n\nimport re\nfrom prompt_toolkit.key_binding import KeyPressEvent\n\n\ndef parenthesis(event: KeyPressEvent):\n """Auto-close parenthesis"""\n event.current_buffer.insert_text("()")\n event.current_buffer.cursor_left()\n\n\ndef brackets(event: KeyPressEvent):\n """Auto-close brackets"""\n event.current_buffer.insert_text("[]")\n event.current_buffer.cursor_left()\n\n\ndef braces(event: KeyPressEvent):\n """Auto-close braces"""\n event.current_buffer.insert_text("{}")\n event.current_buffer.cursor_left()\n\n\ndef double_quote(event: KeyPressEvent):\n """Auto-close double quotes"""\n event.current_buffer.insert_text('""')\n event.current_buffer.cursor_left()\n\n\ndef single_quote(event: KeyPressEvent):\n """Auto-close single quotes"""\n event.current_buffer.insert_text("''")\n event.current_buffer.cursor_left()\n\n\ndef docstring_double_quotes(event: KeyPressEvent):\n """Auto-close docstring (double quotes)"""\n event.current_buffer.insert_text('""""')\n event.current_buffer.cursor_left(3)\n\n\ndef docstring_single_quotes(event: KeyPressEvent):\n """Auto-close docstring (single quotes)"""\n event.current_buffer.insert_text("''''")\n event.current_buffer.cursor_left(3)\n\n\ndef raw_string_parenthesis(event: KeyPressEvent):\n """Auto-close parenthesis in raw strings"""\n matches = re.match(\n r".*(r|R)[\"'](-*)",\n event.current_buffer.document.current_line_before_cursor,\n )\n dashes = matches.group(2) if matches else ""\n event.current_buffer.insert_text("()" + dashes)\n event.current_buffer.cursor_left(len(dashes) + 1)\n\n\ndef raw_string_bracket(event: KeyPressEvent):\n """Auto-close bracker in raw strings"""\n matches = re.match(\n r".*(r|R)[\"'](-*)",\n event.current_buffer.document.current_line_before_cursor,\n )\n dashes = matches.group(2) if matches else ""\n event.current_buffer.insert_text("[]" + dashes)\n event.current_buffer.cursor_left(len(dashes) + 1)\n\n\ndef raw_string_braces(event: KeyPressEvent):\n """Auto-close braces in raw strings"""\n matches = re.match(\n r".*(r|R)[\"'](-*)",\n event.current_buffer.document.current_line_before_cursor,\n )\n dashes = matches.group(2) if matches else ""\n event.current_buffer.insert_text("{}" + dashes)\n event.current_buffer.cursor_left(len(dashes) + 1)\n\n\ndef skip_over(event: KeyPressEvent):\n """Skip over automatically added parenthesis/quote.\n\n (rather than adding another parenthesis/quote)"""\n event.current_buffer.cursor_right()\n\n\ndef delete_pair(event: KeyPressEvent):\n """Delete auto-closed parenthesis"""\n event.current_buffer.delete()\n event.current_buffer.delete_before_cursor()\n\n\nauto_match_parens = {"(": parenthesis, "[": brackets, "{": braces}\nauto_match_parens_raw_string = {\n "(": raw_string_parenthesis,\n "[": raw_string_bracket,\n "{": raw_string_braces,\n}\n
.venv\Lib\site-packages\IPython\terminal\shortcuts\auto_match.py
auto_match.py
Python
3,066
0.85
0.161905
0
vue-tools
456
2025-02-09T12:06:39.873846
MIT
false
ec65eb25825a9c3819397e72bb1147f1
import re\nimport asyncio\nimport tokenize\nfrom io import StringIO\nfrom typing import Callable, List, Optional, Union, Generator, Tuple, ClassVar, Any\nimport warnings\n\nimport prompt_toolkit\nfrom prompt_toolkit.buffer import Buffer\nfrom prompt_toolkit.key_binding import KeyPressEvent\nfrom prompt_toolkit.key_binding.bindings import named_commands as nc\nfrom prompt_toolkit.auto_suggest import AutoSuggestFromHistory, Suggestion\nfrom prompt_toolkit.document import Document\nfrom prompt_toolkit.history import History\nfrom prompt_toolkit.shortcuts import PromptSession\nfrom prompt_toolkit.layout.processors import (\n Processor,\n Transformation,\n TransformationInput,\n)\n\nfrom IPython.core.getipython import get_ipython\nfrom IPython.utils.tokenutil import generate_tokens\n\nfrom .filters import pass_through\n\n\ndef _get_query(document: Document):\n return document.lines[document.cursor_position_row]\n\n\nclass AppendAutoSuggestionInAnyLine(Processor):\n """\n Append the auto suggestion to lines other than the last (appending to the\n last line is natively supported by the prompt toolkit).\n\n This has a private `_debug` attribute that can be set to True to display\n debug information as virtual suggestion on the end of any line. You can do\n so with:\n\n >>> from IPython.terminal.shortcuts.auto_suggest import AppendAutoSuggestionInAnyLine\n >>> AppendAutoSuggestionInAnyLine._debug = True\n\n """\n\n _debug: ClassVar[bool] = False\n\n def __init__(self, style: str = "class:auto-suggestion") -> None:\n self.style = style\n\n def apply_transformation(self, ti: TransformationInput) -> Transformation:\n """\n Apply transformation to the line that is currently being edited.\n\n This is a variation of the original implementation in prompt toolkit\n that allows to not only append suggestions to any line, but also to show\n multi-line suggestions.\n\n As transformation are applied on a line-by-line basis; we need to trick\n a bit, and elide any line that is after the line we are currently\n editing, until we run out of completions. We cannot shift the existing\n lines\n\n There are multiple cases to handle:\n\n The completions ends before the end of the buffer:\n We can resume showing the normal line, and say that some code may\n be hidden.\n\n The completions ends at the end of the buffer\n We can just say that some code may be hidden.\n\n And separately:\n\n The completions ends beyond the end of the buffer\n We need to both say that some code may be hidden, and that some\n lines are not shown.\n\n """\n last_line_number = ti.document.line_count - 1\n is_last_line = ti.lineno == last_line_number\n\n noop = lambda text: Transformation(\n fragments=ti.fragments + [(self.style, " " + text if self._debug else "")]\n )\n if ti.document.line_count == 1:\n return noop("noop:oneline")\n if ti.document.cursor_position_row == last_line_number and is_last_line:\n # prompt toolkit already appends something; just leave it be\n return noop("noop:last line and cursor")\n\n # first everything before the current line is unchanged.\n if ti.lineno < ti.document.cursor_position_row:\n return noop("noop:before cursor")\n\n buffer = ti.buffer_control.buffer\n if not buffer.suggestion or not ti.document.is_cursor_at_the_end_of_line:\n return noop("noop:not eol")\n\n delta = ti.lineno - ti.document.cursor_position_row\n suggestions = buffer.suggestion.text.splitlines()\n\n if len(suggestions) == 0:\n return noop("noop: no suggestions")\n\n if prompt_toolkit.VERSION < (3, 0, 49):\n if len(suggestions) > 1 and prompt_toolkit.VERSION < (3, 0, 49):\n if ti.lineno == ti.document.cursor_position_row:\n return Transformation(\n fragments=ti.fragments\n + [\n (\n "red",\n "(Cannot show multiline suggestion; requires prompt_toolkit > 3.0.49)",\n )\n ]\n )\n else:\n return Transformation(fragments=ti.fragments)\n elif len(suggestions) == 1:\n if ti.lineno == ti.document.cursor_position_row:\n return Transformation(\n fragments=ti.fragments + [(self.style, suggestions[0])]\n )\n return Transformation(fragments=ti.fragments)\n\n if delta == 0:\n suggestion = suggestions[0]\n return Transformation(fragments=ti.fragments + [(self.style, suggestion)])\n if is_last_line:\n if delta < len(suggestions):\n suggestion = f"… rest of suggestion ({len(suggestions) - delta} lines) and code hidden"\n return Transformation([(self.style, suggestion)])\n\n n_elided = len(suggestions)\n for i in range(len(suggestions)):\n ll = ti.get_line(last_line_number - i)\n el = "".join(l[1] for l in ll).strip()\n if el:\n break\n else:\n n_elided -= 1\n if n_elided:\n return Transformation([(self.style, f"… {n_elided} line(s) hidden")])\n else:\n return Transformation(\n ti.get_line(last_line_number - len(suggestions) + 1)\n + ([(self.style, "shift-last-line")] if self._debug else [])\n )\n\n elif delta < len(suggestions):\n suggestion = suggestions[delta]\n return Transformation([(self.style, suggestion)])\n else:\n shift = ti.lineno - len(suggestions) + 1\n return Transformation(ti.get_line(shift))\n\n\nclass NavigableAutoSuggestFromHistory(AutoSuggestFromHistory):\n """\n A subclass of AutoSuggestFromHistory that allow navigation to next/previous\n suggestion from history. To do so it remembers the current position, but it\n state need to carefully be cleared on the right events.\n """\n\n skip_lines: int\n _connected_apps: list[PromptSession]\n\n # handle to the currently running llm task that appends suggestions to the\n # current buffer; we keep a handle to it in order to cancel it when there is a cursor movement, or\n # another request.\n _llm_task: asyncio.Task | None = None\n\n # This is the constructor of the LLM provider from jupyter-ai\n # to which we forward the request to generate inline completions.\n _init_llm_provider: Callable | None\n\n _llm_provider_instance: Any | None\n _llm_prefixer: Callable = lambda self, x: "wrong"\n\n def __init__(self):\n super().__init__()\n self.skip_lines = 0\n self._connected_apps = []\n self._llm_provider_instance = None\n self._init_llm_provider = None\n self._request_number = 0\n\n def reset_history_position(self, _: Buffer) -> None:\n self.skip_lines = 0\n\n def disconnect(self) -> None:\n self._cancel_running_llm_task()\n for pt_app in self._connected_apps:\n text_insert_event = pt_app.default_buffer.on_text_insert\n text_insert_event.remove_handler(self.reset_history_position)\n\n def connect(self, pt_app: PromptSession) -> None:\n self._connected_apps.append(pt_app)\n # note: `on_text_changed` could be used for a bit different behaviour\n # on character deletion (i.e. resetting history position on backspace)\n pt_app.default_buffer.on_text_insert.add_handler(self.reset_history_position)\n pt_app.default_buffer.on_cursor_position_changed.add_handler(self._dismiss)\n\n def get_suggestion(\n self, buffer: Buffer, document: Document\n ) -> Optional[Suggestion]:\n text = _get_query(document)\n\n if text.strip():\n for suggestion, _ in self._find_next_match(\n text, self.skip_lines, buffer.history\n ):\n return Suggestion(suggestion)\n\n return None\n\n def _dismiss(self, buffer, *args, **kwargs) -> None:\n self._cancel_running_llm_task()\n buffer.suggestion = None\n\n def _find_match(\n self, text: str, skip_lines: float, history: History, previous: bool\n ) -> Generator[Tuple[str, float], None, None]:\n """\n text : str\n Text content to find a match for, the user cursor is most of the\n time at the end of this text.\n skip_lines : float\n number of items to skip in the search, this is used to indicate how\n far in the list the user has navigated by pressing up or down.\n The float type is used as the base value is +inf\n history : History\n prompt_toolkit History instance to fetch previous entries from.\n previous : bool\n Direction of the search, whether we are looking previous match\n (True), or next match (False).\n\n Yields\n ------\n Tuple with:\n str:\n current suggestion.\n float:\n will actually yield only ints, which is passed back via skip_lines,\n which may be a +inf (float)\n\n\n """\n line_number = -1\n for string in reversed(list(history.get_strings())):\n for line in reversed(string.splitlines()):\n line_number += 1\n if not previous and line_number < skip_lines:\n continue\n # do not return empty suggestions as these\n # close the auto-suggestion overlay (and are useless)\n if line.startswith(text) and len(line) > len(text):\n yield line[len(text) :], line_number\n if previous and line_number >= skip_lines:\n return\n\n def _find_next_match(\n self, text: str, skip_lines: float, history: History\n ) -> Generator[Tuple[str, float], None, None]:\n return self._find_match(text, skip_lines, history, previous=False)\n\n def _find_previous_match(self, text: str, skip_lines: float, history: History):\n return reversed(\n list(self._find_match(text, skip_lines, history, previous=True))\n )\n\n def up(self, query: str, other_than: str, history: History) -> None:\n self._cancel_running_llm_task()\n for suggestion, line_number in self._find_next_match(\n query, self.skip_lines, history\n ):\n # if user has history ['very.a', 'very', 'very.b'] and typed 'very'\n # we want to switch from 'very.b' to 'very.a' because a) if the\n # suggestion equals current text, prompt-toolkit aborts suggesting\n # b) user likely would not be interested in 'very' anyways (they\n # already typed it).\n if query + suggestion != other_than:\n self.skip_lines = line_number\n break\n else:\n # no matches found, cycle back to beginning\n self.skip_lines = 0\n\n def down(self, query: str, other_than: str, history: History) -> None:\n self._cancel_running_llm_task()\n for suggestion, line_number in self._find_previous_match(\n query, self.skip_lines, history\n ):\n if query + suggestion != other_than:\n self.skip_lines = line_number\n break\n else:\n # no matches found, cycle to end\n for suggestion, line_number in self._find_previous_match(\n query, float("Inf"), history\n ):\n if query + suggestion != other_than:\n self.skip_lines = line_number\n break\n\n def _cancel_running_llm_task(self) -> None:\n """\n Try to cancel the currently running llm_task if exists, and set it to None.\n """\n if self._llm_task is not None:\n if self._llm_task.done():\n self._llm_task = None\n return\n cancelled = self._llm_task.cancel()\n if cancelled:\n self._llm_task = None\n if not cancelled:\n warnings.warn(\n "LLM task not cancelled, does your provider support cancellation?"\n )\n\n @property\n def _llm_provider(self):\n """Lazy-initialized instance of the LLM provider.\n\n Do not use in the constructor, as `_init_llm_provider` can trigger slow side-effects.\n """\n if self._llm_provider_instance is None and self._init_llm_provider:\n self._llm_provider_instance = self._init_llm_provider()\n return self._llm_provider_instance\n\n async def _trigger_llm(self, buffer) -> None:\n """\n This will ask the current llm provider a suggestion for the current buffer.\n\n If there is a currently running llm task, it will cancel it.\n """\n # we likely want to store the current cursor position, and cancel if the cursor has moved.\n try:\n import jupyter_ai_magics\n except ModuleNotFoundError:\n jupyter_ai_magics = None\n if not self._llm_provider:\n warnings.warn("No LLM provider found, cannot trigger LLM completions")\n return\n if jupyter_ai_magics is None:\n warnings.warn("LLM Completion requires `jupyter_ai_magics` to be installed")\n\n self._cancel_running_llm_task()\n\n async def error_catcher(buffer):\n """\n This catches and log any errors, as otherwise this is just\n lost in the void of the future running task.\n """\n try:\n await self._trigger_llm_core(buffer)\n except Exception as e:\n get_ipython().log.error("error %s", e)\n raise\n\n # here we need a cancellable task so we can't just await the error caught\n self._llm_task = asyncio.create_task(error_catcher(buffer))\n await self._llm_task\n\n async def _trigger_llm_core(self, buffer: Buffer):\n """\n This is the core of the current llm request.\n\n Here we build a compatible `InlineCompletionRequest` and ask the llm\n provider to stream it's response back to us iteratively setting it as\n the suggestion on the current buffer.\n\n Unlike with JupyterAi, as we do not have multiple cells, the cell id\n is always set to `None`.\n\n We set the prefix to the current cell content, but could also insert the\n rest of the history or even just the non-fail history.\n\n In the same way, we do not have cell id.\n\n LLM provider may return multiple suggestion stream, but for the time\n being we only support one.\n\n Here we make the assumption that the provider will have\n stream_inline_completions, I'm not sure it is the case for all\n providers.\n """\n try:\n import jupyter_ai.completions.models as jai_models\n except ModuleNotFoundError:\n jai_models = None\n\n if not jai_models:\n raise ValueError("jupyter-ai is not installed")\n\n if not self._llm_provider:\n raise ValueError("No LLM provider found, cannot trigger LLM completions")\n\n hm = buffer.history.shell.history_manager\n prefix = self._llm_prefixer(hm)\n get_ipython().log.debug("prefix: %s", prefix)\n\n self._request_number += 1\n request_number = self._request_number\n\n request = jai_models.InlineCompletionRequest(\n number=request_number,\n prefix=prefix + buffer.document.text_before_cursor,\n suffix=buffer.document.text_after_cursor,\n mime="text/x-python",\n stream=True,\n path=None,\n language="python",\n cell_id=None,\n )\n\n async for reply_and_chunks in self._llm_provider.stream_inline_completions(\n request\n ):\n if self._request_number != request_number:\n # If a new suggestion was requested, skip processing this one.\n return\n if isinstance(reply_and_chunks, jai_models.InlineCompletionReply):\n if len(reply_and_chunks.list.items) > 1:\n raise ValueError(\n "Terminal IPython cannot deal with multiple LLM suggestions at once"\n )\n buffer.suggestion = Suggestion(\n reply_and_chunks.list.items[0].insertText\n )\n buffer.on_suggestion_set.fire()\n elif isinstance(reply_and_chunks, jai_models.InlineCompletionStreamChunk):\n buffer.suggestion = Suggestion(reply_and_chunks.response.insertText)\n buffer.on_suggestion_set.fire()\n return\n\n\nasync def llm_autosuggestion(event: KeyPressEvent):\n """\n Ask the AutoSuggester from history to delegate to ask an LLM for completion\n\n This will first make sure that the current buffer have _MIN_LINES (7)\n available lines to insert the LLM completion\n\n Provisional as of 8.32, may change without warnings\n\n """\n _MIN_LINES = 5\n provider = get_ipython().auto_suggest\n if not isinstance(provider, NavigableAutoSuggestFromHistory):\n return\n doc = event.current_buffer.document\n lines_to_insert = max(0, _MIN_LINES - doc.line_count + doc.cursor_position_row)\n for _ in range(lines_to_insert):\n event.current_buffer.insert_text("\n", move_cursor=False, fire_event=False)\n\n await provider._trigger_llm(event.current_buffer)\n\n\ndef accept_or_jump_to_end(event: KeyPressEvent):\n """Apply autosuggestion or jump to end of line."""\n buffer = event.current_buffer\n d = buffer.document\n after_cursor = d.text[d.cursor_position :]\n lines = after_cursor.split("\n")\n end_of_current_line = lines[0].strip()\n suggestion = buffer.suggestion\n if (suggestion is not None) and (suggestion.text) and (end_of_current_line == ""):\n buffer.insert_text(suggestion.text)\n else:\n nc.end_of_line(event)\n\n\ndef accept(event: KeyPressEvent):\n """Accept autosuggestion"""\n buffer = event.current_buffer\n suggestion = buffer.suggestion\n if suggestion:\n buffer.insert_text(suggestion.text)\n else:\n nc.forward_char(event)\n\n\ndef discard(event: KeyPressEvent):\n """Discard autosuggestion"""\n buffer = event.current_buffer\n buffer.suggestion = None\n\n\ndef accept_word(event: KeyPressEvent):\n """Fill partial autosuggestion by word"""\n buffer = event.current_buffer\n suggestion = buffer.suggestion\n if suggestion:\n t = re.split(r"(\S+\s+)", suggestion.text)\n buffer.insert_text(next((x for x in t if x), ""))\n else:\n nc.forward_word(event)\n\n\ndef accept_character(event: KeyPressEvent):\n """Fill partial autosuggestion by character"""\n b = event.current_buffer\n suggestion = b.suggestion\n if suggestion and suggestion.text:\n b.insert_text(suggestion.text[0])\n\n\ndef accept_and_keep_cursor(event: KeyPressEvent):\n """Accept autosuggestion and keep cursor in place"""\n buffer = event.current_buffer\n old_position = buffer.cursor_position\n suggestion = buffer.suggestion\n if suggestion:\n buffer.insert_text(suggestion.text)\n buffer.cursor_position = old_position\n\n\ndef accept_and_move_cursor_left(event: KeyPressEvent):\n """Accept autosuggestion and move cursor left in place"""\n accept_and_keep_cursor(event)\n nc.backward_char(event)\n\n\ndef _update_hint(buffer: Buffer):\n if buffer.auto_suggest:\n suggestion = buffer.auto_suggest.get_suggestion(buffer, buffer.document)\n buffer.suggestion = suggestion\n\n\ndef backspace_and_resume_hint(event: KeyPressEvent):\n """Resume autosuggestions after deleting last character"""\n nc.backward_delete_char(event)\n _update_hint(event.current_buffer)\n\n\ndef resume_hinting(event: KeyPressEvent):\n """Resume autosuggestions"""\n pass_through.reply(event)\n # Order matters: if update happened first and event reply second, the\n # suggestion would be auto-accepted if both actions are bound to same key.\n _update_hint(event.current_buffer)\n\n\ndef up_and_update_hint(event: KeyPressEvent):\n """Go up and update hint"""\n current_buffer = event.current_buffer\n\n current_buffer.auto_up(count=event.arg)\n _update_hint(current_buffer)\n\n\ndef down_and_update_hint(event: KeyPressEvent):\n """Go down and update hint"""\n current_buffer = event.current_buffer\n\n current_buffer.auto_down(count=event.arg)\n _update_hint(current_buffer)\n\n\ndef accept_token(event: KeyPressEvent):\n """Fill partial autosuggestion by token"""\n b = event.current_buffer\n suggestion = b.suggestion\n\n if suggestion:\n prefix = _get_query(b.document)\n text = prefix + suggestion.text\n\n tokens: List[Optional[str]] = [None, None, None]\n substrings = [""]\n i = 0\n\n for token in generate_tokens(StringIO(text).readline):\n if token.type == tokenize.NEWLINE:\n index = len(text)\n else:\n index = text.index(token[1], len(substrings[-1]))\n substrings.append(text[:index])\n tokenized_so_far = substrings[-1]\n if tokenized_so_far.startswith(prefix):\n if i == 0 and len(tokenized_so_far) > len(prefix):\n tokens[0] = tokenized_so_far[len(prefix) :]\n substrings.append(tokenized_so_far)\n i += 1\n tokens[i] = token[1]\n if i == 2:\n break\n i += 1\n\n if tokens[0]:\n to_insert: str\n insert_text = substrings[-2]\n if tokens[1] and len(tokens[1]) == 1:\n insert_text = substrings[-1]\n to_insert = insert_text[len(prefix) :]\n b.insert_text(to_insert)\n return\n\n nc.forward_word(event)\n\n\nProvider = Union[AutoSuggestFromHistory, NavigableAutoSuggestFromHistory, None]\n\n\ndef _swap_autosuggestion(\n buffer: Buffer,\n provider: NavigableAutoSuggestFromHistory,\n direction_method: Callable,\n):\n """\n We skip most recent history entry (in either direction) if it equals the\n current autosuggestion because if user cycles when auto-suggestion is shown\n they most likely want something else than what was suggested (otherwise\n they would have accepted the suggestion).\n """\n suggestion = buffer.suggestion\n if not suggestion:\n return\n\n query = _get_query(buffer.document)\n current = query + suggestion.text\n\n direction_method(query=query, other_than=current, history=buffer.history)\n\n new_suggestion = provider.get_suggestion(buffer, buffer.document)\n buffer.suggestion = new_suggestion\n\n\ndef swap_autosuggestion_up(event: KeyPressEvent):\n """Get next autosuggestion from history."""\n shell = get_ipython()\n provider = shell.auto_suggest\n\n if not isinstance(provider, NavigableAutoSuggestFromHistory):\n return\n\n return _swap_autosuggestion(\n buffer=event.current_buffer, provider=provider, direction_method=provider.up\n )\n\n\ndef swap_autosuggestion_down(event: KeyPressEvent):\n """Get previous autosuggestion from history."""\n shell = get_ipython()\n provider = shell.auto_suggest\n\n if not isinstance(provider, NavigableAutoSuggestFromHistory):\n return\n\n return _swap_autosuggestion(\n buffer=event.current_buffer,\n provider=provider,\n direction_method=provider.down,\n )\n
.venv\Lib\site-packages\IPython\terminal\shortcuts\auto_suggest.py
auto_suggest.py
Python
23,803
0.95
0.187215
0.043396
node-utils
504
2024-10-01T05:47:56.237937
GPL-3.0
false
9d3a6e53b5271a2b9bc306c1e422ef53
"""\nModule to define and register Terminal IPython shortcuts with\n:mod:`prompt_toolkit`\n"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport os\nimport signal\nimport sys\nimport warnings\nfrom dataclasses import dataclass\nfrom typing import Callable, Any, Optional, List\n\nfrom prompt_toolkit.application.current import get_app\nfrom prompt_toolkit.key_binding import KeyBindings\nfrom prompt_toolkit.key_binding.key_processor import KeyPressEvent\nfrom prompt_toolkit.key_binding.bindings import named_commands as nc\nfrom prompt_toolkit.key_binding.bindings.completion import (\n display_completions_like_readline,\n)\nfrom prompt_toolkit.key_binding.vi_state import InputMode, ViState\nfrom prompt_toolkit.filters import Condition\n\nfrom IPython.core.getipython import get_ipython\nfrom . import auto_match as match\nfrom . import auto_suggest\nfrom .filters import filter_from_string\nfrom IPython.utils.decorators import undoc\n\nfrom prompt_toolkit.enums import DEFAULT_BUFFER\n\n__all__ = ["create_ipython_shortcuts"]\n\n\n@dataclass\nclass BaseBinding:\n command: Callable[[KeyPressEvent], Any]\n keys: List[str]\n\n\n@dataclass\nclass RuntimeBinding(BaseBinding):\n filter: Condition\n\n\n@dataclass\nclass Binding(BaseBinding):\n # while filter could be created by referencing variables directly (rather\n # than created from strings), by using strings we ensure that users will\n # be able to create filters in configuration (e.g. JSON) files too, which\n # also benefits the documentation by enforcing human-readable filter names.\n condition: Optional[str] = None\n\n def __post_init__(self):\n if self.condition:\n self.filter = filter_from_string(self.condition)\n else:\n self.filter = None\n\n\ndef create_identifier(handler: Callable):\n parts = handler.__module__.split(".")\n name = handler.__name__\n package = parts[0]\n if len(parts) > 1:\n final_module = parts[-1]\n return f"{package}:{final_module}.{name}"\n else:\n return f"{package}:{name}"\n\n\nAUTO_MATCH_BINDINGS = [\n *[\n Binding(\n cmd, [key], "focused_insert & auto_match & followed_by_closing_paren_or_end"\n )\n for key, cmd in match.auto_match_parens.items()\n ],\n *[\n # raw string\n Binding(cmd, [key], "focused_insert & auto_match & preceded_by_raw_str_prefix")\n for key, cmd in match.auto_match_parens_raw_string.items()\n ],\n Binding(\n match.double_quote,\n ['"'],\n "focused_insert"\n " & auto_match"\n " & not_inside_unclosed_string"\n " & preceded_by_paired_double_quotes"\n " & followed_by_closing_paren_or_end",\n ),\n Binding(\n match.single_quote,\n ["'"],\n "focused_insert"\n " & auto_match"\n " & not_inside_unclosed_string"\n " & preceded_by_paired_single_quotes"\n " & followed_by_closing_paren_or_end",\n ),\n Binding(\n match.docstring_double_quotes,\n ['"'],\n "focused_insert"\n " & auto_match"\n " & not_inside_unclosed_string"\n " & preceded_by_two_double_quotes",\n ),\n Binding(\n match.docstring_single_quotes,\n ["'"],\n "focused_insert"\n " & auto_match"\n " & not_inside_unclosed_string"\n " & preceded_by_two_single_quotes",\n ),\n Binding(\n match.skip_over,\n [")"],\n "focused_insert & auto_match & followed_by_closing_round_paren",\n ),\n Binding(\n match.skip_over,\n ["]"],\n "focused_insert & auto_match & followed_by_closing_bracket",\n ),\n Binding(\n match.skip_over,\n ["}"],\n "focused_insert & auto_match & followed_by_closing_brace",\n ),\n Binding(\n match.skip_over, ['"'], "focused_insert & auto_match & followed_by_double_quote"\n ),\n Binding(\n match.skip_over, ["'"], "focused_insert & auto_match & followed_by_single_quote"\n ),\n Binding(\n match.delete_pair,\n ["backspace"],\n "focused_insert"\n " & preceded_by_opening_round_paren"\n " & auto_match"\n " & followed_by_closing_round_paren",\n ),\n Binding(\n match.delete_pair,\n ["backspace"],\n "focused_insert"\n " & preceded_by_opening_bracket"\n " & auto_match"\n " & followed_by_closing_bracket",\n ),\n Binding(\n match.delete_pair,\n ["backspace"],\n "focused_insert"\n " & preceded_by_opening_brace"\n " & auto_match"\n " & followed_by_closing_brace",\n ),\n Binding(\n match.delete_pair,\n ["backspace"],\n "focused_insert"\n " & preceded_by_double_quote"\n " & auto_match"\n " & followed_by_double_quote",\n ),\n Binding(\n match.delete_pair,\n ["backspace"],\n "focused_insert"\n " & preceded_by_single_quote"\n " & auto_match"\n " & followed_by_single_quote",\n ),\n]\n\nAUTO_SUGGEST_BINDINGS = [\n # there are two reasons for re-defining bindings defined upstream:\n # 1) prompt-toolkit does not execute autosuggestion bindings in vi mode,\n # 2) prompt-toolkit checks if we are at the end of text, not end of line\n # hence it does not work in multi-line mode of navigable provider\n Binding(\n auto_suggest.accept_or_jump_to_end,\n ["end"],\n "has_suggestion & default_buffer_focused & emacs_like_insert_mode",\n ),\n Binding(\n auto_suggest.accept_or_jump_to_end,\n ["c-e"],\n "has_suggestion & default_buffer_focused & emacs_like_insert_mode",\n ),\n Binding(\n auto_suggest.accept,\n ["c-f"],\n "has_suggestion & default_buffer_focused & emacs_like_insert_mode",\n ),\n Binding(\n auto_suggest.accept,\n ["right"],\n "has_suggestion & default_buffer_focused & emacs_like_insert_mode & is_cursor_at_the_end_of_line",\n ),\n Binding(\n auto_suggest.accept_word,\n ["escape", "f"],\n "has_suggestion & default_buffer_focused & emacs_like_insert_mode",\n ),\n Binding(\n auto_suggest.accept_token,\n ["c-right"],\n "has_suggestion & default_buffer_focused & emacs_like_insert_mode",\n ),\n Binding(\n auto_suggest.discard,\n ["escape"],\n # note this one is using `emacs_insert_mode`, not `emacs_like_insert_mode`\n # as in `vi_insert_mode` we do not want `escape` to be shadowed (ever).\n "has_suggestion & default_buffer_focused & emacs_insert_mode",\n ),\n Binding(\n auto_suggest.discard,\n ["delete"],\n "has_suggestion & default_buffer_focused & emacs_insert_mode",\n ),\n Binding(\n auto_suggest.swap_autosuggestion_up,\n ["c-up"],\n "navigable_suggestions"\n " & ~has_line_above"\n " & has_suggestion"\n " & default_buffer_focused",\n ),\n Binding(\n auto_suggest.swap_autosuggestion_down,\n ["c-down"],\n "navigable_suggestions"\n " & ~has_line_below"\n " & has_suggestion"\n " & default_buffer_focused",\n ),\n Binding(\n auto_suggest.up_and_update_hint,\n ["c-up"],\n "has_line_above & navigable_suggestions & default_buffer_focused",\n ),\n Binding(\n auto_suggest.down_and_update_hint,\n ["c-down"],\n "has_line_below & navigable_suggestions & default_buffer_focused",\n ),\n Binding(\n auto_suggest.accept_character,\n ["escape", "right"],\n "has_suggestion & default_buffer_focused & emacs_like_insert_mode",\n ),\n Binding(\n auto_suggest.accept_and_move_cursor_left,\n ["c-left"],\n "has_suggestion & default_buffer_focused & emacs_like_insert_mode",\n ),\n Binding(\n auto_suggest.accept_and_keep_cursor,\n ["escape", "down"],\n "has_suggestion & default_buffer_focused & emacs_insert_mode",\n ),\n Binding(\n auto_suggest.backspace_and_resume_hint,\n ["backspace"],\n # no `has_suggestion` here to allow resuming if no suggestion\n "default_buffer_focused & emacs_like_insert_mode",\n ),\n Binding(\n auto_suggest.resume_hinting,\n ["right"],\n "is_cursor_at_the_end_of_line"\n " & default_buffer_focused"\n " & emacs_like_insert_mode"\n " & pass_through",\n ),\n]\n\n\nSIMPLE_CONTROL_BINDINGS = [\n Binding(cmd, [key], "vi_insert_mode & default_buffer_focused & ebivim")\n for key, cmd in {\n "c-a": nc.beginning_of_line,\n "c-b": nc.backward_char,\n "c-k": nc.kill_line,\n "c-w": nc.backward_kill_word,\n "c-y": nc.yank,\n "c-_": nc.undo,\n }.items()\n]\n\n\nALT_AND_COMOBO_CONTROL_BINDINGS = [\n Binding(cmd, list(keys), "vi_insert_mode & default_buffer_focused & ebivim")\n for keys, cmd in {\n # Control Combos\n ("c-x", "c-e"): nc.edit_and_execute,\n ("c-x", "e"): nc.edit_and_execute,\n # Alt\n ("escape", "b"): nc.backward_word,\n ("escape", "c"): nc.capitalize_word,\n ("escape", "d"): nc.kill_word,\n ("escape", "h"): nc.backward_kill_word,\n ("escape", "l"): nc.downcase_word,\n ("escape", "u"): nc.uppercase_word,\n ("escape", "y"): nc.yank_pop,\n ("escape", "."): nc.yank_last_arg,\n }.items()\n]\n\n\ndef add_binding(bindings: KeyBindings, binding: Binding):\n bindings.add(\n *binding.keys,\n **({"filter": binding.filter} if binding.filter is not None else {}),\n )(binding.command)\n\n\ndef create_ipython_shortcuts(shell, skip=None) -> KeyBindings:\n """Set up the prompt_toolkit keyboard shortcuts for IPython.\n\n Parameters\n ----------\n shell: InteractiveShell\n The current IPython shell Instance\n skip: List[Binding]\n Bindings to skip.\n\n Returns\n -------\n KeyBindings\n the keybinding instance for prompt toolkit.\n\n """\n kb = KeyBindings()\n skip = skip or []\n for binding in KEY_BINDINGS:\n skip_this_one = False\n for to_skip in skip:\n if (\n to_skip.command == binding.command\n and to_skip.filter == binding.filter\n and to_skip.keys == binding.keys\n ):\n skip_this_one = True\n break\n if skip_this_one:\n continue\n add_binding(kb, binding)\n\n def get_input_mode(self):\n app = get_app()\n app.ttimeoutlen = shell.ttimeoutlen\n app.timeoutlen = shell.timeoutlen\n\n return self._input_mode\n\n def set_input_mode(self, mode):\n shape = {InputMode.NAVIGATION: 2, InputMode.REPLACE: 4}.get(mode, 6)\n cursor = "\x1b[{} q".format(shape)\n\n sys.stdout.write(cursor)\n sys.stdout.flush()\n\n self._input_mode = mode\n\n if shell.editing_mode == "vi" and shell.modal_cursor:\n ViState._input_mode = InputMode.INSERT # type: ignore\n ViState.input_mode = property(get_input_mode, set_input_mode) # type: ignore\n\n return kb\n\n\ndef reformat_and_execute(event):\n """Reformat code and execute it"""\n shell = get_ipython()\n reformat_text_before_cursor(\n event.current_buffer, event.current_buffer.document, shell\n )\n event.current_buffer.validate_and_handle()\n\n\ndef reformat_text_before_cursor(buffer, document, shell):\n text = buffer.delete_before_cursor(len(document.text[: document.cursor_position]))\n try:\n formatted_text = shell.reformat_handler(text)\n buffer.insert_text(formatted_text)\n except Exception as e:\n buffer.insert_text(text)\n\n\ndef handle_return_or_newline_or_execute(event):\n shell = get_ipython()\n if getattr(shell, "handle_return", None):\n return shell.handle_return(shell)(event)\n else:\n return newline_or_execute_outer(shell)(event)\n\n\ndef newline_or_execute_outer(shell):\n def newline_or_execute(event):\n """When the user presses return, insert a newline or execute the code."""\n b = event.current_buffer\n d = b.document\n\n if b.complete_state:\n cc = b.complete_state.current_completion\n if cc:\n b.apply_completion(cc)\n else:\n b.cancel_completion()\n return\n\n # If there's only one line, treat it as if the cursor is at the end.\n # See https://github.com/ipython/ipython/issues/10425\n if d.line_count == 1:\n check_text = d.text\n else:\n check_text = d.text[: d.cursor_position]\n status, indent = shell.check_complete(check_text)\n\n # if all we have after the cursor is whitespace: reformat current text\n # before cursor\n after_cursor = d.text[d.cursor_position :]\n reformatted = False\n if not after_cursor.strip():\n reformat_text_before_cursor(b, d, shell)\n reformatted = True\n if not (\n d.on_last_line\n or d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()\n ):\n if shell.autoindent:\n b.insert_text("\n" + indent)\n else:\n b.insert_text("\n")\n return\n\n if (status != "incomplete") and b.accept_handler:\n if not reformatted:\n reformat_text_before_cursor(b, d, shell)\n b.validate_and_handle()\n else:\n if shell.autoindent:\n b.insert_text("\n" + indent)\n else:\n b.insert_text("\n")\n\n return newline_or_execute\n\n\ndef previous_history_or_previous_completion(event):\n """\n Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.\n\n If completer is open this still select previous completion.\n """\n event.current_buffer.auto_up()\n\n\ndef next_history_or_next_completion(event):\n """\n Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.\n\n If completer is open this still select next completion.\n """\n event.current_buffer.auto_down()\n\n\ndef dismiss_completion(event):\n """Dismiss completion"""\n b = event.current_buffer\n if b.complete_state:\n b.cancel_completion()\n\n\ndef reset_buffer(event):\n """Reset buffer"""\n b = event.current_buffer\n if b.complete_state:\n b.cancel_completion()\n else:\n b.reset()\n\n\ndef reset_search_buffer(event):\n """Reset search buffer"""\n if event.current_buffer.document.text:\n event.current_buffer.reset()\n else:\n event.app.layout.focus(DEFAULT_BUFFER)\n\n\ndef suspend_to_bg(event):\n """Suspend to background"""\n event.app.suspend_to_background()\n\n\ndef quit(event):\n """\n Quit application with ``SIGQUIT`` if supported or ``sys.exit`` otherwise.\n\n On platforms that support SIGQUIT, send SIGQUIT to the current process.\n On other platforms, just exit the process with a message.\n """\n sigquit = getattr(signal, "SIGQUIT", None)\n if sigquit is not None:\n os.kill(0, signal.SIGQUIT)\n else:\n sys.exit("Quit")\n\n\ndef indent_buffer(event):\n """Indent buffer"""\n event.current_buffer.insert_text(" " * 4)\n\n\ndef newline_autoindent(event):\n """Insert a newline after the cursor indented appropriately.\n\n Fancier version of former ``newline_with_copy_margin`` which should\n compute the correct indentation of the inserted line. That is to say, indent\n by 4 extra space after a function definition, class definition, context\n manager... And dedent by 4 space after ``pass``, ``return``, ``raise ...``.\n """\n shell = get_ipython()\n inputsplitter = shell.input_transformer_manager\n b = event.current_buffer\n d = b.document\n\n if b.complete_state:\n b.cancel_completion()\n text = d.text[: d.cursor_position] + "\n"\n _, indent = inputsplitter.check_complete(text)\n b.insert_text("\n" + (" " * (indent or 0)), move_cursor=False)\n\n\ndef open_input_in_editor(event):\n """Open code from input in external editor"""\n event.app.current_buffer.open_in_editor()\n\n\nif sys.platform == "win32":\n from IPython.core.error import TryNext\n from IPython.lib.clipboard import (\n ClipboardEmpty,\n tkinter_clipboard_get,\n win32_clipboard_get,\n )\n\n @undoc\n def win_paste(event):\n try:\n text = win32_clipboard_get()\n except TryNext:\n try:\n text = tkinter_clipboard_get()\n except (TryNext, ClipboardEmpty):\n return\n except ClipboardEmpty:\n return\n event.current_buffer.insert_text(text.replace("\t", " " * 4))\n\nelse:\n\n @undoc\n def win_paste(event):\n """Stub used on other platforms"""\n pass\n\n\nKEY_BINDINGS = [\n Binding(\n handle_return_or_newline_or_execute,\n ["enter"],\n "default_buffer_focused & ~has_selection & insert_mode",\n ),\n Binding(\n reformat_and_execute,\n ["escape", "enter"],\n "default_buffer_focused & ~has_selection & insert_mode & ebivim",\n ),\n Binding(quit, ["c-\\"]),\n Binding(\n previous_history_or_previous_completion,\n ["c-p"],\n "vi_insert_mode & default_buffer_focused",\n ),\n Binding(\n next_history_or_next_completion,\n ["c-n"],\n "vi_insert_mode & default_buffer_focused",\n ),\n Binding(dismiss_completion, ["c-g"], "default_buffer_focused & has_completions"),\n Binding(reset_buffer, ["c-c"], "default_buffer_focused"),\n Binding(reset_search_buffer, ["c-c"], "search_buffer_focused"),\n Binding(suspend_to_bg, ["c-z"], "supports_suspend"),\n Binding(\n indent_buffer,\n ["tab"], # Ctrl+I == Tab\n "default_buffer_focused & ~has_selection & insert_mode & cursor_in_leading_ws",\n ),\n Binding(newline_autoindent, ["c-o"], "default_buffer_focused & emacs_insert_mode"),\n Binding(open_input_in_editor, ["f2"], "default_buffer_focused"),\n *AUTO_MATCH_BINDINGS,\n *AUTO_SUGGEST_BINDINGS,\n Binding(\n display_completions_like_readline,\n ["c-i"],\n "readline_like_completions"\n " & default_buffer_focused"\n " & ~has_selection"\n " & insert_mode"\n " & ~cursor_in_leading_ws",\n ),\n Binding(win_paste, ["c-v"], "default_buffer_focused & ~vi_mode & is_windows_os"),\n *SIMPLE_CONTROL_BINDINGS,\n *ALT_AND_COMOBO_CONTROL_BINDINGS,\n]\n\nUNASSIGNED_ALLOWED_COMMANDS = [\n auto_suggest.llm_autosuggestion,\n nc.beginning_of_buffer,\n nc.end_of_buffer,\n nc.end_of_line,\n nc.forward_word,\n nc.unix_line_discard,\n]\n
.venv\Lib\site-packages\IPython\terminal\shortcuts\__init__.py
__init__.py
Python
18,563
0.95
0.106918
0.050542
node-utils
176
2025-05-03T12:33:58.238157
GPL-3.0
false
b3f2a1d27d1540b6392d6f450e8d3094
\n\n
.venv\Lib\site-packages\IPython\terminal\shortcuts\__pycache__\auto_match.cpython-313.pyc
auto_match.cpython-313.pyc
Other
4,848
0.95
0.074074
0
node-utils
515
2024-10-15T14:16:03.412161
Apache-2.0
false
03bb0524818e2e16cc9fd45f2ed09e4e
\n\n
.venv\Lib\site-packages\IPython\terminal\shortcuts\__pycache__\auto_suggest.cpython-313.pyc
auto_suggest.cpython-313.pyc
Other
30,033
0.95
0.029605
0.014981
node-utils
753
2025-05-27T21:08:19.899421
MIT
false
be047a5071aea2d9159ba619b3045290
\n\n
.venv\Lib\site-packages\IPython\terminal\shortcuts\__pycache__\filters.cpython-313.pyc
filters.cpython-313.pyc
Other
13,881
0.95
0.009709
0
node-utils
554
2025-05-24T21:02:09.982081
MIT
false
e172544d53745f8cd03e3bcc2c77c3a1
\n\n
.venv\Lib\site-packages\IPython\terminal\shortcuts\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
22,266
0.95
0.02451
0
python-kit
532
2023-08-30T22:52:20.220331
GPL-3.0
false
df4ab9c940a506736c988f6bd92bf56d
\n\n
.venv\Lib\site-packages\IPython\terminal\__pycache__\debugger.cpython-313.pyc
debugger.cpython-313.pyc
Other
9,171
0.8
0.025316
0.027397
node-utils
470
2023-07-18T19:05:04.197525
MIT
false
d5a243c7a1c4b6fd5d05313e17d6fb7b
\n\n
.venv\Lib\site-packages\IPython\terminal\__pycache__\embed.cpython-313.pyc
embed.cpython-313.pyc
Other
17,454
0.95
0.087719
0.005051
react-lib
412
2024-10-25T13:20:24.172396
BSD-3-Clause
false
7071e0fe34aca8a63b896c825885830c
\n\n
.venv\Lib\site-packages\IPython\terminal\__pycache__\interactiveshell.cpython-313.pyc
interactiveshell.cpython-313.pyc
Other
47,393
0.95
0.071121
0.009456
awesome-app
138
2024-09-08T00:04:31.297303
MIT
false
840cc87155a6389b1671864331db09f2
\n\n
.venv\Lib\site-packages\IPython\terminal\__pycache__\ipapp.cpython-313.pyc
ipapp.cpython-313.pyc
Other
14,455
0.8
0.072
0.008547
awesome-app
259
2025-01-14T01:10:25.921138
Apache-2.0
false
71df078d283788b5415256f9768a4cd5
\n\n
.venv\Lib\site-packages\IPython\terminal\__pycache__\magics.cpython-313.pyc
magics.cpython-313.pyc
Other
9,796
0.8
0.038217
0
node-utils
612
2023-11-13T07:15:23.576239
MIT
false
3ab1ec4389f79b3a91db5afa4b12e3e9
\n\n
.venv\Lib\site-packages\IPython\terminal\__pycache__\prompts.cpython-313.pyc
prompts.cpython-313.pyc
Other
8,333
0.95
0
0
node-utils
75
2024-05-16T23:17:31.947101
GPL-3.0
false
3dbc234aebddc8659ff463807faa9c1c
\n\n
.venv\Lib\site-packages\IPython\terminal\__pycache__\ptutils.cpython-313.pyc
ptutils.cpython-313.pyc
Other
9,877
0.95
0.017699
0
react-lib
717
2025-03-13T10:44:03.194121
Apache-2.0
false
3a521c07985567f3e5d6a92326b01758
\n\n
.venv\Lib\site-packages\IPython\terminal\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
191
0.7
0
0
python-kit
808
2025-05-22T19:39:54.369249
Apache-2.0
false
20704c169a73d3a5af1bf6a2641b6caf
import os\nimport shutil\nimport sys\nimport tempfile\nfrom importlib import import_module\n\nimport pytest\n\n# Expose the unittest-driven decorators\nfrom .ipunittest import ipdoctest, ipdocstring\n\ndef skipif(skip_condition, msg=None):\n """Make function raise SkipTest exception if skip_condition is true\n\n Parameters\n ----------\n\n skip_condition : bool or callable\n Flag to determine whether to skip test. If the condition is a\n callable, it is used at runtime to dynamically make the decision. This\n is useful for tests that may require costly imports, to delay the cost\n until the test suite is actually executed.\n msg : string\n Message to give on raising a SkipTest exception.\n\n Returns\n -------\n decorator : function\n Decorator, which, when applied to a function, causes SkipTest\n to be raised when the skip_condition was True, and the function\n to be called normally otherwise.\n """\n if msg is None:\n msg = "Test skipped due to test condition."\n\n assert isinstance(skip_condition, bool)\n return pytest.mark.skipif(skip_condition, reason=msg)\n\n\n# A version with the condition set to true, common case just to attach a message\n# to a skip decorator\ndef skip(msg=None):\n """Decorator factory - mark a test function for skipping from test suite.\n\n Parameters\n ----------\n msg : string\n Optional message to be added.\n\n Returns\n -------\n decorator : function\n Decorator, which, when applied to a function, causes SkipTest\n to be raised, with the optional message added.\n """\n if msg and not isinstance(msg, str):\n raise ValueError(\n "invalid object passed to `@skip` decorator, did you "\n "meant `@skip()` with brackets ?"\n )\n return skipif(True, msg)\n\n\ndef onlyif(condition, msg):\n """The reverse from skipif, see skipif for details."""\n\n return skipif(not condition, msg)\n\n\n# -----------------------------------------------------------------------------\n# Utility functions for decorators\ndef module_not_available(module):\n """Can module be imported? Returns true if module does NOT import.\n\n This is used to make a decorator to skip tests that require module to be\n available, but delay the 'import numpy' to test execution time.\n """\n try:\n mod = import_module(module)\n mod_not_avail = False\n except ImportError:\n mod_not_avail = True\n\n return mod_not_avail\n\n\n# -----------------------------------------------------------------------------\n# Decorators for public use\n\n# Decorators to skip certain tests on specific platforms.\nskip_win32 = skipif(sys.platform == "win32", "This test does not run under Windows")\n\n\n# Decorators to skip tests if not on specific platforms.\nskip_if_not_win32 = skipif(sys.platform != "win32", "This test only runs under Windows")\nskip_if_not_osx = skipif(\n not sys.platform.startswith("darwin"), "This test only runs under macOS"\n)\n\n_x11_skip_cond = (\n sys.platform not in ("darwin", "win32") and os.environ.get("DISPLAY", "") == ""\n)\n_x11_skip_msg = "Skipped under *nix when X11/XOrg not available"\n\nskip_if_no_x11 = skipif(_x11_skip_cond, _x11_skip_msg)\n\n# Other skip decorators\n\n# generic skip without module\nskip_without = lambda mod: skipif(\n module_not_available(mod), "This test requires %s" % mod\n)\n\nskipif_not_numpy = skip_without("numpy")\n\nskipif_not_matplotlib = skip_without("matplotlib")\n\n# A null 'decorator', useful to make more readable code that needs to pick\n# between different decorators based on OS or other conditions\nnull_deco = lambda f: f\n\n# Some tests only run where we can use unicode paths. Note that we can't just\n# check os.path.supports_unicode_filenames, which is always False on Linux.\ntry:\n f = tempfile.NamedTemporaryFile(prefix="tmp€")\nexcept UnicodeEncodeError:\n unicode_paths = False\n# TODO: should this be finnally ?\nelse:\n unicode_paths = True\n f.close()\n\nonlyif_unicode_paths = onlyif(\n unicode_paths,\n ("This test is only applicable where we can use unicode in filenames."),\n)\n\n\ndef onlyif_cmds_exist(*commands):\n """\n Decorator to skip test when at least one of `commands` is not found.\n """\n for cmd in commands:\n reason = f"This test runs only if command '{cmd}' is installed"\n if not shutil.which(cmd):\n\n return pytest.mark.skip(reason=reason)\n return null_deco\n
.venv\Lib\site-packages\IPython\testing\decorators.py
decorators.py
Python
4,430
0.95
0.182432
0.141593
awesome-app
567
2024-08-11T12:59:06.508214
BSD-3-Clause
true
31d9698adde1bf6a4553e405cbe9d0f4
"""Global IPython app to support test running.\n\nWe must start our own ipython object and heavily muck with it so that all the\nmodifications IPython makes to system behavior don't send the doctest machinery\ninto a fit. This code should be considered a gross hack, but it gets the job\ndone.\n"""\n\n# Copyright (c) IPython Development Team.\n# Distributed under the terms of the Modified BSD License.\n\nimport builtins as builtin_mod\nimport sys\nimport types\n\nfrom pathlib import Path\n\nfrom . import tools\n\nfrom IPython.core import page\nfrom IPython.utils import io\nfrom IPython.terminal.interactiveshell import TerminalInteractiveShell\n\n\ndef get_ipython():\n # This will get replaced by the real thing once we start IPython below\n return start_ipython()\n\n\n# A couple of methods to override those in the running IPython to interact\n# better with doctest (doctest captures on raw stdout, so we need to direct\n# various types of output there otherwise it will miss them).\n\ndef xsys(self, cmd):\n """Replace the default system call with a capturing one for doctest.\n """\n # We use getoutput, but we need to strip it because pexpect captures\n # the trailing newline differently from commands.getoutput\n print(self.getoutput(cmd, split=False, depth=1).rstrip(), end='', file=sys.stdout)\n sys.stdout.flush()\n\n\ndef _showtraceback(self, etype, evalue, stb):\n """Print the traceback purely on stdout for doctest to capture it.\n """\n print(self.InteractiveTB.stb2text(stb), file=sys.stdout)\n\n\ndef start_ipython():\n """Start a global IPython shell, which we need for IPython-specific syntax.\n """\n global get_ipython\n\n # This function should only ever run once!\n if hasattr(start_ipython, 'already_called'):\n return\n start_ipython.already_called = True\n\n # Store certain global objects that IPython modifies\n _displayhook = sys.displayhook\n _excepthook = sys.excepthook\n _main = sys.modules.get('__main__')\n\n # Create custom argv and namespaces for our IPython to be test-friendly\n config = tools.default_config()\n config.TerminalInteractiveShell.simple_prompt = True\n\n # Create and initialize our test-friendly IPython instance.\n shell = TerminalInteractiveShell.instance(config=config,\n )\n\n # A few more tweaks needed for playing nicely with doctests...\n\n # remove history file\n shell.tempfiles.append(Path(config.HistoryManager.hist_file))\n\n # These traps are normally only active for interactive use, set them\n # permanently since we'll be mocking interactive sessions.\n shell.builtin_trap.activate()\n\n # Modify the IPython system call with one that uses getoutput, so that we\n # can capture subcommands and print them to Python's stdout, otherwise the\n # doctest machinery would miss them.\n shell.system = types.MethodType(xsys, shell)\n\n shell._showtraceback = types.MethodType(_showtraceback, shell)\n\n # IPython is ready, now clean up some global state...\n\n # Deactivate the various python system hooks added by ipython for\n # interactive convenience so we don't confuse the doctest system\n sys.modules['__main__'] = _main\n sys.displayhook = _displayhook\n sys.excepthook = _excepthook\n\n # So that ipython magics and aliases can be doctested (they work by making\n # a call into a global _ip object). Also make the top-level get_ipython\n # now return this without recursively calling here again.\n _ip = shell\n get_ipython = _ip.get_ipython\n builtin_mod._ip = _ip\n builtin_mod.ip = _ip\n builtin_mod.get_ipython = get_ipython\n\n # Override paging, so we don't require user interaction during the tests.\n def nopage(strng, start=0, screen_lines=0, pager_cmd=None):\n if isinstance(strng, dict):\n strng = strng.get('text/plain', '')\n print(strng)\n \n page.orig_page = page.pager_page\n page.pager_page = nopage\n\n return _ip\n
.venv\Lib\site-packages\IPython\testing\globalipapp.py
globalipapp.py
Python
3,948
0.95
0.131579
0.309524
python-kit
16
2023-08-08T05:43:07.870644
Apache-2.0
true
6e71fdb689758487e1ebfea97cdbfdcd
"""Decorators marks that a doctest should be skipped.\n\nThe IPython.testing.decorators module triggers various extra imports, including\nnumpy and sympy if they're present. Since this decorator is used in core parts\nof IPython, it's in a separate module so that running IPython doesn't trigger\nthose imports."""\n\n# Copyright (C) IPython Development Team\n# Distributed under the terms of the Modified BSD License.\n\n\ndef skip_doctest(f):\n """Decorator - mark a function or method for skipping its doctest.\n\n This decorator allows you to mark a function whose docstring you wish to\n omit from testing, while preserving the docstring for introspection, help,\n etc."""\n f.__skip_doctest__ = True\n return f\n
.venv\Lib\site-packages\IPython\testing\skipdoctest.py
skipdoctest.py
Python
717
0.95
0.368421
0.142857
react-lib
836
2023-11-24T21:17:06.191502
BSD-3-Clause
true
3540711af58a730a414efa4e8e66fc21
"""Testing support (tools to test IPython itself).\n"""\n\n#-----------------------------------------------------------------------------\n# Copyright (C) 2009-2011 The IPython 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\nimport os\n\n#-----------------------------------------------------------------------------\n# Constants\n#-----------------------------------------------------------------------------\n\n# We scale all timeouts via this factor, slow machines can increase it\nIPYTHON_TESTING_TIMEOUT_SCALE = float(os.getenv(\n 'IPYTHON_TESTING_TIMEOUT_SCALE', 1))\n
.venv\Lib\site-packages\IPython\testing\__init__.py
__init__.py
Python
784
0.95
0
0.666667
react-lib
345
2024-02-04T12:43:13.554241
Apache-2.0
true
722ac16e04858cd6f12a1c41061cf566
"""Simple example using doctests.\n\nThis file just contains doctests both using plain python and IPython prompts.\nAll tests should be loaded by nose.\n"""\n\nimport os\n\n\ndef pyfunc():\n """Some pure python tests...\n\n >>> pyfunc()\n 'pyfunc'\n\n >>> import os\n\n >>> 2+3\n 5\n\n >>> for i in range(3):\n ... print(i, end=' ')\n ... print(i+1, end=' ')\n ...\n 0 1 1 2 2 3 \n """\n return 'pyfunc'\n\ndef ipfunc():\n """Some ipython tests...\n\n In [1]: import os\n\n In [3]: 2+3\n Out[3]: 5\n\n In [26]: for i in range(3):\n ....: print(i, end=' ')\n ....: print(i+1, end=' ')\n ....:\n 0 1 1 2 2 3\n\n\n It's OK to use '_' for the last result, but do NOT try to use IPython's\n numbered history of _NN outputs, since those won't exist under the\n doctest environment:\n\n In [7]: 'hi'\n Out[7]: 'hi'\n\n In [8]: print(repr(_))\n 'hi'\n\n In [7]: 3+4\n Out[7]: 7\n\n In [8]: _+3\n Out[8]: 10\n\n In [9]: ipfunc()\n Out[9]: 'ipfunc'\n """\n return "ipfunc"\n\n\ndef ipos():\n """Examples that access the operating system work:\n\n In [1]: !echo hello\n hello\n\n In [2]: !echo hello > /tmp/foo_iptest\n\n In [3]: !cat /tmp/foo_iptest\n hello\n\n In [4]: rm -f /tmp/foo_iptest\n """\n pass\n\n\nipos.__skip_doctest__ = os.name == "nt"\n\n\ndef ranfunc():\n """A function with some random output.\n\n Normal examples are verified as usual:\n >>> 1+3\n 4\n\n But if you put '# random' in the output, it is ignored:\n >>> 1+3\n junk goes here... # random\n\n >>> 1+2\n again, anything goes #random\n if multiline, the random mark is only needed once.\n\n >>> 1+2\n You can also put the random marker at the end:\n # random\n\n >>> 1+2\n # random\n .. or at the beginning.\n\n More correct input is properly verified:\n >>> ranfunc()\n 'ranfunc'\n """\n return 'ranfunc'\n\n\ndef random_all():\n """A function where we ignore the output of ALL examples.\n\n Examples:\n\n # all-random\n\n This mark tells the testing machinery that all subsequent examples should\n be treated as random (ignoring their output). They are still executed,\n so if a they raise an error, it will be detected as such, but their\n output is completely ignored.\n\n >>> 1+3\n junk goes here...\n\n >>> 1+3\n klasdfj;\n\n >>> 1+2\n again, anything goes\n blah...\n """\n pass\n\ndef iprand():\n """Some ipython tests with random output.\n\n In [7]: 3+4\n Out[7]: 7\n\n In [8]: print('hello')\n world # random\n\n In [9]: iprand()\n Out[9]: 'iprand'\n """\n return 'iprand'\n\ndef iprand_all():\n """Some ipython tests with fully random output.\n\n # all-random\n \n In [7]: 1\n Out[7]: 99\n\n In [8]: print('hello')\n world\n\n In [9]: iprand_all()\n Out[9]: 'junk'\n """\n return 'iprand_all'\n
.venv\Lib\site-packages\IPython\testing\plugin\dtexample.py
dtexample.py
Python
2,921
0.95
0.095808
0.034783
python-kit
367
2025-04-15T03:13:29.555379
GPL-3.0
true
7eaf930e8855aa596ab9a1d9d747d7df
"""Nose Plugin that supports IPython doctests.\n\nLimitations:\n\n- When generating examples for use as doctests, make sure that you have\n pretty-printing OFF. This can be done either by setting the\n ``PlainTextFormatter.pprint`` option in your configuration file to False, or\n by interactively disabling it with %Pprint. This is required so that IPython\n output matches that of normal Python, which is used by doctest for internal\n execution.\n\n- Do not rely on specific prompt numbers for results (such as using\n '_34==True', for example). For IPython tests run via an external process the\n prompt numbers may be different, and IPython tests run as normal python code\n won't even have these special _NN variables set at all.\n"""\n\n#-----------------------------------------------------------------------------\n# Module imports\n\n# From the standard library\nimport doctest\nimport logging\nimport re\n\nfrom testpath import modified_env\n\n#-----------------------------------------------------------------------------\n# Module globals and other constants\n#-----------------------------------------------------------------------------\n\nlog = logging.getLogger(__name__)\n\n\n#-----------------------------------------------------------------------------\n# Classes and functions\n#-----------------------------------------------------------------------------\n\n\nclass DocTestFinder(doctest.DocTestFinder):\n def _get_test(self, obj, name, module, globs, source_lines):\n test = super()._get_test(obj, name, module, globs, source_lines)\n\n if bool(getattr(obj, "__skip_doctest__", False)) and test is not None:\n for example in test.examples:\n example.options[doctest.SKIP] = True\n\n return test\n\n\nclass IPDoctestOutputChecker(doctest.OutputChecker):\n """Second-chance checker with support for random tests.\n\n If the default comparison doesn't pass, this checker looks in the expected\n output string for flags that tell us to ignore the output.\n """\n\n random_re = re.compile(r'#\s*random\s+')\n\n def check_output(self, want, got, optionflags):\n """Check output, accepting special markers embedded in the output.\n\n If the output didn't pass the default validation but the special string\n '#random' is included, we accept it."""\n\n # Let the original tester verify first, in case people have valid tests\n # that happen to have a comment saying '#random' embedded in.\n ret = doctest.OutputChecker.check_output(self, want, got,\n optionflags)\n if not ret and self.random_re.search(want):\n # print('RANDOM OK:',want, file=sys.stderr) # dbg\n return True\n\n return ret\n\n\n# A simple subclassing of the original with a different class name, so we can\n# distinguish and treat differently IPython examples from pure python ones.\nclass IPExample(doctest.Example): pass\n\n\nclass IPDocTestParser(doctest.DocTestParser):\n """\n A class used to parse strings containing doctest examples.\n\n Note: This is a version modified to properly recognize IPython input and\n convert any IPython examples into valid Python ones.\n """\n # This regular expression is used to find doctest examples in a\n # string. It defines three groups: `source` is the source code\n # (including leading indentation and prompts); `indent` is the\n # indentation of the first (PS1) line of the source code; and\n # `want` is the expected output (including leading indentation).\n\n # Classic Python prompts or default IPython ones\n _PS1_PY = r'>>>'\n _PS2_PY = r'\.\.\.'\n\n _PS1_IP = r'In\ \[\d+\]:'\n _PS2_IP = r'\ \ \ \.\.\.+:'\n\n _RE_TPL = r'''\n # Source consists of a PS1 line followed by zero or more PS2 lines.\n (?P<source>\n (?:^(?P<indent> [ ]*) (?P<ps1> %s) .*) # PS1 line\n (?:\n [ ]* (?P<ps2> %s) .*)*) # PS2 lines\n \n? # a newline\n # Want consists of any non-blank lines that do not start with PS1.\n (?P<want> (?:(?![ ]*$) # Not a blank line\n (?![ ]*%s) # Not a line starting with PS1\n (?![ ]*%s) # Not a line starting with PS2\n .*$\n? # But any other line\n )*)\n '''\n\n _EXAMPLE_RE_PY = re.compile( _RE_TPL % (_PS1_PY,_PS2_PY,_PS1_PY,_PS2_PY),\n re.MULTILINE | re.VERBOSE)\n\n _EXAMPLE_RE_IP = re.compile( _RE_TPL % (_PS1_IP,_PS2_IP,_PS1_IP,_PS2_IP),\n re.MULTILINE | re.VERBOSE)\n\n # Mark a test as being fully random. In this case, we simply append the\n # random marker ('#random') to each individual example's output. This way\n # we don't need to modify any other code.\n _RANDOM_TEST = re.compile(r'#\s*all-random\s+')\n\n def ip2py(self,source):\n """Convert input IPython source into valid Python."""\n block = _ip.input_transformer_manager.transform_cell(source)\n if len(block.splitlines()) == 1:\n return _ip.prefilter(block)\n else:\n return block\n\n def parse(self, string, name='<string>'):\n """\n Divide the given string into examples and intervening text,\n and return them as a list of alternating Examples and strings.\n Line numbers for the Examples are 0-based. The optional\n argument `name` is a name identifying this string, and is only\n used for error messages.\n """\n\n # print('Parse string:\n',string) # dbg\n\n string = string.expandtabs()\n # If all lines begin with the same indentation, then strip it.\n min_indent = self._min_indent(string)\n if min_indent > 0:\n string = '\n'.join([l[min_indent:] for l in string.split('\n')])\n\n output = []\n charno, lineno = 0, 0\n\n # We make 'all random' tests by adding the '# random' mark to every\n # block of output in the test.\n if self._RANDOM_TEST.search(string):\n random_marker = '\n# random'\n else:\n random_marker = ''\n\n # Whether to convert the input from ipython to python syntax\n ip2py = False\n # Find all doctest examples in the string. First, try them as Python\n # examples, then as IPython ones\n terms = list(self._EXAMPLE_RE_PY.finditer(string))\n if terms:\n # Normal Python example\n Example = doctest.Example\n else:\n # It's an ipython example.\n terms = list(self._EXAMPLE_RE_IP.finditer(string))\n Example = IPExample\n ip2py = True\n\n for m in terms:\n # Add the pre-example text to `output`.\n output.append(string[charno:m.start()])\n # Update lineno (lines before this example)\n lineno += string.count('\n', charno, m.start())\n # Extract info from the regexp match.\n (source, options, want, exc_msg) = \\n self._parse_example(m, name, lineno,ip2py)\n\n # Append the random-output marker (it defaults to empty in most\n # cases, it's only non-empty for 'all-random' tests):\n want += random_marker\n\n # Create an Example, and add it to the list.\n if not self._IS_BLANK_OR_COMMENT(source):\n output.append(Example(source, want, exc_msg,\n lineno=lineno,\n indent=min_indent+len(m.group('indent')),\n options=options))\n # Update lineno (lines inside this example)\n lineno += string.count('\n', m.start(), m.end())\n # Update charno.\n charno = m.end()\n # Add any remaining post-example text to `output`.\n output.append(string[charno:])\n return output\n\n def _parse_example(self, m, name, lineno,ip2py=False):\n """\n Given a regular expression match from `_EXAMPLE_RE` (`m`),\n return a pair `(source, want)`, where `source` is the matched\n example's source code (with prompts and indentation stripped);\n and `want` is the example's expected output (with indentation\n stripped).\n\n `name` is the string's name, and `lineno` is the line number\n where the example starts; both are used for error messages.\n\n Optional:\n `ip2py`: if true, filter the input via IPython to convert the syntax\n into valid python.\n """\n\n # Get the example's indentation level.\n indent = len(m.group('indent'))\n\n # Divide source into lines; check that they're properly\n # indented; and then strip their indentation & prompts.\n source_lines = m.group('source').split('\n')\n\n # We're using variable-length input prompts\n ps1 = m.group('ps1')\n ps2 = m.group('ps2')\n ps1_len = len(ps1)\n\n self._check_prompt_blank(source_lines, indent, name, lineno,ps1_len)\n if ps2:\n self._check_prefix(source_lines[1:], ' '*indent + ps2, name, lineno)\n\n source = '\n'.join([sl[indent+ps1_len+1:] for sl in source_lines])\n\n if ip2py:\n # Convert source input from IPython into valid Python syntax\n source = self.ip2py(source)\n\n # Divide want into lines; check that it's properly indented; and\n # then strip the indentation. Spaces before the last newline should\n # be preserved, so plain rstrip() isn't good enough.\n want = m.group('want')\n want_lines = want.split('\n')\n if len(want_lines) > 1 and re.match(r' *$', want_lines[-1]):\n del want_lines[-1] # forget final newline & spaces after it\n self._check_prefix(want_lines, ' '*indent, name,\n lineno + len(source_lines))\n\n # Remove ipython output prompt that might be present in the first line\n want_lines[0] = re.sub(r'Out\[\d+\]: \s*?\n?','',want_lines[0])\n\n want = '\n'.join([wl[indent:] for wl in want_lines])\n\n # If `want` contains a traceback message, then extract it.\n m = self._EXCEPTION_RE.match(want)\n if m:\n exc_msg = m.group('msg')\n else:\n exc_msg = None\n\n # Extract options from the source.\n options = self._find_options(source, name, lineno)\n\n return source, options, want, exc_msg\n\n def _check_prompt_blank(self, lines, indent, name, lineno, ps1_len):\n """\n Given the lines of a source string (including prompts and\n leading indentation), check to make sure that every prompt is\n followed by a space character. If any line is not followed by\n a space character, then raise ValueError.\n\n Note: IPython-modified version which takes the input prompt length as a\n parameter, so that prompts of variable length can be dealt with.\n """\n space_idx = indent+ps1_len\n min_len = space_idx+1\n for i, line in enumerate(lines):\n if len(line) >= min_len and line[space_idx] != ' ':\n raise ValueError('line %r of the docstring for %s '\n 'lacks blank after %s: %r' %\n (lineno+i+1, name,\n line[indent:space_idx], line))\n\n\nSKIP = doctest.register_optionflag('SKIP')\n\n\nclass IPDocTestRunner(doctest.DocTestRunner):\n """Test runner that synchronizes the IPython namespace with test globals.\n """\n\n def run(self, test, compileflags=None, out=None, clear_globs=True):\n # Override terminal size to standardise traceback format\n with modified_env({'COLUMNS': '80', 'LINES': '24'}):\n return super(IPDocTestRunner,self).run(test,\n compileflags,out,clear_globs)\n
.venv\Lib\site-packages\IPython\testing\plugin\ipdoctest.py
ipdoctest.py
Python
11,881
0.95
0.150502
0.235043
python-kit
527
2024-01-20T09:35:24.645345
MIT
true
201c7f0236c8619724029523625517bd
"""Simple example using doctests.\n\nThis file just contains doctests both using plain python and IPython prompts.\nAll tests should be loaded by Pytest.\n"""\n\n\ndef pyfunc():\n """Some pure python tests...\n\n >>> pyfunc()\n 'pyfunc'\n\n >>> import os\n\n >>> 2+3\n 5\n\n >>> for i in range(3):\n ... print(i, end=' ')\n ... print(i+1, end=' ')\n ...\n 0 1 1 2 2 3\n """\n return "pyfunc"\n\n\ndef ipyfunc():\n """Some IPython tests...\n\n In [1]: ipyfunc()\n Out[1]: 'ipyfunc'\n\n In [2]: import os\n\n In [3]: 2+3\n Out[3]: 5\n\n In [4]: for i in range(3):\n ...: print(i, end=' ')\n ...: print(i+1, end=' ')\n ...:\n Out[4]: 0 1 1 2 2 3\n """\n return "ipyfunc"\n
.venv\Lib\site-packages\IPython\testing\plugin\simple.py
simple.py
Python
727
0.85
0.088889
0
python-kit
646
2025-01-05T22:28:39.326834
GPL-3.0
true
41a2ea0aa50547fcb209923dea66bfc8
x = 1\nprint("x is:", x)\n
.venv\Lib\site-packages\IPython\testing\plugin\simplevars.py
simplevars.py
Python
24
0.5
0
0
node-utils
280
2024-01-15T03:35:48.418159
Apache-2.0
true
5edd8c95466e000ac9c2a9fb31c81132
=======================\n Combo testing example\n=======================\n\nThis is a simple example that mixes ipython doctests::\n\n In [1]: import code\n\n In [2]: 2**12\n Out[2]: 4096\n\nwith command-line example information that does *not* get executed::\n\n $ mpirun -n 4 ipengine --controller-port=10000 --controller-ip=host0\n\nand with literal examples of Python source code::\n\n controller = dict(host='myhost',\n engine_port=None, # default is 10105\n control_port=None,\n )\n\n # keys are hostnames, values are the number of engine on that host\n engines = dict(node1=2,\n node2=2,\n node3=2,\n node3=2,\n )\n\n # Force failure to detect that this test is being run.\n 1/0\n\nThese source code examples are executed but no output is compared at all. An\nerror or failure is reported only if an exception is raised.\n\nNOTE: the execution of pure python blocks is not yet working!\n
.venv\Lib\site-packages\IPython\testing\plugin\test_combo.txt
test_combo.txt
Other
923
0.95
0.027778
0.08
awesome-app
443
2024-11-14T14:28:04.893720
Apache-2.0
true
24c5983ae106ab4dd2348bc3ac0b95b2
=====================================\n Tests in example form - pure python\n=====================================\n\nThis file contains doctest examples embedded as code blocks, using normal\nPython prompts. See the accompanying file for similar examples using IPython\nprompts (you can't mix both types within one file). The following will be run\nas a test::\n\n >>> 1+1\n 2\n >>> print ("hello")\n hello\n\nMore than one example works::\n\n >>> s="Hello World"\n\n >>> s.upper()\n 'HELLO WORLD'\n\nbut you should note that the *entire* test file is considered to be a single\ntest. Individual code blocks that fail are printed separately as ``example\nfailures``, but the whole file is still counted and reported as one test.\n
.venv\Lib\site-packages\IPython\testing\plugin\test_example.txt
test_example.txt
Other
730
0.7
0.041667
0
python-kit
524
2024-12-16T11:35:17.399847
MIT
true
5ed6e05370d8cee9e332dcd284ff8282
=================================\n Tests in example form - IPython\n=================================\n\nYou can write text files with examples that use IPython prompts (as long as you\nuse the nose ipython doctest plugin), but you can not mix and match prompt\nstyles in a single file. That is, you either use all ``>>>`` prompts or all\nIPython-style prompts. Your test suite *can* have both types, you just need to\nput each type of example in a separate. Using IPython prompts, you can paste\ndirectly from your session::\n\n In [5]: s="Hello World"\n\n In [6]: s.upper()\n Out[6]: 'HELLO WORLD'\n\nAnother example::\n\n In [8]: 1+3\n Out[8]: 4\n\nJust like in IPython docstrings, you can use all IPython syntax and features::\n\n In [9]: !echo hello\n hello\n\n In [10]: a='hi'\n\n In [11]: !echo $a\n hi\n
.venv\Lib\site-packages\IPython\testing\plugin\test_exampleip.txt
test_exampleip.txt
Other
814
0.7
0
0
react-lib
569
2025-03-24T04:44:32.883623
MIT
true
d28dcdce0933b1045a8dcdacfc545319
"""Tests for the ipdoctest machinery itself.\n\nNote: in a file named test_X, functions whose only test is their docstring (as\na doctest) and which have no test functionality of their own, should be called\n'doctest_foo' instead of 'test_foo', otherwise they get double-counted (the\nempty function call is counted as a test, which just inflates tests numbers\nartificially).\n"""\n\ndef doctest_simple():\n """ipdoctest must handle simple inputs\n \n In [1]: 1\n Out[1]: 1\n\n In [2]: print(1)\n 1\n """\n\ndef doctest_multiline1():\n """The ipdoctest machinery must handle multiline examples gracefully.\n\n In [2]: for i in range(4):\n ...: print(i)\n ...: \n 0\n 1\n 2\n 3\n """\n\ndef doctest_multiline2():\n """Multiline examples that define functions and print output.\n\n In [7]: def f(x):\n ...: return x+1\n ...: \n\n In [8]: f(1)\n Out[8]: 2\n\n In [9]: def g(x):\n ...: print('x is:',x)\n ...: \n\n In [10]: g(1)\n x is: 1\n\n In [11]: g('hello')\n x is: hello\n """\n\n\ndef doctest_multiline3():\n """Multiline examples with blank lines.\n\n In [12]: def h(x):\n ....: if x>1:\n ....: return x**2\n ....: # To leave a blank line in the input, you must mark it\n ....: # with a comment character:\n ....: #\n ....: # otherwise the doctest parser gets confused.\n ....: else:\n ....: return -1\n ....: \n\n In [13]: h(5)\n Out[13]: 25\n\n In [14]: h(1)\n Out[14]: -1\n\n In [15]: h(0)\n Out[15]: -1\n """\n\n\ndef doctest_builtin_underscore():\n """Defining builtins._ should not break anything outside the doctest\n while also should be working as expected inside the doctest.\n\n In [1]: import builtins\n\n In [2]: builtins._ = 42\n\n In [3]: builtins._\n Out[3]: 42\n\n In [4]: _\n Out[4]: 42\n """\n
.venv\Lib\site-packages\IPython\testing\plugin\test_ipdoctest.py
test_ipdoctest.py
Python
1,907
0.95
0.141304
0
awesome-app
646
2024-05-18T23:21:21.479091
Apache-2.0
true
75d03012dce819e31097a3e92a0f705e
"""Some simple tests for the plugin while running scripts.\n"""\n# Module imports\n# Std lib\nimport inspect\n\n# Our own\n\n#-----------------------------------------------------------------------------\n# Testing functions\n\ndef test_trivial():\n """A trivial passing test."""\n pass\n\ndef doctest_run():\n """Test running a trivial script.\n\n In [13]: run simplevars.py\n x is: 1\n """\n\ndef doctest_runvars():\n """Test that variables defined in scripts get loaded correctly via %run.\n\n In [13]: run simplevars.py\n x is: 1\n\n In [14]: x\n Out[14]: 1\n """\n\ndef doctest_ivars():\n """Test that variables defined interactively are picked up.\n In [5]: zz=1\n\n In [6]: zz\n Out[6]: 1\n """\n
.venv\Lib\site-packages\IPython\testing\plugin\test_refs.py
test_refs.py
Python
715
0.95
0.153846
0.172414
node-utils
109
2025-03-28T03:54:09.172541
Apache-2.0
true
b26390f79728476442c08b518f6fe17a
\n\n
.venv\Lib\site-packages\IPython\testing\plugin\__pycache__\dtexample.cpython-313.pyc
dtexample.cpython-313.pyc
Other
3,231
0.95
0.064748
0.040404
awesome-app
293
2025-03-13T09:05:00.256315
GPL-3.0
true
1e7d0bcbd6474d7c75bd29a6a46aff82
\n\n
.venv\Lib\site-packages\IPython\testing\plugin\__pycache__\ipdoctest.cpython-313.pyc
ipdoctest.cpython-313.pyc
Other
11,784
0.95
0.07362
0.027027
python-kit
875
2024-07-23T09:53:33.964940
MIT
true
13fd3a0f28af9d18778346ba8a45fcbb
\n\n
.venv\Lib\site-packages\IPython\testing\plugin\__pycache__\pytest_ipdoctest.cpython-313.pyc
pytest_ipdoctest.cpython-313.pyc
Other
38,902
0.95
0.021798
0.011561
vue-tools
778
2025-04-21T03:46:46.584378
GPL-3.0
true
23d1979990f58c89b02ad45e867193fc
\n\n
.venv\Lib\site-packages\IPython\testing\plugin\__pycache__\setup.cpython-313.pyc
setup.cpython-313.pyc
Other
665
0.8
0
0
python-kit
598
2025-02-24T01:49:05.030894
Apache-2.0
true
9ca9c258381b3a3cc90933472b61b937
\n\n
.venv\Lib\site-packages\IPython\testing\plugin\__pycache__\simple.cpython-313.pyc
simple.cpython-313.pyc
Other
967
0.85
0.054054
0
python-kit
93
2023-10-14T12:07:54.070431
BSD-3-Clause
true
7139130cb72f8309d8855c71cf24c961