diff --git a/.gitattributes b/.gitattributes index e6ee50d647facba9421f76149219275219b10300..e4b13a817dcafbe0f97ec40f95b3c3e85a6f2c73 100644 --- a/.gitattributes +++ b/.gitattributes @@ -381,3 +381,12 @@ material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space: material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908276/1908277.tif filter=lfs diff=lfs merge=lfs -text material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908282/1908283.tif filter=lfs diff=lfs merge=lfs -text material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908310/1908311.tif filter=lfs diff=lfs merge=lfs -text +material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Images/TSEM/1908315.tif filter=lfs diff=lfs merge=lfs -text +material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908258/1908259.tif filter=lfs diff=lfs merge=lfs -text +material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908290/1908290.tif filter=lfs diff=lfs merge=lfs -text +material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected/1908312_m.tif filter=lfs diff=lfs merge=lfs -text +material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected/1908248_m.tif filter=lfs diff=lfs merge=lfs -text +material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected/1908290_m.tif filter=lfs diff=lfs merge=lfs -text +material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected/1908320_m.tif filter=lfs diff=lfs merge=lfs -text +material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_Manual_4connected/1908260_m.tif filter=lfs diff=lfs merge=lfs -text +material/dataset/Datasets/Electron[[:space:]]Microscopy[[:space:]]Image[[:space:]]Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908264/1908264.tif filter=lfs diff=lfs merge=lfs -text diff --git a/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908248_m.tif b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908248_m.tif new file mode 100644 index 0000000000000000000000000000000000000000..c8c36e42477b5fbb5d7b69de60181d43ba107ef4 --- /dev/null +++ b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908248_m.tif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:88e01da63b51ca9156aadd6035ca509e23518bfc277834839ec9780e38494ca9 +size 787398 diff --git a/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908260_m.tif b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908260_m.tif new file mode 100644 index 0000000000000000000000000000000000000000..b867b67843f3a733690d0a0f283fe897abcfa76e --- /dev/null +++ b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908260_m.tif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:860e47455ec73f87701db3d34fe77744e8469ef845bfd6b15d518bdbb01b3acb +size 787398 diff --git a/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908290_m.tif b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908290_m.tif new file mode 100644 index 0000000000000000000000000000000000000000..cd099b945f02e0cb489cb869c3165f1c99d335d0 --- /dev/null +++ b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908290_m.tif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:da1f120818f450a133385cfc2968aabdebf95f06a2eade70a06e144f05b3e531 +size 787398 diff --git a/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908312_m.tif b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908312_m.tif new file mode 100644 index 0000000000000000000000000000000000000000..125b693ad0414cc0771996c846b6088339d661b6 --- /dev/null +++ b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908312_m.tif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:666cbfeea42da81ccf5f4ff547e764e223808a38f92eac5170d67bb5f253c9a3 +size 787398 diff --git a/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908320_m.tif b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908320_m.tif new file mode 100644 index 0000000000000000000000000000000000000000..0ec0a902d3ef78418388dac0098eba00c36952d2 --- /dev/null +++ b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_Manual_4connected/1908320_m.tif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3f6df7a2ba1dd1f60ab011727704999b23c051f61c19b8f4fbcf62d5f4f5de02 +size 787398 diff --git a/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908258/1908259.tif b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908258/1908259.tif new file mode 100644 index 0000000000000000000000000000000000000000..c426449290a9f8a647ec93f980e8d367b6c25601 --- /dev/null +++ b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908258/1908259.tif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec483732cfa75e61236a65e95caeeee39d9f641344158638fff3928791f6999b +size 729295 diff --git a/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908264/1908264.tif b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908264/1908264.tif new file mode 100644 index 0000000000000000000000000000000000000000..d3dba0cd407ec5b7076e92750b0e8199245f3d2b --- /dev/null +++ b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908264/1908264.tif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:39702e39ffb67f7f7012770834f1050f74868cc76bd644466518f9c335c47c2a +size 729295 diff --git a/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908290/1908290.tif b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908290/1908290.tif new file mode 100644 index 0000000000000000000000000000000000000000..ef8e427684da43d81fd2ffc2394dbd631fe7f79e --- /dev/null +++ b/material/dataset/Datasets/Electron Microscopy Image Masks/TiO2_Masks_TSEM/Image_Registration/Input/1908290/1908290.tif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:534470a4e9c649361b72ebc1cbaa14b7371266acd1c8d19f2d59714e11df9f1d +size 729295 diff --git a/material/dataset/Datasets/Electron Microscopy Images/TSEM/1908315.tif b/material/dataset/Datasets/Electron Microscopy Images/TSEM/1908315.tif new file mode 100644 index 0000000000000000000000000000000000000000..c6ff6a2cc8e8f056ee9e651d726adaab667f9bdb --- /dev/null +++ b/material/dataset/Datasets/Electron Microscopy Images/TSEM/1908315.tif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8f284b06f6adb3263620751c56dc34c5d5cc99e15d3f7f2ca4bf067b06a9733 +size 887568 diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/application.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/application.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09350493702ada6ef75c3b6781b86c81661899fc Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/application.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/autocall.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/autocall.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a5ab4444e00c697ed168554119b0a27a9a2019c Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/autocall.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/events.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/events.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3be191de0b1911371d7cf861e757efa97d88e210 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/events.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/guarded_eval.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/guarded_eval.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b6f1fd00227b48491801a4aa58df770ad4b6c175 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/guarded_eval.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/history.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/history.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8359c6796b68f6034fef7e007b52bd093691da0 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/history.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/prefilter.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/prefilter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..985fe5ecd6582a8ddf1281119f6124b3dd17086e Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/prefilter.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/shellapp.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/shellapp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0928766dc716820d4065ecc0785e3c366d737b2a Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/__pycache__/shellapp.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/completerlib.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/completerlib.py new file mode 100644 index 0000000000000000000000000000000000000000..f15490f2a969bd9048eef3f1411914b58d9fca4c --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/completerlib.py @@ -0,0 +1,382 @@ +# encoding: utf-8 +"""Implementations for various useful completers. + +These are all loaded by default by IPython. +""" +#----------------------------------------------------------------------------- +# Copyright (C) 2010-2011 The IPython Development Team. +# +# Distributed under the terms of the BSD License. +# +# The full license is in the file COPYING.txt, distributed with this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +# Stdlib imports +import glob +import inspect +import os +import re +import sys +from importlib import import_module +from importlib.machinery import all_suffixes + + +# Third-party imports +from time import time +from zipimport import zipimporter + +# Our own imports +from .completer import expand_user, compress_user +from .error import TryNext +from ..utils._process_common import arg_split + +# FIXME: this should be pulled in with the right call via the component system +from IPython import get_ipython + +from typing import List + +#----------------------------------------------------------------------------- +# Globals and constants +#----------------------------------------------------------------------------- +_suffixes = all_suffixes() + +# Time in seconds after which the rootmodules will be stored permanently in the +# ipython ip.db database (kept in the user's .ipython dir). +TIMEOUT_STORAGE = 2 + +# Time in seconds after which we give up +TIMEOUT_GIVEUP = 20 + +# Regular expression for the python import statement +import_re = re.compile(r'(?P[^\W\d]\w*?)' + r'(?P[/\\]__init__)?' + r'(?P%s)$' % + r'|'.join(re.escape(s) for s in _suffixes)) + +# RE for the ipython %run command (python + ipython scripts) +magic_run_re = re.compile(r'.*(\.ipy|\.ipynb|\.py[w]?)$') + +#----------------------------------------------------------------------------- +# Local utilities +#----------------------------------------------------------------------------- + + +def module_list(path: str) -> List[str]: + """ + Return the list containing the names of the modules available in the given + folder. + """ + # sys.path has the cwd as an empty string, but isdir/listdir need it as '.' + if path == '': + path = '.' + + # A few local constants to be used in loops below + pjoin = os.path.join + + if os.path.isdir(path): + # Build a list of all files in the directory and all files + # in its subdirectories. For performance reasons, do not + # recurse more than one level into subdirectories. + files: List[str] = [] + for root, dirs, nondirs in os.walk(path, followlinks=True): + subdir = root[len(path)+1:] + if subdir: + files.extend(pjoin(subdir, f) for f in nondirs) + dirs[:] = [] # Do not recurse into additional subdirectories. + else: + files.extend(nondirs) + + else: + try: + files = list(zipimporter(path)._files.keys()) # type: ignore + except Exception: + files = [] + + # Build a list of modules which match the import_re regex. + modules = [] + for f in files: + m = import_re.match(f) + if m: + modules.append(m.group('name')) + return list(set(modules)) + + +def get_root_modules(): + """ + Returns a list containing the names of all the modules available in the + folders of the pythonpath. + + ip.db['rootmodules_cache'] maps sys.path entries to list of modules. + """ + ip = get_ipython() + if ip is None: + # No global shell instance to store cached list of modules. + # Don't try to scan for modules every time. + return list(sys.builtin_module_names) + + if getattr(ip.db, "_mock", False): + rootmodules_cache = {} + else: + rootmodules_cache = ip.db.get("rootmodules_cache", {}) + rootmodules = list(sys.builtin_module_names) + start_time = time() + store = False + for path in sys.path: + try: + modules = rootmodules_cache[path] + except KeyError: + modules = module_list(path) + try: + modules.remove('__init__') + except ValueError: + pass + if path not in ('', '.'): # cwd modules should not be cached + rootmodules_cache[path] = modules + if time() - start_time > TIMEOUT_STORAGE and not store: + store = True + print("\nCaching the list of root modules, please wait!") + print("(This will only be done once - type '%rehashx' to " + "reset cache!)\n") + sys.stdout.flush() + if time() - start_time > TIMEOUT_GIVEUP: + print("This is taking too long, we give up.\n") + return [] + rootmodules.extend(modules) + if store: + ip.db['rootmodules_cache'] = rootmodules_cache + rootmodules = list(set(rootmodules)) + return rootmodules + + +def is_importable(module, attr: str, only_modules) -> bool: + if only_modules: + try: + mod = getattr(module, attr) + except ModuleNotFoundError: + # See gh-14434 + return False + return inspect.ismodule(mod) + else: + return not(attr[:2] == '__' and attr[-2:] == '__') + +def is_possible_submodule(module, attr): + try: + obj = getattr(module, attr) + except AttributeError: + # Is possibly an unimported submodule + return True + except TypeError: + # https://github.com/ipython/ipython/issues/9678 + return False + return inspect.ismodule(obj) + + +def try_import(mod: str, only_modules=False) -> List[str]: + """ + Try to import given module and return list of potential completions. + """ + mod = mod.rstrip('.') + try: + m = import_module(mod) + except: + return [] + + m_is_init = '__init__' in (getattr(m, '__file__', '') or '') + + completions = [] + if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init: + completions.extend( [attr for attr in dir(m) if + is_importable(m, attr, only_modules)]) + + m_all = getattr(m, "__all__", []) + if only_modules: + completions.extend(attr for attr in m_all if is_possible_submodule(m, attr)) + else: + completions.extend(m_all) + + if m_is_init: + file_ = m.__file__ + file_path = os.path.dirname(file_) # type: ignore + if file_path is not None: + completions.extend(module_list(file_path)) + completions_set = {c for c in completions if isinstance(c, str)} + completions_set.discard('__init__') + return list(completions_set) + + +#----------------------------------------------------------------------------- +# Completion-related functions. +#----------------------------------------------------------------------------- + +def quick_completer(cmd, completions): + r""" Easily create a trivial completer for a command. + + Takes either a list of completions, or all completions in string (that will + be split on whitespace). + + Example:: + + [d:\ipython]|1> import ipy_completers + [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz']) + [d:\ipython]|3> foo b + bar baz + [d:\ipython]|3> foo ba + """ + + if isinstance(completions, str): + completions = completions.split() + + def do_complete(self, event): + return completions + + get_ipython().set_hook('complete_command',do_complete, str_key = cmd) + +def module_completion(line): + """ + Returns a list containing the completion possibilities for an import line. + + The line looks like this : + 'import xml.d' + 'from xml.dom import' + """ + + words = line.split(' ') + nwords = len(words) + + # from whatever -> 'import ' + if nwords == 3 and words[0] == 'from': + return ['import '] + + # 'from xy' or 'import xy' + if nwords < 3 and (words[0] in {'%aimport', 'import', 'from'}) : + if nwords == 1: + return get_root_modules() + mod = words[1].split('.') + if len(mod) < 2: + return get_root_modules() + completion_list = try_import('.'.join(mod[:-1]), True) + return ['.'.join(mod[:-1] + [el]) for el in completion_list] + + # 'from xyz import abc' + if nwords >= 3 and words[0] == 'from': + mod = words[1] + return try_import(mod) + +#----------------------------------------------------------------------------- +# Completers +#----------------------------------------------------------------------------- +# These all have the func(self, event) signature to be used as custom +# completers + +def module_completer(self,event): + """Give completions after user has typed 'import ...' or 'from ...'""" + + # This works in all versions of python. While 2.5 has + # pkgutil.walk_packages(), that particular routine is fairly dangerous, + # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full + # of possibly problematic side effects. + # This search the folders in the sys.path for available modules. + + return module_completion(event.line) + +# FIXME: there's a lot of logic common to the run, cd and builtin file +# completers, that is currently reimplemented in each. + +def magic_run_completer(self, event): + """Complete files that end in .py or .ipy or .ipynb for the %run command. + """ + comps = arg_split(event.line, strict=False) + # relpath should be the current token that we need to complete. + if (len(comps) > 1) and (not event.line.endswith(' ')): + relpath = comps[-1].strip("'\"") + else: + relpath = '' + + #print("\nev=", event) # dbg + #print("rp=", relpath) # dbg + #print('comps=', comps) # dbg + + lglob = glob.glob + isdir = os.path.isdir + relpath, tilde_expand, tilde_val = expand_user(relpath) + + # Find if the user has already typed the first filename, after which we + # should complete on all files, since after the first one other files may + # be arguments to the input script. + + if any(magic_run_re.match(c) for c in comps): + matches = [f.replace('\\','/') + ('/' if isdir(f) else '') + for f in lglob(relpath+'*')] + else: + dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)] + pys = [f.replace('\\','/') + for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') + + lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')] + + matches = dirs + pys + + #print('run comp:', dirs+pys) # dbg + return [compress_user(p, tilde_expand, tilde_val) for p in matches] + + +def cd_completer(self, event): + """Completer function for cd, which only returns directories.""" + ip = get_ipython() + relpath = event.symbol + + #print(event) # dbg + if event.line.endswith('-b') or ' -b ' in event.line: + # return only bookmark completions + bkms = self.db.get('bookmarks', None) + if bkms: + return bkms.keys() + else: + return [] + + if event.symbol == '-': + width_dh = str(len(str(len(ip.user_ns['_dh']) + 1))) + # jump in directory history by number + fmt = '-%0' + width_dh +'d [%s]' + ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])] + if len(ents) > 1: + return ents + return [] + + if event.symbol.startswith('--'): + return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']] + + # Expand ~ in path and normalize directory separators. + relpath, tilde_expand, tilde_val = expand_user(relpath) + relpath = relpath.replace('\\','/') + + found = [] + for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*') + if os.path.isdir(f)]: + if ' ' in d: + # we don't want to deal with any of that, complex code + # for this is elsewhere + raise TryNext + + found.append(d) + + if not found: + if os.path.isdir(relpath): + return [compress_user(relpath, tilde_expand, tilde_val)] + + # if no completions so far, try bookmarks + bks = self.db.get('bookmarks',{}) + bkmatches = [s for s in bks if s.startswith(event.symbol)] + if bkmatches: + return bkmatches + + raise TryNext + + return [compress_user(p, tilde_expand, tilde_val) for p in found] + +def reset_completer(self, event): + "A completer for %reset magic" + return '-f -s in out array dhist'.split() diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/extensions.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..27c6a4116d436a9bc618076ebb4479e32f0f8bb7 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/extensions.py @@ -0,0 +1,135 @@ +# encoding: utf-8 +"""A class for managing IPython extensions.""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + +import os +import os.path +import sys +from importlib import import_module, reload + +from traitlets.config.configurable import Configurable +from IPython.utils.path import ensure_dir_exists +from traitlets import Instance + + +#----------------------------------------------------------------------------- +# Main class +#----------------------------------------------------------------------------- + +BUILTINS_EXTS = {"storemagic": False, "autoreload": False} + + +class ExtensionManager(Configurable): + """A class to manage IPython extensions. + + An IPython extension is an importable Python module that has + a function with the signature:: + + def load_ipython_extension(ipython): + # Do things with ipython + + This function is called after your extension is imported and the + currently active :class:`InteractiveShell` instance is passed as + the only argument. You can do anything you want with IPython at + that point, including defining new magic and aliases, adding new + components, etc. + + You can also optionally define an :func:`unload_ipython_extension(ipython)` + function, which will be called if the user unloads or reloads the extension. + The extension manager will only call :func:`load_ipython_extension` again + if the extension is reloaded. + + You can put your extension modules anywhere you want, as long as + they can be imported by Python's standard import mechanism. + """ + + shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True) + + def __init__(self, shell=None, **kwargs): + super(ExtensionManager, self).__init__(shell=shell, **kwargs) + self.loaded = set() + + def load_extension(self, module_str: str): + """Load an IPython extension by its module name. + + Returns the string "already loaded" if the extension is already loaded, + "no load function" if the module doesn't have a load_ipython_extension + function, or None if it succeeded. + """ + try: + return self._load_extension(module_str) + except ModuleNotFoundError: + if module_str in BUILTINS_EXTS: + BUILTINS_EXTS[module_str] = True + return self._load_extension("IPython.extensions." + module_str) + raise + + def _load_extension(self, module_str: str): + if module_str in self.loaded: + return "already loaded" + + assert self.shell is not None + + with self.shell.builtin_trap: + if module_str not in sys.modules: + mod = import_module(module_str) + mod = sys.modules[module_str] + if self._call_load_ipython_extension(mod): + self.loaded.add(module_str) + else: + return "no load function" + + def unload_extension(self, module_str: str): + """Unload an IPython extension by its module name. + + This function looks up the extension's name in ``sys.modules`` and + simply calls ``mod.unload_ipython_extension(self)``. + + Returns the string "no unload function" if the extension doesn't define + a function to unload itself, "not loaded" if the extension isn't loaded, + otherwise None. + """ + if BUILTINS_EXTS.get(module_str, False) is True: + module_str = "IPython.extensions." + module_str + if module_str not in self.loaded: + return "not loaded" + + if module_str in sys.modules: + mod = sys.modules[module_str] + if self._call_unload_ipython_extension(mod): + self.loaded.discard(module_str) + else: + return "no unload function" + + def reload_extension(self, module_str: str): + """Reload an IPython extension by calling reload. + + If the module has not been loaded before, + :meth:`InteractiveShell.load_extension` is called. Otherwise + :func:`reload` is called and then the :func:`load_ipython_extension` + function of the module, if it exists is called. + """ + + if BUILTINS_EXTS.get(module_str, False) is True: + module_str = "IPython.extensions." + module_str + + if (module_str in self.loaded) and (module_str in sys.modules): + self.unload_extension(module_str) + mod = sys.modules[module_str] + reload(mod) + if self._call_load_ipython_extension(mod): + self.loaded.add(module_str) + else: + self.load_extension(module_str) + + def _call_load_ipython_extension(self, mod): + if hasattr(mod, 'load_ipython_extension'): + mod.load_ipython_extension(self.shell) + return True + + def _call_unload_ipython_extension(self, mod): + if hasattr(mod, 'unload_ipython_extension'): + mod.unload_ipython_extension(self.shell) + return True diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/history.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/history.py new file mode 100644 index 0000000000000000000000000000000000000000..f59ca11916868f3182ff9e4dd6c289c387056d0f --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/history.py @@ -0,0 +1,989 @@ +""" History related magics and functionality """ + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + + +import atexit +import datetime +import re +import sqlite3 +import threading +from pathlib import Path + +from decorator import decorator +from traitlets import ( + Any, + Bool, + Dict, + Instance, + Integer, + List, + TraitError, + Unicode, + Union, + default, + observe, +) +from traitlets.config.configurable import LoggingConfigurable + +from IPython.paths import locate_profile +from IPython.utils.decorators import undoc + +#----------------------------------------------------------------------------- +# Classes and functions +#----------------------------------------------------------------------------- + +@undoc +class DummyDB(object): + """Dummy DB that will act as a black hole for history. + + Only used in the absence of sqlite""" + def execute(*args, **kwargs): + return [] + + def commit(self, *args, **kwargs): + pass + + def __enter__(self, *args, **kwargs): + pass + + def __exit__(self, *args, **kwargs): + pass + + +@decorator +def only_when_enabled(f, self, *a, **kw): + """Decorator: return an empty list in the absence of sqlite.""" + if not self.enabled: + return [] + else: + return f(self, *a, **kw) + + +# use 16kB as threshold for whether a corrupt history db should be saved +# that should be at least 100 entries or so +_SAVE_DB_SIZE = 16384 + +@decorator +def catch_corrupt_db(f, self, *a, **kw): + """A decorator which wraps HistoryAccessor method calls to catch errors from + a corrupt SQLite database, move the old database out of the way, and create + a new one. + + We avoid clobbering larger databases because this may be triggered due to filesystem issues, + not just a corrupt file. + """ + try: + return f(self, *a, **kw) + except (sqlite3.DatabaseError, sqlite3.OperationalError) as e: + self._corrupt_db_counter += 1 + self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e) + if self.hist_file != ':memory:': + if self._corrupt_db_counter > self._corrupt_db_limit: + self.hist_file = ':memory:' + self.log.error("Failed to load history too many times, history will not be saved.") + elif self.hist_file.is_file(): + # move the file out of the way + base = str(self.hist_file.parent / self.hist_file.stem) + ext = self.hist_file.suffix + size = self.hist_file.stat().st_size + if size >= _SAVE_DB_SIZE: + # if there's significant content, avoid clobbering + now = datetime.datetime.now().isoformat().replace(':', '.') + newpath = base + '-corrupt-' + now + ext + # don't clobber previous corrupt backups + for i in range(100): + if not Path(newpath).exists(): + break + else: + newpath = base + '-corrupt-' + now + (u'-%i' % i) + ext + else: + # not much content, possibly empty; don't worry about clobbering + # maybe we should just delete it? + newpath = base + '-corrupt' + ext + self.hist_file.rename(newpath) + self.log.error("History file was moved to %s and a new file created.", newpath) + self.init_db() + return [] + else: + # Failed with :memory:, something serious is wrong + raise + + +class HistoryAccessorBase(LoggingConfigurable): + """An abstract class for History Accessors """ + + def get_tail(self, n=10, raw=True, output=False, include_latest=False): + raise NotImplementedError + + def search(self, pattern="*", raw=True, search_raw=True, + output=False, n=None, unique=False): + raise NotImplementedError + + def get_range(self, session, start=1, stop=None, raw=True,output=False): + raise NotImplementedError + + def get_range_by_str(self, rangestr, raw=True, output=False): + raise NotImplementedError + + +class HistoryAccessor(HistoryAccessorBase): + """Access the history database without adding to it. + + This is intended for use by standalone history tools. IPython shells use + HistoryManager, below, which is a subclass of this.""" + + # counter for init_db retries, so we don't keep trying over and over + _corrupt_db_counter = 0 + # after two failures, fallback on :memory: + _corrupt_db_limit = 2 + + # String holding the path to the history file + hist_file = Union( + [Instance(Path), Unicode()], + help="""Path to file to use for SQLite history database. + + By default, IPython will put the history database in the IPython + profile directory. If you would rather share one history among + profiles, you can set this value in each, so that they are consistent. + + Due to an issue with fcntl, SQLite is known to misbehave on some NFS + mounts. If you see IPython hanging, try setting this to something on a + local disk, e.g:: + + ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite + + you can also use the specific value `:memory:` (including the colon + at both end but not the back ticks), to avoid creating an history file. + + """, + ).tag(config=True) + + enabled = Bool(True, + help="""enable the SQLite history + + set enabled=False to disable the SQLite history, + in which case there will be no stored history, no SQLite connection, + and no background saving thread. This may be necessary in some + threaded environments where IPython is embedded. + """, + ).tag(config=True) + + connection_options = Dict( + help="""Options for configuring the SQLite connection + + These options are passed as keyword args to sqlite3.connect + when establishing database connections. + """ + ).tag(config=True) + + @default("connection_options") + def _default_connection_options(self): + return dict(check_same_thread=False) + + # The SQLite database + db = Any() + @observe('db') + def _db_changed(self, change): + """validate the db, since it can be an Instance of two different types""" + new = change['new'] + connection_types = (DummyDB, sqlite3.Connection) + if not isinstance(new, connection_types): + msg = "%s.db must be sqlite3 Connection or DummyDB, not %r" % \ + (self.__class__.__name__, new) + raise TraitError(msg) + + def __init__(self, profile="default", hist_file="", **traits): + """Create a new history accessor. + + Parameters + ---------- + profile : str + The name of the profile from which to open history. + hist_file : str + Path to an SQLite history database stored by IPython. If specified, + hist_file overrides profile. + config : :class:`~traitlets.config.loader.Config` + Config object. hist_file can also be set through this. + """ + super(HistoryAccessor, self).__init__(**traits) + # defer setting hist_file from kwarg until after init, + # otherwise the default kwarg value would clobber any value + # set by config + if hist_file: + self.hist_file = hist_file + + try: + self.hist_file + except TraitError: + # No one has set the hist_file, yet. + self.hist_file = self._get_hist_file_name(profile) + + self.init_db() + + def _get_hist_file_name(self, profile='default'): + """Find the history file for the given profile name. + + This is overridden by the HistoryManager subclass, to use the shell's + active profile. + + Parameters + ---------- + profile : str + The name of a profile which has a history file. + """ + return Path(locate_profile(profile)) / "history.sqlite" + + @catch_corrupt_db + def init_db(self): + """Connect to the database, and create tables if necessary.""" + if not self.enabled: + self.db = DummyDB() + return + + # use detect_types so that timestamps return datetime objects + kwargs = dict(detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) + kwargs.update(self.connection_options) + self.db = sqlite3.connect(str(self.hist_file), **kwargs) + with self.db: + self.db.execute( + """CREATE TABLE IF NOT EXISTS sessions (session integer + primary key autoincrement, start timestamp, + end timestamp, num_cmds integer, remark text)""" + ) + self.db.execute( + """CREATE TABLE IF NOT EXISTS history + (session integer, line integer, source text, source_raw text, + PRIMARY KEY (session, line))""" + ) + # Output history is optional, but ensure the table's there so it can be + # enabled later. + self.db.execute( + """CREATE TABLE IF NOT EXISTS output_history + (session integer, line integer, output text, + PRIMARY KEY (session, line))""" + ) + # success! reset corrupt db count + self._corrupt_db_counter = 0 + + def writeout_cache(self): + """Overridden by HistoryManager to dump the cache before certain + database lookups.""" + pass + + ## ------------------------------- + ## Methods for retrieving history: + ## ------------------------------- + def _run_sql(self, sql, params, raw=True, output=False, latest=False): + """Prepares and runs an SQL query for the history database. + + Parameters + ---------- + sql : str + Any filtering expressions to go after SELECT ... FROM ... + params : tuple + Parameters passed to the SQL query (to replace "?") + raw, output : bool + See :meth:`get_range` + latest : bool + Select rows with max (session, line) + + Returns + ------- + Tuples as :meth:`get_range` + """ + toget = 'source_raw' if raw else 'source' + sqlfrom = "history" + if output: + sqlfrom = "history LEFT JOIN output_history USING (session, line)" + toget = "history.%s, output_history.output" % toget + if latest: + toget += ", MAX(session * 128 * 1024 + line)" + this_querry = "SELECT session, line, %s FROM %s " % (toget, sqlfrom) + sql + cur = self.db.execute(this_querry, params) + if latest: + cur = (row[:-1] for row in cur) + if output: # Regroup into 3-tuples, and parse JSON + return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur) + return cur + + @only_when_enabled + @catch_corrupt_db + def get_session_info(self, session): + """Get info about a session. + + Parameters + ---------- + session : int + Session number to retrieve. + + Returns + ------- + session_id : int + Session ID number + start : datetime + Timestamp for the start of the session. + end : datetime + Timestamp for the end of the session, or None if IPython crashed. + num_cmds : int + Number of commands run, or None if IPython crashed. + remark : unicode + A manually set description. + """ + query = "SELECT * from sessions where session == ?" + return self.db.execute(query, (session,)).fetchone() + + @catch_corrupt_db + def get_last_session_id(self): + """Get the last session ID currently in the database. + + Within IPython, this should be the same as the value stored in + :attr:`HistoryManager.session_number`. + """ + for record in self.get_tail(n=1, include_latest=True): + return record[0] + + @catch_corrupt_db + def get_tail(self, n=10, raw=True, output=False, include_latest=False): + """Get the last n lines from the history database. + + Parameters + ---------- + n : int + The number of lines to get + raw, output : bool + See :meth:`get_range` + include_latest : bool + If False (default), n+1 lines are fetched, and the latest one + is discarded. This is intended to be used where the function + is called by a user command, which it should not return. + + Returns + ------- + Tuples as :meth:`get_range` + """ + self.writeout_cache() + if not include_latest: + n += 1 + cur = self._run_sql( + "ORDER BY session DESC, line DESC LIMIT ?", (n,), raw=raw, output=output + ) + if not include_latest: + return reversed(list(cur)[1:]) + return reversed(list(cur)) + + @catch_corrupt_db + def search(self, pattern="*", raw=True, search_raw=True, + output=False, n=None, unique=False): + """Search the database using unix glob-style matching (wildcards + * and ?). + + Parameters + ---------- + pattern : str + The wildcarded pattern to match when searching + search_raw : bool + If True, search the raw input, otherwise, the parsed input + raw, output : bool + See :meth:`get_range` + n : None or int + If an integer is given, it defines the limit of + returned entries. + unique : bool + When it is true, return only unique entries. + + Returns + ------- + Tuples as :meth:`get_range` + """ + tosearch = "source_raw" if search_raw else "source" + if output: + tosearch = "history." + tosearch + self.writeout_cache() + sqlform = "WHERE %s GLOB ?" % tosearch + params = (pattern,) + if unique: + sqlform += ' GROUP BY {0}'.format(tosearch) + if n is not None: + sqlform += " ORDER BY session DESC, line DESC LIMIT ?" + params += (n,) + elif unique: + sqlform += " ORDER BY session, line" + cur = self._run_sql(sqlform, params, raw=raw, output=output, latest=unique) + if n is not None: + return reversed(list(cur)) + return cur + + @catch_corrupt_db + def get_range(self, session, start=1, stop=None, raw=True,output=False): + """Retrieve input by session. + + Parameters + ---------- + session : int + Session number to retrieve. + start : int + First line to retrieve. + stop : int + End of line range (excluded from output itself). If None, retrieve + to the end of the session. + raw : bool + If True, return untranslated input + output : bool + If True, attempt to include output. This will be 'real' Python + objects for the current session, or text reprs from previous + sessions if db_log_output was enabled at the time. Where no output + is found, None is used. + + Returns + ------- + entries + An iterator over the desired lines. Each line is a 3-tuple, either + (session, line, input) if output is False, or + (session, line, (input, output)) if output is True. + """ + if stop: + lineclause = "line >= ? AND line < ?" + params = (session, start, stop) + else: + lineclause = "line>=?" + params = (session, start) + + return self._run_sql("WHERE session==? AND %s" % lineclause, + params, raw=raw, output=output) + + def get_range_by_str(self, rangestr, raw=True, output=False): + """Get lines of history from a string of ranges, as used by magic + commands %hist, %save, %macro, etc. + + Parameters + ---------- + rangestr : str + A string specifying ranges, e.g. "5 ~2/1-4". If empty string is used, + this will return everything from current session's history. + + See the documentation of :func:`%history` for the full details. + + raw, output : bool + As :meth:`get_range` + + Returns + ------- + Tuples as :meth:`get_range` + """ + for sess, s, e in extract_hist_ranges(rangestr): + for line in self.get_range(sess, s, e, raw=raw, output=output): + yield line + + +class HistoryManager(HistoryAccessor): + """A class to organize all history-related functionality in one place. + """ + # Public interface + + # An instance of the IPython shell we are attached to + shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', + allow_none=True) + # Lists to hold processed and raw history. These start with a blank entry + # so that we can index them starting from 1 + input_hist_parsed = List([""]) + input_hist_raw = List([""]) + # A list of directories visited during session + dir_hist: List = List() + + @default("dir_hist") + def _dir_hist_default(self): + try: + return [Path.cwd()] + except OSError: + return [] + + # A dict of output history, keyed with ints from the shell's + # execution count. + output_hist = Dict() + # The text/plain repr of outputs. + output_hist_reprs = Dict() + + # The number of the current session in the history database + session_number = Integer() + + db_log_output = Bool(False, + help="Should the history database include output? (default: no)" + ).tag(config=True) + db_cache_size = Integer(0, + help="Write to database every x commands (higher values save disk access & power).\n" + "Values of 1 or less effectively disable caching." + ).tag(config=True) + # The input and output caches + db_input_cache: List = List() + db_output_cache: List = List() + + # History saving in separate thread + save_thread = Instance('IPython.core.history.HistorySavingThread', + allow_none=True) + save_flag = Instance(threading.Event, allow_none=True) + + # Private interface + # Variables used to store the three last inputs from the user. On each new + # history update, we populate the user's namespace with these, shifted as + # necessary. + _i00 = Unicode("") + _i = Unicode("") + _ii = Unicode("") + _iii = Unicode("") + + # A regex matching all forms of the exit command, so that we don't store + # them in the history (it's annoying to rewind the first entry and land on + # an exit call). + _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$") + + def __init__(self, shell=None, config=None, **traits): + """Create a new history manager associated with a shell instance. + """ + super(HistoryManager, self).__init__(shell=shell, config=config, + **traits) + self.save_flag = threading.Event() + self.db_input_cache_lock = threading.Lock() + self.db_output_cache_lock = threading.Lock() + + try: + self.new_session() + except sqlite3.OperationalError: + self.log.error("Failed to create history session in %s. History will not be saved.", + self.hist_file, exc_info=True) + self.hist_file = ':memory:' + + if self.enabled and self.hist_file != ':memory:': + self.save_thread = HistorySavingThread(self) + try: + self.save_thread.start() + except RuntimeError: + self.log.error( + "Failed to start history saving thread. History will not be saved.", + exc_info=True, + ) + self.hist_file = ":memory:" + + def _get_hist_file_name(self, profile=None): + """Get default history file name based on the Shell's profile. + + The profile parameter is ignored, but must exist for compatibility with + the parent class.""" + profile_dir = self.shell.profile_dir.location + return Path(profile_dir) / "history.sqlite" + + @only_when_enabled + def new_session(self, conn=None): + """Get a new session number.""" + if conn is None: + conn = self.db + + with conn: + cur = conn.execute( + """INSERT INTO sessions VALUES (NULL, ?, NULL, + NULL, '') """, + (datetime.datetime.now().isoformat(" "),), + ) + self.session_number = cur.lastrowid + + def end_session(self): + """Close the database session, filling in the end time and line count.""" + self.writeout_cache() + with self.db: + self.db.execute( + """UPDATE sessions SET end=?, num_cmds=? WHERE + session==?""", + ( + datetime.datetime.now().isoformat(" "), + len(self.input_hist_parsed) - 1, + self.session_number, + ), + ) + self.session_number = 0 + + def name_session(self, name): + """Give the current session a name in the history database.""" + with self.db: + self.db.execute("UPDATE sessions SET remark=? WHERE session==?", + (name, self.session_number)) + + def reset(self, new_session=True): + """Clear the session history, releasing all object references, and + optionally open a new session.""" + self.output_hist.clear() + # The directory history can't be completely empty + self.dir_hist[:] = [Path.cwd()] + + if new_session: + if self.session_number: + self.end_session() + self.input_hist_parsed[:] = [""] + self.input_hist_raw[:] = [""] + self.new_session() + + # ------------------------------ + # Methods for retrieving history + # ------------------------------ + def get_session_info(self, session=0): + """Get info about a session. + + Parameters + ---------- + session : int + Session number to retrieve. The current session is 0, and negative + numbers count back from current session, so -1 is the previous session. + + Returns + ------- + session_id : int + Session ID number + start : datetime + Timestamp for the start of the session. + end : datetime + Timestamp for the end of the session, or None if IPython crashed. + num_cmds : int + Number of commands run, or None if IPython crashed. + remark : unicode + A manually set description. + """ + if session <= 0: + session += self.session_number + + return super(HistoryManager, self).get_session_info(session=session) + + @catch_corrupt_db + def get_tail(self, n=10, raw=True, output=False, include_latest=False): + """Get the last n lines from the history database. + + Most recent entry last. + + Completion will be reordered so that that the last ones are when + possible from current session. + + Parameters + ---------- + n : int + The number of lines to get + raw, output : bool + See :meth:`get_range` + include_latest : bool + If False (default), n+1 lines are fetched, and the latest one + is discarded. This is intended to be used where the function + is called by a user command, which it should not return. + + Returns + ------- + Tuples as :meth:`get_range` + """ + self.writeout_cache() + if not include_latest: + n += 1 + # cursor/line/entry + this_cur = list( + self._run_sql( + "WHERE session == ? ORDER BY line DESC LIMIT ? ", + (self.session_number, n), + raw=raw, + output=output, + ) + ) + other_cur = list( + self._run_sql( + "WHERE session != ? ORDER BY session DESC, line DESC LIMIT ?", + (self.session_number, n), + raw=raw, + output=output, + ) + ) + + everything = this_cur + other_cur + + everything = everything[:n] + + if not include_latest: + return list(everything)[:0:-1] + return list(everything)[::-1] + + def _get_range_session(self, start=1, stop=None, raw=True, output=False): + """Get input and output history from the current session. Called by + get_range, and takes similar parameters.""" + input_hist = self.input_hist_raw if raw else self.input_hist_parsed + + n = len(input_hist) + if start < 0: + start += n + if not stop or (stop > n): + stop = n + elif stop < 0: + stop += n + + for i in range(start, stop): + if output: + line = (input_hist[i], self.output_hist_reprs.get(i)) + else: + line = input_hist[i] + yield (0, i, line) + + def get_range(self, session=0, start=1, stop=None, raw=True,output=False): + """Retrieve input by session. + + Parameters + ---------- + session : int + Session number to retrieve. The current session is 0, and negative + numbers count back from current session, so -1 is previous session. + start : int + First line to retrieve. + stop : int + End of line range (excluded from output itself). If None, retrieve + to the end of the session. + raw : bool + If True, return untranslated input + output : bool + If True, attempt to include output. This will be 'real' Python + objects for the current session, or text reprs from previous + sessions if db_log_output was enabled at the time. Where no output + is found, None is used. + + Returns + ------- + entries + An iterator over the desired lines. Each line is a 3-tuple, either + (session, line, input) if output is False, or + (session, line, (input, output)) if output is True. + """ + if session <= 0: + session += self.session_number + if session==self.session_number: # Current session + return self._get_range_session(start, stop, raw, output) + return super(HistoryManager, self).get_range(session, start, stop, raw, + output) + + ## ---------------------------- + ## Methods for storing history: + ## ---------------------------- + def store_inputs(self, line_num, source, source_raw=None): + """Store source and raw input in history and create input cache + variables ``_i*``. + + Parameters + ---------- + line_num : int + The prompt number of this input. + source : str + Python input. + source_raw : str, optional + If given, this is the raw input without any IPython transformations + applied to it. If not given, ``source`` is used. + """ + if source_raw is None: + source_raw = source + source = source.rstrip('\n') + source_raw = source_raw.rstrip('\n') + + # do not store exit/quit commands + if self._exit_re.match(source_raw.strip()): + return + + self.input_hist_parsed.append(source) + self.input_hist_raw.append(source_raw) + + with self.db_input_cache_lock: + self.db_input_cache.append((line_num, source, source_raw)) + # Trigger to flush cache and write to DB. + if len(self.db_input_cache) >= self.db_cache_size: + self.save_flag.set() + + # update the auto _i variables + self._iii = self._ii + self._ii = self._i + self._i = self._i00 + self._i00 = source_raw + + # hackish access to user namespace to create _i1,_i2... dynamically + new_i = '_i%s' % line_num + to_main = {'_i': self._i, + '_ii': self._ii, + '_iii': self._iii, + new_i : self._i00 } + + if self.shell is not None: + self.shell.push(to_main, interactive=False) + + def store_output(self, line_num): + """If database output logging is enabled, this saves all the + outputs from the indicated prompt number to the database. It's + called by run_cell after code has been executed. + + Parameters + ---------- + line_num : int + The line number from which to save outputs + """ + if (not self.db_log_output) or (line_num not in self.output_hist_reprs): + return + output = self.output_hist_reprs[line_num] + + with self.db_output_cache_lock: + self.db_output_cache.append((line_num, output)) + if self.db_cache_size <= 1: + self.save_flag.set() + + def _writeout_input_cache(self, conn): + with conn: + for line in self.db_input_cache: + conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)", + (self.session_number,)+line) + + def _writeout_output_cache(self, conn): + with conn: + for line in self.db_output_cache: + conn.execute("INSERT INTO output_history VALUES (?, ?, ?)", + (self.session_number,)+line) + + @only_when_enabled + def writeout_cache(self, conn=None): + """Write any entries in the cache to the database.""" + if conn is None: + conn = self.db + + with self.db_input_cache_lock: + try: + self._writeout_input_cache(conn) + except sqlite3.IntegrityError: + self.new_session(conn) + print("ERROR! Session/line number was not unique in", + "database. History logging moved to new session", + self.session_number) + try: + # Try writing to the new session. If this fails, don't + # recurse + self._writeout_input_cache(conn) + except sqlite3.IntegrityError: + pass + finally: + self.db_input_cache = [] + + with self.db_output_cache_lock: + try: + self._writeout_output_cache(conn) + except sqlite3.IntegrityError: + print("!! Session/line number for output was not unique", + "in database. Output will not be stored.") + finally: + self.db_output_cache = [] + + +class HistorySavingThread(threading.Thread): + """This thread takes care of writing history to the database, so that + the UI isn't held up while that happens. + + It waits for the HistoryManager's save_flag to be set, then writes out + the history cache. The main thread is responsible for setting the flag when + the cache size reaches a defined threshold.""" + daemon = True + stop_now = False + enabled = True + def __init__(self, history_manager): + super(HistorySavingThread, self).__init__(name="IPythonHistorySavingThread") + self.history_manager = history_manager + self.enabled = history_manager.enabled + + @only_when_enabled + def run(self): + atexit.register(self.stop) + # We need a separate db connection per thread: + try: + self.db = sqlite3.connect( + str(self.history_manager.hist_file), + **self.history_manager.connection_options, + ) + while True: + self.history_manager.save_flag.wait() + if self.stop_now: + self.db.close() + return + self.history_manager.save_flag.clear() + self.history_manager.writeout_cache(self.db) + except Exception as e: + print(("The history saving thread hit an unexpected error (%s)." + "History will not be written to the database.") % repr(e)) + finally: + atexit.unregister(self.stop) + + def stop(self): + """This can be called from the main thread to safely stop this thread. + + Note that it does not attempt to write out remaining history before + exiting. That should be done by calling the HistoryManager's + end_session method.""" + self.stop_now = True + self.history_manager.save_flag.set() + self.join() + + +# To match, e.g. ~5/8-~2/3 +range_re = re.compile(r""" +((?P~?\d+)/)? +(?P\d+)? +((?P[\-:]) + ((?P~?\d+)/)? + (?P\d+))? +$""", re.VERBOSE) + + +def extract_hist_ranges(ranges_str): + """Turn a string of history ranges into 3-tuples of (session, start, stop). + + Empty string results in a `[(0, 1, None)]`, i.e. "everything from current + session". + + Examples + -------- + >>> list(extract_hist_ranges("~8/5-~7/4 2")) + [(-8, 5, None), (-7, 1, 5), (0, 2, 3)] + """ + if ranges_str == "": + yield (0, 1, None) # Everything from current session + return + + for range_str in ranges_str.split(): + rmatch = range_re.match(range_str) + if not rmatch: + continue + start = rmatch.group("start") + if start: + start = int(start) + end = rmatch.group("end") + # If no end specified, get (a, a + 1) + end = int(end) if end else start + 1 + else: # start not specified + if not rmatch.group('startsess'): # no startsess + continue + start = 1 + end = None # provide the entire session hist + + if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3] + end += 1 + startsess = rmatch.group("startsess") or "0" + endsess = rmatch.group("endsess") or startsess + startsess = int(startsess.replace("~","-")) + endsess = int(endsess.replace("~","-")) + assert endsess >= startsess, "start session must be earlier than end session" + + if endsess == startsess: + yield (startsess, start, end) + continue + # Multiple sessions in one range: + yield (startsess, start, None) + for sess in range(startsess+1, endsess): + yield (sess, 1, None) + yield (endsess, 1, end) + + +def _format_lineno(session, line): + """Helper function to format line numbers properly.""" + if session == 0: + return str(line) + return "%s#%s" % (session, line) diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/hooks.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..484ebe459a7194aa07636f79f0c53e384915c464 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/hooks.py @@ -0,0 +1,173 @@ +"""Hooks for IPython. + +In Python, it is possible to overwrite any method of any object if you really +want to. But IPython exposes a few 'hooks', methods which are *designed* to +be overwritten by users for customization purposes. This module defines the +default versions of all such hooks, which get used by IPython if not +overridden by the user. + +Hooks are simple functions, but they should be declared with ``self`` as their +first argument, because when activated they are registered into IPython as +instance methods. The self argument will be the IPython running instance +itself, so hooks have full access to the entire IPython object. + +If you wish to define a new hook and activate it, you can make an :doc:`extension +` or a :ref:`startup script `. For +example, you could use a startup file like this:: + + import os + + def calljed(self,filename, linenum): + "My editor hook calls the jed editor directly." + print("Calling my own editor, jed ...") + if os.system('jed +%d %s' % (linenum,filename)) != 0: + raise TryNext() + + def load_ipython_extension(ip): + ip.set_hook('editor', calljed) + +""" + +#***************************************************************************** +# Copyright (C) 2005 Fernando Perez. +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING, distributed as part of this software. +#***************************************************************************** + +import os +import subprocess +import sys + +from .error import TryNext + +# List here all the default hooks. For now it's just the editor functions +# but over time we'll move here all the public API for user-accessible things. + +__all__ = [ + "editor", + "synchronize_with_editor", + "show_in_pager", + "pre_prompt_hook", + "clipboard_get", +] + +deprecated = {'pre_run_code_hook': "a callback for the 'pre_execute' or 'pre_run_cell' event", + 'late_startup_hook': "a callback for the 'shell_initialized' event", + 'shutdown_hook': "the atexit module", + } + +def editor(self, filename, linenum=None, wait=True): + """Open the default editor at the given filename and linenumber. + + This is IPython's default editor hook, you can use it as an example to + write your own modified one. To set your own editor function as the + new editor hook, call ip.set_hook('editor',yourfunc).""" + + # IPython configures a default editor at startup by reading $EDITOR from + # the environment, and falling back on vi (unix) or notepad (win32). + editor = self.editor + + # marker for at which line to open the file (for existing objects) + if linenum is None or editor=='notepad': + linemark = '' + else: + linemark = '+%d' % int(linenum) + + # Enclose in quotes if necessary and legal + if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': + editor = '"%s"' % editor + + # Call the actual editor + proc = subprocess.Popen('%s %s %s' % (editor, linemark, filename), + shell=True) + if wait and proc.wait() != 0: + raise TryNext() + + +def synchronize_with_editor(self, filename, linenum, column): + pass + + +class CommandChainDispatcher: + """ Dispatch calls to a chain of commands until some func can handle it + + Usage: instantiate, execute "add" to add commands (with optional + priority), execute normally via f() calling mechanism. + + """ + def __init__(self,commands=None): + if commands is None: + self.chain = [] + else: + self.chain = commands + + + def __call__(self,*args, **kw): + """ Command chain is called just like normal func. + + This will call all funcs in chain with the same args as were given to + this function, and return the result of first func that didn't raise + TryNext""" + last_exc = TryNext() + for prio,cmd in self.chain: + # print("prio",prio,"cmd",cmd) # dbg + try: + return cmd(*args, **kw) + except TryNext as exc: + last_exc = exc + # if no function will accept it, raise TryNext up to the caller + raise last_exc + + def __str__(self): + return str(self.chain) + + def add(self, func, priority=0): + """ Add a func to the cmd chain with given priority """ + self.chain.append((priority, func)) + self.chain.sort(key=lambda x: x[0]) + + def __iter__(self): + """ Return all objects in chain. + + Handy if the objects are not callable. + """ + return iter(self.chain) + + +def show_in_pager(self, data, start, screen_lines): + """ Run a string through pager """ + # raising TryNext here will use the default paging functionality + raise TryNext + + +def pre_prompt_hook(self): + """ Run before displaying the next prompt + + Use this e.g. to display output from asynchronous operations (in order + to not mess up text entry) + """ + + return None + + +def clipboard_get(self): + """ Get text from the clipboard. + """ + from ..lib.clipboard import ( + osx_clipboard_get, + tkinter_clipboard_get, + win32_clipboard_get, + wayland_clipboard_get, + ) + if sys.platform == 'win32': + chain = [win32_clipboard_get, tkinter_clipboard_get] + elif sys.platform == 'darwin': + chain = [osx_clipboard_get, tkinter_clipboard_get] + else: + chain = [wayland_clipboard_get, tkinter_clipboard_get] + dispatcher = CommandChainDispatcher() + for func in chain: + dispatcher.add(func) + text = dispatcher() + return text diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/latex_symbols.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/latex_symbols.py new file mode 100644 index 0000000000000000000000000000000000000000..164d917beb64cb0bd44c67a3391a3ab051ca7609 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/latex_symbols.py @@ -0,0 +1,1301 @@ +# encoding: utf-8 + +# DO NOT EDIT THIS FILE BY HAND. + +# To update this file, run the script /tools/gen_latex_symbols.py using Python 3 + +# This file is autogenerated from the file: +# https://raw.githubusercontent.com/JuliaLang/julia/master/base/latex_symbols.jl +# This original list is filtered to remove any unicode characters that are not valid +# Python identifiers. + +latex_symbols = { + + "\\euler" : "ℯ", + "\\^a" : "ᵃ", + "\\^b" : "ᵇ", + "\\^c" : "ᶜ", + "\\^d" : "ᵈ", + "\\^e" : "ᵉ", + "\\^f" : "ᶠ", + "\\^g" : "ᵍ", + "\\^h" : "ʰ", + "\\^i" : "ⁱ", + "\\^j" : "ʲ", + "\\^k" : "ᵏ", + "\\^l" : "ˡ", + "\\^m" : "ᵐ", + "\\^n" : "ⁿ", + "\\^o" : "ᵒ", + "\\^p" : "ᵖ", + "\\^r" : "ʳ", + "\\^s" : "ˢ", + "\\^t" : "ᵗ", + "\\^u" : "ᵘ", + "\\^v" : "ᵛ", + "\\^w" : "ʷ", + "\\^x" : "ˣ", + "\\^y" : "ʸ", + "\\^z" : "ᶻ", + "\\^A" : "ᴬ", + "\\^B" : "ᴮ", + "\\^D" : "ᴰ", + "\\^E" : "ᴱ", + "\\^G" : "ᴳ", + "\\^H" : "ᴴ", + "\\^I" : "ᴵ", + "\\^J" : "ᴶ", + "\\^K" : "ᴷ", + "\\^L" : "ᴸ", + "\\^M" : "ᴹ", + "\\^N" : "ᴺ", + "\\^O" : "ᴼ", + "\\^P" : "ᴾ", + "\\^R" : "ᴿ", + "\\^T" : "ᵀ", + "\\^U" : "ᵁ", + "\\^V" : "ⱽ", + "\\^W" : "ᵂ", + "\\^alpha" : "ᵅ", + "\\^beta" : "ᵝ", + "\\^gamma" : "ᵞ", + "\\^delta" : "ᵟ", + "\\^epsilon" : "ᵋ", + "\\^theta" : "ᶿ", + "\\^iota" : "ᶥ", + "\\^phi" : "ᵠ", + "\\^chi" : "ᵡ", + "\\^Phi" : "ᶲ", + "\\_a" : "ₐ", + "\\_e" : "ₑ", + "\\_h" : "ₕ", + "\\_i" : "ᵢ", + "\\_j" : "ⱼ", + "\\_k" : "ₖ", + "\\_l" : "ₗ", + "\\_m" : "ₘ", + "\\_n" : "ₙ", + "\\_o" : "ₒ", + "\\_p" : "ₚ", + "\\_r" : "ᵣ", + "\\_s" : "ₛ", + "\\_t" : "ₜ", + "\\_u" : "ᵤ", + "\\_v" : "ᵥ", + "\\_x" : "ₓ", + "\\_schwa" : "ₔ", + "\\_beta" : "ᵦ", + "\\_gamma" : "ᵧ", + "\\_rho" : "ᵨ", + "\\_phi" : "ᵩ", + "\\_chi" : "ᵪ", + "\\hbar" : "ħ", + "\\sout" : "̶", + "\\ordfeminine" : "ª", + "\\cdotp" : "·", + "\\ordmasculine" : "º", + "\\AA" : "Å", + "\\AE" : "Æ", + "\\DH" : "Ð", + "\\O" : "Ø", + "\\TH" : "Þ", + "\\ss" : "ß", + "\\aa" : "å", + "\\ae" : "æ", + "\\eth" : "ð", + "\\dh" : "ð", + "\\o" : "ø", + "\\th" : "þ", + "\\DJ" : "Đ", + "\\dj" : "đ", + "\\imath" : "ı", + "\\jmath" : "ȷ", + "\\L" : "Ł", + "\\l" : "ł", + "\\NG" : "Ŋ", + "\\ng" : "ŋ", + "\\OE" : "Œ", + "\\oe" : "œ", + "\\hvlig" : "ƕ", + "\\nrleg" : "ƞ", + "\\doublepipe" : "ǂ", + "\\trna" : "ɐ", + "\\trnsa" : "ɒ", + "\\openo" : "ɔ", + "\\rtld" : "ɖ", + "\\schwa" : "ə", + "\\varepsilon" : "ε", + "\\pgamma" : "ɣ", + "\\pbgam" : "ɤ", + "\\trnh" : "ɥ", + "\\btdl" : "ɬ", + "\\rtll" : "ɭ", + "\\trnm" : "ɯ", + "\\trnmlr" : "ɰ", + "\\ltlmr" : "ɱ", + "\\ltln" : "ɲ", + "\\rtln" : "ɳ", + "\\clomeg" : "ɷ", + "\\ltphi" : "ɸ", + "\\trnr" : "ɹ", + "\\trnrl" : "ɺ", + "\\rttrnr" : "ɻ", + "\\rl" : "ɼ", + "\\rtlr" : "ɽ", + "\\fhr" : "ɾ", + "\\rtls" : "ʂ", + "\\esh" : "ʃ", + "\\trnt" : "ʇ", + "\\rtlt" : "ʈ", + "\\pupsil" : "ʊ", + "\\pscrv" : "ʋ", + "\\invv" : "ʌ", + "\\invw" : "ʍ", + "\\trny" : "ʎ", + "\\rtlz" : "ʐ", + "\\yogh" : "ʒ", + "\\glst" : "ʔ", + "\\reglst" : "ʕ", + "\\inglst" : "ʖ", + "\\turnk" : "ʞ", + "\\dyogh" : "ʤ", + "\\tesh" : "ʧ", + "\\rasp" : "ʼ", + "\\verts" : "ˈ", + "\\verti" : "ˌ", + "\\lmrk" : "ː", + "\\hlmrk" : "ˑ", + "\\grave" : "̀", + "\\acute" : "́", + "\\hat" : "̂", + "\\tilde" : "̃", + "\\bar" : "̄", + "\\breve" : "̆", + "\\dot" : "̇", + "\\ddot" : "̈", + "\\ocirc" : "̊", + "\\H" : "̋", + "\\check" : "̌", + "\\palh" : "̡", + "\\rh" : "̢", + "\\c" : "̧", + "\\k" : "̨", + "\\sbbrg" : "̪", + "\\strike" : "̶", + "\\Alpha" : "Α", + "\\Beta" : "Β", + "\\Gamma" : "Γ", + "\\Delta" : "Δ", + "\\Epsilon" : "Ε", + "\\Zeta" : "Ζ", + "\\Eta" : "Η", + "\\Theta" : "Θ", + "\\Iota" : "Ι", + "\\Kappa" : "Κ", + "\\Lambda" : "Λ", + "\\Xi" : "Ξ", + "\\Pi" : "Π", + "\\Rho" : "Ρ", + "\\Sigma" : "Σ", + "\\Tau" : "Τ", + "\\Upsilon" : "Υ", + "\\Phi" : "Φ", + "\\Chi" : "Χ", + "\\Psi" : "Ψ", + "\\Omega" : "Ω", + "\\alpha" : "α", + "\\beta" : "β", + "\\gamma" : "γ", + "\\delta" : "δ", + "\\zeta" : "ζ", + "\\eta" : "η", + "\\theta" : "θ", + "\\iota" : "ι", + "\\kappa" : "κ", + "\\lambda" : "λ", + "\\mu" : "μ", + "\\nu" : "ν", + "\\xi" : "ξ", + "\\pi" : "π", + "\\rho" : "ρ", + "\\varsigma" : "ς", + "\\sigma" : "σ", + "\\tau" : "τ", + "\\upsilon" : "υ", + "\\varphi" : "φ", + "\\chi" : "χ", + "\\psi" : "ψ", + "\\omega" : "ω", + "\\vartheta" : "ϑ", + "\\phi" : "ϕ", + "\\varpi" : "ϖ", + "\\Stigma" : "Ϛ", + "\\Digamma" : "Ϝ", + "\\digamma" : "ϝ", + "\\Koppa" : "Ϟ", + "\\Sampi" : "Ϡ", + "\\varkappa" : "ϰ", + "\\varrho" : "ϱ", + "\\varTheta" : "ϴ", + "\\epsilon" : "ϵ", + "\\dddot" : "⃛", + "\\ddddot" : "⃜", + "\\hslash" : "ℏ", + "\\Im" : "ℑ", + "\\ell" : "ℓ", + "\\wp" : "℘", + "\\Re" : "ℜ", + "\\aleph" : "ℵ", + "\\beth" : "ℶ", + "\\gimel" : "ℷ", + "\\daleth" : "ℸ", + "\\bbPi" : "ℿ", + "\\Zbar" : "Ƶ", + "\\overbar" : "̅", + "\\ovhook" : "̉", + "\\candra" : "̐", + "\\oturnedcomma" : "̒", + "\\ocommatopright" : "̕", + "\\droang" : "̚", + "\\wideutilde" : "̰", + "\\not" : "̸", + "\\upMu" : "Μ", + "\\upNu" : "Ν", + "\\upOmicron" : "Ο", + "\\upepsilon" : "ε", + "\\upomicron" : "ο", + "\\upvarbeta" : "ϐ", + "\\upoldKoppa" : "Ϙ", + "\\upoldkoppa" : "ϙ", + "\\upstigma" : "ϛ", + "\\upkoppa" : "ϟ", + "\\upsampi" : "ϡ", + "\\tieconcat" : "⁀", + "\\leftharpoonaccent" : "⃐", + "\\rightharpoonaccent" : "⃑", + "\\vertoverlay" : "⃒", + "\\overleftarrow" : "⃖", + "\\vec" : "⃗", + "\\overleftrightarrow" : "⃡", + "\\annuity" : "⃧", + "\\threeunderdot" : "⃨", + "\\widebridgeabove" : "⃩", + "\\bbC" : "ℂ", + "\\eulermascheroni" : "ℇ", + "\\scrg" : "ℊ", + "\\scrH" : "ℋ", + "\\frakH" : "ℌ", + "\\bbH" : "ℍ", + "\\planck" : "ℎ", + "\\scrI" : "ℐ", + "\\scrL" : "ℒ", + "\\bbN" : "ℕ", + "\\bbP" : "ℙ", + "\\bbQ" : "ℚ", + "\\scrR" : "ℛ", + "\\bbR" : "ℝ", + "\\bbZ" : "ℤ", + "\\frakZ" : "ℨ", + "\\Angstrom" : "Å", + "\\scrB" : "ℬ", + "\\frakC" : "ℭ", + "\\scre" : "ℯ", + "\\scrE" : "ℰ", + "\\scrF" : "ℱ", + "\\Finv" : "Ⅎ", + "\\scrM" : "ℳ", + "\\scro" : "ℴ", + "\\bbgamma" : "ℽ", + "\\bbGamma" : "ℾ", + "\\bbiD" : "ⅅ", + "\\bbid" : "ⅆ", + "\\bbie" : "ⅇ", + "\\bbii" : "ⅈ", + "\\bbij" : "ⅉ", + "\\bfA" : "𝐀", + "\\bfB" : "𝐁", + "\\bfC" : "𝐂", + "\\bfD" : "𝐃", + "\\bfE" : "𝐄", + "\\bfF" : "𝐅", + "\\bfG" : "𝐆", + "\\bfH" : "𝐇", + "\\bfI" : "𝐈", + "\\bfJ" : "𝐉", + "\\bfK" : "𝐊", + "\\bfL" : "𝐋", + "\\bfM" : "𝐌", + "\\bfN" : "𝐍", + "\\bfO" : "𝐎", + "\\bfP" : "𝐏", + "\\bfQ" : "𝐐", + "\\bfR" : "𝐑", + "\\bfS" : "𝐒", + "\\bfT" : "𝐓", + "\\bfU" : "𝐔", + "\\bfV" : "𝐕", + "\\bfW" : "𝐖", + "\\bfX" : "𝐗", + "\\bfY" : "𝐘", + "\\bfZ" : "𝐙", + "\\bfa" : "𝐚", + "\\bfb" : "𝐛", + "\\bfc" : "𝐜", + "\\bfd" : "𝐝", + "\\bfe" : "𝐞", + "\\bff" : "𝐟", + "\\bfg" : "𝐠", + "\\bfh" : "𝐡", + "\\bfi" : "𝐢", + "\\bfj" : "𝐣", + "\\bfk" : "𝐤", + "\\bfl" : "𝐥", + "\\bfm" : "𝐦", + "\\bfn" : "𝐧", + "\\bfo" : "𝐨", + "\\bfp" : "𝐩", + "\\bfq" : "𝐪", + "\\bfr" : "𝐫", + "\\bfs" : "𝐬", + "\\bft" : "𝐭", + "\\bfu" : "𝐮", + "\\bfv" : "𝐯", + "\\bfw" : "𝐰", + "\\bfx" : "𝐱", + "\\bfy" : "𝐲", + "\\bfz" : "𝐳", + "\\itA" : "𝐴", + "\\itB" : "𝐵", + "\\itC" : "𝐶", + "\\itD" : "𝐷", + "\\itE" : "𝐸", + "\\itF" : "𝐹", + "\\itG" : "𝐺", + "\\itH" : "𝐻", + "\\itI" : "𝐼", + "\\itJ" : "𝐽", + "\\itK" : "𝐾", + "\\itL" : "𝐿", + "\\itM" : "𝑀", + "\\itN" : "𝑁", + "\\itO" : "𝑂", + "\\itP" : "𝑃", + "\\itQ" : "𝑄", + "\\itR" : "𝑅", + "\\itS" : "𝑆", + "\\itT" : "𝑇", + "\\itU" : "𝑈", + "\\itV" : "𝑉", + "\\itW" : "𝑊", + "\\itX" : "𝑋", + "\\itY" : "𝑌", + "\\itZ" : "𝑍", + "\\ita" : "𝑎", + "\\itb" : "𝑏", + "\\itc" : "𝑐", + "\\itd" : "𝑑", + "\\ite" : "𝑒", + "\\itf" : "𝑓", + "\\itg" : "𝑔", + "\\iti" : "𝑖", + "\\itj" : "𝑗", + "\\itk" : "𝑘", + "\\itl" : "𝑙", + "\\itm" : "𝑚", + "\\itn" : "𝑛", + "\\ito" : "𝑜", + "\\itp" : "𝑝", + "\\itq" : "𝑞", + "\\itr" : "𝑟", + "\\its" : "𝑠", + "\\itt" : "𝑡", + "\\itu" : "𝑢", + "\\itv" : "𝑣", + "\\itw" : "𝑤", + "\\itx" : "𝑥", + "\\ity" : "𝑦", + "\\itz" : "𝑧", + "\\biA" : "𝑨", + "\\biB" : "𝑩", + "\\biC" : "𝑪", + "\\biD" : "𝑫", + "\\biE" : "𝑬", + "\\biF" : "𝑭", + "\\biG" : "𝑮", + "\\biH" : "𝑯", + "\\biI" : "𝑰", + "\\biJ" : "𝑱", + "\\biK" : "𝑲", + "\\biL" : "𝑳", + "\\biM" : "𝑴", + "\\biN" : "𝑵", + "\\biO" : "𝑶", + "\\biP" : "𝑷", + "\\biQ" : "𝑸", + "\\biR" : "𝑹", + "\\biS" : "𝑺", + "\\biT" : "𝑻", + "\\biU" : "𝑼", + "\\biV" : "𝑽", + "\\biW" : "𝑾", + "\\biX" : "𝑿", + "\\biY" : "𝒀", + "\\biZ" : "𝒁", + "\\bia" : "𝒂", + "\\bib" : "𝒃", + "\\bic" : "𝒄", + "\\bid" : "𝒅", + "\\bie" : "𝒆", + "\\bif" : "𝒇", + "\\big" : "𝒈", + "\\bih" : "𝒉", + "\\bii" : "𝒊", + "\\bij" : "𝒋", + "\\bik" : "𝒌", + "\\bil" : "𝒍", + "\\bim" : "𝒎", + "\\bin" : "𝒏", + "\\bio" : "𝒐", + "\\bip" : "𝒑", + "\\biq" : "𝒒", + "\\bir" : "𝒓", + "\\bis" : "𝒔", + "\\bit" : "𝒕", + "\\biu" : "𝒖", + "\\biv" : "𝒗", + "\\biw" : "𝒘", + "\\bix" : "𝒙", + "\\biy" : "𝒚", + "\\biz" : "𝒛", + "\\scrA" : "𝒜", + "\\scrC" : "𝒞", + "\\scrD" : "𝒟", + "\\scrG" : "𝒢", + "\\scrJ" : "𝒥", + "\\scrK" : "𝒦", + "\\scrN" : "𝒩", + "\\scrO" : "𝒪", + "\\scrP" : "𝒫", + "\\scrQ" : "𝒬", + "\\scrS" : "𝒮", + "\\scrT" : "𝒯", + "\\scrU" : "𝒰", + "\\scrV" : "𝒱", + "\\scrW" : "𝒲", + "\\scrX" : "𝒳", + "\\scrY" : "𝒴", + "\\scrZ" : "𝒵", + "\\scra" : "𝒶", + "\\scrb" : "𝒷", + "\\scrc" : "𝒸", + "\\scrd" : "𝒹", + "\\scrf" : "𝒻", + "\\scrh" : "𝒽", + "\\scri" : "𝒾", + "\\scrj" : "𝒿", + "\\scrk" : "𝓀", + "\\scrm" : "𝓂", + "\\scrn" : "𝓃", + "\\scrp" : "𝓅", + "\\scrq" : "𝓆", + "\\scrr" : "𝓇", + "\\scrs" : "𝓈", + "\\scrt" : "𝓉", + "\\scru" : "𝓊", + "\\scrv" : "𝓋", + "\\scrw" : "𝓌", + "\\scrx" : "𝓍", + "\\scry" : "𝓎", + "\\scrz" : "𝓏", + "\\bscrA" : "𝓐", + "\\bscrB" : "𝓑", + "\\bscrC" : "𝓒", + "\\bscrD" : "𝓓", + "\\bscrE" : "𝓔", + "\\bscrF" : "𝓕", + "\\bscrG" : "𝓖", + "\\bscrH" : "𝓗", + "\\bscrI" : "𝓘", + "\\bscrJ" : "𝓙", + "\\bscrK" : "𝓚", + "\\bscrL" : "𝓛", + "\\bscrM" : "𝓜", + "\\bscrN" : "𝓝", + "\\bscrO" : "𝓞", + "\\bscrP" : "𝓟", + "\\bscrQ" : "𝓠", + "\\bscrR" : "𝓡", + "\\bscrS" : "𝓢", + "\\bscrT" : "𝓣", + "\\bscrU" : "𝓤", + "\\bscrV" : "𝓥", + "\\bscrW" : "𝓦", + "\\bscrX" : "𝓧", + "\\bscrY" : "𝓨", + "\\bscrZ" : "𝓩", + "\\bscra" : "𝓪", + "\\bscrb" : "𝓫", + "\\bscrc" : "𝓬", + "\\bscrd" : "𝓭", + "\\bscre" : "𝓮", + "\\bscrf" : "𝓯", + "\\bscrg" : "𝓰", + "\\bscrh" : "𝓱", + "\\bscri" : "𝓲", + "\\bscrj" : "𝓳", + "\\bscrk" : "𝓴", + "\\bscrl" : "𝓵", + "\\bscrm" : "𝓶", + "\\bscrn" : "𝓷", + "\\bscro" : "𝓸", + "\\bscrp" : "𝓹", + "\\bscrq" : "𝓺", + "\\bscrr" : "𝓻", + "\\bscrs" : "𝓼", + "\\bscrt" : "𝓽", + "\\bscru" : "𝓾", + "\\bscrv" : "𝓿", + "\\bscrw" : "𝔀", + "\\bscrx" : "𝔁", + "\\bscry" : "𝔂", + "\\bscrz" : "𝔃", + "\\frakA" : "𝔄", + "\\frakB" : "𝔅", + "\\frakD" : "𝔇", + "\\frakE" : "𝔈", + "\\frakF" : "𝔉", + "\\frakG" : "𝔊", + "\\frakJ" : "𝔍", + "\\frakK" : "𝔎", + "\\frakL" : "𝔏", + "\\frakM" : "𝔐", + "\\frakN" : "𝔑", + "\\frakO" : "𝔒", + "\\frakP" : "𝔓", + "\\frakQ" : "𝔔", + "\\frakS" : "𝔖", + "\\frakT" : "𝔗", + "\\frakU" : "𝔘", + "\\frakV" : "𝔙", + "\\frakW" : "𝔚", + "\\frakX" : "𝔛", + "\\frakY" : "𝔜", + "\\fraka" : "𝔞", + "\\frakb" : "𝔟", + "\\frakc" : "𝔠", + "\\frakd" : "𝔡", + "\\frake" : "𝔢", + "\\frakf" : "𝔣", + "\\frakg" : "𝔤", + "\\frakh" : "𝔥", + "\\fraki" : "𝔦", + "\\frakj" : "𝔧", + "\\frakk" : "𝔨", + "\\frakl" : "𝔩", + "\\frakm" : "𝔪", + "\\frakn" : "𝔫", + "\\frako" : "𝔬", + "\\frakp" : "𝔭", + "\\frakq" : "𝔮", + "\\frakr" : "𝔯", + "\\fraks" : "𝔰", + "\\frakt" : "𝔱", + "\\fraku" : "𝔲", + "\\frakv" : "𝔳", + "\\frakw" : "𝔴", + "\\frakx" : "𝔵", + "\\fraky" : "𝔶", + "\\frakz" : "𝔷", + "\\bbA" : "𝔸", + "\\bbB" : "𝔹", + "\\bbD" : "𝔻", + "\\bbE" : "𝔼", + "\\bbF" : "𝔽", + "\\bbG" : "𝔾", + "\\bbI" : "𝕀", + "\\bbJ" : "𝕁", + "\\bbK" : "𝕂", + "\\bbL" : "𝕃", + "\\bbM" : "𝕄", + "\\bbO" : "𝕆", + "\\bbS" : "𝕊", + "\\bbT" : "𝕋", + "\\bbU" : "𝕌", + "\\bbV" : "𝕍", + "\\bbW" : "𝕎", + "\\bbX" : "𝕏", + "\\bbY" : "𝕐", + "\\bba" : "𝕒", + "\\bbb" : "𝕓", + "\\bbc" : "𝕔", + "\\bbd" : "𝕕", + "\\bbe" : "𝕖", + "\\bbf" : "𝕗", + "\\bbg" : "𝕘", + "\\bbh" : "𝕙", + "\\bbi" : "𝕚", + "\\bbj" : "𝕛", + "\\bbk" : "𝕜", + "\\bbl" : "𝕝", + "\\bbm" : "𝕞", + "\\bbn" : "𝕟", + "\\bbo" : "𝕠", + "\\bbp" : "𝕡", + "\\bbq" : "𝕢", + "\\bbr" : "𝕣", + "\\bbs" : "𝕤", + "\\bbt" : "𝕥", + "\\bbu" : "𝕦", + "\\bbv" : "𝕧", + "\\bbw" : "𝕨", + "\\bbx" : "𝕩", + "\\bby" : "𝕪", + "\\bbz" : "𝕫", + "\\bfrakA" : "𝕬", + "\\bfrakB" : "𝕭", + "\\bfrakC" : "𝕮", + "\\bfrakD" : "𝕯", + "\\bfrakE" : "𝕰", + "\\bfrakF" : "𝕱", + "\\bfrakG" : "𝕲", + "\\bfrakH" : "𝕳", + "\\bfrakI" : "𝕴", + "\\bfrakJ" : "𝕵", + "\\bfrakK" : "𝕶", + "\\bfrakL" : "𝕷", + "\\bfrakM" : "𝕸", + "\\bfrakN" : "𝕹", + "\\bfrakO" : "𝕺", + "\\bfrakP" : "𝕻", + "\\bfrakQ" : "𝕼", + "\\bfrakR" : "𝕽", + "\\bfrakS" : "𝕾", + "\\bfrakT" : "𝕿", + "\\bfrakU" : "𝖀", + "\\bfrakV" : "𝖁", + "\\bfrakW" : "𝖂", + "\\bfrakX" : "𝖃", + "\\bfrakY" : "𝖄", + "\\bfrakZ" : "𝖅", + "\\bfraka" : "𝖆", + "\\bfrakb" : "𝖇", + "\\bfrakc" : "𝖈", + "\\bfrakd" : "𝖉", + "\\bfrake" : "𝖊", + "\\bfrakf" : "𝖋", + "\\bfrakg" : "𝖌", + "\\bfrakh" : "𝖍", + "\\bfraki" : "𝖎", + "\\bfrakj" : "𝖏", + "\\bfrakk" : "𝖐", + "\\bfrakl" : "𝖑", + "\\bfrakm" : "𝖒", + "\\bfrakn" : "𝖓", + "\\bfrako" : "𝖔", + "\\bfrakp" : "𝖕", + "\\bfrakq" : "𝖖", + "\\bfrakr" : "𝖗", + "\\bfraks" : "𝖘", + "\\bfrakt" : "𝖙", + "\\bfraku" : "𝖚", + "\\bfrakv" : "𝖛", + "\\bfrakw" : "𝖜", + "\\bfrakx" : "𝖝", + "\\bfraky" : "𝖞", + "\\bfrakz" : "𝖟", + "\\sansA" : "𝖠", + "\\sansB" : "𝖡", + "\\sansC" : "𝖢", + "\\sansD" : "𝖣", + "\\sansE" : "𝖤", + "\\sansF" : "𝖥", + "\\sansG" : "𝖦", + "\\sansH" : "𝖧", + "\\sansI" : "𝖨", + "\\sansJ" : "𝖩", + "\\sansK" : "𝖪", + "\\sansL" : "𝖫", + "\\sansM" : "𝖬", + "\\sansN" : "𝖭", + "\\sansO" : "𝖮", + "\\sansP" : "𝖯", + "\\sansQ" : "𝖰", + "\\sansR" : "𝖱", + "\\sansS" : "𝖲", + "\\sansT" : "𝖳", + "\\sansU" : "𝖴", + "\\sansV" : "𝖵", + "\\sansW" : "𝖶", + "\\sansX" : "𝖷", + "\\sansY" : "𝖸", + "\\sansZ" : "𝖹", + "\\sansa" : "𝖺", + "\\sansb" : "𝖻", + "\\sansc" : "𝖼", + "\\sansd" : "𝖽", + "\\sanse" : "𝖾", + "\\sansf" : "𝖿", + "\\sansg" : "𝗀", + "\\sansh" : "𝗁", + "\\sansi" : "𝗂", + "\\sansj" : "𝗃", + "\\sansk" : "𝗄", + "\\sansl" : "𝗅", + "\\sansm" : "𝗆", + "\\sansn" : "𝗇", + "\\sanso" : "𝗈", + "\\sansp" : "𝗉", + "\\sansq" : "𝗊", + "\\sansr" : "𝗋", + "\\sanss" : "𝗌", + "\\sanst" : "𝗍", + "\\sansu" : "𝗎", + "\\sansv" : "𝗏", + "\\sansw" : "𝗐", + "\\sansx" : "𝗑", + "\\sansy" : "𝗒", + "\\sansz" : "𝗓", + "\\bsansA" : "𝗔", + "\\bsansB" : "𝗕", + "\\bsansC" : "𝗖", + "\\bsansD" : "𝗗", + "\\bsansE" : "𝗘", + "\\bsansF" : "𝗙", + "\\bsansG" : "𝗚", + "\\bsansH" : "𝗛", + "\\bsansI" : "𝗜", + "\\bsansJ" : "𝗝", + "\\bsansK" : "𝗞", + "\\bsansL" : "𝗟", + "\\bsansM" : "𝗠", + "\\bsansN" : "𝗡", + "\\bsansO" : "𝗢", + "\\bsansP" : "𝗣", + "\\bsansQ" : "𝗤", + "\\bsansR" : "𝗥", + "\\bsansS" : "𝗦", + "\\bsansT" : "𝗧", + "\\bsansU" : "𝗨", + "\\bsansV" : "𝗩", + "\\bsansW" : "𝗪", + "\\bsansX" : "𝗫", + "\\bsansY" : "𝗬", + "\\bsansZ" : "𝗭", + "\\bsansa" : "𝗮", + "\\bsansb" : "𝗯", + "\\bsansc" : "𝗰", + "\\bsansd" : "𝗱", + "\\bsanse" : "𝗲", + "\\bsansf" : "𝗳", + "\\bsansg" : "𝗴", + "\\bsansh" : "𝗵", + "\\bsansi" : "𝗶", + "\\bsansj" : "𝗷", + "\\bsansk" : "𝗸", + "\\bsansl" : "𝗹", + "\\bsansm" : "𝗺", + "\\bsansn" : "𝗻", + "\\bsanso" : "𝗼", + "\\bsansp" : "𝗽", + "\\bsansq" : "𝗾", + "\\bsansr" : "𝗿", + "\\bsanss" : "𝘀", + "\\bsanst" : "𝘁", + "\\bsansu" : "𝘂", + "\\bsansv" : "𝘃", + "\\bsansw" : "𝘄", + "\\bsansx" : "𝘅", + "\\bsansy" : "𝘆", + "\\bsansz" : "𝘇", + "\\isansA" : "𝘈", + "\\isansB" : "𝘉", + "\\isansC" : "𝘊", + "\\isansD" : "𝘋", + "\\isansE" : "𝘌", + "\\isansF" : "𝘍", + "\\isansG" : "𝘎", + "\\isansH" : "𝘏", + "\\isansI" : "𝘐", + "\\isansJ" : "𝘑", + "\\isansK" : "𝘒", + "\\isansL" : "𝘓", + "\\isansM" : "𝘔", + "\\isansN" : "𝘕", + "\\isansO" : "𝘖", + "\\isansP" : "𝘗", + "\\isansQ" : "𝘘", + "\\isansR" : "𝘙", + "\\isansS" : "𝘚", + "\\isansT" : "𝘛", + "\\isansU" : "𝘜", + "\\isansV" : "𝘝", + "\\isansW" : "𝘞", + "\\isansX" : "𝘟", + "\\isansY" : "𝘠", + "\\isansZ" : "𝘡", + "\\isansa" : "𝘢", + "\\isansb" : "𝘣", + "\\isansc" : "𝘤", + "\\isansd" : "𝘥", + "\\isanse" : "𝘦", + "\\isansf" : "𝘧", + "\\isansg" : "𝘨", + "\\isansh" : "𝘩", + "\\isansi" : "𝘪", + "\\isansj" : "𝘫", + "\\isansk" : "𝘬", + "\\isansl" : "𝘭", + "\\isansm" : "𝘮", + "\\isansn" : "𝘯", + "\\isanso" : "𝘰", + "\\isansp" : "𝘱", + "\\isansq" : "𝘲", + "\\isansr" : "𝘳", + "\\isanss" : "𝘴", + "\\isanst" : "𝘵", + "\\isansu" : "𝘶", + "\\isansv" : "𝘷", + "\\isansw" : "𝘸", + "\\isansx" : "𝘹", + "\\isansy" : "𝘺", + "\\isansz" : "𝘻", + "\\bisansA" : "𝘼", + "\\bisansB" : "𝘽", + "\\bisansC" : "𝘾", + "\\bisansD" : "𝘿", + "\\bisansE" : "𝙀", + "\\bisansF" : "𝙁", + "\\bisansG" : "𝙂", + "\\bisansH" : "𝙃", + "\\bisansI" : "𝙄", + "\\bisansJ" : "𝙅", + "\\bisansK" : "𝙆", + "\\bisansL" : "𝙇", + "\\bisansM" : "𝙈", + "\\bisansN" : "𝙉", + "\\bisansO" : "𝙊", + "\\bisansP" : "𝙋", + "\\bisansQ" : "𝙌", + "\\bisansR" : "𝙍", + "\\bisansS" : "𝙎", + "\\bisansT" : "𝙏", + "\\bisansU" : "𝙐", + "\\bisansV" : "𝙑", + "\\bisansW" : "𝙒", + "\\bisansX" : "𝙓", + "\\bisansY" : "𝙔", + "\\bisansZ" : "𝙕", + "\\bisansa" : "𝙖", + "\\bisansb" : "𝙗", + "\\bisansc" : "𝙘", + "\\bisansd" : "𝙙", + "\\bisanse" : "𝙚", + "\\bisansf" : "𝙛", + "\\bisansg" : "𝙜", + "\\bisansh" : "𝙝", + "\\bisansi" : "𝙞", + "\\bisansj" : "𝙟", + "\\bisansk" : "𝙠", + "\\bisansl" : "𝙡", + "\\bisansm" : "𝙢", + "\\bisansn" : "𝙣", + "\\bisanso" : "𝙤", + "\\bisansp" : "𝙥", + "\\bisansq" : "𝙦", + "\\bisansr" : "𝙧", + "\\bisanss" : "𝙨", + "\\bisanst" : "𝙩", + "\\bisansu" : "𝙪", + "\\bisansv" : "𝙫", + "\\bisansw" : "𝙬", + "\\bisansx" : "𝙭", + "\\bisansy" : "𝙮", + "\\bisansz" : "𝙯", + "\\ttA" : "𝙰", + "\\ttB" : "𝙱", + "\\ttC" : "𝙲", + "\\ttD" : "𝙳", + "\\ttE" : "𝙴", + "\\ttF" : "𝙵", + "\\ttG" : "𝙶", + "\\ttH" : "𝙷", + "\\ttI" : "𝙸", + "\\ttJ" : "𝙹", + "\\ttK" : "𝙺", + "\\ttL" : "𝙻", + "\\ttM" : "𝙼", + "\\ttN" : "𝙽", + "\\ttO" : "𝙾", + "\\ttP" : "𝙿", + "\\ttQ" : "𝚀", + "\\ttR" : "𝚁", + "\\ttS" : "𝚂", + "\\ttT" : "𝚃", + "\\ttU" : "𝚄", + "\\ttV" : "𝚅", + "\\ttW" : "𝚆", + "\\ttX" : "𝚇", + "\\ttY" : "𝚈", + "\\ttZ" : "𝚉", + "\\tta" : "𝚊", + "\\ttb" : "𝚋", + "\\ttc" : "𝚌", + "\\ttd" : "𝚍", + "\\tte" : "𝚎", + "\\ttf" : "𝚏", + "\\ttg" : "𝚐", + "\\tth" : "𝚑", + "\\tti" : "𝚒", + "\\ttj" : "𝚓", + "\\ttk" : "𝚔", + "\\ttl" : "𝚕", + "\\ttm" : "𝚖", + "\\ttn" : "𝚗", + "\\tto" : "𝚘", + "\\ttp" : "𝚙", + "\\ttq" : "𝚚", + "\\ttr" : "𝚛", + "\\tts" : "𝚜", + "\\ttt" : "𝚝", + "\\ttu" : "𝚞", + "\\ttv" : "𝚟", + "\\ttw" : "𝚠", + "\\ttx" : "𝚡", + "\\tty" : "𝚢", + "\\ttz" : "𝚣", + "\\bfAlpha" : "𝚨", + "\\bfBeta" : "𝚩", + "\\bfGamma" : "𝚪", + "\\bfDelta" : "𝚫", + "\\bfEpsilon" : "𝚬", + "\\bfZeta" : "𝚭", + "\\bfEta" : "𝚮", + "\\bfTheta" : "𝚯", + "\\bfIota" : "𝚰", + "\\bfKappa" : "𝚱", + "\\bfLambda" : "𝚲", + "\\bfMu" : "𝚳", + "\\bfNu" : "𝚴", + "\\bfXi" : "𝚵", + "\\bfOmicron" : "𝚶", + "\\bfPi" : "𝚷", + "\\bfRho" : "𝚸", + "\\bfvarTheta" : "𝚹", + "\\bfSigma" : "𝚺", + "\\bfTau" : "𝚻", + "\\bfUpsilon" : "𝚼", + "\\bfPhi" : "𝚽", + "\\bfChi" : "𝚾", + "\\bfPsi" : "𝚿", + "\\bfOmega" : "𝛀", + "\\bfalpha" : "𝛂", + "\\bfbeta" : "𝛃", + "\\bfgamma" : "𝛄", + "\\bfdelta" : "𝛅", + "\\bfepsilon" : "𝛆", + "\\bfzeta" : "𝛇", + "\\bfeta" : "𝛈", + "\\bftheta" : "𝛉", + "\\bfiota" : "𝛊", + "\\bfkappa" : "𝛋", + "\\bflambda" : "𝛌", + "\\bfmu" : "𝛍", + "\\bfnu" : "𝛎", + "\\bfxi" : "𝛏", + "\\bfomicron" : "𝛐", + "\\bfpi" : "𝛑", + "\\bfrho" : "𝛒", + "\\bfvarsigma" : "𝛓", + "\\bfsigma" : "𝛔", + "\\bftau" : "𝛕", + "\\bfupsilon" : "𝛖", + "\\bfvarphi" : "𝛗", + "\\bfchi" : "𝛘", + "\\bfpsi" : "𝛙", + "\\bfomega" : "𝛚", + "\\bfvarepsilon" : "𝛜", + "\\bfvartheta" : "𝛝", + "\\bfvarkappa" : "𝛞", + "\\bfphi" : "𝛟", + "\\bfvarrho" : "𝛠", + "\\bfvarpi" : "𝛡", + "\\itAlpha" : "𝛢", + "\\itBeta" : "𝛣", + "\\itGamma" : "𝛤", + "\\itDelta" : "𝛥", + "\\itEpsilon" : "𝛦", + "\\itZeta" : "𝛧", + "\\itEta" : "𝛨", + "\\itTheta" : "𝛩", + "\\itIota" : "𝛪", + "\\itKappa" : "𝛫", + "\\itLambda" : "𝛬", + "\\itMu" : "𝛭", + "\\itNu" : "𝛮", + "\\itXi" : "𝛯", + "\\itOmicron" : "𝛰", + "\\itPi" : "𝛱", + "\\itRho" : "𝛲", + "\\itvarTheta" : "𝛳", + "\\itSigma" : "𝛴", + "\\itTau" : "𝛵", + "\\itUpsilon" : "𝛶", + "\\itPhi" : "𝛷", + "\\itChi" : "𝛸", + "\\itPsi" : "𝛹", + "\\itOmega" : "𝛺", + "\\italpha" : "𝛼", + "\\itbeta" : "𝛽", + "\\itgamma" : "𝛾", + "\\itdelta" : "𝛿", + "\\itepsilon" : "𝜀", + "\\itzeta" : "𝜁", + "\\iteta" : "𝜂", + "\\ittheta" : "𝜃", + "\\itiota" : "𝜄", + "\\itkappa" : "𝜅", + "\\itlambda" : "𝜆", + "\\itmu" : "𝜇", + "\\itnu" : "𝜈", + "\\itxi" : "𝜉", + "\\itomicron" : "𝜊", + "\\itpi" : "𝜋", + "\\itrho" : "𝜌", + "\\itvarsigma" : "𝜍", + "\\itsigma" : "𝜎", + "\\ittau" : "𝜏", + "\\itupsilon" : "𝜐", + "\\itphi" : "𝜑", + "\\itchi" : "𝜒", + "\\itpsi" : "𝜓", + "\\itomega" : "𝜔", + "\\itvarepsilon" : "𝜖", + "\\itvartheta" : "𝜗", + "\\itvarkappa" : "𝜘", + "\\itvarphi" : "𝜙", + "\\itvarrho" : "𝜚", + "\\itvarpi" : "𝜛", + "\\biAlpha" : "𝜜", + "\\biBeta" : "𝜝", + "\\biGamma" : "𝜞", + "\\biDelta" : "𝜟", + "\\biEpsilon" : "𝜠", + "\\biZeta" : "𝜡", + "\\biEta" : "𝜢", + "\\biTheta" : "𝜣", + "\\biIota" : "𝜤", + "\\biKappa" : "𝜥", + "\\biLambda" : "𝜦", + "\\biMu" : "𝜧", + "\\biNu" : "𝜨", + "\\biXi" : "𝜩", + "\\biOmicron" : "𝜪", + "\\biPi" : "𝜫", + "\\biRho" : "𝜬", + "\\bivarTheta" : "𝜭", + "\\biSigma" : "𝜮", + "\\biTau" : "𝜯", + "\\biUpsilon" : "𝜰", + "\\biPhi" : "𝜱", + "\\biChi" : "𝜲", + "\\biPsi" : "𝜳", + "\\biOmega" : "𝜴", + "\\bialpha" : "𝜶", + "\\bibeta" : "𝜷", + "\\bigamma" : "𝜸", + "\\bidelta" : "𝜹", + "\\biepsilon" : "𝜺", + "\\bizeta" : "𝜻", + "\\bieta" : "𝜼", + "\\bitheta" : "𝜽", + "\\biiota" : "𝜾", + "\\bikappa" : "𝜿", + "\\bilambda" : "𝝀", + "\\bimu" : "𝝁", + "\\binu" : "𝝂", + "\\bixi" : "𝝃", + "\\biomicron" : "𝝄", + "\\bipi" : "𝝅", + "\\birho" : "𝝆", + "\\bivarsigma" : "𝝇", + "\\bisigma" : "𝝈", + "\\bitau" : "𝝉", + "\\biupsilon" : "𝝊", + "\\biphi" : "𝝋", + "\\bichi" : "𝝌", + "\\bipsi" : "𝝍", + "\\biomega" : "𝝎", + "\\bivarepsilon" : "𝝐", + "\\bivartheta" : "𝝑", + "\\bivarkappa" : "𝝒", + "\\bivarphi" : "𝝓", + "\\bivarrho" : "𝝔", + "\\bivarpi" : "𝝕", + "\\bsansAlpha" : "𝝖", + "\\bsansBeta" : "𝝗", + "\\bsansGamma" : "𝝘", + "\\bsansDelta" : "𝝙", + "\\bsansEpsilon" : "𝝚", + "\\bsansZeta" : "𝝛", + "\\bsansEta" : "𝝜", + "\\bsansTheta" : "𝝝", + "\\bsansIota" : "𝝞", + "\\bsansKappa" : "𝝟", + "\\bsansLambda" : "𝝠", + "\\bsansMu" : "𝝡", + "\\bsansNu" : "𝝢", + "\\bsansXi" : "𝝣", + "\\bsansOmicron" : "𝝤", + "\\bsansPi" : "𝝥", + "\\bsansRho" : "𝝦", + "\\bsansvarTheta" : "𝝧", + "\\bsansSigma" : "𝝨", + "\\bsansTau" : "𝝩", + "\\bsansUpsilon" : "𝝪", + "\\bsansPhi" : "𝝫", + "\\bsansChi" : "𝝬", + "\\bsansPsi" : "𝝭", + "\\bsansOmega" : "𝝮", + "\\bsansalpha" : "𝝰", + "\\bsansbeta" : "𝝱", + "\\bsansgamma" : "𝝲", + "\\bsansdelta" : "𝝳", + "\\bsansepsilon" : "𝝴", + "\\bsanszeta" : "𝝵", + "\\bsanseta" : "𝝶", + "\\bsanstheta" : "𝝷", + "\\bsansiota" : "𝝸", + "\\bsanskappa" : "𝝹", + "\\bsanslambda" : "𝝺", + "\\bsansmu" : "𝝻", + "\\bsansnu" : "𝝼", + "\\bsansxi" : "𝝽", + "\\bsansomicron" : "𝝾", + "\\bsanspi" : "𝝿", + "\\bsansrho" : "𝞀", + "\\bsansvarsigma" : "𝞁", + "\\bsanssigma" : "𝞂", + "\\bsanstau" : "𝞃", + "\\bsansupsilon" : "𝞄", + "\\bsansphi" : "𝞅", + "\\bsanschi" : "𝞆", + "\\bsanspsi" : "𝞇", + "\\bsansomega" : "𝞈", + "\\bsansvarepsilon" : "𝞊", + "\\bsansvartheta" : "𝞋", + "\\bsansvarkappa" : "𝞌", + "\\bsansvarphi" : "𝞍", + "\\bsansvarrho" : "𝞎", + "\\bsansvarpi" : "𝞏", + "\\bisansAlpha" : "𝞐", + "\\bisansBeta" : "𝞑", + "\\bisansGamma" : "𝞒", + "\\bisansDelta" : "𝞓", + "\\bisansEpsilon" : "𝞔", + "\\bisansZeta" : "𝞕", + "\\bisansEta" : "𝞖", + "\\bisansTheta" : "𝞗", + "\\bisansIota" : "𝞘", + "\\bisansKappa" : "𝞙", + "\\bisansLambda" : "𝞚", + "\\bisansMu" : "𝞛", + "\\bisansNu" : "𝞜", + "\\bisansXi" : "𝞝", + "\\bisansOmicron" : "𝞞", + "\\bisansPi" : "𝞟", + "\\bisansRho" : "𝞠", + "\\bisansvarTheta" : "𝞡", + "\\bisansSigma" : "𝞢", + "\\bisansTau" : "𝞣", + "\\bisansUpsilon" : "𝞤", + "\\bisansPhi" : "𝞥", + "\\bisansChi" : "𝞦", + "\\bisansPsi" : "𝞧", + "\\bisansOmega" : "𝞨", + "\\bisansalpha" : "𝞪", + "\\bisansbeta" : "𝞫", + "\\bisansgamma" : "𝞬", + "\\bisansdelta" : "𝞭", + "\\bisansepsilon" : "𝞮", + "\\bisanszeta" : "𝞯", + "\\bisanseta" : "𝞰", + "\\bisanstheta" : "𝞱", + "\\bisansiota" : "𝞲", + "\\bisanskappa" : "𝞳", + "\\bisanslambda" : "𝞴", + "\\bisansmu" : "𝞵", + "\\bisansnu" : "𝞶", + "\\bisansxi" : "𝞷", + "\\bisansomicron" : "𝞸", + "\\bisanspi" : "𝞹", + "\\bisansrho" : "𝞺", + "\\bisansvarsigma" : "𝞻", + "\\bisanssigma" : "𝞼", + "\\bisanstau" : "𝞽", + "\\bisansupsilon" : "𝞾", + "\\bisansphi" : "𝞿", + "\\bisanschi" : "𝟀", + "\\bisanspsi" : "𝟁", + "\\bisansomega" : "𝟂", + "\\bisansvarepsilon" : "𝟄", + "\\bisansvartheta" : "𝟅", + "\\bisansvarkappa" : "𝟆", + "\\bisansvarphi" : "𝟇", + "\\bisansvarrho" : "𝟈", + "\\bisansvarpi" : "𝟉", + "\\bfzero" : "𝟎", + "\\bfone" : "𝟏", + "\\bftwo" : "𝟐", + "\\bfthree" : "𝟑", + "\\bffour" : "𝟒", + "\\bffive" : "𝟓", + "\\bfsix" : "𝟔", + "\\bfseven" : "𝟕", + "\\bfeight" : "𝟖", + "\\bfnine" : "𝟗", + "\\bbzero" : "𝟘", + "\\bbone" : "𝟙", + "\\bbtwo" : "𝟚", + "\\bbthree" : "𝟛", + "\\bbfour" : "𝟜", + "\\bbfive" : "𝟝", + "\\bbsix" : "𝟞", + "\\bbseven" : "𝟟", + "\\bbeight" : "𝟠", + "\\bbnine" : "𝟡", + "\\sanszero" : "𝟢", + "\\sansone" : "𝟣", + "\\sanstwo" : "𝟤", + "\\sansthree" : "𝟥", + "\\sansfour" : "𝟦", + "\\sansfive" : "𝟧", + "\\sanssix" : "𝟨", + "\\sansseven" : "𝟩", + "\\sanseight" : "𝟪", + "\\sansnine" : "𝟫", + "\\bsanszero" : "𝟬", + "\\bsansone" : "𝟭", + "\\bsanstwo" : "𝟮", + "\\bsansthree" : "𝟯", + "\\bsansfour" : "𝟰", + "\\bsansfive" : "𝟱", + "\\bsanssix" : "𝟲", + "\\bsansseven" : "𝟳", + "\\bsanseight" : "𝟴", + "\\bsansnine" : "𝟵", + "\\ttzero" : "𝟶", + "\\ttone" : "𝟷", + "\\tttwo" : "𝟸", + "\\ttthree" : "𝟹", + "\\ttfour" : "𝟺", + "\\ttfive" : "𝟻", + "\\ttsix" : "𝟼", + "\\ttseven" : "𝟽", + "\\tteight" : "𝟾", + "\\ttnine" : "𝟿", + "\\underbar" : "̲", + "\\underleftrightarrow" : "͍", +} + + +reverse_latex_symbol = { v:k for k,v in latex_symbols.items()} diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/logger.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..101665bcc217233035477f2625840d1141ba341f --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/logger.py @@ -0,0 +1,231 @@ +"""Logger class for IPython's logging facilities. +""" + +#***************************************************************************** +# Copyright (C) 2001 Janko Hauser and +# Copyright (C) 2001-2006 Fernando Perez +# +# Distributed under the terms of the BSD License. The full license is in +# the file COPYING, distributed as part of this software. +#***************************************************************************** + +#**************************************************************************** +# Modules and globals + +# Python standard modules +import glob +import io +import logging +import os +import time + + +# prevent jedi/parso's debug messages pipe into interactiveshell +logging.getLogger("parso").setLevel(logging.WARNING) + +#**************************************************************************** +# FIXME: This class isn't a mixin anymore, but it still needs attributes from +# ipython and does input cache management. Finish cleanup later... + +class Logger(object): + """A Logfile class with different policies for file creation""" + + def __init__(self, home_dir, logfname='Logger.log', loghead=u'', + logmode='over'): + + # this is the full ipython instance, we need some attributes from it + # which won't exist until later. What a mess, clean up later... + self.home_dir = home_dir + + self.logfname = logfname + self.loghead = loghead + self.logmode = logmode + self.logfile = None + + # Whether to log raw or processed input + self.log_raw_input = False + + # whether to also log output + self.log_output = False + + # whether to put timestamps before each log entry + self.timestamp = False + + # activity control flags + self.log_active = False + + # logmode is a validated property + def _set_mode(self,mode): + if mode not in ['append','backup','global','over','rotate']: + raise ValueError('invalid log mode %s given' % mode) + self._logmode = mode + + def _get_mode(self): + return self._logmode + + logmode = property(_get_mode,_set_mode) + + def logstart(self, logfname=None, loghead=None, logmode=None, + log_output=False, timestamp=False, log_raw_input=False): + """Generate a new log-file with a default header. + + Raises RuntimeError if the log has already been started""" + + if self.logfile is not None: + raise RuntimeError('Log file is already active: %s' % + self.logfname) + + # The parameters can override constructor defaults + if logfname is not None: self.logfname = logfname + if loghead is not None: self.loghead = loghead + if logmode is not None: self.logmode = logmode + + # Parameters not part of the constructor + self.timestamp = timestamp + self.log_output = log_output + self.log_raw_input = log_raw_input + + # init depending on the log mode requested + isfile = os.path.isfile + logmode = self.logmode + + if logmode == 'append': + self.logfile = io.open(self.logfname, 'a', encoding='utf-8') + + elif logmode == 'backup': + if isfile(self.logfname): + backup_logname = self.logfname+'~' + # Manually remove any old backup, since os.rename may fail + # under Windows. + if isfile(backup_logname): + os.remove(backup_logname) + os.rename(self.logfname,backup_logname) + self.logfile = io.open(self.logfname, 'w', encoding='utf-8') + + elif logmode == 'global': + self.logfname = os.path.join(self.home_dir,self.logfname) + self.logfile = io.open(self.logfname, 'a', encoding='utf-8') + + elif logmode == 'over': + if isfile(self.logfname): + os.remove(self.logfname) + self.logfile = io.open(self.logfname,'w', encoding='utf-8') + + elif logmode == 'rotate': + if isfile(self.logfname): + if isfile(self.logfname+'.001~'): + old = glob.glob(self.logfname+'.*~') + old.sort() + old.reverse() + for f in old: + root, ext = os.path.splitext(f) + num = int(ext[1:-1])+1 + os.rename(f, root+'.'+repr(num).zfill(3)+'~') + os.rename(self.logfname, self.logfname+'.001~') + self.logfile = io.open(self.logfname, 'w', encoding='utf-8') + + if logmode != 'append': + self.logfile.write(self.loghead) + + self.logfile.flush() + self.log_active = True + + def switch_log(self,val): + """Switch logging on/off. val should be ONLY a boolean.""" + + if val not in [False,True,0,1]: + raise ValueError('Call switch_log ONLY with a boolean argument, ' + 'not with: %s' % val) + + label = {0:'OFF',1:'ON',False:'OFF',True:'ON'} + + if self.logfile is None: + print(""" +Logging hasn't been started yet (use logstart for that). + +%logon/%logoff are for temporarily starting and stopping logging for a logfile +which already exists. But you must first start the logging process with +%logstart (optionally giving a logfile name).""") + + else: + if self.log_active == val: + print('Logging is already',label[val]) + else: + print('Switching logging',label[val]) + self.log_active = not self.log_active + self.log_active_out = self.log_active + + def logstate(self): + """Print a status message about the logger.""" + if self.logfile is None: + print('Logging has not been activated.') + else: + state = self.log_active and 'active' or 'temporarily suspended' + print('Filename :', self.logfname) + print('Mode :', self.logmode) + print('Output logging :', self.log_output) + print('Raw input log :', self.log_raw_input) + print('Timestamping :', self.timestamp) + print('State :', state) + + def log(self, line_mod, line_ori): + """Write the sources to a log. + + Inputs: + + - line_mod: possibly modified input, such as the transformations made + by input prefilters or input handlers of various kinds. This should + always be valid Python. + + - line_ori: unmodified input line from the user. This is not + necessarily valid Python. + """ + + # Write the log line, but decide which one according to the + # log_raw_input flag, set when the log is started. + if self.log_raw_input: + self.log_write(line_ori) + else: + self.log_write(line_mod) + + def log_write(self, data, kind='input'): + """Write data to the log file, if active""" + + # print('data: %r' % data) # dbg + if self.log_active and data: + write = self.logfile.write + if kind=='input': + if self.timestamp: + write(time.strftime('# %a, %d %b %Y %H:%M:%S\n', time.localtime())) + write(data) + elif kind=='output' and self.log_output: + odata = u'\n'.join([u'#[Out]# %s' % s + for s in data.splitlines()]) + write(u'%s\n' % odata) + try: + self.logfile.flush() + except OSError: + print("Failed to flush the log file.") + print( + f"Please check that {self.logfname} exists and have the right permissions." + ) + print( + "Also consider turning off the log with `%logstop` to avoid this warning." + ) + + def logstop(self): + """Fully stop logging and close log file. + + In order to start logging again, a new logstart() call needs to be + made, possibly (though not necessarily) with a new filename, mode and + other options.""" + + if self.logfile is not None: + self.logfile.close() + self.logfile = None + else: + print("Logging hadn't been started.") + self.log_active = False + + # For backwards compatibility, in case anyone was using this. + close_log = logstop diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/__init__.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05f472bbb1429c2f1855fa110fa67e10b52a3f10 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/bad_all.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/bad_all.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da33e91b034cbab781c882778684fd5bc2d82bfc Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/bad_all.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/print_argv.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/print_argv.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6caaf745c4f2890b9cd38a71c810d31d8078172 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/print_argv.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/simpleerr.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/simpleerr.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..695c253f4321693242e0b589a17eb0dcad4aaeb3 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/simpleerr.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/tclass.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/tclass.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..108f2edec9bf700c0de5f0bbfc15baac1ce7b68f Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/tclass.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_alias.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_alias.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6885c1c38a8bee75969a490a2c363999ef2850b Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_alias.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_application.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_application.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a723d2087d5acc1ff0238889962835d6b06b0bb Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_application.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_async_helpers.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_async_helpers.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b93efda36b341dd2855749dd37349866a200c73b Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_async_helpers.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_autocall.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_autocall.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c108b6f3045b95e78d9bd7067e9b6f7a3ba99474 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_autocall.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_completer.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_completer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9658a60b4fdfb0dd3358d3144ec99256d4d2be1 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_completer.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_display.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_display.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb8a5f5238cf6b0ecd8b76e07b3c13ba211ae6cd Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_display.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_displayhook.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_displayhook.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d0468f96be1fca5be3d78b522f1d7e0c5f4723de Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_displayhook.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_events.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_events.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5524796a016e457b8bfa3a6646bfc0a635e7a8ca Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_events.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_exceptiongroup_tb.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_exceptiongroup_tb.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6d2dd4e2578f7ba10317cf83ac98e28dff3e3ea Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_exceptiongroup_tb.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_extension.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_extension.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66bbb22ff6585bbc0429ad2e80f18f2fbdedad10 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_extension.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_formatters.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_formatters.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08e239a381d019af746f96c0c58b7512943089c5 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_formatters.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_hooks.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_hooks.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ec49db5c00f8ea2142b2f3e959e0e6ce324256f Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_hooks.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_imports.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_imports.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bfe18f0ff51df333cd5aa391d510b9febf61428 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_imports.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_inputtransformer2.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_inputtransformer2.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1679adeac61fe68fd47b0e3163101a9aed5ce3a Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_inputtransformer2.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_interactiveshell.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_interactiveshell.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f743fd2ae087835af5d7decc85eb119b08c689a6 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_interactiveshell.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_iplib.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_iplib.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ded41c6567b58324dec12fe404479ee918c8acba Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_iplib.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_logger.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_logger.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..beee910eb956d9b0125fba4aed434015ffa4a367 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_logger.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_magic.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_magic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c87d100fa91720b057d792a48533b59bab5c7772 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_magic.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_magic_terminal.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_magic_terminal.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2bdb786d7d046807d3c4b101bc49e12ac5aadd4f Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_magic_terminal.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_page.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_page.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60f00c2a986483428b79a61a2a2e2da73657e13a Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_page.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_paths.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_paths.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..871bdece677860e1230d863e93618c96172284f7 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_paths.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_pylabtools.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_pylabtools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6efd95b44d29029db3c2025b7faf48d30a33205a Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_pylabtools.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_shellapp.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_shellapp.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41e3c0c2533fa05f6e07a3e9507069b47a5f62f4 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_shellapp.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_splitinput.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_splitinput.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9101f8e7c51a775ff42ea41db9c76cdd88dc5cc1 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_splitinput.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_ultratb.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_ultratb.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6bc94106dada4922597bce2a1896b4717ba1fe5f Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/__pycache__/test_ultratb.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/bad_all.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/bad_all.py new file mode 100644 index 0000000000000000000000000000000000000000..a7716ab6f328de060c5e472dfd2e8d47ee21a99d --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/bad_all.py @@ -0,0 +1,14 @@ +"""Module with bad __all__ + +To test https://github.com/ipython/ipython/issues/9678 +""" + +def evil(): + pass + +def puppies(): + pass + +__all__ = [evil, # Bad + 'puppies', # Good + ] diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/nonascii.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/nonascii.py new file mode 100644 index 0000000000000000000000000000000000000000..12738e3adc28b064c434a835a4df206ed88ae79f --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/nonascii.py @@ -0,0 +1,4 @@ +# coding: iso-8859-5 +# (Unlikely to be the default encoding for most testers.) +# ±¶ÿàáâãäåæçèéêëìíîï <- Cyrillic characters +u = "®âðÄ" diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/print_argv.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/print_argv.py new file mode 100644 index 0000000000000000000000000000000000000000..4ec9e2799ede8f83053fbe20df50b0ee097dda77 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/print_argv.py @@ -0,0 +1,3 @@ +import sys + +print(sys.argv[1:]) diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_async_helpers.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_async_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..48e31231906f286a2a8b49c0db26863e1c8912d3 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_async_helpers.py @@ -0,0 +1,325 @@ +""" +Test for async helpers. + +Should only trigger on python 3.5+ or will have syntax errors. +""" +from itertools import chain, repeat +from textwrap import dedent, indent +from typing import TYPE_CHECKING +from unittest import TestCase + +import pytest + +from IPython.core.async_helpers import _should_be_async +from IPython.testing.decorators import skip_without + +if TYPE_CHECKING: + from IPython import get_ipython + + ip = get_ipython() + + +def iprc(x): + return ip.run_cell(dedent(x)).raise_error() + + +def iprc_nr(x): + return ip.run_cell(dedent(x)) + + +class AsyncTest(TestCase): + def test_should_be_async(self): + self.assertFalse(_should_be_async("False")) + self.assertTrue(_should_be_async("await bar()")) + self.assertTrue(_should_be_async("x = await bar()")) + self.assertFalse( + _should_be_async( + dedent( + """ + async def awaitable(): + pass + """ + ) + ) + ) + + def _get_top_level_cases(self): + # These are test cases that should be valid in a function + # but invalid outside of a function. + test_cases = [] + test_cases.append(('basic', "{val}")) + + # Note, in all conditional cases, I use True instead of + # False so that the peephole optimizer won't optimize away + # the return, so CPython will see this as a syntax error: + # + # while True: + # break + # return + # + # But not this: + # + # while False: + # return + # + # See https://bugs.python.org/issue1875 + + test_cases.append(('if', dedent(""" + if True: + {val} + """))) + + test_cases.append(('while', dedent(""" + while True: + {val} + break + """))) + + test_cases.append(('try', dedent(""" + try: + {val} + except: + pass + """))) + + test_cases.append(('except', dedent(""" + try: + pass + except: + {val} + """))) + + test_cases.append(('finally', dedent(""" + try: + pass + except: + pass + finally: + {val} + """))) + + test_cases.append(('for', dedent(""" + for _ in range(4): + {val} + """))) + + + test_cases.append(('nested', dedent(""" + if True: + while True: + {val} + break + """))) + + test_cases.append(('deep-nested', dedent(""" + if True: + while True: + break + for x in range(3): + if True: + while True: + for x in range(3): + {val} + """))) + + return test_cases + + def _get_ry_syntax_errors(self): + # This is a mix of tests that should be a syntax error if + # return or yield whether or not they are in a function + + test_cases = [] + + test_cases.append(('class', dedent(""" + class V: + {val} + """))) + + test_cases.append(('nested-class', dedent(""" + class V: + class C: + {val} + """))) + + return test_cases + + + def test_top_level_return_error(self): + tl_err_test_cases = self._get_top_level_cases() + tl_err_test_cases.extend(self._get_ry_syntax_errors()) + + vals = ('return', 'yield', 'yield from (_ for _ in range(3))', + dedent(''' + def f(): + pass + return + '''), + ) + + for test_name, test_case in tl_err_test_cases: + # This example should work if 'pass' is used as the value + with self.subTest((test_name, 'pass')): + iprc(test_case.format(val='pass')) + + # It should fail with all the values + for val in vals: + with self.subTest((test_name, val)): + msg = "Syntax error not raised for %s, %s" % (test_name, val) + with self.assertRaises(SyntaxError, msg=msg): + iprc(test_case.format(val=val)) + + def test_in_func_no_error(self): + # Test that the implementation of top-level return/yield + # detection isn't *too* aggressive, and works inside a function + func_contexts = [] + + func_contexts.append(('func', False, dedent(""" + def f():"""))) + + func_contexts.append(('method', False, dedent(""" + class MyClass: + def __init__(self): + """))) + + func_contexts.append(('async-func', True, dedent(""" + async def f():"""))) + + func_contexts.append(('async-method', True, dedent(""" + class MyClass: + async def f(self):"""))) + + func_contexts.append(('closure', False, dedent(""" + def f(): + def g(): + """))) + + def nest_case(context, case): + # Detect indentation + lines = context.strip().splitlines() + prefix_len = 0 + for c in lines[-1]: + if c != ' ': + break + prefix_len += 1 + + indented_case = indent(case, ' ' * (prefix_len + 4)) + return context + '\n' + indented_case + + # Gather and run the tests + + # yield is allowed in async functions, starting in Python 3.6, + # and yield from is not allowed in any version + vals = ('return', 'yield', 'yield from (_ for _ in range(3))') + + success_tests = zip(self._get_top_level_cases(), repeat(False)) + failure_tests = zip(self._get_ry_syntax_errors(), repeat(True)) + + tests = chain(success_tests, failure_tests) + + for context_name, async_func, context in func_contexts: + for (test_name, test_case), should_fail in tests: + nested_case = nest_case(context, test_case) + + for val in vals: + test_id = (context_name, test_name, val) + cell = nested_case.format(val=val) + + with self.subTest(test_id): + if should_fail: + msg = ("SyntaxError not raised for %s" % + str(test_id)) + with self.assertRaises(SyntaxError, msg=msg): + iprc(cell) + + print(cell) + else: + iprc(cell) + + def test_nonlocal(self): + # fails if outer scope is not a function scope or if var not defined + with self.assertRaises(SyntaxError): + iprc("nonlocal x") + iprc(""" + x = 1 + def f(): + nonlocal x + x = 10000 + yield x + """) + iprc(""" + def f(): + def g(): + nonlocal x + x = 10000 + yield x + """) + + # works if outer scope is a function scope and var exists + iprc(""" + def f(): + x = 20 + def g(): + nonlocal x + x = 10000 + yield x + """) + + + def test_execute(self): + iprc(""" + import asyncio + await asyncio.sleep(0.001) + """ + ) + + def test_autoawait(self): + iprc("%autoawait False") + iprc("%autoawait True") + iprc(""" + from asyncio import sleep + await sleep(0.1) + """ + ) + + def test_memory_error(self): + """ + The pgen parser in 3.8 or before use to raise MemoryError on too many + nested parens anymore""" + + iprc("(" * 200 + ")" * 200) + + @pytest.mark.xfail(reason="fail on curio 1.6 and before on Python 3.12") + @pytest.mark.skip( + reason="skip_without(curio) fails on 3.12 for now even with other skip so must uncond skip" + ) + # @skip_without("curio") + def test_autoawait_curio(self): + iprc("%autoawait curio") + + @skip_without('trio') + def test_autoawait_trio(self): + iprc("%autoawait trio") + + @skip_without('trio') + def test_autoawait_trio_wrong_sleep(self): + iprc("%autoawait trio") + res = iprc_nr(""" + import asyncio + await asyncio.sleep(0) + """) + with self.assertRaises(TypeError): + res.raise_error() + + @skip_without('trio') + def test_autoawait_asyncio_wrong_sleep(self): + iprc("%autoawait asyncio") + res = iprc_nr(""" + import trio + await trio.sleep(0) + """) + with self.assertRaises(RuntimeError): + res.raise_error() + + + def tearDown(self): + ip.loop_runner = "asyncio" diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_autocall.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_autocall.py new file mode 100644 index 0000000000000000000000000000000000000000..f371a4bf750e7544da91a0639608f5188db16bdc --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_autocall.py @@ -0,0 +1,68 @@ +"""These kinds of tests are less than ideal, but at least they run. + +This was an old test that was being run interactively in the top-level tests/ +directory, which we are removing. For now putting this here ensures at least +we do run the test, though ultimately this functionality should all be tested +with better-isolated tests that don't rely on the global instance in iptest. +""" + +from IPython.core.splitinput import LineInfo +from IPython.core.prefilter import AutocallChecker + + +def doctest_autocall(): + """ + In [1]: def f1(a,b,c): + ...: return a+b+c + ...: + + In [2]: def f2(a): + ...: return a + a + ...: + + In [3]: def r(x): + ...: return True + ...: + + In [4]: ;f2 a b c + Out[4]: 'a b ca b c' + + In [5]: assert _ == "a b ca b c" + + In [6]: ,f1 a b c + Out[6]: 'abc' + + In [7]: assert _ == 'abc' + + In [8]: print(_) + abc + + In [9]: /f1 1,2,3 + Out[9]: 6 + + In [10]: assert _ == 6 + + In [11]: /f2 4 + Out[11]: 8 + + In [12]: assert _ == 8 + + In [12]: del f1, f2 + + In [13]: ,r a + Out[13]: True + + In [14]: assert _ == True + + In [15]: r'a' + Out[15]: 'a' + + In [16]: assert _ == 'a' + """ + + +def test_autocall_should_ignore_raw_strings(): + line_info = LineInfo("r'a'") + pm = ip.prefilter_manager + ac = AutocallChecker(shell=pm.shell, prefilter_manager=pm, config=pm.config) + assert ac.check(line_info) is None diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_compilerop.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_compilerop.py new file mode 100644 index 0000000000000000000000000000000000000000..8a5c9dc085b277442cde8d1f5638bd4f61040e2d --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_compilerop.py @@ -0,0 +1,68 @@ +# coding: utf-8 +"""Tests for the compilerop module. +""" +#----------------------------------------------------------------------------- +# Copyright (C) 2010-2011 The IPython Development Team. +# +# Distributed under the terms of the BSD License. +# +# The full license is in the file COPYING.txt, distributed with this software. +#----------------------------------------------------------------------------- + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +# Stdlib imports +import linecache +import sys + +# Our own imports +from IPython.core import compilerop + +#----------------------------------------------------------------------------- +# Test functions +#----------------------------------------------------------------------------- + +def test_code_name(): + code = 'x=1' + name = compilerop.code_name(code) + assert name.startswith(" ncache + +def test_proper_default_encoding(): + # Check we're in a proper Python 2 environment (some imports, such + # as GTK, can change the default encoding, which can hide bugs.) + assert sys.getdefaultencoding() == "utf-8" + +def test_cache_unicode(): + cp = compilerop.CachingCompiler() + ncache = len(linecache.cache) + cp.cache(u"t = 'žćčšđ'") + assert len(linecache.cache) > ncache + +def test_compiler_check_cache(): + """Test the compiler properly manages the cache. + """ + # Rather simple-minded tests that just exercise the API + cp = compilerop.CachingCompiler() + cp.cache('x=1', 99) + # Ensure now that after clearing the cache, our entries survive + linecache.checkcache() + assert any( + k.startswith(" 131808: + size, start, stop, prct = recompute_unicode_ranges() + message = f"""_UNICODE_RANGES likely wrong and need updating. This is + likely due to a new release of Python. We've find that the biggest gap + in unicode characters has reduces in size to be {size} characters + ({prct}), from {start}, to {stop}. In completer.py likely update to + + _UNICODE_RANGES = [(32, {start}), ({stop}, 0xe01f0)] + + And update the assertion below to use + + len_exp <= {len_exp} + """ + assert len_exp == len_test, message + + # fail if new unicode symbols have been added. + assert len_exp <= 143668, message + + +@contextmanager +def greedy_completion(): + ip = get_ipython() + greedy_original = ip.Completer.greedy + try: + ip.Completer.greedy = True + yield + finally: + ip.Completer.greedy = greedy_original + + +@contextmanager +def evaluation_policy(evaluation: str): + ip = get_ipython() + evaluation_original = ip.Completer.evaluation + try: + ip.Completer.evaluation = evaluation + yield + finally: + ip.Completer.evaluation = evaluation_original + + +@contextmanager +def custom_matchers(matchers): + ip = get_ipython() + try: + ip.Completer.custom_matchers.extend(matchers) + yield + finally: + ip.Completer.custom_matchers.clear() + + +if sys.platform == "win32": + pairs = [ + ("abc", "abc"), + (" abc", '" abc"'), + ("a bc", '"a bc"'), + ("a bc", '"a bc"'), + (" bc", '" bc"'), + ] +else: + pairs = [ + ("abc", "abc"), + (" abc", r"\ abc"), + ("a bc", r"a\ bc"), + ("a bc", r"a\ \ bc"), + (" bc", r"\ \ bc"), + # On posix, we also protect parens and other special characters. + ("a(bc", r"a\(bc"), + ("a)bc", r"a\)bc"), + ("a( )bc", r"a\(\ \)bc"), + ("a[1]bc", r"a\[1\]bc"), + ("a{1}bc", r"a\{1\}bc"), + ("a#bc", r"a\#bc"), + ("a?bc", r"a\?bc"), + ("a=bc", r"a\=bc"), + ("a\\bc", r"a\\bc"), + ("a|bc", r"a\|bc"), + ("a;bc", r"a\;bc"), + ("a:bc", r"a\:bc"), + ("a'bc", r"a\'bc"), + ("a*bc", r"a\*bc"), + ('a"bc', r"a\"bc"), + ("a^bc", r"a\^bc"), + ("a&bc", r"a\&bc"), + ] + + +@pytest.mark.parametrize("s1,expected", pairs) +def test_protect_filename(s1, expected): + assert completer.protect_filename(s1) == expected + + +def check_line_split(splitter, test_specs): + for part1, part2, split in test_specs: + cursor_pos = len(part1) + line = part1 + part2 + out = splitter.split_line(line, cursor_pos) + assert out == split + +def test_line_split(): + """Basic line splitter test with default specs.""" + sp = completer.CompletionSplitter() + # The format of the test specs is: part1, part2, expected answer. Parts 1 + # and 2 are joined into the 'line' sent to the splitter, as if the cursor + # was at the end of part1. So an empty part2 represents someone hitting + # tab at the end of the line, the most common case. + t = [ + ("run some/script", "", "some/script"), + ("run scripts/er", "ror.py foo", "scripts/er"), + ("echo $HOM", "", "HOM"), + ("print sys.pa", "", "sys.pa"), + ("print(sys.pa", "", "sys.pa"), + ("execfile('scripts/er", "", "scripts/er"), + ("a[x.", "", "x."), + ("a[x.", "y", "x."), + ('cd "some_file/', "", "some_file/"), + ] + check_line_split(sp, t) + # Ensure splitting works OK with unicode by re-running the tests with + # all inputs turned into unicode + check_line_split(sp, [map(str, p) for p in t]) + + +class NamedInstanceClass: + instances = {} + + def __init__(self, name): + self.instances[name] = self + + @classmethod + def _ipython_key_completions_(cls): + return cls.instances.keys() + + +class KeyCompletable: + def __init__(self, things=()): + self.things = things + + def _ipython_key_completions_(self): + return list(self.things) + + +class TestCompleter(unittest.TestCase): + def setUp(self): + """ + We want to silence all PendingDeprecationWarning when testing the completer + """ + self._assertwarns = self.assertWarns(PendingDeprecationWarning) + self._assertwarns.__enter__() + + def tearDown(self): + try: + self._assertwarns.__exit__(None, None, None) + except AssertionError: + pass + + def test_custom_completion_error(self): + """Test that errors from custom attribute completers are silenced.""" + ip = get_ipython() + + class A: + pass + + ip.user_ns["x"] = A() + + @complete_object.register(A) + def complete_A(a, existing_completions): + raise TypeError("this should be silenced") + + ip.complete("x.") + + def test_custom_completion_ordering(self): + """Test that errors from custom attribute completers are silenced.""" + ip = get_ipython() + + _, matches = ip.complete('in') + assert matches.index('input') < matches.index('int') + + def complete_example(a): + return ['example2', 'example1'] + + ip.Completer.custom_completers.add_re('ex*', complete_example) + _, matches = ip.complete('ex') + assert matches.index('example2') < matches.index('example1') + + def test_unicode_completions(self): + ip = get_ipython() + # Some strings that trigger different types of completion. Check them both + # in str and unicode forms + s = ["ru", "%ru", "cd /", "floa", "float(x)/"] + for t in s + list(map(str, s)): + # We don't need to check exact completion values (they may change + # depending on the state of the namespace, but at least no exceptions + # should be thrown and the return value should be a pair of text, list + # values. + text, matches = ip.complete(t) + self.assertIsInstance(text, str) + self.assertIsInstance(matches, list) + + def test_latex_completions(self): + + ip = get_ipython() + # Test some random unicode symbols + keys = random.sample(sorted(latex_symbols), 10) + for k in keys: + text, matches = ip.complete(k) + self.assertEqual(text, k) + self.assertEqual(matches, [latex_symbols[k]]) + # Test a more complex line + text, matches = ip.complete("print(\\alpha") + self.assertEqual(text, "\\alpha") + self.assertEqual(matches[0], latex_symbols["\\alpha"]) + # Test multiple matching latex symbols + text, matches = ip.complete("\\al") + self.assertIn("\\alpha", matches) + self.assertIn("\\aleph", matches) + + def test_latex_no_results(self): + """ + forward latex should really return nothing in either field if nothing is found. + """ + ip = get_ipython() + text, matches = ip.Completer.latex_matches("\\really_i_should_match_nothing") + self.assertEqual(text, "") + self.assertEqual(matches, ()) + + def test_back_latex_completion(self): + ip = get_ipython() + + # do not return more than 1 matches for \beta, only the latex one. + name, matches = ip.complete("\\β") + self.assertEqual(matches, ["\\beta"]) + + def test_back_unicode_completion(self): + ip = get_ipython() + + name, matches = ip.complete("\\Ⅴ") + self.assertEqual(matches, ["\\ROMAN NUMERAL FIVE"]) + + def test_forward_unicode_completion(self): + ip = get_ipython() + + name, matches = ip.complete("\\ROMAN NUMERAL FIVE") + self.assertEqual(matches, ["Ⅴ"]) # This is not a V + self.assertEqual(matches, ["\u2164"]) # same as above but explicit. + + def test_delim_setting(self): + sp = completer.CompletionSplitter() + sp.delims = " " + self.assertEqual(sp.delims, " ") + self.assertEqual(sp._delim_expr, r"[\ ]") + + def test_spaces(self): + """Test with only spaces as split chars.""" + sp = completer.CompletionSplitter() + sp.delims = " " + t = [("foo", "", "foo"), ("run foo", "", "foo"), ("run foo", "bar", "foo")] + check_line_split(sp, t) + + def test_has_open_quotes1(self): + for s in ["'", "'''", "'hi' '"]: + self.assertEqual(completer.has_open_quotes(s), "'") + + def test_has_open_quotes2(self): + for s in ['"', '"""', '"hi" "']: + self.assertEqual(completer.has_open_quotes(s), '"') + + def test_has_open_quotes3(self): + for s in ["''", "''' '''", "'hi' 'ipython'"]: + self.assertFalse(completer.has_open_quotes(s)) + + def test_has_open_quotes4(self): + for s in ['""', '""" """', '"hi" "ipython"']: + self.assertFalse(completer.has_open_quotes(s)) + + @pytest.mark.xfail( + sys.platform == "win32", reason="abspath completions fail on Windows" + ) + def test_abspath_file_completions(self): + ip = get_ipython() + with TemporaryDirectory() as tmpdir: + prefix = os.path.join(tmpdir, "foo") + suffixes = ["1", "2"] + names = [prefix + s for s in suffixes] + for n in names: + open(n, "w", encoding="utf-8").close() + + # Check simple completion + c = ip.complete(prefix)[1] + self.assertEqual(c, names) + + # Now check with a function call + cmd = 'a = f("%s' % prefix + c = ip.complete(prefix, cmd)[1] + comp = [prefix + s for s in suffixes] + self.assertEqual(c, comp) + + def test_local_file_completions(self): + ip = get_ipython() + with TemporaryWorkingDirectory(): + prefix = "./foo" + suffixes = ["1", "2"] + names = [prefix + s for s in suffixes] + for n in names: + open(n, "w", encoding="utf-8").close() + + # Check simple completion + c = ip.complete(prefix)[1] + self.assertEqual(c, names) + + # Now check with a function call + cmd = 'a = f("%s' % prefix + c = ip.complete(prefix, cmd)[1] + comp = {prefix + s for s in suffixes} + self.assertTrue(comp.issubset(set(c))) + + def test_quoted_file_completions(self): + ip = get_ipython() + + def _(text): + return ip.Completer._complete( + cursor_line=0, cursor_pos=len(text), full_text=text + )["IPCompleter.file_matcher"]["completions"] + + with TemporaryWorkingDirectory(): + name = "foo'bar" + open(name, "w", encoding="utf-8").close() + + # Don't escape Windows + escaped = name if sys.platform == "win32" else "foo\\'bar" + + # Single quote matches embedded single quote + c = _("open('foo")[0] + self.assertEqual(c.text, escaped) + + # Double quote requires no escape + c = _('open("foo')[0] + self.assertEqual(c.text, name) + + # No quote requires an escape + c = _("%ls foo")[0] + self.assertEqual(c.text, escaped) + + @pytest.mark.xfail( + sys.version_info.releaselevel in ("alpha",), + reason="Parso does not yet parse 3.13", + ) + def test_all_completions_dups(self): + """ + Make sure the output of `IPCompleter.all_completions` does not have + duplicated prefixes. + """ + ip = get_ipython() + c = ip.Completer + ip.ex("class TestClass():\n\ta=1\n\ta1=2") + for jedi_status in [True, False]: + with provisionalcompleter(): + ip.Completer.use_jedi = jedi_status + matches = c.all_completions("TestCl") + assert matches == ["TestClass"], (jedi_status, matches) + matches = c.all_completions("TestClass.") + assert len(matches) > 2, (jedi_status, matches) + matches = c.all_completions("TestClass.a") + if jedi_status: + assert matches == ["TestClass.a", "TestClass.a1"], jedi_status + else: + assert matches == [".a", ".a1"], jedi_status + + @pytest.mark.xfail( + sys.version_info.releaselevel in ("alpha",), + reason="Parso does not yet parse 3.13", + ) + def test_jedi(self): + """ + A couple of issue we had with Jedi + """ + ip = get_ipython() + + def _test_complete(reason, s, comp, start=None, end=None): + l = len(s) + start = start if start is not None else l + end = end if end is not None else l + with provisionalcompleter(): + ip.Completer.use_jedi = True + completions = set(ip.Completer.completions(s, l)) + ip.Completer.use_jedi = False + assert Completion(start, end, comp) in completions, reason + + def _test_not_complete(reason, s, comp): + l = len(s) + with provisionalcompleter(): + ip.Completer.use_jedi = True + completions = set(ip.Completer.completions(s, l)) + ip.Completer.use_jedi = False + assert Completion(l, l, comp) not in completions, reason + + import jedi + + jedi_version = tuple(int(i) for i in jedi.__version__.split(".")[:3]) + if jedi_version > (0, 10): + _test_complete("jedi >0.9 should complete and not crash", "a=1;a.", "real") + _test_complete("can infer first argument", 'a=(1,"foo");a[0].', "real") + _test_complete("can infer second argument", 'a=(1,"foo");a[1].', "capitalize") + _test_complete("cover duplicate completions", "im", "import", 0, 2) + + _test_not_complete("does not mix types", 'a=(1,"foo");a[0].', "capitalize") + + @pytest.mark.xfail( + sys.version_info.releaselevel in ("alpha",), + reason="Parso does not yet parse 3.13", + ) + def test_completion_have_signature(self): + """ + Lets make sure jedi is capable of pulling out the signature of the function we are completing. + """ + ip = get_ipython() + with provisionalcompleter(): + ip.Completer.use_jedi = True + completions = ip.Completer.completions("ope", 3) + c = next(completions) # should be `open` + ip.Completer.use_jedi = False + assert "file" in c.signature, "Signature of function was not found by completer" + assert ( + "encoding" in c.signature + ), "Signature of function was not found by completer" + + @pytest.mark.xfail( + sys.version_info.releaselevel in ("alpha",), + reason="Parso does not yet parse 3.13", + ) + def test_completions_have_type(self): + """ + Lets make sure matchers provide completion type. + """ + ip = get_ipython() + with provisionalcompleter(): + ip.Completer.use_jedi = False + completions = ip.Completer.completions("%tim", 3) + c = next(completions) # should be `%time` or similar + assert c.type == "magic", "Type of magic was not assigned by completer" + + @pytest.mark.xfail( + parse(version("jedi")) <= parse("0.18.0"), + reason="Known failure on jedi<=0.18.0", + strict=True, + ) + def test_deduplicate_completions(self): + """ + Test that completions are correctly deduplicated (even if ranges are not the same) + """ + ip = get_ipython() + ip.ex( + textwrap.dedent( + """ + class Z: + zoo = 1 + """ + ) + ) + with provisionalcompleter(): + ip.Completer.use_jedi = True + l = list( + _deduplicate_completions("Z.z", ip.Completer.completions("Z.z", 3)) + ) + ip.Completer.use_jedi = False + + assert len(l) == 1, "Completions (Z.z) correctly deduplicate: %s " % l + assert l[0].text == "zoo" # and not `it.accumulate` + + @pytest.mark.xfail( + sys.version_info.releaselevel in ("alpha",), + reason="Parso does not yet parse 3.13", + ) + def test_greedy_completions(self): + """ + Test the capability of the Greedy completer. + + Most of the test here does not really show off the greedy completer, for proof + each of the text below now pass with Jedi. The greedy completer is capable of more. + + See the :any:`test_dict_key_completion_contexts` + + """ + ip = get_ipython() + ip.ex("a=list(range(5))") + ip.ex("d = {'a b': str}") + _, c = ip.complete(".", line="a[0].") + self.assertFalse(".real" in c, "Shouldn't have completed on a[0]: %s" % c) + + def _(line, cursor_pos, expect, message, completion): + with greedy_completion(), provisionalcompleter(): + ip.Completer.use_jedi = False + _, c = ip.complete(".", line=line, cursor_pos=cursor_pos) + self.assertIn(expect, c, message % c) + + ip.Completer.use_jedi = True + with provisionalcompleter(): + completions = ip.Completer.completions(line, cursor_pos) + self.assertIn(completion, list(completions)) + + with provisionalcompleter(): + _( + "a[0].", + 5, + ".real", + "Should have completed on a[0].: %s", + Completion(5, 5, "real"), + ) + _( + "a[0].r", + 6, + ".real", + "Should have completed on a[0].r: %s", + Completion(5, 6, "real"), + ) + _( + "a[0].from_", + 10, + ".from_bytes", + "Should have completed on a[0].from_: %s", + Completion(5, 10, "from_bytes"), + ) + _( + "assert str.star", + 14, + ".startswith", + "Should have completed on `assert str.star`: %s", + Completion(11, 14, "startswith"), + ) + _( + "d['a b'].str", + 12, + ".strip", + "Should have completed on `d['a b'].str`: %s", + Completion(9, 12, "strip"), + ) + _( + "a.app", + 4, + ".append", + "Should have completed on `a.app`: %s", + Completion(2, 4, "append"), + ) + + def test_omit__names(self): + # also happens to test IPCompleter as a configurable + ip = get_ipython() + ip._hidden_attr = 1 + ip._x = {} + c = ip.Completer + ip.ex("ip=get_ipython()") + cfg = Config() + cfg.IPCompleter.omit__names = 0 + c.update_config(cfg) + with provisionalcompleter(): + c.use_jedi = False + s, matches = c.complete("ip.") + self.assertIn(".__str__", matches) + self.assertIn("._hidden_attr", matches) + + # c.use_jedi = True + # completions = set(c.completions('ip.', 3)) + # self.assertIn(Completion(3, 3, '__str__'), completions) + # self.assertIn(Completion(3,3, "_hidden_attr"), completions) + + cfg = Config() + cfg.IPCompleter.omit__names = 1 + c.update_config(cfg) + with provisionalcompleter(): + c.use_jedi = False + s, matches = c.complete("ip.") + self.assertNotIn(".__str__", matches) + # self.assertIn('ip._hidden_attr', matches) + + # c.use_jedi = True + # completions = set(c.completions('ip.', 3)) + # self.assertNotIn(Completion(3,3,'__str__'), completions) + # self.assertIn(Completion(3,3, "_hidden_attr"), completions) + + cfg = Config() + cfg.IPCompleter.omit__names = 2 + c.update_config(cfg) + with provisionalcompleter(): + c.use_jedi = False + s, matches = c.complete("ip.") + self.assertNotIn(".__str__", matches) + self.assertNotIn("._hidden_attr", matches) + + # c.use_jedi = True + # completions = set(c.completions('ip.', 3)) + # self.assertNotIn(Completion(3,3,'__str__'), completions) + # self.assertNotIn(Completion(3,3, "_hidden_attr"), completions) + + with provisionalcompleter(): + c.use_jedi = False + s, matches = c.complete("ip._x.") + self.assertIn(".keys", matches) + + # c.use_jedi = True + # completions = set(c.completions('ip._x.', 6)) + # self.assertIn(Completion(6,6, "keys"), completions) + + del ip._hidden_attr + del ip._x + + def test_limit_to__all__False_ok(self): + """ + Limit to all is deprecated, once we remove it this test can go away. + """ + ip = get_ipython() + c = ip.Completer + c.use_jedi = False + ip.ex("class D: x=24") + ip.ex("d=D()") + cfg = Config() + cfg.IPCompleter.limit_to__all__ = False + c.update_config(cfg) + s, matches = c.complete("d.") + self.assertIn(".x", matches) + + def test_get__all__entries_ok(self): + class A: + __all__ = ["x", 1] + + words = completer.get__all__entries(A()) + self.assertEqual(words, ["x"]) + + def test_get__all__entries_no__all__ok(self): + class A: + pass + + words = completer.get__all__entries(A()) + self.assertEqual(words, []) + + def test_completes_globals_as_args_of_methods(self): + ip = get_ipython() + c = ip.Completer + c.use_jedi = False + ip.ex("long_variable_name = 1") + ip.ex("a = []") + s, matches = c.complete(None, "a.sort(lo") + self.assertIn("long_variable_name", matches) + + def test_completes_attributes_in_fstring_expressions(self): + ip = get_ipython() + c = ip.Completer + c.use_jedi = False + + class CustomClass: + def method_one(self): + pass + + ip.user_ns["custom_obj"] = CustomClass() + + # Test completion inside f-string expressions + s, matches = c.complete(None, "f'{custom_obj.meth") + self.assertIn(".method_one", matches) + + def test_completes_in_dict_expressions(self): + ip = get_ipython() + c = ip.Completer + c.use_jedi = False + ip.ex("class Test: pass") + ip.ex("test_obj = Test()") + ip.ex("test_obj.attribute = 'value'") + + # Test completion in dictionary expressions + s, matches = c.complete(None, "d = {'key': test_obj.attr") + self.assertIn(".attribute", matches) + + # Test global completion in dictionary expressions with dots + s, matches = c.complete(None, "d = {'k.e.y': Te") + self.assertIn("Test", matches) + + def test_func_kw_completions(self): + ip = get_ipython() + c = ip.Completer + c.use_jedi = False + ip.ex("def myfunc(a=1,b=2): return a+b") + s, matches = c.complete(None, "myfunc(1,b") + self.assertIn("b=", matches) + # Simulate completing with cursor right after b (pos==10): + s, matches = c.complete(None, "myfunc(1,b)", 10) + self.assertIn("b=", matches) + s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b') + self.assertIn("b=", matches) + # builtin function + s, matches = c.complete(None, "min(k, k") + self.assertIn("key=", matches) + + def test_default_arguments_from_docstring(self): + ip = get_ipython() + c = ip.Completer + kwd = c._default_arguments_from_docstring("min(iterable[, key=func]) -> value") + self.assertEqual(kwd, ["key"]) + # with cython type etc + kwd = c._default_arguments_from_docstring( + "Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n" + ) + self.assertEqual(kwd, ["ncall", "resume", "nsplit"]) + # white spaces + kwd = c._default_arguments_from_docstring( + "\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n" + ) + self.assertEqual(kwd, ["ncall", "resume", "nsplit"]) + + def test_line_magics(self): + ip = get_ipython() + c = ip.Completer + s, matches = c.complete(None, "lsmag") + self.assertIn("%lsmagic", matches) + s, matches = c.complete(None, "%lsmag") + self.assertIn("%lsmagic", matches) + + def test_cell_magics(self): + from IPython.core.magic import register_cell_magic + + @register_cell_magic + def _foo_cellm(line, cell): + pass + + ip = get_ipython() + c = ip.Completer + + s, matches = c.complete(None, "_foo_ce") + self.assertIn("%%_foo_cellm", matches) + s, matches = c.complete(None, "%%_foo_ce") + self.assertIn("%%_foo_cellm", matches) + + def test_line_cell_magics(self): + from IPython.core.magic import register_line_cell_magic + + @register_line_cell_magic + def _bar_cellm(line, cell): + pass + + ip = get_ipython() + c = ip.Completer + + # The policy here is trickier, see comments in completion code. The + # returned values depend on whether the user passes %% or not explicitly, + # and this will show a difference if the same name is both a line and cell + # magic. + s, matches = c.complete(None, "_bar_ce") + self.assertIn("%_bar_cellm", matches) + self.assertIn("%%_bar_cellm", matches) + s, matches = c.complete(None, "%_bar_ce") + self.assertIn("%_bar_cellm", matches) + self.assertIn("%%_bar_cellm", matches) + s, matches = c.complete(None, "%%_bar_ce") + self.assertNotIn("%_bar_cellm", matches) + self.assertIn("%%_bar_cellm", matches) + + def test_magic_completion_order(self): + ip = get_ipython() + c = ip.Completer + + # Test ordering of line and cell magics. + text, matches = c.complete("timeit") + self.assertEqual(matches, ["%timeit", "%%timeit"]) + + def test_magic_completion_shadowing(self): + ip = get_ipython() + c = ip.Completer + c.use_jedi = False + + # Before importing matplotlib, %matplotlib magic should be the only option. + text, matches = c.complete("mat") + self.assertEqual(matches, ["%matplotlib"]) + + # The newly introduced name should shadow the magic. + ip.run_cell("matplotlib = 1") + text, matches = c.complete("mat") + self.assertEqual(matches, ["matplotlib"]) + + # After removing matplotlib from namespace, the magic should again be + # the only option. + del ip.user_ns["matplotlib"] + text, matches = c.complete("mat") + self.assertEqual(matches, ["%matplotlib"]) + + def test_magic_completion_shadowing_explicit(self): + """ + If the user try to complete a shadowed magic, and explicit % start should + still return the completions. + """ + ip = get_ipython() + c = ip.Completer + + # Before importing matplotlib, %matplotlib magic should be the only option. + text, matches = c.complete("%mat") + self.assertEqual(matches, ["%matplotlib"]) + + ip.run_cell("matplotlib = 1") + + # After removing matplotlib from namespace, the magic should still be + # the only option. + text, matches = c.complete("%mat") + self.assertEqual(matches, ["%matplotlib"]) + + def test_magic_config(self): + ip = get_ipython() + c = ip.Completer + + s, matches = c.complete(None, "conf") + self.assertIn("%config", matches) + s, matches = c.complete(None, "conf") + self.assertNotIn("AliasManager", matches) + s, matches = c.complete(None, "config ") + self.assertIn("AliasManager", matches) + s, matches = c.complete(None, "%config ") + self.assertIn("AliasManager", matches) + s, matches = c.complete(None, "config Ali") + self.assertListEqual(["AliasManager"], matches) + s, matches = c.complete(None, "%config Ali") + self.assertListEqual(["AliasManager"], matches) + s, matches = c.complete(None, "config AliasManager") + self.assertListEqual(["AliasManager"], matches) + s, matches = c.complete(None, "%config AliasManager") + self.assertListEqual(["AliasManager"], matches) + s, matches = c.complete(None, "config AliasManager.") + self.assertIn("AliasManager.default_aliases", matches) + s, matches = c.complete(None, "%config AliasManager.") + self.assertIn("AliasManager.default_aliases", matches) + s, matches = c.complete(None, "config AliasManager.de") + self.assertListEqual(["AliasManager.default_aliases"], matches) + s, matches = c.complete(None, "config AliasManager.de") + self.assertListEqual(["AliasManager.default_aliases"], matches) + + def test_magic_color(self): + ip = get_ipython() + c = ip.Completer + + s, matches = c.complete(None, "colo") + self.assertIn("%colors", matches) + s, matches = c.complete(None, "colo") + self.assertNotIn("NoColor", matches) + s, matches = c.complete(None, "%colors") # No trailing space + self.assertNotIn("NoColor", matches) + s, matches = c.complete(None, "colors ") + self.assertIn("NoColor", matches) + s, matches = c.complete(None, "%colors ") + self.assertIn("NoColor", matches) + s, matches = c.complete(None, "colors NoCo") + self.assertListEqual(["NoColor"], matches) + s, matches = c.complete(None, "%colors NoCo") + self.assertListEqual(["NoColor"], matches) + + def test_match_dict_keys(self): + """ + Test that match_dict_keys works on a couple of use case does return what + expected, and does not crash + """ + delims = " \t\n`!@#$^&*()=+[{]}\\|;:'\",<>?" + + def match(*args, **kwargs): + quote, offset, matches = match_dict_keys(*args, delims=delims, **kwargs) + return quote, offset, list(matches) + + keys = ["foo", b"far"] + assert match(keys, "b'") == ("'", 2, ["far"]) + assert match(keys, "b'f") == ("'", 2, ["far"]) + assert match(keys, 'b"') == ('"', 2, ["far"]) + assert match(keys, 'b"f') == ('"', 2, ["far"]) + + assert match(keys, "'") == ("'", 1, ["foo"]) + assert match(keys, "'f") == ("'", 1, ["foo"]) + assert match(keys, '"') == ('"', 1, ["foo"]) + assert match(keys, '"f') == ('"', 1, ["foo"]) + + # Completion on first item of tuple + keys = [("foo", 1111), ("foo", 2222), (3333, "bar"), (3333, "test")] + assert match(keys, "'f") == ("'", 1, ["foo"]) + assert match(keys, "33") == ("", 0, ["3333"]) + + # Completion on numbers + keys = [ + 0xDEADBEEF, + 1111, + 1234, + "1999", + 0b10101, + 22, + ] # 0xDEADBEEF = 3735928559; 0b10101 = 21 + assert match(keys, "0xdead") == ("", 0, ["0xdeadbeef"]) + assert match(keys, "1") == ("", 0, ["1111", "1234"]) + assert match(keys, "2") == ("", 0, ["21", "22"]) + assert match(keys, "0b101") == ("", 0, ["0b10101", "0b10110"]) + + # Should yield on variables + assert match(keys, "a_variable") == ("", 0, []) + + # Should pass over invalid literals + assert match(keys, "'' ''") == ("", 0, []) + + def test_match_dict_keys_tuple(self): + """ + Test that match_dict_keys called with extra prefix works on a couple of use case, + does return what expected, and does not crash. + """ + delims = " \t\n`!@#$^&*()=+[{]}\\|;:'\",<>?" + + keys = [("foo", "bar"), ("foo", "oof"), ("foo", b"bar"), ('other', 'test')] + + def match(*args, extra=None, **kwargs): + quote, offset, matches = match_dict_keys( + *args, delims=delims, extra_prefix=extra, **kwargs + ) + return quote, offset, list(matches) + + # Completion on first key == "foo" + assert match(keys, "'", extra=("foo",)) == ("'", 1, ["bar", "oof"]) + assert match(keys, '"', extra=("foo",)) == ('"', 1, ["bar", "oof"]) + assert match(keys, "'o", extra=("foo",)) == ("'", 1, ["oof"]) + assert match(keys, '"o', extra=("foo",)) == ('"', 1, ["oof"]) + assert match(keys, "b'", extra=("foo",)) == ("'", 2, ["bar"]) + assert match(keys, 'b"', extra=("foo",)) == ('"', 2, ["bar"]) + assert match(keys, "b'b", extra=("foo",)) == ("'", 2, ["bar"]) + assert match(keys, 'b"b', extra=("foo",)) == ('"', 2, ["bar"]) + + # No Completion + assert match(keys, "'", extra=("no_foo",)) == ("'", 1, []) + assert match(keys, "'", extra=("fo",)) == ("'", 1, []) + + keys = [("foo1", "foo2", "foo3", "foo4"), ("foo1", "foo2", "bar", "foo4")] + assert match(keys, "'foo", extra=("foo1",)) == ("'", 1, ["foo2"]) + assert match(keys, "'foo", extra=("foo1", "foo2")) == ("'", 1, ["foo3"]) + assert match(keys, "'foo", extra=("foo1", "foo2", "foo3")) == ("'", 1, ["foo4"]) + assert match(keys, "'foo", extra=("foo1", "foo2", "foo3", "foo4")) == ( + "'", + 1, + [], + ) + + keys = [("foo", 1111), ("foo", "2222"), (3333, "bar"), (3333, 4444)] + assert match(keys, "'", extra=("foo",)) == ("'", 1, ["2222"]) + assert match(keys, "", extra=("foo",)) == ("", 0, ["1111", "'2222'"]) + assert match(keys, "'", extra=(3333,)) == ("'", 1, ["bar"]) + assert match(keys, "", extra=(3333,)) == ("", 0, ["'bar'", "4444"]) + assert match(keys, "'", extra=("3333",)) == ("'", 1, []) + assert match(keys, "33") == ("", 0, ["3333"]) + + def test_dict_key_completion_closures(self): + ip = get_ipython() + complete = ip.Completer.complete + ip.Completer.auto_close_dict_keys = True + + ip.user_ns["d"] = { + # tuple only + ("aa", 11): None, + # tuple and non-tuple + ("bb", 22): None, + "bb": None, + # non-tuple only + "cc": None, + # numeric tuple only + (77, "x"): None, + # numeric tuple and non-tuple + (88, "y"): None, + 88: None, + # numeric non-tuple only + 99: None, + } + + _, matches = complete(line_buffer="d[") + # should append `, ` if matches a tuple only + self.assertIn("'aa', ", matches) + # should not append anything if matches a tuple and an item + self.assertIn("'bb'", matches) + # should append `]` if matches and item only + self.assertIn("'cc']", matches) + + # should append `, ` if matches a tuple only + self.assertIn("77, ", matches) + # should not append anything if matches a tuple and an item + self.assertIn("88", matches) + # should append `]` if matches and item only + self.assertIn("99]", matches) + + _, matches = complete(line_buffer="d['aa', ") + # should restrict matches to those matching tuple prefix + self.assertIn("11]", matches) + self.assertNotIn("'bb'", matches) + self.assertNotIn("'bb', ", matches) + self.assertNotIn("'bb']", matches) + self.assertNotIn("'cc'", matches) + self.assertNotIn("'cc', ", matches) + self.assertNotIn("'cc']", matches) + ip.Completer.auto_close_dict_keys = False + + def test_dict_key_completion_string(self): + """Test dictionary key completion for string keys""" + ip = get_ipython() + complete = ip.Completer.complete + + ip.user_ns["d"] = {"abc": None} + + # check completion at different stages + _, matches = complete(line_buffer="d[") + self.assertIn("'abc'", matches) + self.assertNotIn("'abc']", matches) + + _, matches = complete(line_buffer="d['") + self.assertIn("abc", matches) + self.assertNotIn("abc']", matches) + + _, matches = complete(line_buffer="d['a") + self.assertIn("abc", matches) + self.assertNotIn("abc']", matches) + + # check use of different quoting + _, matches = complete(line_buffer='d["') + self.assertIn("abc", matches) + self.assertNotIn('abc"]', matches) + + _, matches = complete(line_buffer='d["a') + self.assertIn("abc", matches) + self.assertNotIn('abc"]', matches) + + # check sensitivity to following context + _, matches = complete(line_buffer="d[]", cursor_pos=2) + self.assertIn("'abc'", matches) + + _, matches = complete(line_buffer="d['']", cursor_pos=3) + self.assertIn("abc", matches) + self.assertNotIn("abc'", matches) + self.assertNotIn("abc']", matches) + + # check multiple solutions are correctly returned and that noise is not + ip.user_ns["d"] = { + "abc": None, + "abd": None, + "bad": None, + object(): None, + 5: None, + ("abe", None): None, + (None, "abf"): None + } + + _, matches = complete(line_buffer="d['a") + self.assertIn("abc", matches) + self.assertIn("abd", matches) + self.assertNotIn("bad", matches) + self.assertNotIn("abe", matches) + self.assertNotIn("abf", matches) + assert not any(m.endswith(("]", '"', "'")) for m in matches), matches + + # check escaping and whitespace + ip.user_ns["d"] = {"a\nb": None, "a'b": None, 'a"b': None, "a word": None} + _, matches = complete(line_buffer="d['a") + self.assertIn("a\\nb", matches) + self.assertIn("a\\'b", matches) + self.assertIn('a"b', matches) + self.assertIn("a word", matches) + assert not any(m.endswith(("]", '"', "'")) for m in matches), matches + + # - can complete on non-initial word of the string + _, matches = complete(line_buffer="d['a w") + self.assertIn("word", matches) + + # - understands quote escaping + _, matches = complete(line_buffer="d['a\\'") + self.assertIn("b", matches) + + # - default quoting should work like repr + _, matches = complete(line_buffer="d[") + self.assertIn('"a\'b"', matches) + + # - when opening quote with ", possible to match with unescaped apostrophe + _, matches = complete(line_buffer="d[\"a'") + self.assertIn("b", matches) + + # need to not split at delims that readline won't split at + if "-" not in ip.Completer.splitter.delims: + ip.user_ns["d"] = {"before-after": None} + _, matches = complete(line_buffer="d['before-af") + self.assertIn("before-after", matches) + + # check completion on tuple-of-string keys at different stage - on first key + ip.user_ns["d"] = {('foo', 'bar'): None} + _, matches = complete(line_buffer="d[") + self.assertIn("'foo'", matches) + self.assertNotIn("'foo']", matches) + self.assertNotIn("'bar'", matches) + self.assertNotIn("foo", matches) + self.assertNotIn("bar", matches) + + # - match the prefix + _, matches = complete(line_buffer="d['f") + self.assertIn("foo", matches) + self.assertNotIn("foo']", matches) + self.assertNotIn('foo"]', matches) + _, matches = complete(line_buffer="d['foo") + self.assertIn("foo", matches) + + # - can complete on second key + _, matches = complete(line_buffer="d['foo', ") + self.assertIn("'bar'", matches) + _, matches = complete(line_buffer="d['foo', 'b") + self.assertIn("bar", matches) + self.assertNotIn("foo", matches) + + # - does not propose missing keys + _, matches = complete(line_buffer="d['foo', 'f") + self.assertNotIn("bar", matches) + self.assertNotIn("foo", matches) + + # check sensitivity to following context + _, matches = complete(line_buffer="d['foo',]", cursor_pos=8) + self.assertIn("'bar'", matches) + self.assertNotIn("bar", matches) + self.assertNotIn("'foo'", matches) + self.assertNotIn("foo", matches) + + _, matches = complete(line_buffer="d['']", cursor_pos=3) + self.assertIn("foo", matches) + assert not any(m.endswith(("]", '"', "'")) for m in matches), matches + + _, matches = complete(line_buffer='d[""]', cursor_pos=3) + self.assertIn("foo", matches) + assert not any(m.endswith(("]", '"', "'")) for m in matches), matches + + _, matches = complete(line_buffer='d["foo","]', cursor_pos=9) + self.assertIn("bar", matches) + assert not any(m.endswith(("]", '"', "'")) for m in matches), matches + + _, matches = complete(line_buffer='d["foo",]', cursor_pos=8) + self.assertIn("'bar'", matches) + self.assertNotIn("bar", matches) + + # Can complete with longer tuple keys + ip.user_ns["d"] = {('foo', 'bar', 'foobar'): None} + + # - can complete second key + _, matches = complete(line_buffer="d['foo', 'b") + self.assertIn("bar", matches) + self.assertNotIn("foo", matches) + self.assertNotIn("foobar", matches) + + # - can complete third key + _, matches = complete(line_buffer="d['foo', 'bar', 'fo") + self.assertIn("foobar", matches) + self.assertNotIn("foo", matches) + self.assertNotIn("bar", matches) + + def test_dict_key_completion_numbers(self): + ip = get_ipython() + complete = ip.Completer.complete + + ip.user_ns["d"] = { + 0xDEADBEEF: None, # 3735928559 + 1111: None, + 1234: None, + "1999": None, + 0b10101: None, # 21 + 22: None, + } + _, matches = complete(line_buffer="d[1") + self.assertIn("1111", matches) + self.assertIn("1234", matches) + self.assertNotIn("1999", matches) + self.assertNotIn("'1999'", matches) + + _, matches = complete(line_buffer="d[0xdead") + self.assertIn("0xdeadbeef", matches) + + _, matches = complete(line_buffer="d[2") + self.assertIn("21", matches) + self.assertIn("22", matches) + + _, matches = complete(line_buffer="d[0b101") + self.assertIn("0b10101", matches) + self.assertIn("0b10110", matches) + + def test_dict_key_completion_contexts(self): + """Test expression contexts in which dict key completion occurs""" + ip = get_ipython() + complete = ip.Completer.complete + d = {"abc": None} + ip.user_ns["d"] = d + + class C: + data = d + + ip.user_ns["C"] = C + ip.user_ns["get"] = lambda: d + ip.user_ns["nested"] = {"x": d} + + def assert_no_completion(**kwargs): + _, matches = complete(**kwargs) + self.assertNotIn("abc", matches) + self.assertNotIn("abc'", matches) + self.assertNotIn("abc']", matches) + self.assertNotIn("'abc'", matches) + self.assertNotIn("'abc']", matches) + + def assert_completion(**kwargs): + _, matches = complete(**kwargs) + self.assertIn("'abc'", matches) + self.assertNotIn("'abc']", matches) + + # no completion after string closed, even if reopened + assert_no_completion(line_buffer="d['a'") + assert_no_completion(line_buffer='d["a"') + assert_no_completion(line_buffer="d['a' + ") + assert_no_completion(line_buffer="d['a' + '") + + # completion in non-trivial expressions + assert_completion(line_buffer="+ d[") + assert_completion(line_buffer="(d[") + assert_completion(line_buffer="C.data[") + + # nested dict completion + assert_completion(line_buffer="nested['x'][") + + with evaluation_policy("minimal"): + with pytest.raises(AssertionError): + assert_completion(line_buffer="nested['x'][") + + # greedy flag + def assert_completion(**kwargs): + _, matches = complete(**kwargs) + self.assertIn("get()['abc']", matches) + + assert_no_completion(line_buffer="get()[") + with greedy_completion(): + assert_completion(line_buffer="get()[") + assert_completion(line_buffer="get()['") + assert_completion(line_buffer="get()['a") + assert_completion(line_buffer="get()['ab") + assert_completion(line_buffer="get()['abc") + + def test_dict_key_completion_bytes(self): + """Test handling of bytes in dict key completion""" + ip = get_ipython() + complete = ip.Completer.complete + + ip.user_ns["d"] = {"abc": None, b"abd": None} + + _, matches = complete(line_buffer="d[") + self.assertIn("'abc'", matches) + self.assertIn("b'abd'", matches) + + if False: # not currently implemented + _, matches = complete(line_buffer="d[b") + self.assertIn("b'abd'", matches) + self.assertNotIn("b'abc'", matches) + + _, matches = complete(line_buffer="d[b'") + self.assertIn("abd", matches) + self.assertNotIn("abc", matches) + + _, matches = complete(line_buffer="d[B'") + self.assertIn("abd", matches) + self.assertNotIn("abc", matches) + + _, matches = complete(line_buffer="d['") + self.assertIn("abc", matches) + self.assertNotIn("abd", matches) + + def test_dict_key_completion_unicode_py3(self): + """Test handling of unicode in dict key completion""" + ip = get_ipython() + complete = ip.Completer.complete + + ip.user_ns["d"] = {"a\u05d0": None} + + # query using escape + if sys.platform != "win32": + # Known failure on Windows + _, matches = complete(line_buffer="d['a\\u05d0") + self.assertIn("u05d0", matches) # tokenized after \\ + + # query using character + _, matches = complete(line_buffer="d['a\u05d0") + self.assertIn("a\u05d0", matches) + + with greedy_completion(): + # query using escape + _, matches = complete(line_buffer="d['a\\u05d0") + self.assertIn("d['a\\u05d0']", matches) # tokenized after \\ + + # query using character + _, matches = complete(line_buffer="d['a\u05d0") + self.assertIn("d['a\u05d0']", matches) + + @dec.skip_without("numpy") + def test_struct_array_key_completion(self): + """Test dict key completion applies to numpy struct arrays""" + import numpy + + ip = get_ipython() + complete = ip.Completer.complete + ip.user_ns["d"] = numpy.array([], dtype=[("hello", "f"), ("world", "f")]) + _, matches = complete(line_buffer="d['") + self.assertIn("hello", matches) + self.assertIn("world", matches) + # complete on the numpy struct itself + dt = numpy.dtype( + [("my_head", [("my_dt", ">u4"), ("my_df", ">u4")]), ("my_data", ">f4", 5)] + ) + x = numpy.zeros(2, dtype=dt) + ip.user_ns["d"] = x[1] + _, matches = complete(line_buffer="d['") + self.assertIn("my_head", matches) + self.assertIn("my_data", matches) + + def completes_on_nested(): + ip.user_ns["d"] = numpy.zeros(2, dtype=dt) + _, matches = complete(line_buffer="d[1]['my_head']['") + self.assertTrue(any(["my_dt" in m for m in matches])) + self.assertTrue(any(["my_df" in m for m in matches])) + # complete on a nested level + with greedy_completion(): + completes_on_nested() + + with evaluation_policy("limited"): + completes_on_nested() + + with evaluation_policy("minimal"): + with pytest.raises(AssertionError): + completes_on_nested() + + @dec.skip_without("pandas") + def test_dataframe_key_completion(self): + """Test dict key completion applies to pandas DataFrames""" + import pandas + + ip = get_ipython() + complete = ip.Completer.complete + ip.user_ns["d"] = pandas.DataFrame({"hello": [1], "world": [2]}) + _, matches = complete(line_buffer="d['") + self.assertIn("hello", matches) + self.assertIn("world", matches) + _, matches = complete(line_buffer="d.loc[:, '") + self.assertIn("hello", matches) + self.assertIn("world", matches) + _, matches = complete(line_buffer="d.loc[1:, '") + self.assertIn("hello", matches) + _, matches = complete(line_buffer="d.loc[1:1, '") + self.assertIn("hello", matches) + _, matches = complete(line_buffer="d.loc[1:1:-1, '") + self.assertIn("hello", matches) + _, matches = complete(line_buffer="d.loc[::, '") + self.assertIn("hello", matches) + + def test_dict_key_completion_invalids(self): + """Smoke test cases dict key completion can't handle""" + ip = get_ipython() + complete = ip.Completer.complete + + ip.user_ns["no_getitem"] = None + ip.user_ns["no_keys"] = [] + ip.user_ns["cant_call_keys"] = dict + ip.user_ns["empty"] = {} + ip.user_ns["d"] = {"abc": 5} + + _, matches = complete(line_buffer="no_getitem['") + _, matches = complete(line_buffer="no_keys['") + _, matches = complete(line_buffer="cant_call_keys['") + _, matches = complete(line_buffer="empty['") + _, matches = complete(line_buffer="name_error['") + _, matches = complete(line_buffer="d['\\") # incomplete escape + + def test_object_key_completion(self): + ip = get_ipython() + ip.user_ns["key_completable"] = KeyCompletable(["qwerty", "qwick"]) + + _, matches = ip.Completer.complete(line_buffer="key_completable['qw") + self.assertIn("qwerty", matches) + self.assertIn("qwick", matches) + + def test_class_key_completion(self): + ip = get_ipython() + NamedInstanceClass("qwerty") + NamedInstanceClass("qwick") + ip.user_ns["named_instance_class"] = NamedInstanceClass + + _, matches = ip.Completer.complete(line_buffer="named_instance_class['qw") + self.assertIn("qwerty", matches) + self.assertIn("qwick", matches) + + def test_tryimport(self): + """ + Test that try-import don't crash on trailing dot, and import modules before + """ + from IPython.core.completerlib import try_import + + assert try_import("IPython.") + + def test_aimport_module_completer(self): + ip = get_ipython() + _, matches = ip.complete("i", "%aimport i") + self.assertIn("io", matches) + self.assertNotIn("int", matches) + + def test_nested_import_module_completer(self): + ip = get_ipython() + _, matches = ip.complete(None, "import IPython.co", 17) + self.assertIn("IPython.core", matches) + self.assertNotIn("import IPython.core", matches) + self.assertNotIn("IPython.display", matches) + + def test_import_module_completer(self): + ip = get_ipython() + _, matches = ip.complete("i", "import i") + self.assertIn("io", matches) + self.assertNotIn("int", matches) + + def test_from_module_completer(self): + ip = get_ipython() + _, matches = ip.complete("B", "from io import B", 16) + self.assertIn("BytesIO", matches) + self.assertNotIn("BaseException", matches) + + def test_snake_case_completion(self): + ip = get_ipython() + ip.Completer.use_jedi = False + ip.user_ns["some_three"] = 3 + ip.user_ns["some_four"] = 4 + _, matches = ip.complete("s_", "print(s_f") + self.assertIn("some_three", matches) + self.assertIn("some_four", matches) + + def test_mix_terms(self): + ip = get_ipython() + from textwrap import dedent + + ip.Completer.use_jedi = False + ip.ex( + dedent( + """ + class Test: + def meth(self, meth_arg1): + print("meth") + + def meth_1(self, meth1_arg1, meth1_arg2): + print("meth1") + + def meth_2(self, meth2_arg1, meth2_arg2): + print("meth2") + test = Test() + """ + ) + ) + _, matches = ip.complete(None, "test.meth(") + self.assertIn("meth_arg1=", matches) + self.assertNotIn("meth2_arg1=", matches) + + def test_percent_symbol_restrict_to_magic_completions(self): + ip = get_ipython() + completer = ip.Completer + text = "%a" + + with provisionalcompleter(): + completer.use_jedi = True + completions = completer.completions(text, len(text)) + for c in completions: + self.assertEqual(c.text[0], "%") + + def test_fwd_unicode_restricts(self): + ip = get_ipython() + completer = ip.Completer + text = "\\ROMAN NUMERAL FIVE" + + with provisionalcompleter(): + completer.use_jedi = True + completions = [ + completion.text for completion in completer.completions(text, len(text)) + ] + self.assertEqual(completions, ["\u2164"]) + + def test_dict_key_restrict_to_dicts(self): + """Test that dict key suppresses non-dict completion items""" + ip = get_ipython() + c = ip.Completer + d = {"abc": None} + ip.user_ns["d"] = d + + text = 'd["a' + + def _(): + with provisionalcompleter(): + c.use_jedi = True + return [ + completion.text for completion in c.completions(text, len(text)) + ] + + completions = _() + self.assertEqual(completions, ["abc"]) + + # check that it can be disabled in granular manner: + cfg = Config() + cfg.IPCompleter.suppress_competing_matchers = { + "IPCompleter.dict_key_matcher": False + } + c.update_config(cfg) + + completions = _() + self.assertIn("abc", completions) + self.assertGreater(len(completions), 1) + + def test_matcher_suppression(self): + @completion_matcher(identifier="a_matcher") + def a_matcher(text): + return ["completion_a"] + + @completion_matcher(identifier="b_matcher", api_version=2) + def b_matcher(context: CompletionContext): + text = context.token + result = {"completions": [SimpleCompletion("completion_b")]} + + if text == "suppress c": + result["suppress"] = {"c_matcher"} + + if text.startswith("suppress all"): + result["suppress"] = True + if text == "suppress all but c": + result["do_not_suppress"] = {"c_matcher"} + if text == "suppress all but a": + result["do_not_suppress"] = {"a_matcher"} + + return result + + @completion_matcher(identifier="c_matcher") + def c_matcher(text): + return ["completion_c"] + + with custom_matchers([a_matcher, b_matcher, c_matcher]): + ip = get_ipython() + c = ip.Completer + + def _(text, expected): + c.use_jedi = False + s, matches = c.complete(text) + self.assertEqual(expected, matches) + + _("do not suppress", ["completion_a", "completion_b", "completion_c"]) + _("suppress all", ["completion_b"]) + _("suppress all but a", ["completion_a", "completion_b"]) + _("suppress all but c", ["completion_b", "completion_c"]) + + def configure(suppression_config): + cfg = Config() + cfg.IPCompleter.suppress_competing_matchers = suppression_config + c.update_config(cfg) + + # test that configuration takes priority over the run-time decisions + + configure(False) + _("suppress all", ["completion_a", "completion_b", "completion_c"]) + + configure({"b_matcher": False}) + _("suppress all", ["completion_a", "completion_b", "completion_c"]) + + configure({"a_matcher": False}) + _("suppress all", ["completion_b"]) + + configure({"b_matcher": True}) + _("do not suppress", ["completion_b"]) + + configure(True) + _("do not suppress", ["completion_a"]) + + def test_matcher_suppression_with_iterator(self): + @completion_matcher(identifier="matcher_returning_iterator") + def matcher_returning_iterator(text): + return iter(["completion_iter"]) + + @completion_matcher(identifier="matcher_returning_list") + def matcher_returning_list(text): + return ["completion_list"] + + with custom_matchers([matcher_returning_iterator, matcher_returning_list]): + ip = get_ipython() + c = ip.Completer + + def _(text, expected): + c.use_jedi = False + s, matches = c.complete(text) + self.assertEqual(expected, matches) + + def configure(suppression_config): + cfg = Config() + cfg.IPCompleter.suppress_competing_matchers = suppression_config + c.update_config(cfg) + + configure(False) + _("---", ["completion_iter", "completion_list"]) + + configure(True) + _("---", ["completion_iter"]) + + configure(None) + _("--", ["completion_iter", "completion_list"]) + + @pytest.mark.xfail( + sys.version_info.releaselevel in ("alpha",), + reason="Parso does not yet parse 3.13", + ) + def test_matcher_suppression_with_jedi(self): + ip = get_ipython() + c = ip.Completer + c.use_jedi = True + + def configure(suppression_config): + cfg = Config() + cfg.IPCompleter.suppress_competing_matchers = suppression_config + c.update_config(cfg) + + def _(): + with provisionalcompleter(): + matches = [completion.text for completion in c.completions("dict.", 5)] + self.assertIn("keys", matches) + + configure(False) + _() + + configure(True) + _() + + configure(None) + _() + + def test_matcher_disabling(self): + @completion_matcher(identifier="a_matcher") + def a_matcher(text): + return ["completion_a"] + + @completion_matcher(identifier="b_matcher") + def b_matcher(text): + return ["completion_b"] + + def _(expected): + s, matches = c.complete("completion_") + self.assertEqual(expected, matches) + + with custom_matchers([a_matcher, b_matcher]): + ip = get_ipython() + c = ip.Completer + + _(["completion_a", "completion_b"]) + + cfg = Config() + cfg.IPCompleter.disable_matchers = ["b_matcher"] + c.update_config(cfg) + + _(["completion_a"]) + + cfg.IPCompleter.disable_matchers = [] + c.update_config(cfg) + + def test_matcher_priority(self): + @completion_matcher(identifier="a_matcher", priority=0, api_version=2) + def a_matcher(text): + return {"completions": [SimpleCompletion("completion_a")], "suppress": True} + + @completion_matcher(identifier="b_matcher", priority=2, api_version=2) + def b_matcher(text): + return {"completions": [SimpleCompletion("completion_b")], "suppress": True} + + def _(expected): + s, matches = c.complete("completion_") + self.assertEqual(expected, matches) + + with custom_matchers([a_matcher, b_matcher]): + ip = get_ipython() + c = ip.Completer + + _(["completion_b"]) + a_matcher.matcher_priority = 3 + _(["completion_a"]) + + +@pytest.mark.parametrize( + "line,expected", + [ + # Basic test cases + ("np.", "attribute"), + ("np.ran", "attribute"), + ("np.random.rand(np.random.ran", "attribute"), + ("np.random.rand(n", "global"), + ("d['k.e.y.'](ran", "global"), + ("d[0].k", "attribute"), + ("a = { 'a': np.ran", "attribute"), + ("n", "global"), + ("", "global"), + # Dots in string literals + ('some_var = "this is a string with a dot.', "global"), + ("text = 'another string with a dot.", "global"), + ('f"greeting {user.na', "attribute"), # Cursor in f-string expression + ('t"welcome {guest.na', "attribute"), # Cursor in t-string expression + ('f"hello {name} worl', "global"), # Cursor in f-string outside expression + ('f"hello {{a.', "global"), + ('f"hello {{{a.', "attribute"), + # Backslash escapes in strings + ('var = "string with \\"escaped quote and a dot.', "global"), + ("escaped = 'single \\'quote\\' with a dot.", "global"), + # Multi-line strings + ('multi = """This is line one\nwith a dot.', "global"), + ("multi_single = '''Another\nmulti-line\nwith a dot.", "global"), + # Inline comments + ("x = 5 # This is a comment", "global"), + ("y = obj.method() # Comment after dot.method", "global"), + # Hash symbol within string literals should not be treated as comments + ("d['#'] = np.", "attribute"), + # Nested parentheses with dots + ("complex_expr = (func((obj.method(param.attr", "attribute"), + ("multiple_nesting = {key: [value.attr", "attribute"), + # Numbers + ("3.", "global"), + ("3.14", "global"), + ("-42.14", "global"), + ("x = func(3.14", "global"), + ("x = func(a3.", "attribute"), + ("x = func(a3.12", "global"), + ("3.1.", "attribute"), + ("-3.1.", "attribute"), + ("(3).", "attribute"), + # Additional cases + ("", "global"), + ('str_with_code = "x.attr', "global"), + ('f"formatted {obj.attr', "attribute"), + ('f"formatted {obj.attr}', "global"), + ("dict_with_dots = {'key.with.dots': value.attr", "attribute"), + ("d[f'{a}']['{a.", "global"), + ], +) +def test_completion_context(line, expected): + """Test completion context""" + ip = get_ipython() + get_context = ip.Completer._determine_completion_context + result = get_context(line) + assert result.value == expected, f"Failed on input: '{line}'" + + +@pytest.mark.xfail(reason="Completion context not yet supported") +@pytest.mark.parametrize( + "line, expected", + [ + ("f'{f'a.", "global"), # Nested f-string + ("3a.", "global"), # names starting with numbers or other symbols + ("$).", "global"), # random things with dot at end + ], +) +def test_unsupported_completion_context(line, expected): + """Test unsupported completion context""" + ip = get_ipython() + get_context = ip.Completer._determine_completion_context + result = get_context(line) + assert result.value == expected, f"Failed on input: '{line}'" + + +@pytest.mark.parametrize( + "setup,code,expected,not_expected", + [ + ('a="str"; b=1', "(a, b.", [".bit_count", ".conjugate"], [".count"]), + ('a="str"; b=1', "(a, b).", [".count"], [".bit_count", ".capitalize"]), + ('x="str"; y=1', "x = {1, y.", [".bit_count"], [".count"]), + ('x="str"; y=1', "x = [1, y.", [".bit_count"], [".count"]), + ('x="str"; y=1; fun=lambda x:x', "x = fun(1, y.", [".bit_count"], [".count"]), + ], +) +def test_misc_no_jedi_completions(setup, code, expected, not_expected): + ip = get_ipython() + c = ip.Completer + ip.ex(setup) + with provisionalcompleter(), jedi_status(False): + matches = c.all_completions(code) + assert set(expected) - set(matches) == set(), set(matches) + assert set(matches).intersection(set(not_expected)) == set() + + +@pytest.mark.parametrize( + "code,expected", + [ + (" (a, b", "b"), + ("(a, b", "b"), + ("(a, b)", ""), # trim always start by trimming + (" (a, b)", "(a, b)"), + (" [a, b]", "[a, b]"), + (" a, b", "b"), + ("x = {1, y", "y"), + ("x = [1, y", "y"), + ("x = fun(1, y", "y"), + ], +) +def test_trim_expr(code, expected): + c = get_ipython().Completer + assert c._trim_expr(code) == expected + + +@pytest.mark.parametrize( + "input, expected", + [ + ["1.234", "1.234"], + # should match signed numbers + ["+1", "+1"], + ["-1", "-1"], + ["-1.0", "-1.0"], + ["-1.", "-1."], + ["+1.", "+1."], + [".1", ".1"], + # should not match non-numbers + ["1..", None], + ["..", None], + [".1.", None], + # should match after comma + [",1", "1"], + [", 1", "1"], + [", .1", ".1"], + [", +.1", "+.1"], + # should not match after trailing spaces + [".1 ", None], + # some complex cases + ["0b_0011_1111_0100_1110", "0b_0011_1111_0100_1110"], + ["0xdeadbeef", "0xdeadbeef"], + ["0b_1110_0101", "0b_1110_0101"], + # should not match if in an operation + ["1 + 1", None], + [", 1 + 1", None], + ], +) +def test_match_numeric_literal_for_dict_key(input, expected): + assert _match_number_in_dict_key_prefix(input) == expected diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_completerlib.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_completerlib.py new file mode 100644 index 0000000000000000000000000000000000000000..b8328067a017300735670e590ee30d02b85d7c01 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_completerlib.py @@ -0,0 +1,193 @@ +# -*- coding: utf-8 -*- +"""Tests for completerlib. + +""" + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +import os +import shutil +import sys +import tempfile +import unittest +from os.path import join + +from tempfile import TemporaryDirectory + +from IPython.core.completerlib import magic_run_completer, module_completion, try_import +from IPython.testing.decorators import onlyif_unicode_paths + + +class MockEvent(object): + def __init__(self, line): + self.line = line + +#----------------------------------------------------------------------------- +# Test functions begin +#----------------------------------------------------------------------------- +class Test_magic_run_completer(unittest.TestCase): + files = [u"aao.py", u"a.py", u"b.py", u"aao.txt"] + dirs = [u"adir/", "bdir/"] + + def setUp(self): + self.BASETESTDIR = tempfile.mkdtemp() + for fil in self.files: + with open(join(self.BASETESTDIR, fil), "w", encoding="utf-8") as sfile: + sfile.write("pass\n") + for d in self.dirs: + os.mkdir(join(self.BASETESTDIR, d)) + + self.oldpath = os.getcwd() + os.chdir(self.BASETESTDIR) + + def tearDown(self): + os.chdir(self.oldpath) + shutil.rmtree(self.BASETESTDIR) + + def test_1(self): + """Test magic_run_completer, should match two alternatives + """ + event = MockEvent(u"%run a") + mockself = None + match = set(magic_run_completer(mockself, event)) + self.assertEqual(match, {u"a.py", u"aao.py", u"adir/"}) + + def test_2(self): + """Test magic_run_completer, should match one alternative + """ + event = MockEvent(u"%run aa") + mockself = None + match = set(magic_run_completer(mockself, event)) + self.assertEqual(match, {u"aao.py"}) + + def test_3(self): + """Test magic_run_completer with unterminated " """ + event = MockEvent(u'%run "a') + mockself = None + match = set(magic_run_completer(mockself, event)) + self.assertEqual(match, {u"a.py", u"aao.py", u"adir/"}) + + def test_completion_more_args(self): + event = MockEvent(u'%run a.py ') + match = set(magic_run_completer(None, event)) + self.assertEqual(match, set(self.files + self.dirs)) + + def test_completion_in_dir(self): + # Github issue #3459 + event = MockEvent(u'%run a.py {}'.format(join(self.BASETESTDIR, 'a'))) + print(repr(event.line)) + match = set(magic_run_completer(None, event)) + # We specifically use replace here rather than normpath, because + # at one point there were duplicates 'adir' and 'adir/', and normpath + # would hide the failure for that. + self.assertEqual(match, {join(self.BASETESTDIR, f).replace('\\','/') + for f in (u'a.py', u'aao.py', u'aao.txt', u'adir/')}) + +class Test_magic_run_completer_nonascii(unittest.TestCase): + @onlyif_unicode_paths + def setUp(self): + self.BASETESTDIR = tempfile.mkdtemp() + for fil in [u"aaø.py", u"a.py", u"b.py"]: + with open(join(self.BASETESTDIR, fil), "w", encoding="utf-8") as sfile: + sfile.write("pass\n") + self.oldpath = os.getcwd() + os.chdir(self.BASETESTDIR) + + def tearDown(self): + os.chdir(self.oldpath) + shutil.rmtree(self.BASETESTDIR) + + @onlyif_unicode_paths + def test_1(self): + """Test magic_run_completer, should match two alternatives + """ + event = MockEvent(u"%run a") + mockself = None + match = set(magic_run_completer(mockself, event)) + self.assertEqual(match, {u"a.py", u"aaø.py"}) + + @onlyif_unicode_paths + def test_2(self): + """Test magic_run_completer, should match one alternative + """ + event = MockEvent(u"%run aa") + mockself = None + match = set(magic_run_completer(mockself, event)) + self.assertEqual(match, {u"aaø.py"}) + + @onlyif_unicode_paths + def test_3(self): + """Test magic_run_completer with unterminated " """ + event = MockEvent(u'%run "a') + mockself = None + match = set(magic_run_completer(mockself, event)) + self.assertEqual(match, {u"a.py", u"aaø.py"}) + +# module_completer: + +def test_import_invalid_module(): + """Testing of issue https://github.com/ipython/ipython/issues/1107""" + invalid_module_names = {'foo-bar', 'foo:bar', '10foo'} + valid_module_names = {'foobar'} + with TemporaryDirectory() as tmpdir: + sys.path.insert( 0, tmpdir ) + for name in invalid_module_names | valid_module_names: + filename = os.path.join(tmpdir, name + ".py") + open(filename, "w", encoding="utf-8").close() + + s = set( module_completion('import foo') ) + intersection = s.intersection(invalid_module_names) + assert intersection == set() + + assert valid_module_names.issubset(s), valid_module_names.intersection(s) + + +def test_bad_module_all(): + """Test module with invalid __all__ + + https://github.com/ipython/ipython/issues/9678 + """ + testsdir = os.path.dirname(__file__) + sys.path.insert(0, testsdir) + try: + results = module_completion("from bad_all import ") + assert "puppies" in results + for r in results: + assert isinstance(r, str) + + # bad_all doesn't contain submodules, but this completion + # should finish without raising an exception: + results = module_completion("import bad_all.") + assert results == [] + finally: + sys.path.remove(testsdir) + + +def test_module_without_init(): + """ + Test module without __init__.py. + + https://github.com/ipython/ipython/issues/11226 + """ + fake_module_name = "foo" + with TemporaryDirectory() as tmpdir: + sys.path.insert(0, tmpdir) + try: + os.makedirs(os.path.join(tmpdir, fake_module_name)) + s = try_import(mod=fake_module_name) + assert s == [], f"for module {fake_module_name}" + finally: + sys.path.remove(tmpdir) + + +def test_valid_exported_submodules(): + """ + Test checking exported (__all__) objects are submodules + """ + results = module_completion("import os.pa") + # ensure we get a valid submodule: + assert "os.path" in results + # ensure we don't get objects that aren't submodules: + assert "os.pathconf" not in results diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_debugger.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_debugger.py new file mode 100644 index 0000000000000000000000000000000000000000..6113ff920c4142d169ec3f8e34c113fd4b4ba6e5 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_debugger.py @@ -0,0 +1,592 @@ +"""Tests for debugging machinery. +""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + +import builtins +import os +import sys +import platform + +from tempfile import NamedTemporaryFile +from textwrap import dedent +from unittest.mock import patch + +from IPython.core import debugger +from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE +from IPython.testing.decorators import skip_win32 +import pytest + +#----------------------------------------------------------------------------- +# Helper classes, from CPython's Pdb test suite +#----------------------------------------------------------------------------- + +class _FakeInput(object): + """ + A fake input stream for pdb's interactive debugger. Whenever a + line is read, print it (to simulate the user typing it), and then + return it. The set of lines to return is specified in the + constructor; they should not have trailing newlines. + """ + def __init__(self, lines): + self.lines = iter(lines) + + def readline(self): + line = next(self.lines) + print(line) + return line+'\n' + +class PdbTestInput(object): + """Context manager that makes testing Pdb in doctests easier.""" + + def __init__(self, input): + self.input = input + + def __enter__(self): + self.real_stdin = sys.stdin + sys.stdin = _FakeInput(self.input) + + def __exit__(self, *exc): + sys.stdin = self.real_stdin + +#----------------------------------------------------------------------------- +# Tests +#----------------------------------------------------------------------------- + +def test_ipdb_magics(): + '''Test calling some IPython magics from ipdb. + + First, set up some test functions and classes which we can inspect. + + In [1]: class ExampleClass(object): + ...: """Docstring for ExampleClass.""" + ...: def __init__(self): + ...: """Docstring for ExampleClass.__init__""" + ...: pass + ...: def __str__(self): + ...: return "ExampleClass()" + + In [2]: def example_function(x, y, z="hello"): + ...: """Docstring for example_function.""" + ...: pass + + In [3]: old_trace = sys.gettrace() + + Create a function which triggers ipdb. + + In [4]: def trigger_ipdb(): + ...: a = ExampleClass() + ...: debugger.Pdb().set_trace() + + Run ipdb with faked input & check output. Because of a difference between + Python 3.13 & older versions, the first bit of the output is inconsistent. + We need to use ... to accommodate that, so the examples have to use IPython + prompts so that ... is distinct from the Python PS2 prompt. + + In [5]: with PdbTestInput([ + ...: 'pdef example_function', + ...: 'pdoc ExampleClass', + ...: 'up', + ...: 'down', + ...: 'list', + ...: 'pinfo a', + ...: 'll', + ...: 'continue', + ...: ]): + ...: trigger_ipdb() + ...> (3)trigger_ipdb() + 1 def trigger_ipdb(): + 2 a = ExampleClass() + ----> 3 debugger.Pdb().set_trace() + + ipdb> pdef example_function + example_function(x, y, z='hello') + ipdb> pdoc ExampleClass + Class docstring: + Docstring for ExampleClass. + Init docstring: + Docstring for ExampleClass.__init__ + ipdb> up + > (11)() + 7 'pinfo a', + 8 'll', + 9 'continue', + 10 ]): + ---> 11 trigger_ipdb() + + ipdb> down... + > (3)trigger_ipdb() + 1 def trigger_ipdb(): + 2 a = ExampleClass() + ----> 3 debugger.Pdb().set_trace() + + ipdb> list + 1 def trigger_ipdb(): + 2 a = ExampleClass() + ----> 3 debugger.Pdb().set_trace() + + ipdb> pinfo a + Type: ExampleClass + String form: ExampleClass() + Namespace: Local... + Docstring: Docstring for ExampleClass. + Init docstring: Docstring for ExampleClass.__init__ + ipdb> ll + 1 def trigger_ipdb(): + 2 a = ExampleClass() + ----> 3 debugger.Pdb().set_trace() + + ipdb> continue + + Restore previous trace function, e.g. for coverage.py + + In [6]: sys.settrace(old_trace) + ''' + +def test_ipdb_magics2(): + '''Test ipdb with a very short function. + + >>> old_trace = sys.gettrace() + + >>> def bar(): + ... pass + + Run ipdb. + + >>> with PdbTestInput([ + ... 'continue', + ... ]): + ... debugger.Pdb().runcall(bar) + > (2)bar() + 1 def bar(): + ----> 2 pass + + ipdb> continue + + Restore previous trace function, e.g. for coverage.py + + >>> sys.settrace(old_trace) + ''' + +def can_quit(): + '''Test that quit work in ipydb + + >>> old_trace = sys.gettrace() + + >>> def bar(): + ... pass + + >>> with PdbTestInput([ + ... 'quit', + ... ]): + ... debugger.Pdb().runcall(bar) + > (2)bar() + 1 def bar(): + ----> 2 pass + + ipdb> quit + + Restore previous trace function, e.g. for coverage.py + + >>> sys.settrace(old_trace) + ''' + + +def can_exit(): + '''Test that quit work in ipydb + + >>> old_trace = sys.gettrace() + + >>> def bar(): + ... pass + + >>> with PdbTestInput([ + ... 'exit', + ... ]): + ... debugger.Pdb().runcall(bar) + > (2)bar() + 1 def bar(): + ----> 2 pass + + ipdb> exit + + Restore previous trace function, e.g. for coverage.py + + >>> sys.settrace(old_trace) + ''' + + +def test_interruptible_core_debugger(): + """The debugger can be interrupted. + + The presumption is there is some mechanism that causes a KeyboardInterrupt + (this is implemented in ipykernel). We want to ensure the + KeyboardInterrupt cause debugging to cease. + """ + def raising_input(msg="", called=[0]): + called[0] += 1 + assert called[0] == 1, "input() should only be called once!" + raise KeyboardInterrupt() + + tracer_orig = sys.gettrace() + try: + with patch.object(builtins, "input", raising_input): + debugger.InterruptiblePdb().set_trace() + # The way this test will fail is by set_trace() never exiting, + # resulting in a timeout by the test runner. The alternative + # implementation would involve a subprocess, but that adds issues + # with interrupting subprocesses that are rather complex, so it's + # simpler just to do it this way. + finally: + # restore the original trace function + sys.settrace(tracer_orig) + + +@skip_win32 +def test_xmode_skip(): + """that xmode skip frames + + Not as a doctest as pytest does not run doctests. + """ + import pexpect + env = os.environ.copy() + env["IPY_TEST_SIMPLE_PROMPT"] = "1" + + child = pexpect.spawn( + sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env + ) + child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE + + child.expect("IPython") + child.expect("\n") + child.expect_exact("In [1]") + + block = dedent( + """ + def f(): + __tracebackhide__ = True + g() + + def g(): + raise ValueError + + f() + """ + ) + + for line in block.splitlines(): + child.sendline(line) + child.expect_exact(line) + child.expect_exact("skipping") + + block = dedent( + """ + def f(): + __tracebackhide__ = True + g() + + def g(): + from IPython.core.debugger import set_trace + set_trace() + + f() + """ + ) + + for line in block.splitlines(): + child.sendline(line) + child.expect_exact(line) + + child.expect("ipdb>") + child.sendline("w") + child.expect("hidden") + child.expect("ipdb>") + child.sendline("skip_hidden false") + child.sendline("w") + child.expect("__traceba") + child.expect("ipdb>") + + child.close() + + +skip_decorators_blocks = ( + """ + def helpers_helper(): + pass # should not stop here except breakpoint + """, + """ + def helper_1(): + helpers_helper() # should not stop here + """, + """ + def helper_2(): + pass # should not stop here + """, + """ + def pdb_skipped_decorator2(function): + def wrapped_fn(*args, **kwargs): + __debuggerskip__ = True + helper_2() + __debuggerskip__ = False + result = function(*args, **kwargs) + __debuggerskip__ = True + helper_2() + return result + return wrapped_fn + """, + """ + def pdb_skipped_decorator(function): + def wrapped_fn(*args, **kwargs): + __debuggerskip__ = True + helper_1() + __debuggerskip__ = False + result = function(*args, **kwargs) + __debuggerskip__ = True + helper_2() + return result + return wrapped_fn + """, + """ + @pdb_skipped_decorator + @pdb_skipped_decorator2 + def bar(x, y): + return x * y + """, + """import IPython.terminal.debugger as ipdb""", + """ + def f(): + ipdb.set_trace() + bar(3, 4) + """, + """ + f() + """, +) + + +def _decorator_skip_setup(): + import pexpect + + env = os.environ.copy() + env["IPY_TEST_SIMPLE_PROMPT"] = "1" + env["PROMPT_TOOLKIT_NO_CPR"] = "1" + + child = pexpect.spawn( + sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env + ) + child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE + + child.expect("IPython") + child.expect("\n") + + child.timeout = 5 * IPYTHON_TESTING_TIMEOUT_SCALE + child.str_last_chars = 500 + + dedented_blocks = [dedent(b).strip() for b in skip_decorators_blocks] + in_prompt_number = 1 + for cblock in dedented_blocks: + child.expect_exact(f"In [{in_prompt_number}]:") + in_prompt_number += 1 + for line in cblock.splitlines(): + child.sendline(line) + child.expect_exact(line) + child.sendline("") + return child + + +@pytest.mark.skip(reason="recently fail for unknown reason on CI") +@skip_win32 +def test_decorator_skip(): + """test that decorator frames can be skipped.""" + + child = _decorator_skip_setup() + + child.expect_exact("ipython-input-8") + child.expect_exact("3 bar(3, 4)") + child.expect("ipdb>") + + child.expect("ipdb>") + child.sendline("step") + child.expect_exact("step") + child.expect_exact("--Call--") + child.expect_exact("ipython-input-6") + + child.expect_exact("1 @pdb_skipped_decorator") + + child.sendline("s") + child.expect_exact("return x * y") + + child.close() + + +@pytest.mark.skip(reason="recently fail for unknown reason on CI") +@pytest.mark.skipif(platform.python_implementation() == "PyPy", reason="issues on PyPy") +@skip_win32 +def test_decorator_skip_disabled(): + """test that decorator frame skipping can be disabled""" + + child = _decorator_skip_setup() + + child.expect_exact("3 bar(3, 4)") + + for input_, expected in [ + ("skip_predicates debuggerskip False", ""), + ("skip_predicates", "debuggerskip : False"), + ("step", "---> 2 def wrapped_fn"), + ("step", "----> 3 __debuggerskip__"), + ("step", "----> 4 helper_1()"), + ("step", "---> 1 def helper_1():"), + ("next", "----> 2 helpers_helper()"), + ("next", "--Return--"), + ("next", "----> 5 __debuggerskip__ = False"), + ]: + child.expect("ipdb>") + child.sendline(input_) + child.expect_exact(input_) + child.expect_exact(expected) + + child.close() + + +@pytest.mark.xfail( + sys.version_info.releaselevel not in ("final", "candidate"), + reason="fails on 3.13.dev", + strict=True, +) +@pytest.mark.skipif(platform.python_implementation() == "PyPy", reason="issues on PyPy") +@skip_win32 +def test_decorator_skip_with_breakpoint(): + """test that decorator frame skipping can be disabled""" + + import pexpect + + env = os.environ.copy() + env["IPY_TEST_SIMPLE_PROMPT"] = "1" + env["PROMPT_TOOLKIT_NO_CPR"] = "1" + + child = pexpect.spawn( + sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env + ) + child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE + child.str_last_chars = 500 + + child.expect("IPython") + child.expect("\n") + + child.timeout = 5 * IPYTHON_TESTING_TIMEOUT_SCALE + + ### we need a filename, so we need to exec the full block with a filename + with NamedTemporaryFile(suffix=".py", dir=".", delete=True) as tf: + name = tf.name[:-3].split("/")[-1] + tf.write("\n".join([dedent(x) for x in skip_decorators_blocks[:-1]]).encode()) + tf.flush() + codeblock = f"from {name} import f" + + dedented_blocks = [ + codeblock, + "f()", + ] + + in_prompt_number = 1 + for cblock in dedented_blocks: + child.expect_exact(f"In [{in_prompt_number}]:") + in_prompt_number += 1 + for line in cblock.splitlines(): + child.sendline(line) + child.expect_exact(line) + child.sendline("") + + # From 3.13, set_trace()/breakpoint() stop on the line where they're + # called, instead of the next line. + if sys.version_info >= (3, 13): + child.expect_exact("--> 46 ipdb.set_trace()") + extra_step = [("step", "--> 47 bar(3, 4)")] + else: + child.expect_exact("--> 47 bar(3, 4)") + extra_step = [] + + for input_, expected in ( + [ + (f"b {name}.py:3", ""), + ] + + extra_step + + [ + ("step", "1---> 3 pass # should not stop here except"), + ("step", "---> 38 @pdb_skipped_decorator"), + ("continue", ""), + ] + ): + child.expect("ipdb>") + child.sendline(input_) + child.expect_exact(input_) + child.expect_exact(expected) + + child.close() + + +@skip_win32 +def test_where_erase_value(): + """Test that `where` does not access f_locals and erase values.""" + import pexpect + + env = os.environ.copy() + env["IPY_TEST_SIMPLE_PROMPT"] = "1" + + child = pexpect.spawn( + sys.executable, ["-m", "IPython", "--colors=nocolor"], env=env + ) + child.timeout = 15 * IPYTHON_TESTING_TIMEOUT_SCALE + + child.expect("IPython") + child.expect("\n") + child.expect_exact("In [1]") + + block = dedent( + """ + def simple_f(): + myvar = 1 + print(myvar) + 1/0 + print(myvar) + simple_f() """ + ) + + for line in block.splitlines(): + child.sendline(line) + child.expect_exact(line) + child.expect_exact("ZeroDivisionError") + child.expect_exact("In [2]:") + + child.sendline("%debug") + + ## + child.expect("ipdb>") + + child.sendline("myvar") + child.expect("1") + + ## + child.expect("ipdb>") + + child.sendline("myvar = 2") + + ## + child.expect_exact("ipdb>") + + child.sendline("myvar") + + child.expect_exact("2") + + ## + child.expect("ipdb>") + child.sendline("where") + + ## + child.expect("ipdb>") + child.sendline("myvar") + + child.expect_exact("2") + child.expect("ipdb>") + + child.close() diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_display.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_display.py new file mode 100644 index 0000000000000000000000000000000000000000..b7c525339281c03b07b121923593efe51b1f82bb --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_display.py @@ -0,0 +1,513 @@ +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + +import json +import os +import warnings + +from unittest import mock + +import pytest + +from IPython import display +from IPython.core.getipython import get_ipython +from IPython.utils.io import capture_output +from IPython.utils.tempdir import NamedFileInTemporaryDirectory +from IPython import paths as ipath +from IPython.testing.tools import AssertNotPrints + +import IPython.testing.decorators as dec + +def test_image_size(): + """Simple test for display.Image(args, width=x,height=y)""" + thisurl = 'http://www.google.fr/images/srpr/logo3w.png' + img = display.Image(url=thisurl, width=200, height=200) + assert '' % (thisurl) == img._repr_html_() + img = display.Image(url=thisurl, metadata={'width':200, 'height':200}) + assert '' % (thisurl) == img._repr_html_() + img = display.Image(url=thisurl, width=200) + assert '' % (thisurl) == img._repr_html_() + img = display.Image(url=thisurl) + assert '' % (thisurl) == img._repr_html_() + img = display.Image(url=thisurl, unconfined=True) + assert '' % (thisurl) == img._repr_html_() + + +def test_image_mimes(): + fmt = get_ipython().display_formatter.format + for format in display.Image._ACCEPTABLE_EMBEDDINGS: + mime = display.Image._MIMETYPES[format] + img = display.Image(b'garbage', format=format) + data, metadata = fmt(img) + assert sorted(data) == sorted([mime, "text/plain"]) + + +def test_geojson(): + + gj = display.GeoJSON(data={ + "type": "Feature", + "geometry": { + "type": "Point", + "coordinates": [-81.327, 296.038] + }, + "properties": { + "name": "Inca City" + } + }, + url_template="http://s3-eu-west-1.amazonaws.com/whereonmars.cartodb.net/{basemap_id}/{z}/{x}/{y}.png", + layer_options={ + "basemap_id": "celestia_mars-shaded-16k_global", + "attribution": "Celestia/praesepe", + "minZoom": 0, + "maxZoom": 18, + }, + ) + assert "" == str(gj) + + +def test_retina_png(): + here = os.path.dirname(__file__) + img = display.Image(os.path.join(here, "2x2.png"), retina=True) + assert img.height == 1 + assert img.width == 1 + data, md = img._repr_png_() + assert md["width"] == 1 + assert md["height"] == 1 + + +def test_embed_svg_url(): + import gzip + from io import BytesIO + svg_data = b'' + url = 'http://test.com/circle.svg' + + gzip_svg = BytesIO() + with gzip.open(gzip_svg, 'wb') as fp: + fp.write(svg_data) + gzip_svg = gzip_svg.getvalue() + + def mocked_urlopen(*args, **kwargs): + class MockResponse: + def __init__(self, svg): + self._svg_data = svg + self.headers = {'content-type': 'image/svg+xml'} + + def read(self): + return self._svg_data + + if args[0] == url: + return MockResponse(svg_data) + elif args[0] == url + "z": + ret = MockResponse(gzip_svg) + ret.headers["content-encoding"] = "gzip" + return ret + return MockResponse(None) + + with mock.patch('urllib.request.urlopen', side_effect=mocked_urlopen): + svg = display.SVG(url=url) + assert svg._repr_svg_().startswith("" + assert p.data == "This is a simple test" + + p._show_mem_addr = True + assert repr(p) == object.__repr__(p) + + +def test_displayobject_repr(): + h = display.HTML("
") + assert repr(h) == "" + h._show_mem_addr = True + assert repr(h) == object.__repr__(h) + h._show_mem_addr = False + assert repr(h) == "" + + j = display.Javascript("") + assert repr(j) == "" + j._show_mem_addr = True + assert repr(j) == object.__repr__(j) + j._show_mem_addr = False + assert repr(j) == "" + +@mock.patch('warnings.warn') +def test_encourage_iframe_over_html(m_warn): + display.HTML() + m_warn.assert_not_called() + + display.HTML('
') + m_warn.assert_not_called() + + display.HTML('

Lots of content here

') + m_warn.assert_not_called() + + display.HTML('') + m_warn.assert_called_with('Consider using IPython.display.IFrame instead') + + m_warn.reset_mock() + display.HTML('') + m_warn.assert_called_with('Consider using IPython.display.IFrame instead') + +def test_progress(): + p = display.ProgressBar(10) + assert "0/10" in repr(p) + p.html_width = "100%" + p.progress = 5 + assert ( + p._repr_html_() == "" + ) + + +def test_progress_iter(): + with capture_output(display=False) as captured: + for i in display.ProgressBar(5): + out = captured.stdout + assert "{0}/5".format(i) in out + out = captured.stdout + assert "5/5" in out + + +def test_json(): + d = {'a': 5} + lis = [d] + metadata = [ + {'expanded': False, 'root': 'root'}, + {'expanded': True, 'root': 'root'}, + {'expanded': False, 'root': 'custom'}, + {'expanded': True, 'root': 'custom'}, + ] + json_objs = [ + display.JSON(d), + display.JSON(d, expanded=True), + display.JSON(d, root='custom'), + display.JSON(d, expanded=True, root='custom'), + ] + for j, md in zip(json_objs, metadata): + assert j._repr_json_() == (d, md) + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + j = display.JSON(json.dumps(d)) + assert len(w) == 1 + assert j._repr_json_() == (d, metadata[0]) + + json_objs = [ + display.JSON(lis), + display.JSON(lis, expanded=True), + display.JSON(lis, root='custom'), + display.JSON(lis, expanded=True, root='custom'), + ] + for j, md in zip(json_objs, metadata): + assert j._repr_json_() == (lis, md) + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + j = display.JSON(json.dumps(lis)) + assert len(w) == 1 + assert j._repr_json_() == (lis, metadata[0]) + + +def test_video_embedding(): + """use a tempfile, with dummy-data, to ensure that video embedding doesn't crash""" + v = display.Video("http://ignored") + assert not v.embed + html = v._repr_html_() + assert 'src="data:' not in html + assert 'src="http://ignored"' in html + + with pytest.raises(ValueError): + v = display.Video(b'abc') + + with NamedFileInTemporaryDirectory('test.mp4') as f: + f.write(b'abc') + f.close() + + v = display.Video(f.name) + assert not v.embed + html = v._repr_html_() + assert 'src="data:' not in html + + v = display.Video(f.name, embed=True) + html = v._repr_html_() + assert 'src="data:video/mp4;base64,YWJj"' in html + + v = display.Video(f.name, embed=True, mimetype='video/other') + html = v._repr_html_() + assert 'src="data:video/other;base64,YWJj"' in html + + v = display.Video(b'abc', embed=True, mimetype='video/mp4') + html = v._repr_html_() + assert 'src="data:video/mp4;base64,YWJj"' in html + + v = display.Video(u'YWJj', embed=True, mimetype='video/xyz') + html = v._repr_html_() + assert 'src="data:video/xyz;base64,YWJj"' in html + +def test_html_metadata(): + s = "

Test

" + h = display.HTML(s, metadata={"isolated": True}) + assert h._repr_html_() == (s, {"isolated": True}) + + +def test_display_id(): + ip = get_ipython() + with mock.patch.object(ip.display_pub, 'publish') as pub: + handle = display.display('x') + assert handle is None + handle = display.display('y', display_id='secret') + assert isinstance(handle, display.DisplayHandle) + handle2 = display.display('z', display_id=True) + assert isinstance(handle2, display.DisplayHandle) + assert handle.display_id != handle2.display_id + + assert pub.call_count == 3 + args, kwargs = pub.call_args_list[0] + assert args == () + assert kwargs == { + 'data': { + 'text/plain': repr('x') + }, + 'metadata': {}, + } + args, kwargs = pub.call_args_list[1] + assert args == () + assert kwargs == { + 'data': { + 'text/plain': repr('y') + }, + 'metadata': {}, + 'transient': { + 'display_id': handle.display_id, + }, + } + args, kwargs = pub.call_args_list[2] + assert args == () + assert kwargs == { + 'data': { + 'text/plain': repr('z') + }, + 'metadata': {}, + 'transient': { + 'display_id': handle2.display_id, + }, + } + + +def test_update_display(): + ip = get_ipython() + with mock.patch.object(ip.display_pub, 'publish') as pub: + with pytest.raises(TypeError): + display.update_display('x') + display.update_display('x', display_id='1') + display.update_display('y', display_id='2') + args, kwargs = pub.call_args_list[0] + assert args == () + assert kwargs == { + 'data': { + 'text/plain': repr('x') + }, + 'metadata': {}, + 'transient': { + 'display_id': '1', + }, + 'update': True, + } + args, kwargs = pub.call_args_list[1] + assert args == () + assert kwargs == { + 'data': { + 'text/plain': repr('y') + }, + 'metadata': {}, + 'transient': { + 'display_id': '2', + }, + 'update': True, + } + + +def test_display_handle(): + ip = get_ipython() + handle = display.DisplayHandle() + assert isinstance(handle.display_id, str) + handle = display.DisplayHandle("my-id") + assert handle.display_id == "my-id" + with mock.patch.object(ip.display_pub, "publish") as pub: + handle.display("x") + handle.update("y") + + args, kwargs = pub.call_args_list[0] + assert args == () + assert kwargs == { + 'data': { + 'text/plain': repr('x') + }, + 'metadata': {}, + 'transient': { + 'display_id': handle.display_id, + } + } + args, kwargs = pub.call_args_list[1] + assert args == () + assert kwargs == { + 'data': { + 'text/plain': repr('y') + }, + 'metadata': {}, + 'transient': { + 'display_id': handle.display_id, + }, + 'update': True, + } + + +def test_image_alt_tag(): + """Simple test for display.Image(args, alt=x,)""" + thisurl = "http://example.com/image.png" + img = display.Image(url=thisurl, alt="an image") + assert 'an image' % (thisurl) == img._repr_html_() + img = display.Image(url=thisurl, unconfined=True, alt="an image") + assert ( + 'an image' % (thisurl) + == img._repr_html_() + ) + img = display.Image(url=thisurl, alt='>"& <') + assert '>"& <' % (thisurl) == img._repr_html_() + + img = display.Image(url=thisurl, metadata={"alt": "an image"}) + assert img.alt == "an image" + here = os.path.dirname(__file__) + img = display.Image(os.path.join(here, "2x2.png"), alt="an image") + assert img.alt == "an image" + _, md = img._repr_png_() + assert md["alt"] == "an image" + + +def test_image_bad_filename_raises_proper_exception(): + with pytest.raises(FileNotFoundError): + display.Image("/this/file/does/not/exist/")._repr_png_() diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_events.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_events.py new file mode 100644 index 0000000000000000000000000000000000000000..61bc01d40e5a6317e7ea96e8d40ad5e6eecbe76b --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_events.py @@ -0,0 +1,78 @@ +import unittest +from unittest.mock import Mock + +from IPython.core import events +import IPython.testing.tools as tt + + +@events._define_event +def ping_received(): + pass + + +@events._define_event +def event_with_argument(argument): + pass + + +class CallbackTests(unittest.TestCase): + def setUp(self): + self.em = events.EventManager(get_ipython(), + {'ping_received': ping_received, + 'event_with_argument': event_with_argument}) + + def test_register_unregister(self): + cb = Mock() + + self.em.register('ping_received', cb) + self.em.trigger('ping_received') + self.assertEqual(cb.call_count, 1) + + self.em.unregister('ping_received', cb) + self.em.trigger('ping_received') + self.assertEqual(cb.call_count, 1) + + def test_bare_function_missed_unregister(self): + def cb1(): + ... + + def cb2(): + ... + + self.em.register("ping_received", cb1) + self.assertRaises(ValueError, self.em.unregister, "ping_received", cb2) + self.em.unregister("ping_received", cb1) + + def test_cb_error(self): + cb = Mock(side_effect=ValueError) + self.em.register('ping_received', cb) + with tt.AssertPrints("Error in callback"): + self.em.trigger('ping_received') + + def test_cb_keyboard_interrupt(self): + cb = Mock(side_effect=KeyboardInterrupt) + self.em.register('ping_received', cb) + with tt.AssertPrints("Error in callback"): + self.em.trigger('ping_received') + + def test_unregister_during_callback(self): + invoked = [False] * 3 + + def func1(*_): + invoked[0] = True + self.em.unregister('ping_received', func1) + self.em.register('ping_received', func3) + + def func2(*_): + invoked[1] = True + self.em.unregister('ping_received', func2) + + def func3(*_): + invoked[2] = True + + self.em.register('ping_received', func1) + self.em.register('ping_received', func2) + + self.em.trigger('ping_received') + self.assertEqual([True, True, False], invoked) + self.assertEqual([func3], self.em.callbacks['ping_received']) diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_extension.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_extension.py new file mode 100644 index 0000000000000000000000000000000000000000..24ecf7e97e3e56ea51327cc4704ff1fa749c15aa --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_extension.py @@ -0,0 +1,95 @@ +import os.path + +from tempfile import TemporaryDirectory + +import IPython.testing.tools as tt +from IPython.utils.syspathcontext import prepended_to_syspath + +ext1_content = """ +def load_ipython_extension(ip): + print("Running ext1 load") + +def unload_ipython_extension(ip): + print("Running ext1 unload") +""" + +ext2_content = """ +def load_ipython_extension(ip): + print("Running ext2 load") +""" + +ext3_content = """ +def load_ipython_extension(ip): + ip2 = get_ipython() + print(ip is ip2) +""" + +def test_extension_loading(): + em = get_ipython().extension_manager + with TemporaryDirectory() as td: + ext1 = os.path.join(td, "ext1.py") + with open(ext1, "w", encoding="utf-8") as f: + f.write(ext1_content) + + ext2 = os.path.join(td, "ext2.py") + with open(ext2, "w", encoding="utf-8") as f: + f.write(ext2_content) + + with prepended_to_syspath(td): + assert 'ext1' not in em.loaded + assert 'ext2' not in em.loaded + + # Load extension + with tt.AssertPrints("Running ext1 load"): + assert em.load_extension('ext1') is None + assert 'ext1' in em.loaded + + # Should refuse to load it again + with tt.AssertNotPrints("Running ext1 load"): + assert em.load_extension('ext1') == 'already loaded' + + # Reload + with tt.AssertPrints("Running ext1 unload"): + with tt.AssertPrints("Running ext1 load", suppress=False): + em.reload_extension('ext1') + + # Unload + with tt.AssertPrints("Running ext1 unload"): + assert em.unload_extension('ext1') is None + + # Can't unload again + with tt.AssertNotPrints("Running ext1 unload"): + assert em.unload_extension('ext1') == 'not loaded' + assert em.unload_extension('ext2') == 'not loaded' + + # Load extension 2 + with tt.AssertPrints("Running ext2 load"): + assert em.load_extension('ext2') is None + + # Can't unload this + assert em.unload_extension('ext2') == 'no unload function' + + # But can reload it + with tt.AssertPrints("Running ext2 load"): + em.reload_extension('ext2') + + +def test_extension_builtins(): + em = get_ipython().extension_manager + with TemporaryDirectory() as td: + ext3 = os.path.join(td, "ext3.py") + with open(ext3, "w", encoding="utf-8") as f: + f.write(ext3_content) + + assert 'ext3' not in em.loaded + + with prepended_to_syspath(td): + # Load extension + with tt.AssertPrints("True"): + assert em.load_extension('ext3') is None + assert 'ext3' in em.loaded + + +def test_non_extension(): + em = get_ipython().extension_manager + assert em.load_extension("sys") == "no load function" diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_guarded_eval.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_guarded_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..f9057d87052781ccfb67993a040ac54fa236bdae --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_guarded_eval.py @@ -0,0 +1,785 @@ +import sys +from contextlib import contextmanager +from typing import ( + Annotated, + AnyStr, + NamedTuple, + Literal, + NewType, + Optional, + Protocol, + TypeGuard, + Union, + TypedDict, +) +from functools import partial +from IPython.core.guarded_eval import ( + EvaluationContext, + GuardRejection, + guarded_eval, + _unbind_method, +) +from IPython.testing import decorators as dec +import pytest + + +if sys.version_info < (3, 11): + from typing_extensions import Self, LiteralString +else: + from typing import Self, LiteralString + +if sys.version_info < (3, 12): + from typing_extensions import TypeAliasType +else: + from typing import TypeAliasType + + +def create_context(evaluation: str, **kwargs): + return EvaluationContext(locals=kwargs, globals={}, evaluation=evaluation) + + +forbidden = partial(create_context, "forbidden") +minimal = partial(create_context, "minimal") +limited = partial(create_context, "limited") +unsafe = partial(create_context, "unsafe") +dangerous = partial(create_context, "dangerous") + +LIMITED_OR_HIGHER = [limited, unsafe, dangerous] +MINIMAL_OR_HIGHER = [minimal, *LIMITED_OR_HIGHER] + + +@contextmanager +def module_not_installed(module: str): + import sys + + try: + to_restore = sys.modules[module] + del sys.modules[module] + except KeyError: + to_restore = None + try: + yield + finally: + sys.modules[module] = to_restore + + +def test_external_not_installed(): + """ + Because attribute check requires checking if object is not of allowed + external type, this tests logic for absence of external module. + """ + + class Custom: + def __init__(self): + self.test = 1 + + def __getattr__(self, key): + return key + + with module_not_installed("pandas"): + context = limited(x=Custom()) + with pytest.raises(GuardRejection): + guarded_eval("x.test", context) + + +@dec.skip_without("pandas") +def test_external_changed_api(monkeypatch): + """Check that the execution rejects if external API changed paths""" + import pandas as pd + + series = pd.Series([1], index=["a"]) + + with monkeypatch.context() as m: + m.delattr(pd, "Series") + context = limited(data=series) + with pytest.raises(GuardRejection): + guarded_eval("data.iloc[0]", context) + + +@dec.skip_without("pandas") +def test_pandas_series_iloc(): + import pandas as pd + + series = pd.Series([1], index=["a"]) + context = limited(data=series) + assert guarded_eval("data.iloc[0]", context) == 1 + + +def test_rejects_custom_properties(): + class BadProperty: + @property + def iloc(self): + return [None] + + series = BadProperty() + context = limited(data=series) + + with pytest.raises(GuardRejection): + guarded_eval("data.iloc[0]", context) + + +@dec.skip_without("pandas") +def test_accepts_non_overriden_properties(): + import pandas as pd + + class GoodProperty(pd.Series): + pass + + series = GoodProperty([1], index=["a"]) + context = limited(data=series) + + assert guarded_eval("data.iloc[0]", context) == 1 + + +@dec.skip_without("pandas") +def test_pandas_series(): + import pandas as pd + + context = limited(data=pd.Series([1], index=["a"])) + assert guarded_eval('data["a"]', context) == 1 + with pytest.raises(KeyError): + guarded_eval('data["c"]', context) + + +@dec.skip_without("pandas") +def test_pandas_bad_series(): + import pandas as pd + + class BadItemSeries(pd.Series): + def __getitem__(self, key): + return "CUSTOM_ITEM" + + class BadAttrSeries(pd.Series): + def __getattr__(self, key): + return "CUSTOM_ATTR" + + bad_series = BadItemSeries([1], index=["a"]) + context = limited(data=bad_series) + + with pytest.raises(GuardRejection): + guarded_eval('data["a"]', context) + with pytest.raises(GuardRejection): + guarded_eval('data["c"]', context) + + # note: here result is a bit unexpected because + # pandas `__getattr__` calls `__getitem__`; + # FIXME - special case to handle it? + assert guarded_eval("data.a", context) == "CUSTOM_ITEM" + + context = unsafe(data=bad_series) + assert guarded_eval('data["a"]', context) == "CUSTOM_ITEM" + + bad_attr_series = BadAttrSeries([1], index=["a"]) + context = limited(data=bad_attr_series) + assert guarded_eval('data["a"]', context) == 1 + with pytest.raises(GuardRejection): + guarded_eval("data.a", context) + + +@dec.skip_without("pandas") +def test_pandas_dataframe_loc(): + import pandas as pd + from pandas.testing import assert_series_equal + + data = pd.DataFrame([{"a": 1}]) + context = limited(data=data) + assert_series_equal(guarded_eval('data.loc[:, "a"]', context), data["a"]) + + +def test_named_tuple(): + class GoodNamedTuple(NamedTuple): + a: str + pass + + class BadNamedTuple(NamedTuple): + a: str + + def __getitem__(self, key): + return None + + good = GoodNamedTuple(a="x") + bad = BadNamedTuple(a="x") + + context = limited(data=good) + assert guarded_eval("data[0]", context) == "x" + + context = limited(data=bad) + with pytest.raises(GuardRejection): + guarded_eval("data[0]", context) + + +def test_dict(): + context = limited(data={"a": 1, "b": {"x": 2}, ("x", "y"): 3}) + assert guarded_eval('data["a"]', context) == 1 + assert guarded_eval('data["b"]', context) == {"x": 2} + assert guarded_eval('data["b"]["x"]', context) == 2 + assert guarded_eval('data["x", "y"]', context) == 3 + + assert guarded_eval("data.keys", context) + + +def test_set(): + context = limited(data={"a", "b"}) + assert guarded_eval("data.difference", context) + + +def test_list(): + context = limited(data=[1, 2, 3]) + assert guarded_eval("data[1]", context) == 2 + assert guarded_eval("data.copy", context) + + +def test_dict_literal(): + context = limited() + assert guarded_eval("{}", context) == {} + assert guarded_eval('{"a": 1}', context) == {"a": 1} + + +def test_list_literal(): + context = limited() + assert guarded_eval("[]", context) == [] + assert guarded_eval('[1, "a"]', context) == [1, "a"] + + +def test_set_literal(): + context = limited() + assert guarded_eval("set()", context) == set() + assert guarded_eval('{"a"}', context) == {"a"} + + +def test_evaluates_if_expression(): + context = limited() + assert guarded_eval("2 if True else 3", context) == 2 + assert guarded_eval("4 if False else 5", context) == 5 + + +def test_object(): + obj = object() + context = limited(obj=obj) + assert guarded_eval("obj.__dir__", context) == obj.__dir__ + + +@pytest.mark.parametrize( + "code,expected", + [ + ["int.numerator", int.numerator], + ["float.is_integer", float.is_integer], + ["complex.real", complex.real], + ], +) +def test_number_attributes(code, expected): + assert guarded_eval(code, limited()) == expected + + +def test_method_descriptor(): + context = limited() + assert guarded_eval("list.copy.__name__", context) == "copy" + + +class HeapType: + pass + + +class CallCreatesHeapType: + def __call__(self) -> HeapType: + return HeapType() + + +class CallCreatesBuiltin: + def __call__(self) -> frozenset: + return frozenset() + + +class HasStaticMethod: + @staticmethod + def static_method() -> HeapType: + return HeapType() + + +class InitReturnsFrozenset: + def __new__(self) -> frozenset: # type:ignore[misc] + return frozenset() + + +class StringAnnotation: + def heap(self) -> "HeapType": + return HeapType() + + def copy(self) -> "StringAnnotation": + return StringAnnotation() + + +CustomIntType = NewType("CustomIntType", int) +CustomHeapType = NewType("CustomHeapType", HeapType) +IntTypeAlias = TypeAliasType("IntTypeAlias", int) +HeapTypeAlias = TypeAliasType("HeapTypeAlias", HeapType) + + +class TestProtocol(Protocol): + def test_method(self) -> bool: + pass + + +class TestProtocolImplementer(TestProtocol): + def test_method(self) -> bool: + return True + + +class Movie(TypedDict): + name: str + year: int + + +class SpecialTyping: + def custom_int_type(self) -> CustomIntType: + return CustomIntType(1) + + def custom_heap_type(self) -> CustomHeapType: + return CustomHeapType(HeapType()) + + # TODO: remove type:ignore comment once mypy + # supports explicit calls to `TypeAliasType`, see: + # https://github.com/python/mypy/issues/16614 + def int_type_alias(self) -> IntTypeAlias: # type:ignore[valid-type] + return 1 + + def heap_type_alias(self) -> HeapTypeAlias: # type:ignore[valid-type] + return 1 + + def literal(self) -> Literal[False]: + return False + + def literal_string(self) -> LiteralString: + return "test" + + def self(self) -> Self: + return self + + def any_str(self, x: AnyStr) -> AnyStr: + return x + + def annotated(self) -> Annotated[float, "positive number"]: + return 1 + + def annotated_self(self) -> Annotated[Self, "self with metadata"]: + self._metadata = "test" + return self + + def int_type_guard(self, x) -> TypeGuard[int]: + return isinstance(x, int) + + def optional_float(self) -> Optional[float]: + return 1.0 + + def union_str_and_int(self) -> Union[str, int]: + return "" + + def protocol(self) -> TestProtocol: + return TestProtocolImplementer() + + def typed_dict(self) -> Movie: + return {"name": "The Matrix", "year": 1999} + + +@pytest.mark.parametrize( + "data,code,expected,equality", + [ + [[1, 2, 3], "data.index(2)", 1, True], + [{"a": 1}, "data.keys().isdisjoint({})", True, True], + [StringAnnotation(), "data.heap()", HeapType, False], + [StringAnnotation(), "data.copy()", StringAnnotation, False], + # test cases for `__call__` + [CallCreatesHeapType(), "data()", HeapType, False], + [CallCreatesBuiltin(), "data()", frozenset, False], + # Test cases for `__init__` + [HeapType, "data()", HeapType, False], + [InitReturnsFrozenset, "data()", frozenset, False], + [HeapType(), "data.__class__()", HeapType, False], + # supported special cases for typing + [SpecialTyping(), "data.custom_int_type()", int, False], + [SpecialTyping(), "data.custom_heap_type()", HeapType, False], + [SpecialTyping(), "data.int_type_alias()", int, False], + [SpecialTyping(), "data.heap_type_alias()", HeapType, False], + [SpecialTyping(), "data.self()", SpecialTyping, False], + [SpecialTyping(), "data.literal()", False, True], + [SpecialTyping(), "data.literal_string()", str, False], + [SpecialTyping(), "data.any_str('a')", str, False], + [SpecialTyping(), "data.any_str(b'a')", bytes, False], + [SpecialTyping(), "data.annotated()", float, False], + [SpecialTyping(), "data.annotated_self()", SpecialTyping, False], + [SpecialTyping(), "data.int_type_guard()", int, False], + # test cases for static methods + [HasStaticMethod, "data.static_method()", HeapType, False], + ], +) +def test_evaluates_calls(data, code, expected, equality): + context = limited(data=data, HeapType=HeapType, StringAnnotation=StringAnnotation) + value = guarded_eval(code, context) + if equality: + assert value == expected + else: + assert isinstance(value, expected) + + +@pytest.mark.parametrize( + "data,code,expected_attributes", + [ + [SpecialTyping(), "data.optional_float()", ["is_integer"]], + [ + SpecialTyping(), + "data.union_str_and_int()", + ["capitalize", "as_integer_ratio"], + ], + [SpecialTyping(), "data.protocol()", ["test_method"]], + [SpecialTyping(), "data.typed_dict()", ["keys", "values", "items"]], + ], +) +def test_mocks_attributes_of_call_results(data, code, expected_attributes): + context = limited(data=data, HeapType=HeapType, StringAnnotation=StringAnnotation) + result = guarded_eval(code, context) + for attr in expected_attributes: + assert hasattr(result, attr) + assert attr in dir(result) + + +@pytest.mark.parametrize( + "data,code,expected_items", + [ + [SpecialTyping(), "data.typed_dict()", {"year": int, "name": str}], + ], +) +def test_mocks_items_of_call_results(data, code, expected_items): + context = limited(data=data, HeapType=HeapType, StringAnnotation=StringAnnotation) + result = guarded_eval(code, context) + ipython_keys = result._ipython_key_completions_() + for key, value in expected_items.items(): + assert isinstance(result[key], value) + assert key in ipython_keys + + +@pytest.mark.parametrize( + "data,bad", + [ + [[1, 2, 3], "data.append(4)"], + [{"a": 1}, "data.update()"], + ], +) +def test_rejects_calls_with_side_effects(data, bad): + context = limited(data=data) + + with pytest.raises(GuardRejection): + guarded_eval(bad, context) + + +@pytest.mark.parametrize( + "code,expected", + [ + ["(1\n+\n1)", 2], + ["list(range(10))[-1:]", [9]], + ["list(range(20))[3:-2:3]", [3, 6, 9, 12, 15]], + ], +) +@pytest.mark.parametrize("context", LIMITED_OR_HIGHER) +def test_evaluates_complex_cases(code, expected, context): + assert guarded_eval(code, context()) == expected + + +@pytest.mark.parametrize( + "code,expected", + [ + ["1", 1], + ["1.0", 1.0], + ["0xdeedbeef", 0xDEEDBEEF], + ["True", True], + ["None", None], + ["{}", {}], + ["[]", []], + ], +) +@pytest.mark.parametrize("context", MINIMAL_OR_HIGHER) +def test_evaluates_literals(code, expected, context): + assert guarded_eval(code, context()) == expected + + +@pytest.mark.parametrize( + "code,expected", + [ + ["-5", -5], + ["+5", +5], + ["~5", -6], + ], +) +@pytest.mark.parametrize("context", LIMITED_OR_HIGHER) +def test_evaluates_unary_operations(code, expected, context): + assert guarded_eval(code, context()) == expected + + +@pytest.mark.parametrize( + "code,expected", + [ + ["1 + 1", 2], + ["3 - 1", 2], + ["2 * 3", 6], + ["5 // 2", 2], + ["5 / 2", 2.5], + ["5**2", 25], + ["2 >> 1", 1], + ["2 << 1", 4], + ["1 | 2", 3], + ["1 & 1", 1], + ["1 & 2", 0], + ], +) +@pytest.mark.parametrize("context", LIMITED_OR_HIGHER) +def test_evaluates_binary_operations(code, expected, context): + assert guarded_eval(code, context()) == expected + + +@pytest.mark.parametrize( + "code,expected", + [ + ["2 > 1", True], + ["2 < 1", False], + ["2 <= 1", False], + ["2 <= 2", True], + ["1 >= 2", False], + ["2 >= 2", True], + ["2 == 2", True], + ["1 == 2", False], + ["1 != 2", True], + ["1 != 1", False], + ["1 < 4 < 3", False], + ["(1 < 4) < 3", True], + ["4 > 3 > 2 > 1", True], + ["4 > 3 > 2 > 9", False], + ["1 < 2 < 3 < 4", True], + ["9 < 2 < 3 < 4", False], + ["1 < 2 > 1 > 0 > -1 < 1", True], + ["1 in [1] in [[1]]", True], + ["1 in [1] in [[2]]", False], + ["1 in [1]", True], + ["0 in [1]", False], + ["1 not in [1]", False], + ["0 not in [1]", True], + ["True is True", True], + ["False is False", True], + ["True is False", False], + ["True is not True", False], + ["False is not True", True], + ], +) +@pytest.mark.parametrize("context", LIMITED_OR_HIGHER) +def test_evaluates_comparisons(code, expected, context): + assert guarded_eval(code, context()) == expected + + +def test_guards_comparisons(): + class GoodEq(int): + pass + + class BadEq(int): + def __eq__(self, other): + assert False + + context = limited(bad=BadEq(1), good=GoodEq(1)) + + with pytest.raises(GuardRejection): + guarded_eval("bad == 1", context) + + with pytest.raises(GuardRejection): + guarded_eval("bad != 1", context) + + with pytest.raises(GuardRejection): + guarded_eval("1 == bad", context) + + with pytest.raises(GuardRejection): + guarded_eval("1 != bad", context) + + assert guarded_eval("good == 1", context) is True + assert guarded_eval("good != 1", context) is False + assert guarded_eval("1 == good", context) is True + assert guarded_eval("1 != good", context) is False + + +def test_guards_unary_operations(): + class GoodOp(int): + pass + + class BadOpInv(int): + def __inv__(self, other): + assert False + + class BadOpInverse(int): + def __inv__(self, other): + assert False + + context = limited(good=GoodOp(1), bad1=BadOpInv(1), bad2=BadOpInverse(1)) + + with pytest.raises(GuardRejection): + guarded_eval("~bad1", context) + + with pytest.raises(GuardRejection): + guarded_eval("~bad2", context) + + +def test_guards_binary_operations(): + class GoodOp(int): + pass + + class BadOp(int): + def __add__(self, other): + assert False + + context = limited(good=GoodOp(1), bad=BadOp(1)) + + with pytest.raises(GuardRejection): + guarded_eval("1 + bad", context) + + with pytest.raises(GuardRejection): + guarded_eval("bad + 1", context) + + assert guarded_eval("good + 1", context) == 2 + assert guarded_eval("1 + good", context) == 2 + + +def test_guards_attributes(): + class GoodAttr(float): + pass + + class BadAttr1(float): + def __getattr__(self, key): + assert False + + class BadAttr2(float): + def __getattribute__(self, key): + assert False + + context = limited(good=GoodAttr(0.5), bad1=BadAttr1(0.5), bad2=BadAttr2(0.5)) + + with pytest.raises(GuardRejection): + guarded_eval("bad1.as_integer_ratio", context) + + with pytest.raises(GuardRejection): + guarded_eval("bad2.as_integer_ratio", context) + + assert guarded_eval("good.as_integer_ratio()", context) == (1, 2) + + +@pytest.mark.parametrize("context", MINIMAL_OR_HIGHER) +def test_access_builtins(context): + assert guarded_eval("round", context()) == round + + +def test_access_builtins_fails(): + context = limited() + with pytest.raises(NameError): + guarded_eval("this_is_not_builtin", context) + + +def test_rejects_forbidden(): + context = forbidden() + with pytest.raises(GuardRejection): + guarded_eval("1", context) + + +def test_guards_locals_and_globals(): + context = EvaluationContext( + locals={"local_a": "a"}, globals={"global_b": "b"}, evaluation="minimal" + ) + + with pytest.raises(GuardRejection): + guarded_eval("local_a", context) + + with pytest.raises(GuardRejection): + guarded_eval("global_b", context) + + +def test_access_locals_and_globals(): + context = EvaluationContext( + locals={"local_a": "a"}, globals={"global_b": "b"}, evaluation="limited" + ) + assert guarded_eval("local_a", context) == "a" + assert guarded_eval("global_b", context) == "b" + + +@pytest.mark.parametrize( + "code", + ["def func(): pass", "class C: pass", "x = 1", "x += 1", "del x", "import ast"], +) +@pytest.mark.parametrize("context", [minimal(), limited(), unsafe()]) +def test_rejects_side_effect_syntax(code, context): + with pytest.raises(SyntaxError): + guarded_eval(code, context) + + +def test_subscript(): + context = EvaluationContext( + locals={}, globals={}, evaluation="limited", in_subscript=True + ) + empty_slice = slice(None, None, None) + assert guarded_eval("", context) == tuple() + assert guarded_eval(":", context) == empty_slice + assert guarded_eval("1:2:3", context) == slice(1, 2, 3) + assert guarded_eval(':, "a"', context) == (empty_slice, "a") + + +def test_unbind_method(): + class X(list): + def index(self, k): + return "CUSTOM" + + x = X() + assert _unbind_method(x.index) is X.index + assert _unbind_method([].index) is list.index + assert _unbind_method(list.index) is None + + +def test_assumption_instance_attr_do_not_matter(): + """This is semi-specified in Python documentation. + + However, since the specification says 'not guaranteed + to work' rather than 'is forbidden to work', future + versions could invalidate this assumptions. This test + is meant to catch such a change if it ever comes true. + """ + + class T: + def __getitem__(self, k): + return "a" + + def __getattr__(self, k): + return "a" + + def f(self): + return "b" + + t = T() + t.__getitem__ = f + t.__getattr__ = f + assert t[1] == "a" + assert t[1] == "a" + + +def test_assumption_named_tuples_share_getitem(): + """Check assumption on named tuples sharing __getitem__""" + from typing import NamedTuple + + class A(NamedTuple): + pass + + class B(NamedTuple): + pass + + assert A.__getitem__ == B.__getitem__ + + +@dec.skip_without("numpy") +def test_module_access(): + import numpy + + context = limited(numpy=numpy) + assert guarded_eval("numpy.linalg.norm", context) == numpy.linalg.norm + + context = minimal(numpy=numpy) + with pytest.raises(GuardRejection): + guarded_eval("np.linalg.norm", context) diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_handlers.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..905d9abe07bd3260255637fc2bbcb01977e7dc35 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_handlers.py @@ -0,0 +1,75 @@ +"""Tests for input handlers. +""" +#----------------------------------------------------------------------------- +# Module imports +#----------------------------------------------------------------------------- + +# our own packages +from IPython.core import autocall +from IPython.testing import tools as tt +import pytest +from collections.abc import Callable + +#----------------------------------------------------------------------------- +# Globals +#----------------------------------------------------------------------------- + +# Test functions +#----------------------------------------------------------------------------- + +class CallableIndexable(object): + def __getitem__(self, idx): return True + def __call__(self, *args, **kws): return True + + +class Autocallable(autocall.IPyAutocall): + def __call__(self): + return "called" + + +@pytest.mark.parametrize( + "autocall, input, output", + [ + # For many of the below, we're also checking that leading whitespace + # turns off the esc char, which it should unless there is a continuation + # line. + ("1", '"no change"', '"no change"'), # normal + ("1", "lsmagic", "get_ipython().run_line_magic('lsmagic', '')"), # magic + # Only explicit escapes or instances of IPyAutocallable should get + # expanded + ("0", 'len "abc"', 'len "abc"'), + ("0", "autocallable", "autocallable()"), + # Don't add extra brackets (gh-1117) + ("0", "autocallable()", "autocallable()"), + ("1", 'len "abc"', 'len("abc")'), + ("1", 'len "abc";', 'len("abc");'), # ; is special -- moves out of parens + # Autocall is turned off if first arg is [] and the object + # is both callable and indexable. Like so: + ("1", "len [1,2]", "len([1,2])"), # len doesn't support __getitem__... + ("1", "call_idx [1]", "call_idx [1]"), # call_idx *does*.. + ("1", "call_idx 1", "call_idx(1)"), + ("1", "len", "len"), # only at 2 does it auto-call on single args + ("2", 'len "abc"', 'len("abc")'), + ("2", 'len "abc";', 'len("abc");'), + ("2", "len [1,2]", "len([1,2])"), + ("2", "call_idx [1]", "call_idx [1]"), + ("2", "call_idx 1", "call_idx(1)"), + # T his is what's different: + ("2", "len", "len()"), # only at 2 does it auto-call on single args + ("0", "Callable[[int], None]", "Callable[[int], None]"), + ("1", "Callable[[int], None]", "Callable[[int], None]"), + ("1", "Callable[[int], None]", "Callable[[int], None]"), + ], +) +def test_handlers_I(autocall, input, output): + autocallable = Autocallable() + ip.user_ns["autocallable"] = autocallable + + call_idx = CallableIndexable() + ip.user_ns["call_idx"] = call_idx + + ip.user_ns["Callable"] = Callable + + ip.run_line_magic("autocall", autocall) + assert ip.prefilter_manager.prefilter_lines(input) == output + ip.run_line_magic("autocall", "1") diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_history.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_history.py new file mode 100644 index 0000000000000000000000000000000000000000..fa64fe04df1c72f1fe3ec8a186edcff3587caab9 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_history.py @@ -0,0 +1,306 @@ +# coding: utf-8 +"""Tests for the IPython tab-completion machinery. +""" +#----------------------------------------------------------------------------- +# Module imports +#----------------------------------------------------------------------------- + +# stdlib +import io +import sys +import tempfile +from datetime import datetime +from pathlib import Path + +from tempfile import TemporaryDirectory +# our own packages +from traitlets.config.loader import Config + +from IPython.core.history import HistoryAccessor, HistoryManager, extract_hist_ranges + + +def test_proper_default_encoding(): + assert sys.getdefaultencoding() == "utf-8" + +def test_history(): + ip = get_ipython() + with TemporaryDirectory() as tmpdir: + tmp_path = Path(tmpdir) + hist_manager_ori = ip.history_manager + hist_file = tmp_path / "history.sqlite" + try: + ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file) + hist = ["a=1", "def f():\n test = 1\n return test", "b='€Æ¾÷ß'"] + for i, h in enumerate(hist, start=1): + ip.history_manager.store_inputs(i, h) + + ip.history_manager.db_log_output = True + # Doesn't match the input, but we'll just check it's stored. + ip.history_manager.output_hist_reprs[3] = "spam" + ip.history_manager.store_output(3) + + assert ip.history_manager.input_hist_raw == [""] + hist + + # Detailed tests for _get_range_session + grs = ip.history_manager._get_range_session + assert list(grs(start=2, stop=-1)) == list(zip([0], [2], hist[1:-1])) + assert list(grs(start=-2)) == list(zip([0, 0], [2, 3], hist[-2:])) + assert list(grs(output=True)) == list( + zip([0, 0, 0], [1, 2, 3], zip(hist, [None, None, "spam"])) + ) + + # Check whether specifying a range beyond the end of the current + # session results in an error (gh-804) + ip.run_line_magic("hist", "2-500") + + # Check that we can write non-ascii characters to a file + ip.run_line_magic("hist", "-f %s" % (tmp_path / "test1")) + ip.run_line_magic("hist", "-pf %s" % (tmp_path / "test2")) + ip.run_line_magic("hist", "-nf %s" % (tmp_path / "test3")) + ip.run_line_magic("save", "%s 1-10" % (tmp_path / "test4")) + + # New session + ip.history_manager.reset() + newcmds = ["z=5", "class X(object):\n pass", "k='p'", "z=5"] + for i, cmd in enumerate(newcmds, start=1): + ip.history_manager.store_inputs(i, cmd) + gothist = ip.history_manager.get_range(start=1, stop=4) + assert list(gothist) == list(zip([0, 0, 0], [1, 2, 3], newcmds)) + # Previous session: + gothist = ip.history_manager.get_range(-1, 1, 4) + assert list(gothist) == list(zip([1, 1, 1], [1, 2, 3], hist)) + + newhist = [(2, i, c) for (i, c) in enumerate(newcmds, 1)] + + # Check get_hist_tail + gothist = ip.history_manager.get_tail(5, output=True, + include_latest=True) + expected = [(1, 3, (hist[-1], "spam"))] \ + + [(s, n, (c, None)) for (s, n, c) in newhist] + assert list(gothist) == expected + + gothist = ip.history_manager.get_tail(2) + expected = newhist[-3:-1] + assert list(gothist) == expected + + # Check get_hist_search + + gothist = ip.history_manager.search("*test*") + assert list(gothist) == [(1, 2, hist[1])] + + gothist = ip.history_manager.search("*=*") + assert list(gothist) == [ + (1, 1, hist[0]), + (1, 2, hist[1]), + (1, 3, hist[2]), + newhist[0], + newhist[2], + newhist[3], + ] + + gothist = ip.history_manager.search("*=*", n=4) + assert list(gothist) == [ + (1, 3, hist[2]), + newhist[0], + newhist[2], + newhist[3], + ] + + gothist = ip.history_manager.search("*=*", unique=True) + assert list(gothist) == [ + (1, 1, hist[0]), + (1, 2, hist[1]), + (1, 3, hist[2]), + newhist[2], + newhist[3], + ] + + gothist = ip.history_manager.search("*=*", unique=True, n=3) + assert list(gothist) == [(1, 3, hist[2]), newhist[2], newhist[3]] + + gothist = ip.history_manager.search("b*", output=True) + assert list(gothist) == [(1, 3, (hist[2], "spam"))] + + # Cross testing: check that magic %save can get previous session. + testfilename = (tmp_path / "test.py").resolve() + ip.run_line_magic("save", str(testfilename) + " ~1/1-3") + with io.open(testfilename, encoding="utf-8") as testfile: + assert testfile.read() == "# coding: utf-8\n" + "\n".join(hist) + "\n" + + # Duplicate line numbers - check that it doesn't crash, and + # gets a new session + ip.history_manager.store_inputs(1, "rogue") + ip.history_manager.writeout_cache() + assert ip.history_manager.session_number == 3 + + # Check that session and line values are not just max values + sessid, lineno, entry = newhist[-1] + assert lineno > 1 + ip.history_manager.reset() + lineno = 1 + ip.history_manager.store_inputs(lineno, entry) + gothist = ip.history_manager.search("*=*", unique=True) + hist = list(gothist)[-1] + assert sessid < hist[0] + assert hist[1:] == (lineno, entry) + finally: + # Ensure saving thread is shut down before we try to clean up the files + ip.history_manager.save_thread.stop() + # Forcibly close database rather than relying on garbage collection + ip.history_manager.db.close() + # Restore history manager + ip.history_manager = hist_manager_ori + + +def test_extract_hist_ranges(): + instr = "1 2/3 ~4/5-6 ~4/7-~4/9 ~9/2-~7/5 ~10/" + expected = [(0, 1, 2), # 0 == current session + (2, 3, 4), + (-4, 5, 7), + (-4, 7, 10), + (-9, 2, None), # None == to end + (-8, 1, None), + (-7, 1, 6), + (-10, 1, None)] + actual = list(extract_hist_ranges(instr)) + assert actual == expected + + +def test_extract_hist_ranges_empty_str(): + instr = "" + expected = [(0, 1, None)] # 0 == current session, None == to end + actual = list(extract_hist_ranges(instr)) + assert actual == expected + + +def test_magic_rerun(): + """Simple test for %rerun (no args -> rerun last line)""" + ip = get_ipython() + ip.run_cell("a = 10", store_history=True) + ip.run_cell("a += 1", store_history=True) + assert ip.user_ns["a"] == 11 + ip.run_cell("%rerun", store_history=True) + assert ip.user_ns["a"] == 12 + +def test_timestamp_type(): + ip = get_ipython() + info = ip.history_manager.get_session_info() + assert isinstance(info[1], datetime) + +def test_hist_file_config(): + cfg = Config() + tfile = tempfile.NamedTemporaryFile(delete=False) + cfg.HistoryManager.hist_file = Path(tfile.name) + try: + hm = HistoryManager(shell=get_ipython(), config=cfg) + assert hm.hist_file == cfg.HistoryManager.hist_file + finally: + try: + Path(tfile.name).unlink() + except OSError: + # same catch as in testing.tools.TempFileMixin + # On Windows, even though we close the file, we still can't + # delete it. I have no clue why + pass + +def test_histmanager_disabled(): + """Ensure that disabling the history manager doesn't create a database.""" + cfg = Config() + cfg.HistoryAccessor.enabled = False + + ip = get_ipython() + with TemporaryDirectory() as tmpdir: + hist_manager_ori = ip.history_manager + hist_file = Path(tmpdir) / "history.sqlite" + cfg.HistoryManager.hist_file = hist_file + try: + ip.history_manager = HistoryManager(shell=ip, config=cfg) + hist = ["a=1", "def f():\n test = 1\n return test", "b='€Æ¾÷ß'"] + for i, h in enumerate(hist, start=1): + ip.history_manager.store_inputs(i, h) + assert ip.history_manager.input_hist_raw == [""] + hist + ip.history_manager.reset() + ip.history_manager.end_session() + finally: + ip.history_manager = hist_manager_ori + + # hist_file should not be created + assert hist_file.exists() is False + + +def test_get_tail_session_awareness(): + """Test .get_tail() is: + - session specific in HistoryManager + - session agnostic in HistoryAccessor + same for .get_last_session_id() + """ + ip = get_ipython() + with TemporaryDirectory() as tmpdir: + tmp_path = Path(tmpdir) + hist_file = tmp_path / "history.sqlite" + get_source = lambda x: x[2] + hm1 = None + hm2 = None + ha = None + try: + # hm1 creates a new session and adds history entries, + # ha catches up + hm1 = HistoryManager(shell=ip, hist_file=hist_file) + hm1_last_sid = hm1.get_last_session_id + ha = HistoryAccessor(hist_file=hist_file) + ha_last_sid = ha.get_last_session_id + + hist1 = ["a=1", "b=1", "c=1"] + for i, h in enumerate(hist1 + [""], start=1): + hm1.store_inputs(i, h) + assert list(map(get_source, hm1.get_tail())) == hist1 + assert list(map(get_source, ha.get_tail())) == hist1 + sid1 = hm1_last_sid() + assert sid1 is not None + assert ha_last_sid() == sid1 + + # hm2 creates a new session and adds entries, + # ha catches up + hm2 = HistoryManager(shell=ip, hist_file=hist_file) + hm2_last_sid = hm2.get_last_session_id + + hist2 = ["a=2", "b=2", "c=2"] + for i, h in enumerate(hist2 + [""], start=1): + hm2.store_inputs(i, h) + tail = hm2.get_tail(n=3) + assert list(map(get_source, tail)) == hist2 + tail = ha.get_tail(n=3) + assert list(map(get_source, tail)) == hist2 + sid2 = hm2_last_sid() + assert sid2 is not None + assert ha_last_sid() == sid2 + assert sid2 != sid1 + + # but hm1 still maintains its point of reference + # and adding more entries to it doesn't change others + # immediate perspective + assert hm1_last_sid() == sid1 + tail = hm1.get_tail(n=3) + assert list(map(get_source, tail)) == hist1 + + hist3 = ["a=3", "b=3", "c=3"] + for i, h in enumerate(hist3 + [""], start=5): + hm1.store_inputs(i, h) + tail = hm1.get_tail(n=7) + assert list(map(get_source, tail)) == hist1 + [""] + hist3 + tail = hm2.get_tail(n=3) + assert list(map(get_source, tail)) == hist2 + tail = ha.get_tail(n=3) + assert list(map(get_source, tail)) == hist2 + assert hm1_last_sid() == sid1 + assert hm2_last_sid() == sid2 + assert ha_last_sid() == sid2 + finally: + if hm1: + hm1.save_thread.stop() + hm1.db.close() + if hm2: + hm2.save_thread.stop() + hm2.db.close() + if ha: + ha.db.close() diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_inputtransformer.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_inputtransformer.py new file mode 100644 index 0000000000000000000000000000000000000000..bfc936d3176caed123d057abeac904fe0042790e --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_inputtransformer.py @@ -0,0 +1,469 @@ +import tokenize + +from IPython.testing import tools as tt + +from IPython.core import inputtransformer as ipt + +def transform_and_reset(transformer): + transformer = transformer() + def transform(inp): + try: + return transformer.push(inp) + finally: + transformer.reset() + + return transform + +# Transformer tests +def transform_checker(tests, transformer, **kwargs): + """Utility to loop over test inputs""" + transformer = transformer(**kwargs) + try: + for inp, tr in tests: + if inp is None: + out = transformer.reset() + else: + out = transformer.push(inp) + assert out == tr + finally: + transformer.reset() + +# Data for all the syntax tests in the form of lists of pairs of +# raw/transformed input. We store it here as a global dict so that we can use +# it both within single-function tests and also to validate the behavior of the +# larger objects + +syntax = \ + dict(assign_system = + [('a =! ls', "a = get_ipython().getoutput('ls')"), + ('b = !ls', "b = get_ipython().getoutput('ls')"), + ('c= !ls', "c = get_ipython().getoutput('ls')"), + ('d == !ls', 'd == !ls'), # Invalid syntax, but we leave == alone. + ('x=1', 'x=1'), # normal input is unmodified + (' ',' '), # blank lines are kept intact + # Tuple unpacking + ("a, b = !echo 'a\\nb'", "a, b = get_ipython().getoutput(\"echo 'a\\\\nb'\")"), + ("a,= !echo 'a'", "a, = get_ipython().getoutput(\"echo 'a'\")"), + ("a, *bc = !echo 'a\\nb\\nc'", "a, *bc = get_ipython().getoutput(\"echo 'a\\\\nb\\\\nc'\")"), + # Tuple unpacking with regular Python expressions, not our syntax. + ("a, b = range(2)", "a, b = range(2)"), + ("a, = range(1)", "a, = range(1)"), + ("a, *bc = range(3)", "a, *bc = range(3)"), + ], + + assign_magic = + [('a =% who', "a = get_ipython().run_line_magic('who', '')"), + ('b = %who', "b = get_ipython().run_line_magic('who', '')"), + ('c= %ls', "c = get_ipython().run_line_magic('ls', '')"), + ('d == %ls', 'd == %ls'), # Invalid syntax, but we leave == alone. + ('x=1', 'x=1'), # normal input is unmodified + (' ',' '), # blank lines are kept intact + ("a, b = %foo", "a, b = get_ipython().run_line_magic('foo', '')"), + ], + classic_prompt=[ + (">>> x=1", "x=1"), + ("x=1", "x=1"), # normal input is unmodified + (" ", " "), # blank lines are kept intact + ], + ipy_prompt=[ + ("In [1]: x=1", "x=1"), + ("x=1", "x=1"), # normal input is unmodified + (" ", " "), # blank lines are kept intact + ], + # Tests for the escape transformer to leave normal code alone + escaped_noesc=[ + (" ", " "), + ("x=1", "x=1"), + ], + # System calls + escaped_shell=[ + ("!ls", "get_ipython().system('ls')"), + # Double-escape shell, this means to capture the output of the + # subprocess and return it + ("!!ls", "get_ipython().getoutput('ls')"), + ], + # Help/object info + escaped_help=[ + ("?", "get_ipython().show_usage()"), + ("?x1", "get_ipython().run_line_magic('pinfo', 'x1')"), + ("??x2", "get_ipython().run_line_magic('pinfo2', 'x2')"), + ("?a.*s", "get_ipython().run_line_magic('psearch', 'a.*s')"), + ("?%hist1", "get_ipython().run_line_magic('pinfo', '%hist1')"), + ("?%%hist2", "get_ipython().run_line_magic('pinfo', '%%hist2')"), + ("?abc = qwe", "get_ipython().run_line_magic('pinfo', 'abc')"), + ], + end_help=[ + ("x3?", "get_ipython().run_line_magic('pinfo', 'x3')"), + ("x4??", "get_ipython().run_line_magic('pinfo2', 'x4')"), + ("%hist1?", "get_ipython().run_line_magic('pinfo', '%hist1')"), + ("%hist2??", "get_ipython().run_line_magic('pinfo2', '%hist2')"), + ("%%hist3?", "get_ipython().run_line_magic('pinfo', '%%hist3')"), + ("%%hist4??", "get_ipython().run_line_magic('pinfo2', '%%hist4')"), + ("π.foo?", "get_ipython().run_line_magic('pinfo', 'π.foo')"), + ("f*?", "get_ipython().run_line_magic('psearch', 'f*')"), + ("ax.*aspe*?", "get_ipython().run_line_magic('psearch', 'ax.*aspe*')"), + ("a = abc?", "get_ipython().run_line_magic('pinfo', 'abc')"), + ("a = abc.qe??", "get_ipython().run_line_magic('pinfo2', 'abc.qe')"), + ("a = *.items?", "get_ipython().run_line_magic('psearch', '*.items')"), + ("plot(a?", "get_ipython().run_line_magic('pinfo', 'a')"), + ("a*2 #comment?", "a*2 #comment?"), + ], + # Explicit magic calls + escaped_magic=[ + ("%cd", "get_ipython().run_line_magic('cd', '')"), + ("%cd /home", "get_ipython().run_line_magic('cd', '/home')"), + # Backslashes need to be escaped. + ("%cd C:\\User", "get_ipython().run_line_magic('cd', 'C:\\\\User')"), + (" %magic", " get_ipython().run_line_magic('magic', '')"), + ], + # Quoting with separate arguments + escaped_quote=[ + (",f", 'f("")'), + (",f x", 'f("x")'), + (" ,f y", ' f("y")'), + (",f a b", 'f("a", "b")'), + ], + # Quoting with single argument + escaped_quote2=[ + (";f", 'f("")'), + (";f x", 'f("x")'), + (" ;f y", ' f("y")'), + (";f a b", 'f("a b")'), + ], + # Simply apply parens + escaped_paren=[ + ("/f", "f()"), + ("/f x", "f(x)"), + (" /f y", " f(y)"), + ("/f a b", "f(a, b)"), + ], + # Check that we transform prompts before other transforms + mixed=[ + ("In [1]: %lsmagic", "get_ipython().run_line_magic('lsmagic', '')"), + (">>> %lsmagic", "get_ipython().run_line_magic('lsmagic', '')"), + ("In [2]: !ls", "get_ipython().system('ls')"), + ("In [3]: abs?", "get_ipython().run_line_magic('pinfo', 'abs')"), + ("In [4]: b = %who", "b = get_ipython().run_line_magic('who', '')"), + ], +) + +# multiline syntax examples. Each of these should be a list of lists, with +# each entry itself having pairs of raw/transformed input. The union (with +# '\n'.join() of the transformed inputs is what the splitter should produce +# when fed the raw lines one at a time via push. +syntax_ml = \ + dict(classic_prompt = + [ [('>>> for i in range(10):','for i in range(10):'), + ('... print i',' print i'), + ('... ', ''), + ], + [('>>> a="""','a="""'), + ('... 123"""','123"""'), + ], + [('a="""','a="""'), + ('... 123','123'), + ('... 456"""','456"""'), + ], + [('a="""','a="""'), + ('>>> 123','123'), + ('... 456"""','456"""'), + ], + [('a="""','a="""'), + ('123','123'), + ('... 456"""','... 456"""'), + ], + [('....__class__','....__class__'), + ], + [('a=5', 'a=5'), + ('...', ''), + ], + [('>>> def f(x):', 'def f(x):'), + ('...', ''), + ('... return x', ' return x'), + ], + [('board = """....', 'board = """....'), + ('....', '....'), + ('...."""', '...."""'), + ], + ], + + ipy_prompt = + [ [('In [24]: for i in range(10):','for i in range(10):'), + (' ....: print i',' print i'), + (' ....: ', ''), + ], + [('In [24]: for i in range(10):','for i in range(10):'), + # Qt console prompts expand with spaces, not dots + (' ...: print i',' print i'), + (' ...: ', ''), + ], + [('In [24]: for i in range(10):','for i in range(10):'), + # Sometimes whitespace preceding '...' has been removed + ('...: print i',' print i'), + ('...: ', ''), + ], + [('In [24]: for i in range(10):','for i in range(10):'), + # Space after last continuation prompt has been removed (issue #6674) + ('...: print i',' print i'), + ('...:', ''), + ], + [('In [2]: a="""','a="""'), + (' ...: 123"""','123"""'), + ], + [('a="""','a="""'), + (' ...: 123','123'), + (' ...: 456"""','456"""'), + ], + [('a="""','a="""'), + ('In [1]: 123','123'), + (' ...: 456"""','456"""'), + ], + [('a="""','a="""'), + ('123','123'), + (' ...: 456"""',' ...: 456"""'), + ], + ], + + multiline_datastructure_prompt = + [ [('>>> a = [1,','a = [1,'), + ('... 2]','2]'), + ], + ], + + multiline_datastructure = + [ [('b = ("%s"', None), + ('# comment', None), + ('%foo )', 'b = ("%s"\n# comment\n%foo )'), + ], + ], + + multiline_string = + [ [("'''foo?", None), + ("bar'''", "'''foo?\nbar'''"), + ], + ], + + leading_indent = + [ [(' print "hi"','print "hi"'), + ], + [(' for a in range(5):','for a in range(5):'), + (' a*2',' a*2'), + ], + [(' a="""','a="""'), + (' 123"""','123"""'), + ], + [('a="""','a="""'), + (' 123"""',' 123"""'), + ], + ], + + cellmagic = + [ [('%%foo a', None), + (None, "get_ipython().run_cell_magic('foo', 'a', '')"), + ], + [('%%bar 123', None), + ('hello', None), + (None , "get_ipython().run_cell_magic('bar', '123', 'hello')"), + ], + [('a=5', 'a=5'), + ('%%cellmagic', '%%cellmagic'), + ], + ], + + escaped = + [ [('%abc def \\', None), + ('ghi', "get_ipython().run_line_magic('abc', 'def ghi')"), + ], + [('%abc def \\', None), + ('ghi\\', None), + (None, "get_ipython().run_line_magic('abc', 'def ghi')"), + ], + ], + + assign_magic = + [ [('a = %bc de \\', None), + ('fg', "a = get_ipython().run_line_magic('bc', 'de fg')"), + ], + [('a = %bc de \\', None), + ('fg\\', None), + (None, "a = get_ipython().run_line_magic('bc', 'de fg')"), + ], + ], + + assign_system = + [ [('a = !bc de \\', None), + ('fg', "a = get_ipython().getoutput('bc de fg')"), + ], + [('a = !bc de \\', None), + ('fg\\', None), + (None, "a = get_ipython().getoutput('bc de fg')"), + ], + ], + ) + + +def test_assign_system(): + tt.check_pairs(transform_and_reset(ipt.assign_from_system), syntax['assign_system']) + +def test_assign_magic(): + tt.check_pairs(transform_and_reset(ipt.assign_from_magic), syntax['assign_magic']) + +def test_classic_prompt(): + tt.check_pairs(transform_and_reset(ipt.classic_prompt), syntax['classic_prompt']) + for example in syntax_ml['classic_prompt']: + transform_checker(example, ipt.classic_prompt) + for example in syntax_ml['multiline_datastructure_prompt']: + transform_checker(example, ipt.classic_prompt) + + # Check that we don't transform the second line if the first is obviously + # IPython syntax + transform_checker([ + ('%foo', '%foo'), + ('>>> bar', '>>> bar'), + ], ipt.classic_prompt) + + +def test_ipy_prompt(): + tt.check_pairs(transform_and_reset(ipt.ipy_prompt), syntax['ipy_prompt']) + for example in syntax_ml['ipy_prompt']: + transform_checker(example, ipt.ipy_prompt) + + # Check that we don't transform the second line if we're inside a cell magic + transform_checker([ + ('%%foo', '%%foo'), + ('In [1]: bar', 'In [1]: bar'), + ], ipt.ipy_prompt) + +def test_assemble_logical_lines(): + tests = \ + [ [("a = \\", None), + ("123", "a = 123"), + ], + [("a = \\", None), # Test resetting when within a multi-line string + ("12 *\\", None), + (None, "a = 12 *"), + ], + [("# foo\\", "# foo\\"), # Comments can't be continued like this + ], + ] + for example in tests: + transform_checker(example, ipt.assemble_logical_lines) + +def test_assemble_python_lines(): + tests = \ + [ [("a = '''", None), + ("abc'''", "a = '''\nabc'''"), + ], + [("a = '''", None), # Test resetting when within a multi-line string + ("def", None), + (None, "a = '''\ndef"), + ], + [("a = [1,", None), + ("2]", "a = [1,\n2]"), + ], + [("a = [1,", None), # Test resetting when within a multi-line string + ("2,", None), + (None, "a = [1,\n2,"), + ], + [("a = '''", None), # Test line continuation within a multi-line string + ("abc\\", None), + ("def", None), + ("'''", "a = '''\nabc\\\ndef\n'''"), + ], + ] + syntax_ml['multiline_datastructure'] + for example in tests: + transform_checker(example, ipt.assemble_python_lines) + + +def test_help_end(): + tt.check_pairs(transform_and_reset(ipt.help_end), syntax['end_help']) + +def test_escaped_noesc(): + tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_noesc']) + + +def test_escaped_shell(): + tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_shell']) + + +def test_escaped_help(): + tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_help']) + + +def test_escaped_magic(): + tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_magic']) + + +def test_escaped_quote(): + tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote']) + + +def test_escaped_quote2(): + tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote2']) + + +def test_escaped_paren(): + tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_paren']) + + +def test_cellmagic(): + for example in syntax_ml['cellmagic']: + transform_checker(example, ipt.cellmagic) + + line_example = [('%%bar 123', None), + ('hello', None), + ('' , "get_ipython().run_cell_magic('bar', '123', 'hello')"), + ] + transform_checker(line_example, ipt.cellmagic, end_on_blank_line=True) + +def test_has_comment(): + tests = [('text', False), + ('text #comment', True), + ('text #comment\n', True), + ('#comment', True), + ('#comment\n', True), + ('a = "#string"', False), + ('a = "#string" # comment', True), + ('a #comment not "string"', True), + ] + tt.check_pairs(ipt.has_comment, tests) + +@ipt.TokenInputTransformer.wrap +def decistmt(tokens): + """Substitute Decimals for floats in a string of statements. + + Based on an example from the tokenize module docs. + """ + result = [] + for toknum, tokval, _, _, _ in tokens: + if toknum == tokenize.NUMBER and '.' in tokval: # replace NUMBER tokens + yield from [ + (tokenize.NAME, 'Decimal'), + (tokenize.OP, '('), + (tokenize.STRING, repr(tokval)), + (tokenize.OP, ')') + ] + else: + yield (toknum, tokval) + + + +def test_token_input_transformer(): + tests = [('1.2', "Decimal ('1.2')"), + ('"1.2"', '"1.2"'), + ] + tt.check_pairs(transform_and_reset(decistmt), tests) + ml_tests = \ + [ [("a = 1.2; b = '''x", None), + ("y'''", "a =Decimal ('1.2');b ='''x\ny'''"), + ], + [("a = [1.2,", None), + ("3]", "a =[Decimal ('1.2'),\n3 ]"), + ], + [("a = '''foo", None), # Test resetting when within a multi-line string + ("bar", None), + (None, "a = '''foo\nbar"), + ], + ] + for example in ml_tests: + transform_checker(example, decistmt) diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_inputtransformer2_line.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_inputtransformer2_line.py new file mode 100644 index 0000000000000000000000000000000000000000..ec7a8736412acfe3b0206f031dd85625124b1844 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_inputtransformer2_line.py @@ -0,0 +1,167 @@ +"""Tests for the line-based transformers in IPython.core.inputtransformer2 + +Line-based transformers are the simpler ones; token-based transformers are +more complex. See test_inputtransformer2 for tests for token-based transformers. +""" + +from IPython.core import inputtransformer2 as ipt2 + +CELL_MAGIC = ("""\ +%%foo arg +body 1 +body 2 +""", """\ +get_ipython().run_cell_magic('foo', 'arg', 'body 1\\nbody 2\\n') +""") + +def test_cell_magic(): + for sample, expected in [CELL_MAGIC]: + assert ipt2.cell_magic(sample.splitlines(keepends=True)) == expected.splitlines( + keepends=True + ) + +CLASSIC_PROMPT = ("""\ +>>> for a in range(5): +... print(a) +""", """\ +for a in range(5): + print(a) +""") + +CLASSIC_PROMPT_L2 = ("""\ +for a in range(5): +... print(a) +... print(a ** 2) +""", """\ +for a in range(5): + print(a) + print(a ** 2) +""") + +def test_classic_prompt(): + for sample, expected in [CLASSIC_PROMPT, CLASSIC_PROMPT_L2]: + assert ipt2.classic_prompt( + sample.splitlines(keepends=True) + ) == expected.splitlines(keepends=True) + +IPYTHON_PROMPT = ("""\ +In [1]: for a in range(5): + ...: print(a) +""", """\ +for a in range(5): + print(a) +""") + +IPYTHON_PROMPT_L2 = ("""\ +for a in range(5): + ...: print(a) + ...: print(a ** 2) +""", """\ +for a in range(5): + print(a) + print(a ** 2) +""") + + +IPYTHON_PROMPT_VI_INS = ( + """\ +[ins] In [11]: def a(): + ...: 123 + ...: + ...: 123 +""", + """\ +def a(): + 123 + +123 +""", +) + +IPYTHON_PROMPT_VI_NAV = ( + """\ +[nav] In [11]: def a(): + ...: 123 + ...: + ...: 123 +""", + """\ +def a(): + 123 + +123 +""", +) + + +def test_ipython_prompt(): + for sample, expected in [ + IPYTHON_PROMPT, + IPYTHON_PROMPT_L2, + IPYTHON_PROMPT_VI_INS, + IPYTHON_PROMPT_VI_NAV, + ]: + assert ipt2.ipython_prompt( + sample.splitlines(keepends=True) + ) == expected.splitlines(keepends=True) + + +INDENT_SPACES = ("""\ + if True: + a = 3 +""", """\ +if True: + a = 3 +""") + +INDENT_TABS = ("""\ +\tif True: +\t\tb = 4 +""", """\ +if True: +\tb = 4 +""") + +def test_leading_indent(): + for sample, expected in [INDENT_SPACES, INDENT_TABS]: + assert ipt2.leading_indent( + sample.splitlines(keepends=True) + ) == expected.splitlines(keepends=True) + +LEADING_EMPTY_LINES = ("""\ + \t + +if True: + a = 3 + +b = 4 +""", """\ +if True: + a = 3 + +b = 4 +""") + +ONLY_EMPTY_LINES = ("""\ + \t + +""", """\ + \t + +""") + +def test_leading_empty_lines(): + for sample, expected in [LEADING_EMPTY_LINES, ONLY_EMPTY_LINES]: + assert ipt2.leading_empty_lines( + sample.splitlines(keepends=True) + ) == expected.splitlines(keepends=True) + +CRLF_MAGIC = ([ + "%%ls\r\n" +], [ + "get_ipython().run_cell_magic('ls', '', '')\n" +]) + +def test_crlf_magic(): + for sample, expected in [CRLF_MAGIC]: + assert ipt2.cell_magic(sample) == expected diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_iplib.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_iplib.py new file mode 100644 index 0000000000000000000000000000000000000000..a5e51fbc246891981c91da5ec8193cd685d22694 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_iplib.py @@ -0,0 +1,246 @@ +"""Tests for the key interactiveshell module, where the main ipython class is defined. +""" + +import stack_data +import sys + +SV_VERSION = tuple([int(x) for x in stack_data.__version__.split(".")[0:2]]) + + +def test_reset(): + """reset must clear most namespaces.""" + + # Check that reset runs without error + ip.reset() + + # Once we've reset it (to clear of any junk that might have been there from + # other tests, we can count how many variables are in the user's namespace + nvars_user_ns = len(ip.user_ns) + nvars_hidden = len(ip.user_ns_hidden) + + # Now add a few variables to user_ns, and check that reset clears them + ip.user_ns['x'] = 1 + ip.user_ns['y'] = 1 + ip.reset() + + # Finally, check that all namespaces have only as many variables as we + # expect to find in them: + assert len(ip.user_ns) == nvars_user_ns + assert len(ip.user_ns_hidden) == nvars_hidden + + +# Tests for reporting of exceptions in various modes, handling of SystemExit, +# and %tb functionality. This is really a mix of testing ultraTB and interactiveshell. + +def doctest_tb_plain(): + """ + In [18]: xmode plain + Exception reporting mode: Plain + + In [19]: run simpleerr.py + Traceback (most recent call last): + File ...:... + bar(mode) + File ...:... in bar + div0() + File ...:... in div0 + x/y + ZeroDivisionError: ... + """ + + +def doctest_tb_context(): + """ + In [3]: xmode context + Exception reporting mode: Context + + In [4]: run simpleerr.py + --------------------------------------------------------------------------- + ZeroDivisionError Traceback (most recent call last) + + ... + 30 except IndexError: + 31 mode = 'div' + ---> 33 bar(mode) + + ... in bar(mode) + 15 "bar" + 16 if mode=='div': + ---> 17 div0() + 18 elif mode=='exit': + 19 try: + + ... in div0() + 6 x = 1 + 7 y = 0 + ----> 8 x/y + + ZeroDivisionError: ...""" + + +def doctest_tb_verbose(): + """ + In [5]: xmode verbose + Exception reporting mode: Verbose + + In [6]: run simpleerr.py + --------------------------------------------------------------------------- + ZeroDivisionError Traceback (most recent call last) + + ... + 30 except IndexError: + 31 mode = 'div' + ---> 33 bar(mode) + mode = 'div' + + ... in bar(mode='div') + 15 "bar" + 16 if mode=='div': + ---> 17 div0() + 18 elif mode=='exit': + 19 try: + + ... in div0() + 6 x = 1 + 7 y = 0 + ----> 8 x/y + x = 1 + y = 0 + + ZeroDivisionError: ... + """ + + +def doctest_tb_sysexit(): + """ + In [17]: %xmode plain + Exception reporting mode: Plain + + In [18]: %run simpleerr.py exit + An exception has occurred, use %tb to see the full traceback. + SystemExit: (1, 'Mode = exit') + + In [19]: %run simpleerr.py exit 2 + An exception has occurred, use %tb to see the full traceback. + SystemExit: (2, 'Mode = exit') + + In [20]: %tb + Traceback (most recent call last): + File ...:... in execfile + exec(compiler(f.read(), fname, "exec"), glob, loc) + File ...:... + bar(mode) + File ...:... in bar + sysexit(stat, mode) + File ...:... in sysexit + raise SystemExit(stat, f"Mode = {mode}") + SystemExit: (2, 'Mode = exit') + + In [21]: %xmode context + Exception reporting mode: Context + + In [22]: %tb + --------------------------------------------------------------------------- + SystemExit Traceback (most recent call last) + File ..., in execfile(fname, glob, loc, compiler) + ... with open(fname, "rb") as f: + ... compiler = compiler or compile + ---> ... exec(compiler(f.read(), fname, "exec"), glob, loc) + ... + 30 except IndexError: + 31 mode = 'div' + ---> 33 bar(mode) + + ...bar(mode) + 21 except: + 22 stat = 1 + ---> 23 sysexit(stat, mode) + 24 else: + 25 raise ValueError('Unknown mode') + + ...sysexit(stat, mode) + 10 def sysexit(stat, mode): + ---> 11 raise SystemExit(stat, f"Mode = {mode}") + + SystemExit: (2, 'Mode = exit') + """ + + +if SV_VERSION < (0, 6): + + def doctest_tb_sysexit_verbose_stack_data_05(): + """ + In [18]: %run simpleerr.py exit + An exception has occurred, use %tb to see the full traceback. + SystemExit: (1, 'Mode = exit') + + In [19]: %run simpleerr.py exit 2 + An exception has occurred, use %tb to see the full traceback. + SystemExit: (2, 'Mode = exit') + + In [23]: %xmode verbose + Exception reporting mode: Verbose + + In [24]: %tb + --------------------------------------------------------------------------- + SystemExit Traceback (most recent call last) + + ... + 30 except IndexError: + 31 mode = 'div' + ---> 33 bar(mode) + mode = 'exit' + + ... in bar(mode='exit') + ... except: + ... stat = 1 + ---> ... sysexit(stat, mode) + mode = 'exit' + stat = 2 + ... else: + ... raise ValueError('Unknown mode') + + ... in sysexit(stat=2, mode='exit') + 10 def sysexit(stat, mode): + ---> 11 raise SystemExit(stat, f"Mode = {mode}") + stat = 2 + + SystemExit: (2, 'Mode = exit') + """ + + +def test_run_cell(): + import textwrap + + ip.run_cell("a = 10\na+=1") + ip.run_cell("assert a == 11\nassert 1") + + assert ip.user_ns["a"] == 11 + complex = textwrap.dedent( + """ + if 1: + print "hello" + if 1: + print "world" + + if 2: + print "foo" + + if 3: + print "bar" + + if 4: + print "bar" + + """ + ) + # Simply verifies that this kind of input is run + ip.run_cell(complex) + + +def test_db(): + """Test the internal database used for variable persistence.""" + ip.db["__unittest_"] = 12 + assert ip.db["__unittest_"] == 12 + del ip.db["__unittest_"] + assert "__unittest_" not in ip.db diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_magic_terminal.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_magic_terminal.py new file mode 100644 index 0000000000000000000000000000000000000000..5dfa0f0ed652e637dab0eee8eb9443483405cd19 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_magic_terminal.py @@ -0,0 +1,216 @@ +"""Tests for various magic functions specific to the terminal frontend.""" + +#----------------------------------------------------------------------------- +# Imports +#----------------------------------------------------------------------------- + +import sys +from io import StringIO +from unittest import TestCase + +from IPython.testing import tools as tt +#----------------------------------------------------------------------------- +# Test functions begin +#----------------------------------------------------------------------------- + + +MINIMAL_LAZY_MAGIC = """ +from IPython.core.magic import ( + Magics, + magics_class, + line_magic, + cell_magic, +) + + +@magics_class +class LazyMagics(Magics): + @line_magic + def lazy_line(self, line): + print("Lazy Line") + + @cell_magic + def lazy_cell(self, line, cell): + print("Lazy Cell") + + +def load_ipython_extension(ipython): + ipython.register_magics(LazyMagics) +""" + +def check_cpaste(code, should_fail=False): + """Execute code via 'cpaste' and ensure it was executed, unless + should_fail is set. + """ + ip.user_ns['code_ran'] = False + + src = StringIO() + src.write(code) + src.write('\n--\n') + src.seek(0) + + stdin_save = sys.stdin + sys.stdin = src + + try: + context = tt.AssertPrints if should_fail else tt.AssertNotPrints + with context("Traceback (most recent call last)"): + ip.run_line_magic("cpaste", "") + + if not should_fail: + assert ip.user_ns['code_ran'], "%r failed" % code + finally: + sys.stdin = stdin_save + +def test_cpaste(): + """Test cpaste magic""" + + def runf(): + """Marker function: sets a flag when executed. + """ + ip.user_ns['code_ran'] = True + return 'runf' # return string so '+ runf()' doesn't result in success + + tests = {'pass': ["runf()", + "In [1]: runf()", + "In [1]: if 1:\n ...: runf()", + "> > > runf()", + ">>> runf()", + " >>> runf()", + ], + + 'fail': ["1 + runf()", + "++ runf()", + ]} + + ip.user_ns['runf'] = runf + + for code in tests['pass']: + check_cpaste(code) + + for code in tests['fail']: + check_cpaste(code, should_fail=True) + + + +class PasteTestCase(TestCase): + """Multiple tests for clipboard pasting""" + + def paste(self, txt, flags='-q'): + """Paste input text, by default in quiet mode""" + ip.hooks.clipboard_get = lambda: txt + ip.run_line_magic("paste", flags) + + def setUp(self): + # Inject fake clipboard hook but save original so we can restore it later + self.original_clip = ip.hooks.clipboard_get + + def tearDown(self): + # Restore original hook + ip.hooks.clipboard_get = self.original_clip + + def test_paste(self): + ip.user_ns.pop("x", None) + self.paste("x = 1") + self.assertEqual(ip.user_ns["x"], 1) + ip.user_ns.pop("x") + + def test_paste_pyprompt(self): + ip.user_ns.pop("x", None) + self.paste(">>> x=2") + self.assertEqual(ip.user_ns["x"], 2) + ip.user_ns.pop("x") + + def test_paste_py_multi(self): + self.paste( + """ + >>> x = [1,2,3] + >>> y = [] + >>> for i in x: + ... y.append(i**2) + ... + """ + ) + self.assertEqual(ip.user_ns["x"], [1, 2, 3]) + self.assertEqual(ip.user_ns["y"], [1, 4, 9]) + + def test_paste_py_multi_r(self): + "Now, test that self.paste -r works" + self.test_paste_py_multi() + self.assertEqual(ip.user_ns.pop("x"), [1, 2, 3]) + self.assertEqual(ip.user_ns.pop("y"), [1, 4, 9]) + self.assertFalse("x" in ip.user_ns) + ip.run_line_magic("paste", "-r") + self.assertEqual(ip.user_ns["x"], [1, 2, 3]) + self.assertEqual(ip.user_ns["y"], [1, 4, 9]) + + def test_paste_email(self): + "Test pasting of email-quoted contents" + self.paste( + """\ + >> def foo(x): + >> return x + 1 + >> xx = foo(1.1)""" + ) + self.assertEqual(ip.user_ns["xx"], 2.1) + + def test_paste_email2(self): + "Email again; some programs add a space also at each quoting level" + self.paste( + """\ + > > def foo(x): + > > return x + 1 + > > yy = foo(2.1) """ + ) + self.assertEqual(ip.user_ns["yy"], 3.1) + + def test_paste_email_py(self): + "Email quoting of interactive input" + self.paste( + """\ + >> >>> def f(x): + >> ... return x+1 + >> ... + >> >>> zz = f(2.5) """ + ) + self.assertEqual(ip.user_ns["zz"], 3.5) + + def test_paste_echo(self): + "Also test self.paste echoing, by temporarily faking the writer" + w = StringIO() + old_write = sys.stdout.write + sys.stdout.write = w.write + code = """ + a = 100 + b = 200""" + try: + self.paste(code,'') + out = w.getvalue() + finally: + sys.stdout.write = old_write + self.assertEqual(ip.user_ns["a"], 100) + self.assertEqual(ip.user_ns["b"], 200) + assert out == code + "\n## -- End pasted text --\n" + + def test_paste_leading_commas(self): + "Test multiline strings with leading commas" + tm = ip.magics_manager.registry['TerminalMagics'] + s = '''\ +a = """ +,1,2,3 +"""''' + ip.user_ns.pop("foo", None) + tm.store_or_execute(s, "foo") + self.assertIn("foo", ip.user_ns) + + def test_paste_trailing_question(self): + "Test pasting sources with trailing question marks" + tm = ip.magics_manager.registry['TerminalMagics'] + s = '''\ +def funcfoo(): + if True: #am i true? + return 'fooresult' +''' + ip.user_ns.pop('funcfoo', None) + self.paste(s) + self.assertEqual(ip.user_ns["funcfoo"](), "fooresult") diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_page.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_page.py new file mode 100644 index 0000000000000000000000000000000000000000..9f6a3742495912f0eb357cd4a7c0411f5210d92a --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_page.py @@ -0,0 +1,20 @@ +#----------------------------------------------------------------------------- +# Copyright (C) 2010-2011 The IPython Development Team. +# +# Distributed under the terms of the BSD License. +# +# The full license is in the file COPYING.txt, distributed with this software. +#----------------------------------------------------------------------------- +import io + +# N.B. For the test suite, page.page is overridden (see IPython.testing.globalipapp) +from IPython.core import page + +def test_detect_screen_size(): + """Simple smoketest for page._detect_screen_size.""" + try: + page._detect_screen_size(True, 25) + except (TypeError, io.UnsupportedOperation): + # This can happen in the test suite, because stdout may not have a + # fileno. + pass diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_run.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_run.py new file mode 100644 index 0000000000000000000000000000000000000000..971f8e30dad1741e853f4b441fc02b3dd1f05772 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_run.py @@ -0,0 +1,626 @@ +# encoding: utf-8 +"""Tests for code execution (%run and related), which is particularly tricky. + +Because of how %run manages namespaces, and the fact that we are trying here to +verify subtle object deletion and reference counting issues, the %run tests +will be kept in this separate file. This makes it easier to aggregate in one +place the tricks needed to handle it; most other magics are much easier to test +and we do so in a common test_magic file. + +Note that any test using `run -i` should make sure to do a `reset` afterwards, +as otherwise it may influence later tests. +""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + + + +import functools +import os +import platform +import random +import string +import sys +import textwrap +import unittest +from os.path import join as pjoin +from unittest.mock import patch + +import pytest +from tempfile import TemporaryDirectory + +from IPython.core import debugger +from IPython.testing import decorators as dec +from IPython.testing import tools as tt +from IPython.utils.io import capture_output + + +def doctest_refbug(): + """Very nasty problem with references held by multiple runs of a script. + See: https://github.com/ipython/ipython/issues/141 + + In [1]: _ip.clear_main_mod_cache() + # random + + In [2]: %run refbug + + In [3]: call_f() + lowercased: hello + + In [4]: %run refbug + + In [5]: call_f() + lowercased: hello + lowercased: hello + """ + + +def doctest_run_builtins(): + r"""Check that %run doesn't damage __builtins__. + + In [1]: import tempfile + + In [2]: bid1 = id(__builtins__) + + In [3]: fname = tempfile.mkstemp('.py')[1] + + In [3]: f = open(fname, 'w', encoding='utf-8') + + In [4]: dummy= f.write('pass\n') + + In [5]: f.flush() + + In [6]: t1 = type(__builtins__) + + In [7]: %run $fname + + In [7]: f.close() + + In [8]: bid2 = id(__builtins__) + + In [9]: t2 = type(__builtins__) + + In [10]: t1 == t2 + Out[10]: True + + In [10]: bid1 == bid2 + Out[10]: True + + In [12]: try: + ....: os.unlink(fname) + ....: except: + ....: pass + ....: + """ + + +def doctest_run_option_parser(): + r"""Test option parser in %run. + + In [1]: %run print_argv.py + [] + + In [2]: %run print_argv.py print*.py + ['print_argv.py'] + + In [3]: %run -G print_argv.py print*.py + ['print*.py'] + + """ + + +@dec.skip_win32 +def doctest_run_option_parser_for_posix(): + r"""Test option parser in %run (Linux/OSX specific). + + You need double quote to escape glob in POSIX systems: + + In [1]: %run print_argv.py print\\*.py + ['print*.py'] + + You can't use quote to escape glob in POSIX systems: + + In [2]: %run print_argv.py 'print*.py' + ['print_argv.py'] + + """ + + +doctest_run_option_parser_for_posix.__skip_doctest__ = sys.platform == "win32" + + +@dec.skip_if_not_win32 +def doctest_run_option_parser_for_windows(): + r"""Test option parser in %run (Windows specific). + + In Windows, you can't escape ``*` `by backslash: + + In [1]: %run print_argv.py print\\*.py + ['print\\\\*.py'] + + You can use quote to escape glob: + + In [2]: %run print_argv.py 'print*.py' + ["'print*.py'"] + + """ + + +doctest_run_option_parser_for_windows.__skip_doctest__ = sys.platform != "win32" + + +def doctest_reset_del(): + """Test that resetting doesn't cause errors in __del__ methods. + + In [2]: class A(object): + ...: def __del__(self): + ...: print(str("Hi")) + ...: + + In [3]: a = A() + + In [4]: get_ipython().reset(); import gc; x = gc.collect(0) + Hi + + In [5]: 1+1 + Out[5]: 2 + """ + +# For some tests, it will be handy to organize them in a class with a common +# setup that makes a temp file + +class TestMagicRunPass(tt.TempFileMixin): + + def setUp(self): + content = "a = [1,2,3]\nb = 1" + self.mktmp(content) + + def run_tmpfile(self): + _ip = get_ipython() + # This fails on Windows if self.tmpfile.name has spaces or "~" in it. + # See below and ticket https://bugs.launchpad.net/bugs/366353 + _ip.run_line_magic("run", self.fname) + + def run_tmpfile_p(self): + _ip = get_ipython() + # This fails on Windows if self.tmpfile.name has spaces or "~" in it. + # See below and ticket https://bugs.launchpad.net/bugs/366353 + _ip.run_line_magic("run", "-p %s" % self.fname) + + def test_builtins_id(self): + """Check that %run doesn't damage __builtins__ """ + _ip = get_ipython() + # Test that the id of __builtins__ is not modified by %run + bid1 = id(_ip.user_ns['__builtins__']) + self.run_tmpfile() + bid2 = id(_ip.user_ns['__builtins__']) + assert bid1 == bid2 + + def test_builtins_type(self): + """Check that the type of __builtins__ doesn't change with %run. + + However, the above could pass if __builtins__ was already modified to + be a dict (it should be a module) by a previous use of %run. So we + also check explicitly that it really is a module: + """ + _ip = get_ipython() + self.run_tmpfile() + assert type(_ip.user_ns["__builtins__"]) == type(sys) + + def test_run_profile(self): + """Test that the option -p, which invokes the profiler, do not + crash by invoking execfile""" + self.run_tmpfile_p() + + def test_run_debug_twice(self): + # https://github.com/ipython/ipython/issues/10028 + _ip = get_ipython() + with tt.fake_input(["c"]): + _ip.run_line_magic("run", "-d %s" % self.fname) + with tt.fake_input(["c"]): + _ip.run_line_magic("run", "-d %s" % self.fname) + + def test_run_debug_twice_with_breakpoint(self): + """Make a valid python temp file.""" + _ip = get_ipython() + with tt.fake_input(["b 2", "c", "c"]): + _ip.run_line_magic("run", "-d %s" % self.fname) + + with tt.fake_input(["c"]): + with tt.AssertNotPrints("KeyError"): + _ip.run_line_magic("run", "-d %s" % self.fname) + + +class TestMagicRunSimple(tt.TempFileMixin): + + def test_simpledef(self): + """Test that simple class definitions work.""" + src = ("class foo: pass\n" + "def f(): return foo()") + self.mktmp(src) + _ip.run_line_magic("run", str(self.fname)) + _ip.run_cell("t = isinstance(f(), foo)") + assert _ip.user_ns["t"] is True + + @pytest.mark.xfail( + platform.python_implementation() == "PyPy", + reason="expecting __del__ call on exit is unreliable and doesn't happen on PyPy", + ) + def test_obj_del(self): + """Test that object's __del__ methods are called on exit.""" + src = ("class A(object):\n" + " def __del__(self):\n" + " print('object A deleted')\n" + "a = A()\n") + self.mktmp(src) + err = None + tt.ipexec_validate(self.fname, 'object A deleted', err) + + def test_aggressive_namespace_cleanup(self): + """Test that namespace cleanup is not too aggressive GH-238 + + Returning from another run magic deletes the namespace""" + # see ticket https://github.com/ipython/ipython/issues/238 + + with tt.TempFileMixin() as empty: + empty.mktmp("") + # On Windows, the filename will have \users in it, so we need to use the + # repr so that the \u becomes \\u. + src = ( + "ip = get_ipython()\n" + "for i in range(5):\n" + " try:\n" + " ip.run_line_magic(%r, %r)\n" + " except NameError as e:\n" + " print(i)\n" + " break\n" % ("run", empty.fname) + ) + self.mktmp(src) + _ip.run_line_magic("run", str(self.fname)) + _ip.run_cell("ip == get_ipython()") + assert _ip.user_ns["i"] == 4 + + def test_run_second(self): + """Test that running a second file doesn't clobber the first, gh-3547""" + self.mktmp("avar = 1\n" "def afunc():\n" " return avar\n") + + with tt.TempFileMixin() as empty: + empty.mktmp("") + + _ip.run_line_magic("run", self.fname) + _ip.run_line_magic("run", empty.fname) + assert _ip.user_ns["afunc"]() == 1 + + def test_tclass(self): + mydir = os.path.dirname(__file__) + tc = os.path.join(mydir, "tclass") + src = f"""\ +import gc +%run "{tc}" C-first +gc.collect(0) +%run "{tc}" C-second +gc.collect(0) +%run "{tc}" C-third +gc.collect(0) +%reset -f +""" + self.mktmp(src, ".ipy") + out = """\ +ARGV 1-: ['C-first'] +ARGV 1-: ['C-second'] +tclass.py: deleting object: C-first +ARGV 1-: ['C-third'] +tclass.py: deleting object: C-second +tclass.py: deleting object: C-third +""" + err = None + tt.ipexec_validate(self.fname, out, err) + + def test_run_i_after_reset(self): + """Check that %run -i still works after %reset (gh-693)""" + src = "yy = zz\n" + self.mktmp(src) + _ip.run_cell("zz = 23") + try: + _ip.run_line_magic("run", "-i %s" % self.fname) + assert _ip.user_ns["yy"] == 23 + finally: + _ip.run_line_magic("reset", "-f") + + _ip.run_cell("zz = 23") + try: + _ip.run_line_magic("run", "-i %s" % self.fname) + assert _ip.user_ns["yy"] == 23 + finally: + _ip.run_line_magic("reset", "-f") + + def test_unicode(self): + """Check that files in odd encodings are accepted.""" + mydir = os.path.dirname(__file__) + na = os.path.join(mydir, "nonascii.py") + _ip.run_line_magic("run", na) + assert _ip.user_ns["u"] == "Ўт№Ф" + + def test_run_py_file_attribute(self): + """Test handling of `__file__` attribute in `%run .py`.""" + src = "t = __file__\n" + self.mktmp(src) + _missing = object() + file1 = _ip.user_ns.get("__file__", _missing) + _ip.run_line_magic("run", self.fname) + file2 = _ip.user_ns.get("__file__", _missing) + + # Check that __file__ was equal to the filename in the script's + # namespace. + assert _ip.user_ns["t"] == self.fname + + # Check that __file__ was not leaked back into user_ns. + assert file1 == file2 + + def test_run_ipy_file_attribute(self): + """Test handling of `__file__` attribute in `%run `.""" + src = "t = __file__\n" + self.mktmp(src, ext='.ipy') + _missing = object() + file1 = _ip.user_ns.get("__file__", _missing) + _ip.run_line_magic("run", self.fname) + file2 = _ip.user_ns.get("__file__", _missing) + + # Check that __file__ was equal to the filename in the script's + # namespace. + assert _ip.user_ns["t"] == self.fname + + # Check that __file__ was not leaked back into user_ns. + assert file1 == file2 + + def test_run_formatting(self): + """ Test that %run -t -N does not raise a TypeError for N > 1.""" + src = "pass" + self.mktmp(src) + _ip.run_line_magic("run", "-t -N 1 %s" % self.fname) + _ip.run_line_magic("run", "-t -N 10 %s" % self.fname) + + def test_ignore_sys_exit(self): + """Test the -e option to ignore sys.exit()""" + src = "import sys; sys.exit(1)" + self.mktmp(src) + with tt.AssertPrints("SystemExit"): + _ip.run_line_magic("run", self.fname) + + with tt.AssertNotPrints("SystemExit"): + _ip.run_line_magic("run", "-e %s" % self.fname) + + def test_run_nb(self): + """Test %run notebook.ipynb""" + pytest.importorskip("nbformat") + from nbformat import v4, writes + nb = v4.new_notebook( + cells=[ + v4.new_markdown_cell("The Ultimate Question of Everything"), + v4.new_code_cell("answer=42") + ] + ) + src = writes(nb, version=4) + self.mktmp(src, ext='.ipynb') + + _ip.run_line_magic("run", self.fname) + + assert _ip.user_ns["answer"] == 42 + + def test_run_nb_error(self): + """Test %run notebook.ipynb error""" + pytest.importorskip("nbformat") + from nbformat import v4, writes + + # %run when a file name isn't provided + pytest.raises(Exception, _ip.magic, "run") + + # %run when a file doesn't exist + pytest.raises(Exception, _ip.magic, "run foobar.ipynb") + + # %run on a notebook with an error + nb = v4.new_notebook( + cells=[ + v4.new_code_cell("0/0") + ] + ) + src = writes(nb, version=4) + self.mktmp(src, ext='.ipynb') + pytest.raises(Exception, _ip.magic, "run %s" % self.fname) + + def test_file_options(self): + src = ('import sys\n' + 'a = " ".join(sys.argv[1:])\n') + self.mktmp(src) + test_opts = "-x 3 --verbose" + _ip.run_line_magic("run", "{0} {1}".format(self.fname, test_opts)) + assert _ip.user_ns["a"] == test_opts + + +class TestMagicRunWithPackage(unittest.TestCase): + + def writefile(self, name, content): + path = os.path.join(self.tempdir.name, name) + d = os.path.dirname(path) + if not os.path.isdir(d): + os.makedirs(d) + with open(path, "w", encoding="utf-8") as f: + f.write(textwrap.dedent(content)) + + def setUp(self): + self.package = package = 'tmp{0}'.format(''.join([random.choice(string.ascii_letters) for i in range(10)])) + """Temporary (probably) valid python package name.""" + + self.value = int(random.random() * 10000) + + self.tempdir = TemporaryDirectory() + self.__orig_cwd = os.getcwd() + sys.path.insert(0, self.tempdir.name) + + self.writefile(os.path.join(package, '__init__.py'), '') + self.writefile(os.path.join(package, 'sub.py'), """ + x = {0!r} + """.format(self.value)) + self.writefile(os.path.join(package, 'relative.py'), """ + from .sub import x + """) + self.writefile(os.path.join(package, 'absolute.py'), """ + from {0}.sub import x + """.format(package)) + self.writefile(os.path.join(package, 'args.py'), """ + import sys + a = " ".join(sys.argv[1:]) + """.format(package)) + + def tearDown(self): + os.chdir(self.__orig_cwd) + sys.path[:] = [p for p in sys.path if p != self.tempdir.name] + self.tempdir.cleanup() + + def check_run_submodule(self, submodule, opts=""): + _ip.user_ns.pop("x", None) + _ip.run_line_magic( + "run", "{2} -m {0}.{1}".format(self.package, submodule, opts) + ) + self.assertEqual( + _ip.user_ns["x"], + self.value, + "Variable `x` is not loaded from module `{0}`.".format(submodule), + ) + + def test_run_submodule_with_absolute_import(self): + self.check_run_submodule('absolute') + + def test_run_submodule_with_relative_import(self): + """Run submodule that has a relative import statement (#2727).""" + self.check_run_submodule('relative') + + def test_prun_submodule_with_absolute_import(self): + self.check_run_submodule('absolute', '-p') + + def test_prun_submodule_with_relative_import(self): + self.check_run_submodule('relative', '-p') + + def with_fake_debugger(func): + @functools.wraps(func) + def wrapper(*args, **kwds): + with patch.object(debugger.Pdb, 'run', staticmethod(eval)): + return func(*args, **kwds) + return wrapper + + @with_fake_debugger + def test_debug_run_submodule_with_absolute_import(self): + self.check_run_submodule('absolute', '-d') + + @with_fake_debugger + def test_debug_run_submodule_with_relative_import(self): + self.check_run_submodule('relative', '-d') + + def test_module_options(self): + _ip.user_ns.pop("a", None) + test_opts = "-x abc -m test" + _ip.run_line_magic("run", "-m {0}.args {1}".format(self.package, test_opts)) + assert _ip.user_ns["a"] == test_opts + + def test_module_options_with_separator(self): + _ip.user_ns.pop("a", None) + test_opts = "-x abc -m test" + _ip.run_line_magic("run", "-m {0}.args -- {1}".format(self.package, test_opts)) + assert _ip.user_ns["a"] == test_opts + + +def test_run__name__(): + with TemporaryDirectory() as td: + path = pjoin(td, "foo.py") + with open(path, "w", encoding="utf-8") as f: + f.write("q = __name__") + + _ip.user_ns.pop("q", None) + _ip.run_line_magic("run", "{}".format(path)) + assert _ip.user_ns.pop("q") == "__main__" + + _ip.run_line_magic("run", "-n {}".format(path)) + assert _ip.user_ns.pop("q") == "foo" + + try: + _ip.run_line_magic("run", "-i -n {}".format(path)) + assert _ip.user_ns.pop("q") == "foo" + finally: + _ip.run_line_magic("reset", "-f") + + +def test_run_tb(): + """Test traceback offset in %run""" + with TemporaryDirectory() as td: + path = pjoin(td, "foo.py") + with open(path, "w", encoding="utf-8") as f: + f.write( + "\n".join( + [ + "def foo():", + " return bar()", + "def bar():", + " raise RuntimeError('hello!')", + "foo()", + ] + ) + ) + with capture_output() as io: + _ip.run_line_magic("run", "{}".format(path)) + out = io.stdout + assert "execfile" not in out + assert "RuntimeError" in out + assert out.count("---->") == 3 + del ip.user_ns['bar'] + del ip.user_ns['foo'] + + +def test_multiprocessing_run(): + """Set we can run mutiprocesgin without messing up up main namespace + + Note that import `nose.tools as nt` modify the values + sys.module['__mp_main__'] so we need to temporarily set it to None to test + the issue. + """ + with TemporaryDirectory() as td: + mpm = sys.modules.get('__mp_main__') + sys.modules['__mp_main__'] = None + try: + path = pjoin(td, "test.py") + with open(path, "w", encoding="utf-8") as f: + f.write("import multiprocessing\nprint('hoy')") + with capture_output() as io: + _ip.run_line_magic('run', path) + _ip.run_cell("i_m_undefined") + out = io.stdout + assert "hoy" in out + assert "AttributeError" not in out + assert "NameError" in out + assert out.count("---->") == 1 + except: + raise + finally: + sys.modules['__mp_main__'] = mpm + + +def test_script_tb(): + """Test traceback offset in `ipython script.py`""" + with TemporaryDirectory() as td: + path = pjoin(td, "foo.py") + with open(path, "w", encoding="utf-8") as f: + f.write( + "\n".join( + [ + "def foo():", + " return bar()", + "def bar():", + " raise RuntimeError('hello!')", + "foo()", + ] + ) + ) + out, err = tt.ipexec(path) + assert "execfile" not in out + assert "RuntimeError" in out + assert out.count("---->") == 3 diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_splitinput.py b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_splitinput.py new file mode 100644 index 0000000000000000000000000000000000000000..f5fc53fafe30f2cea5cc7b8556650b414b682460 --- /dev/null +++ b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/IPython/core/tests/test_splitinput.py @@ -0,0 +1,41 @@ +# coding: utf-8 + +from IPython.core.splitinput import split_user_input, LineInfo + +import pytest + +tests = [ + ("x=1", ("", "", "x", "=1")), + ("?", ("", "?", "", "")), + ("??", ("", "??", "", "")), + (" ?", (" ", "?", "", "")), + (" ??", (" ", "??", "", "")), + ("??x", ("", "??", "x", "")), + ("?x=1", ("", "?", "x", "=1")), + ("!ls", ("", "!", "ls", "")), + (" !ls", (" ", "!", "ls", "")), + ("!!ls", ("", "!!", "ls", "")), + (" !!ls", (" ", "!!", "ls", "")), + (",ls", ("", ",", "ls", "")), + (";ls", ("", ";", "ls", "")), + (" ;ls", (" ", ";", "ls", "")), + ("f.g(x)", ("", "", "f.g", "(x)")), + ("f.g (x)", ("", "", "f.g", " (x)")), + ("?%hist1", ("", "?", "%hist1", "")), + ("?%%hist2", ("", "?", "%%hist2", "")), + ("??%hist3", ("", "??", "%hist3", "")), + ("??%%hist4", ("", "??", "%%hist4", "")), + ("?x*", ("", "?", "x*", "")), + ("Pérez Fernando", ("", "", "Pérez", " Fernando")), +] + + +@pytest.mark.parametrize("input, output", tests) +def test_split_user_input(input, output): + assert split_user_input(input) == output + + +def test_LineInfo(): + """Simple test for LineInfo construction and str()""" + linfo = LineInfo(" %cd /home") + assert str(linfo) == "LineInfo [ |%|cd|/home]" diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/__init__.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e7efc093d52b7566a26c929d9b1b8bb66d23f1f Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/__init__.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/__version__.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/__version__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a2274139641c24bcadc66d228fe0777d35646cd Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/__version__.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/_internal_utils.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/_internal_utils.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5f9725c4e37d21c9d66ff32334abe7f8b2b0573 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/_internal_utils.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/adapters.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/adapters.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d3b8530cb76c7483a6aed750bbeccd5ec7cb13f0 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/adapters.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/compat.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/compat.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f4e283e19e607762ef952b2334f48cfa3293759 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/compat.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/exceptions.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/exceptions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b7c98dd3bc63837aa39c84abec73227e48e7a93 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/exceptions.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/help.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/help.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66a7557896c9770d27a3d6ce5f908233320ef417 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/help.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/packages.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/packages.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9d3dabff809276da0e516d3eead7f56aa551853c Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/packages.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/sessions.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/sessions.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea211c6adc9d7d8272d613d462091d37520358e5 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/sessions.cpython-310.pyc differ diff --git a/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/structures.cpython-310.pyc b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/structures.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac2be935776de31d65de7b94131308c461404956 Binary files /dev/null and b/material/dataset/xpsdeeplearning/.venv/lib/python3.10/site-packages/pip/_vendor/requests/__pycache__/structures.cpython-310.pyc differ