id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
176,295
import collections import contextlib import errno import functools import os import sys import types import sys if sys.version_info[0] < 3: del num, x def redirect_stderr(new_target): original = sys.stderr try: sys.stderr = new_target yield new_target finally: sys.stderr = original
null
176,296
import glob import os import signal import sys import time from ._common import MACOS from ._common import TimeoutExpired from ._common import memoize from ._common import sdiskusage from ._common import usage_percent from ._compat import PY3 from ._compat import ChildProcessError from ._compat import FileNotFoundError from ._compat import InterruptedError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import unicode def pid_exists(pid): """Check whether pid exists in the current process table.""" if pid == 0: # According to "man 2 kill" PID 0 has a special meaning: # it refers to <<every process in the process group of the # calling process>> so we don't want to go any further. # If we get here it means this UNIX platform *does* have # a process with id 0. return True try: os.kill(pid, 0) except ProcessLookupError: return False except PermissionError: # EPERM clearly means there's a process to deny access to return True # According to "man 2 kill" possible error values are # (EINVAL, EPERM, ESRCH) else: return True if enum is not None and hasattr(signal, "Signals"): Negsignal = enum.IntEnum( 'Negsignal', dict([(x.name, -x.value) for x in signal.Signals])) def negsig_to_enum(num): """Convert a negative signal value to an enum.""" try: return Negsignal(num) except ValueError: return num else: # pragma: no cover def negsig_to_enum(num): return num class TimeoutExpired(Error): """Raised on Process.wait(timeout) if timeout expires and process is still alive. """ __module__ = 'psutil' def __init__(self, seconds, pid=None, name=None): Error.__init__(self) self.seconds = seconds self.pid = pid self.name = name self.msg = "timeout after %s seconds" % seconds The provided code snippet includes necessary dependencies for implementing the `wait_pid` function. Write a Python function `def wait_pid(pid, timeout=None, proc_name=None, _waitpid=os.waitpid, _timer=getattr(time, 'monotonic', time.time), _min=min, _sleep=time.sleep, _pid_exists=pid_exists)` to solve the following problem: Wait for a process PID to terminate. If the process terminated normally by calling exit(3) or _exit(2), or by returning from main(), the return value is the positive integer passed to *exit(). If it was terminated by a signal it returns the negated value of the signal which caused the termination (e.g. -SIGTERM). If PID is not a children of os.getpid() (current process) just wait until the process disappears and return None. If PID does not exist at all return None immediately. If *timeout* != None and process is still alive raise TimeoutExpired. timeout=0 is also possible (either return immediately or raise). Here is the function: def wait_pid(pid, timeout=None, proc_name=None, _waitpid=os.waitpid, _timer=getattr(time, 'monotonic', time.time), _min=min, _sleep=time.sleep, _pid_exists=pid_exists): """Wait for a process PID to terminate. If the process terminated normally by calling exit(3) or _exit(2), or by returning from main(), the return value is the positive integer passed to *exit(). If it was terminated by a signal it returns the negated value of the signal which caused the termination (e.g. -SIGTERM). If PID is not a children of os.getpid() (current process) just wait until the process disappears and return None. If PID does not exist at all return None immediately. If *timeout* != None and process is still alive raise TimeoutExpired. timeout=0 is also possible (either return immediately or raise). """ if pid <= 0: raise ValueError("can't wait for PID 0") # see "man waitpid" interval = 0.0001 flags = 0 if timeout is not None: flags |= os.WNOHANG stop_at = _timer() + timeout def sleep(interval): # Sleep for some time and return a new increased interval. if timeout is not None: if _timer() >= stop_at: raise TimeoutExpired(timeout, pid=pid, name=proc_name) _sleep(interval) return _min(interval * 2, 0.04) # See: https://linux.die.net/man/2/waitpid while True: try: retpid, status = os.waitpid(pid, flags) except InterruptedError: interval = sleep(interval) except ChildProcessError: # This has two meanings: # - PID is not a child of os.getpid() in which case # we keep polling until it's gone # - PID never existed in the first place # In both cases we'll eventually return None as we # can't determine its exit status code. while _pid_exists(pid): interval = sleep(interval) return else: if retpid == 0: # WNOHANG flag was used and PID is still running. interval = sleep(interval) continue elif os.WIFEXITED(status): # Process terminated normally by calling exit(3) or _exit(2), # or by returning from main(). The return value is the # positive integer passed to *exit(). return os.WEXITSTATUS(status) elif os.WIFSIGNALED(status): # Process exited due to a signal. Return the negative value # of that signal. return negsig_to_enum(-os.WTERMSIG(status)) # elif os.WIFSTOPPED(status): # # Process was stopped via SIGSTOP or is being traced, and # # waitpid() was called with WUNTRACED flag. PID is still # # alive. From now on waitpid() will keep returning (0, 0) # # until the process state doesn't change. # # It may make sense to catch/enable this since stopped PIDs # # ignore SIGTERM. # interval = sleep(interval) # continue # elif os.WIFCONTINUED(status): # # Process was resumed via SIGCONT and waitpid() was called # # with WCONTINUED flag. # interval = sleep(interval) # continue else: # Should never happen. raise ValueError("unknown process exit status %r" % status)
Wait for a process PID to terminate. If the process terminated normally by calling exit(3) or _exit(2), or by returning from main(), the return value is the positive integer passed to *exit(). If it was terminated by a signal it returns the negated value of the signal which caused the termination (e.g. -SIGTERM). If PID is not a children of os.getpid() (current process) just wait until the process disappears and return None. If PID does not exist at all return None immediately. If *timeout* != None and process is still alive raise TimeoutExpired. timeout=0 is also possible (either return immediately or raise).
176,297
import glob import os import signal import sys import time from ._common import MACOS from ._common import TimeoutExpired from ._common import memoize from ._common import sdiskusage from ._common import usage_percent from ._compat import PY3 from ._compat import ChildProcessError from ._compat import FileNotFoundError from ._compat import InterruptedError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import unicode The provided code snippet includes necessary dependencies for implementing the `get_terminal_map` function. Write a Python function `def get_terminal_map()` to solve the following problem: Get a map of device-id -> path as a dict. Used by Process.terminal() Here is the function: def get_terminal_map(): """Get a map of device-id -> path as a dict. Used by Process.terminal() """ ret = {} ls = glob.glob('/dev/tty*') + glob.glob('/dev/pts/*') for name in ls: assert name not in ret, name try: ret[os.stat(name).st_rdev] = name except FileNotFoundError: pass return ret
Get a map of device-id -> path as a dict. Used by Process.terminal()
176,298
import errno import functools import os import socket import subprocess import sys from collections import namedtuple from socket import AF_INET from . import _common from . import _psposix from . import _psutil_posix as cext_posix from . import _psutil_sunos as cext from ._common import AF_INET6 from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import debug from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize_when_activated from ._common import sockfam_to_enum from ._common import socktype_to_enum from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b PAGE_SIZE = cext_posix.getpagesize() svmem = namedtuple('svmem', ['total', 'available', 'percent', 'used', 'free']) def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (float(used) / total) * 100 except ZeroDivisionError: return 0.0 else: if round_ is not None: ret = round(ret, round_) return ret The provided code snippet includes necessary dependencies for implementing the `virtual_memory` function. Write a Python function `def virtual_memory()` to solve the following problem: Report virtual memory metrics. Here is the function: def virtual_memory(): """Report virtual memory metrics.""" # we could have done this with kstat, but IMHO this is good enough total = os.sysconf('SC_PHYS_PAGES') * PAGE_SIZE # note: there's no difference on Solaris free = avail = os.sysconf('SC_AVPHYS_PAGES') * PAGE_SIZE used = total - free percent = usage_percent(used, total, round_=1) return svmem(total, avail, percent, used, free)
Report virtual memory metrics.
176,299
import errno import functools import os import socket import subprocess import sys from collections import namedtuple from socket import AF_INET from . import _common from . import _psposix from . import _psutil_posix as cext_posix from . import _psutil_sunos as cext from ._common import AF_INET6 from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import debug from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize_when_activated from ._common import sockfam_to_enum from ._common import socktype_to_enum from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b PAGE_SIZE = cext_posix.getpagesize() import sys if sys.version_info[0] < 3: del num, x def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (float(used) / total) * 100 except ZeroDivisionError: return 0.0 else: if round_ is not None: ret = round(ret, round_) return ret PY3 = sys.version_info[0] == 3 if PY3: long = int xrange = range unicode = str basestring = str range = range def u(s): return s def b(s): return s.encode("latin-1") else: long = long range = xrange unicode = unicode basestring = basestring def u(s): return unicode(s, "unicode_escape") def b(s): return s if PY3: super = super else: _builtin_super = super def super(type_=_SENTINEL, type_or_obj=_SENTINEL, framedepth=1): """Like Python 3 builtin super(). If called without any arguments it attempts to infer them at runtime. """ if type_ is _SENTINEL: f = sys._getframe(framedepth) try: # Get the function's first positional argument. type_or_obj = f.f_locals[f.f_code.co_varnames[0]] except (IndexError, KeyError): raise RuntimeError('super() used in a function with no args') try: # Get the MRO so we can crawl it. mro = type_or_obj.__mro__ except (AttributeError, RuntimeError): try: mro = type_or_obj.__class__.__mro__ except AttributeError: raise RuntimeError('super() used in a non-newstyle class') for type_ in mro: # Find the class that owns the currently-executing method. for meth in type_.__dict__.values(): # Drill down through any wrappers to the underlying func. # This handles e.g. classmethod() and staticmethod(). try: while not isinstance(meth, types.FunctionType): if isinstance(meth, property): # Calling __get__ on the property will invoke # user code which might throw exceptions or # have side effects meth = meth.fget else: try: meth = meth.__func__ except AttributeError: meth = meth.__get__(type_or_obj, type_) except (AttributeError, TypeError): continue if meth.func_code is f.f_code: break # found else: # Not found. Move onto the next class in MRO. continue break # found else: raise RuntimeError('super() called outside a method') # Dispatch to builtin super(). if type_or_obj is not _SENTINEL: return _builtin_super(type_, type_or_obj) return _builtin_super(type_) if PY3: FileNotFoundError = FileNotFoundError # NOQA PermissionError = PermissionError # NOQA ProcessLookupError = ProcessLookupError # NOQA InterruptedError = InterruptedError # NOQA ChildProcessError = ChildProcessError # NOQA FileExistsError = FileExistsError # NOQA else: # https://github.com/PythonCharmers/python-future/blob/exceptions/ # src/future/types/exceptions/pep3151.py import platform def _instance_checking_exception(base_exception=Exception): def wrapped(instance_checker): class TemporaryClass(base_exception): def __init__(self, *args, **kwargs): if len(args) == 1 and isinstance(args[0], TemporaryClass): unwrap_me = args[0] for attr in dir(unwrap_me): if not attr.startswith('__'): setattr(self, attr, getattr(unwrap_me, attr)) else: super(TemporaryClass, self).__init__(*args, **kwargs) class __metaclass__(type): def __instancecheck__(cls, inst): return instance_checker(inst) def __subclasscheck__(cls, classinfo): value = sys.exc_info()[1] return isinstance(value, cls) TemporaryClass.__name__ = instance_checker.__name__ TemporaryClass.__doc__ = instance_checker.__doc__ return TemporaryClass return wrapped def FileNotFoundError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.ENOENT def ProcessLookupError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.ESRCH def PermissionError(inst): return getattr(inst, 'errno', _SENTINEL) in ( errno.EACCES, errno.EPERM) def InterruptedError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.EINTR def ChildProcessError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.ECHILD def FileExistsError(inst): return getattr(inst, 'errno', _SENTINEL) == errno.EEXIST if platform.python_implementation() != "CPython": try: raise OSError(errno.EEXIST, "perm") except FileExistsError: pass except OSError: raise RuntimeError( "broken or incompatible Python implementation, see: " "https://github.com/giampaolo/psutil/issues/1659") The provided code snippet includes necessary dependencies for implementing the `swap_memory` function. Write a Python function `def swap_memory()` to solve the following problem: Report swap memory metrics. Here is the function: def swap_memory(): """Report swap memory metrics.""" sin, sout = cext.swap_mem() # XXX # we are supposed to get total/free by doing so: # http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/ # usr/src/cmd/swap/swap.c # ...nevertheless I can't manage to obtain the same numbers as 'swap' # cmdline utility, so let's parse its output (sigh!) p = subprocess.Popen(['/usr/bin/env', 'PATH=/usr/sbin:/sbin:%s' % os.environ['PATH'], 'swap', '-l'], stdout=subprocess.PIPE) stdout, stderr = p.communicate() if PY3: stdout = stdout.decode(sys.stdout.encoding) if p.returncode != 0: raise RuntimeError("'swap -l' failed (retcode=%s)" % p.returncode) lines = stdout.strip().split('\n')[1:] if not lines: raise RuntimeError('no swap device(s) configured') total = free = 0 for line in lines: line = line.split() t, f = line[3:5] total += int(int(t) * 512) free += int(int(f) * 512) used = total - free percent = usage_percent(used, total, round_=1) return _common.sswap(total, used, free, percent, sin * PAGE_SIZE, sout * PAGE_SIZE)
Report swap memory metrics.
176,300
import errno import functools import os import socket import subprocess import sys from collections import namedtuple from socket import AF_INET from . import _common from . import _psposix from . import _psutil_posix as cext_posix from . import _psutil_sunos as cext from ._common import AF_INET6 from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import debug from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize_when_activated from ._common import sockfam_to_enum from ._common import socktype_to_enum from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b scputimes = namedtuple('scputimes', ['user', 'system', 'idle', 'iowait']) def per_cpu_times(): """Return system per-CPU times as a list of named tuples""" ret = cext.per_cpu_times() return [scputimes(*x) for x in ret] The provided code snippet includes necessary dependencies for implementing the `cpu_times` function. Write a Python function `def cpu_times()` to solve the following problem: Return system-wide CPU times as a named tuple Here is the function: def cpu_times(): """Return system-wide CPU times as a named tuple""" ret = cext.per_cpu_times() return scputimes(*[sum(x) for x in zip(*ret)])
Return system-wide CPU times as a named tuple
176,301
import errno import functools import os import socket import subprocess import sys from collections import namedtuple from socket import AF_INET from . import _common from . import _psposix from . import _psutil_posix as cext_posix from . import _psutil_sunos as cext from ._common import AF_INET6 from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import debug from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize_when_activated from ._common import sockfam_to_enum from ._common import socktype_to_enum from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b The provided code snippet includes necessary dependencies for implementing the `cpu_count_logical` function. Write a Python function `def cpu_count_logical()` to solve the following problem: Return the number of logical CPUs in the system. Here is the function: def cpu_count_logical(): """Return the number of logical CPUs in the system.""" try: return os.sysconf("SC_NPROCESSORS_ONLN") except ValueError: # mimic os.cpu_count() behavior return None
Return the number of logical CPUs in the system.
176,302
import errno import functools import os import socket import subprocess import sys from collections import namedtuple from socket import AF_INET from . import _common from . import _psposix from . import _psutil_posix as cext_posix from . import _psutil_sunos as cext from ._common import AF_INET6 from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import debug from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize_when_activated from ._common import sockfam_to_enum from ._common import socktype_to_enum from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b The provided code snippet includes necessary dependencies for implementing the `cpu_count_cores` function. Write a Python function `def cpu_count_cores()` to solve the following problem: Return the number of CPU cores in the system. Here is the function: def cpu_count_cores(): """Return the number of CPU cores in the system.""" return cext.cpu_count_cores()
Return the number of CPU cores in the system.
176,303
import errno import functools import os import socket import subprocess import sys from collections import namedtuple from socket import AF_INET from . import _common from . import _psposix from . import _psutil_posix as cext_posix from . import _psutil_sunos as cext from ._common import AF_INET6 from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import debug from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize_when_activated from ._common import sockfam_to_enum from ._common import socktype_to_enum from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b The provided code snippet includes necessary dependencies for implementing the `cpu_stats` function. Write a Python function `def cpu_stats()` to solve the following problem: Return various CPU stats as a named tuple. Here is the function: def cpu_stats(): """Return various CPU stats as a named tuple.""" ctx_switches, interrupts, syscalls, traps = cext.cpu_stats() soft_interrupts = 0 return _common.scpustats(ctx_switches, interrupts, soft_interrupts, syscalls)
Return various CPU stats as a named tuple.
176,304
import errno import functools import os import socket import subprocess import sys from collections import namedtuple from socket import AF_INET from . import _common from . import _psposix from . import _psutil_posix as cext_posix from . import _psutil_sunos as cext from ._common import AF_INET6 from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import debug from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize_when_activated from ._common import sockfam_to_enum from ._common import socktype_to_enum from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b disk_usage = _psposix.disk_usage def debug(msg): """If PSUTIL_DEBUG env var is set, print a debug message to stderr.""" if PSUTIL_DEBUG: import inspect fname, lineno, func_name, lines, index = inspect.getframeinfo( inspect.currentframe().f_back) if isinstance(msg, Exception): if isinstance(msg, (OSError, IOError, EnvironmentError)): # ...because str(exc) may contain info about the file name msg = "ignoring %s" % msg else: msg = "ignoring %r" % msg print("psutil-debug [%s:%s]> %s" % (fname, lineno, msg), # NOQA file=sys.stderr) The provided code snippet includes necessary dependencies for implementing the `disk_partitions` function. Write a Python function `def disk_partitions(all=False)` to solve the following problem: Return system disk partitions. Here is the function: def disk_partitions(all=False): """Return system disk partitions.""" # TODO - the filtering logic should be better checked so that # it tries to reflect 'df' as much as possible retlist = [] partitions = cext.disk_partitions() for partition in partitions: device, mountpoint, fstype, opts = partition if device == 'none': device = '' if not all: # Differently from, say, Linux, we don't have a list of # common fs types so the best we can do, AFAIK, is to # filter by filesystem having a total size > 0. try: if not disk_usage(mountpoint).total: continue except OSError as err: # https://github.com/giampaolo/psutil/issues/1674 debug("skipping %r: %s" % (mountpoint, err)) continue maxfile = maxpath = None # set later ntuple = _common.sdiskpart(device, mountpoint, fstype, opts, maxfile, maxpath) retlist.append(ntuple) return retlist
Return system disk partitions.
176,305
import errno import functools import os import socket import subprocess import sys from collections import namedtuple from socket import AF_INET from . import _common from . import _psposix from . import _psutil_posix as cext_posix from . import _psutil_sunos as cext from ._common import AF_INET6 from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import debug from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize_when_activated from ._common import sockfam_to_enum from ._common import socktype_to_enum from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b TCP_STATUSES = { cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED, cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT, cext.TCPS_SYN_RCVD: _common.CONN_SYN_RECV, cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1, cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2, cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT, cext.TCPS_CLOSED: _common.CONN_CLOSE, cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT, cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK, cext.TCPS_LISTEN: _common.CONN_LISTEN, cext.TCPS_CLOSING: _common.CONN_CLOSING, cext.PSUTIL_CONN_NONE: _common.CONN_NONE, cext.TCPS_IDLE: CONN_IDLE, # sunos specific cext.TCPS_BOUND: CONN_BOUND, # sunos specific } AF_INET: AddressFamily if AF_INET6 is not None: conn_tmap.update({ "tcp6": ([AF_INET6], [SOCK_STREAM]), "udp6": ([AF_INET6], [SOCK_DGRAM]), }) def sockfam_to_enum(num): """Convert a numeric socket family value to an IntEnum member. If it's not a known member, return the numeric value itself. """ if enum is None: return num else: # pragma: no cover try: return socket.AddressFamily(num) except ValueError: return num def socktype_to_enum(num): """Convert a numeric socket type value to an IntEnum member. If it's not a known member, return the numeric value itself. """ if enum is None: return num else: # pragma: no cover try: return socket.SocketKind(num) except ValueError: return num The provided code snippet includes necessary dependencies for implementing the `net_connections` function. Write a Python function `def net_connections(kind, _pid=-1)` to solve the following problem: Return socket connections. If pid == -1 return system-wide connections (as opposed to connections opened by one process only). Only INET sockets are returned (UNIX are not). Here is the function: def net_connections(kind, _pid=-1): """Return socket connections. If pid == -1 return system-wide connections (as opposed to connections opened by one process only). Only INET sockets are returned (UNIX are not). """ cmap = _common.conn_tmap.copy() if _pid == -1: cmap.pop('unix', 0) if kind not in cmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in cmap]))) families, types = _common.conn_tmap[kind] rawlist = cext.net_connections(_pid) ret = set() for item in rawlist: fd, fam, type_, laddr, raddr, status, pid = item if fam not in families: continue if type_ not in types: continue # TODO: refactor and use _common.conn_to_ntuple. if fam in (AF_INET, AF_INET6): if laddr: laddr = _common.addr(*laddr) if raddr: raddr = _common.addr(*raddr) status = TCP_STATUSES[status] fam = sockfam_to_enum(fam) type_ = socktype_to_enum(type_) if _pid == -1: nt = _common.sconn(fd, fam, type_, laddr, raddr, status, pid) else: nt = _common.pconn(fd, fam, type_, laddr, raddr, status) ret.add(nt) return list(ret)
Return socket connections. If pid == -1 return system-wide connections (as opposed to connections opened by one process only). Only INET sockets are returned (UNIX are not).
176,306
import errno import functools import os import socket import subprocess import sys from collections import namedtuple from socket import AF_INET from . import _common from . import _psposix from . import _psutil_posix as cext_posix from . import _psutil_sunos as cext from ._common import AF_INET6 from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import debug from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize_when_activated from ._common import sockfam_to_enum from ._common import socktype_to_enum from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b The provided code snippet includes necessary dependencies for implementing the `net_if_stats` function. Write a Python function `def net_if_stats()` to solve the following problem: Get NIC stats (isup, duplex, speed, mtu). Here is the function: def net_if_stats(): """Get NIC stats (isup, duplex, speed, mtu).""" ret = cext.net_if_stats() for name, items in ret.items(): isup, duplex, speed, mtu = items if hasattr(_common, 'NicDuplex'): duplex = _common.NicDuplex(duplex) ret[name] = _common.snicstats(isup, duplex, speed, mtu, '') return ret
Get NIC stats (isup, duplex, speed, mtu).
176,307
import errno import functools import os import socket import subprocess import sys from collections import namedtuple from socket import AF_INET from . import _common from . import _psposix from . import _psutil_posix as cext_posix from . import _psutil_sunos as cext from ._common import AF_INET6 from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import debug from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize_when_activated from ._common import sockfam_to_enum from ._common import socktype_to_enum from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b The provided code snippet includes necessary dependencies for implementing the `boot_time` function. Write a Python function `def boot_time()` to solve the following problem: The system boot time expressed in seconds since the epoch. Here is the function: def boot_time(): """The system boot time expressed in seconds since the epoch.""" return cext.boot_time()
The system boot time expressed in seconds since the epoch.
176,308
import errno import functools import os import socket import subprocess import sys from collections import namedtuple from socket import AF_INET from . import _common from . import _psposix from . import _psutil_posix as cext_posix from . import _psutil_sunos as cext from ._common import AF_INET6 from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import debug from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize_when_activated from ._common import sockfam_to_enum from ._common import socktype_to_enum from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b The provided code snippet includes necessary dependencies for implementing the `users` function. Write a Python function `def users()` to solve the following problem: Return currently connected users as a list of namedtuples. Here is the function: def users(): """Return currently connected users as a list of namedtuples.""" retlist = [] rawlist = cext.users() localhost = (':0.0', ':0') for item in rawlist: user, tty, hostname, tstamp, user_process, pid = item # note: the underlying C function includes entries about # system boot, run level and others. We might want # to use them in the future. if not user_process: continue if hostname in localhost: hostname = 'localhost' nt = _common.suser(user, tty, hostname, tstamp, pid) retlist.append(nt) return retlist
Return currently connected users as a list of namedtuples.
176,309
import errno import functools import os import socket import subprocess import sys from collections import namedtuple from socket import AF_INET from . import _common from . import _psposix from . import _psutil_posix as cext_posix from . import _psutil_sunos as cext from ._common import AF_INET6 from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import debug from ._common import get_procfs_path from ._common import isfile_strict from ._common import memoize_when_activated from ._common import sockfam_to_enum from ._common import socktype_to_enum from ._common import usage_percent from ._compat import PY3 from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import b def pids(): """Returns a list of PIDs currently running on the system.""" return [int(x) for x in os.listdir(b(get_procfs_path())) if x.isdigit()] def pid_exists(pid): """Check for the existence of a unix pid.""" return _psposix.pid_exists(pid) class NoSuchProcess(Error): """Exception raised when a process with a certain PID doesn't or no longer exists. """ __module__ = 'psutil' def __init__(self, pid, name=None, msg=None): Error.__init__(self) self.pid = pid self.name = name self.msg = msg or "process no longer exists" class ZombieProcess(NoSuchProcess): """Exception raised when querying a zombie process. This is raised on macOS, BSD and Solaris only, and not always: depending on the query the OS may be able to succeed anyway. On Linux all zombie processes are querable (hence this is never raised). Windows doesn't have zombie processes. """ __module__ = 'psutil' def __init__(self, pid, name=None, ppid=None, msg=None): NoSuchProcess.__init__(self, pid, name, msg) self.ppid = ppid self.msg = msg or "PID still exists but it's a zombie" class AccessDenied(Error): """Exception raised when permission to perform an action is denied.""" __module__ = 'psutil' def __init__(self, pid=None, name=None, msg=None): Error.__init__(self) self.pid = pid self.name = name self.msg = msg or "" The provided code snippet includes necessary dependencies for implementing the `wrap_exceptions` function. Write a Python function `def wrap_exceptions(fun)` to solve the following problem: Call callable into a try/except clause and translate ENOENT, EACCES and EPERM in NoSuchProcess or AccessDenied exceptions. Here is the function: def wrap_exceptions(fun): """Call callable into a try/except clause and translate ENOENT, EACCES and EPERM in NoSuchProcess or AccessDenied exceptions. """ @functools.wraps(fun) def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) except (FileNotFoundError, ProcessLookupError): # ENOENT (no such file or directory) gets raised on open(). # ESRCH (no such process) can get raised on read() if # process is gone in meantime. if not pid_exists(self.pid): raise NoSuchProcess(self.pid, self._name) else: raise ZombieProcess(self.pid, self._name, self._ppid) except PermissionError: raise AccessDenied(self.pid, self._name) except OSError: if self.pid == 0: if 0 in pids(): raise AccessDenied(self.pid, self._name) else: raise raise return wrapper
Call callable into a try/except clause and translate ENOENT, EACCES and EPERM in NoSuchProcess or AccessDenied exceptions.
176,310
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which svmem = namedtuple( 'svmem', ['total', 'available', 'percent', 'used', 'free', 'active', 'inactive', 'buffers', 'cached', 'shared', 'wired']) NETBSD = sys.platform.startswith("netbsd") def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (float(used) / total) * 100 except ZeroDivisionError: return 0.0 else: if round_ is not None: ret = round(ret, round_) return ret The provided code snippet includes necessary dependencies for implementing the `virtual_memory` function. Write a Python function `def virtual_memory()` to solve the following problem: System virtual memory as a namedtuple. Here is the function: def virtual_memory(): """System virtual memory as a namedtuple.""" mem = cext.virtual_mem() total, free, active, inactive, wired, cached, buffers, shared = mem if NETBSD: # On NetBSD buffers and shared mem is determined via /proc. # The C ext set them to 0. with open('/proc/meminfo', 'rb') as f: for line in f: if line.startswith(b'Buffers:'): buffers = int(line.split()[1]) * 1024 elif line.startswith(b'MemShared:'): shared = int(line.split()[1]) * 1024 elif line.startswith(b'Cached:'): cached = int(line.split()[1]) * 1024 avail = inactive + cached + free used = active + wired + cached percent = usage_percent((total - avail), total, round_=1) return svmem(total, avail, percent, used, free, active, inactive, buffers, cached, shared, wired)
System virtual memory as a namedtuple.
176,311
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which def usage_percent(used, total, round_=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (float(used) / total) * 100 except ZeroDivisionError: return 0.0 else: if round_ is not None: ret = round(ret, round_) return ret The provided code snippet includes necessary dependencies for implementing the `swap_memory` function. Write a Python function `def swap_memory()` to solve the following problem: System swap memory as (total, used, free, sin, sout) namedtuple. Here is the function: def swap_memory(): """System swap memory as (total, used, free, sin, sout) namedtuple.""" total, used, free, sin, sout = cext.swap_mem() percent = usage_percent(used, total, round_=1) return _common.sswap(total, used, free, percent, sin, sout)
System swap memory as (total, used, free, sin, sout) namedtuple.
176,312
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which scputimes = namedtuple( 'scputimes', ['user', 'nice', 'system', 'idle', 'irq']) The provided code snippet includes necessary dependencies for implementing the `per_cpu_times` function. Write a Python function `def per_cpu_times()` to solve the following problem: Return system CPU times as a namedtuple Here is the function: def per_cpu_times(): """Return system CPU times as a namedtuple""" ret = [] for cpu_t in cext.per_cpu_times(): user, nice, system, idle, irq = cpu_t item = scputimes(user, nice, system, idle, irq) ret.append(item) return ret
Return system CPU times as a namedtuple
176,313
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which def cpu_times(): """Return system per-CPU times as a namedtuple""" user, nice, system, idle, irq = cext.cpu_times() return scputimes(user, nice, system, idle, irq) def cpu_count_logical(): """Return the number of logical CPUs in the system.""" return cext.cpu_count_logical() The provided code snippet includes necessary dependencies for implementing the `per_cpu_times` function. Write a Python function `def per_cpu_times()` to solve the following problem: Return system CPU times as a namedtuple Here is the function: def per_cpu_times(): """Return system CPU times as a namedtuple""" if cpu_count_logical() == 1: return [cpu_times()] if per_cpu_times.__called__: raise NotImplementedError("supported only starting from FreeBSD 8") per_cpu_times.__called__ = True return [cpu_times()]
Return system CPU times as a namedtuple
176,314
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which def cpu_count_logical(): """Return the number of logical CPUs in the system.""" return cext.cpu_count_logical() def cpu_count_cores(): # OpenBSD and NetBSD do not implement this. return 1 if cpu_count_logical() == 1 else None
null
176,315
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which def cpu_count_logical(): """Return the number of logical CPUs in the system.""" return cext.cpu_count_logical() The provided code snippet includes necessary dependencies for implementing the `cpu_count_cores` function. Write a Python function `def cpu_count_cores()` to solve the following problem: Return the number of CPU cores in the system. Here is the function: def cpu_count_cores(): """Return the number of CPU cores in the system.""" # From the C module we'll get an XML string similar to this: # http://manpages.ubuntu.com/manpages/precise/man4/smp.4freebsd.html # We may get None in case "sysctl kern.sched.topology_spec" # is not supported on this BSD version, in which case we'll mimic # os.cpu_count() and return None. ret = None s = cext.cpu_topology() if s is not None: # get rid of padding chars appended at the end of the string index = s.rfind("</groups>") if index != -1: s = s[:index + 9] root = ET.fromstring(s) try: ret = len(root.findall('group/children/group/cpu')) or None finally: # needed otherwise it will memleak root.clear() if not ret: # If logical CPUs == 1 it's obvious we' have only 1 core. if cpu_count_logical() == 1: return 1 return ret
Return the number of CPU cores in the system.
176,316
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which if FREEBSD: PROC_STATUSES = { cext.SIDL: _common.STATUS_IDLE, cext.SRUN: _common.STATUS_RUNNING, cext.SSLEEP: _common.STATUS_SLEEPING, cext.SSTOP: _common.STATUS_STOPPED, cext.SZOMB: _common.STATUS_ZOMBIE, cext.SWAIT: _common.STATUS_WAITING, cext.SLOCK: _common.STATUS_LOCKED, } elif OPENBSD: PROC_STATUSES = { cext.SIDL: _common.STATUS_IDLE, cext.SSLEEP: _common.STATUS_SLEEPING, cext.SSTOP: _common.STATUS_STOPPED, # According to /usr/include/sys/proc.h SZOMB is unused. # test_zombie_process() shows that SDEAD is the right # equivalent. Also it appears there's no equivalent of # psutil.STATUS_DEAD. SDEAD really means STATUS_ZOMBIE. # cext.SZOMB: _common.STATUS_ZOMBIE, cext.SDEAD: _common.STATUS_ZOMBIE, cext.SZOMB: _common.STATUS_ZOMBIE, # From http://www.eecs.harvard.edu/~margo/cs161/videos/proc.h.txt # OpenBSD has SRUN and SONPROC: SRUN indicates that a process # is runnable but *not* yet running, i.e. is on a run queue. # SONPROC indicates that the process is actually executing on # a CPU, i.e. it is no longer on a run queue. # As such we'll map SRUN to STATUS_WAKING and SONPROC to # STATUS_RUNNING cext.SRUN: _common.STATUS_WAKING, cext.SONPROC: _common.STATUS_RUNNING, } elif NETBSD: PROC_STATUSES = { cext.SIDL: _common.STATUS_IDLE, cext.SSLEEP: _common.STATUS_SLEEPING, cext.SSTOP: _common.STATUS_STOPPED, cext.SZOMB: _common.STATUS_ZOMBIE, cext.SRUN: _common.STATUS_WAKING, cext.SONPROC: _common.STATUS_RUNNING, } if FREEBSD: sdiskio = namedtuple('sdiskio', ['read_count', 'write_count', 'read_bytes', 'write_bytes', 'read_time', 'write_time', 'busy_time']) else: sdiskio = namedtuple('sdiskio', ['read_count', 'write_count', 'read_bytes', 'write_bytes']) if OPENBSD or NETBSD: else: if FREEBSD: elif OPENBSD: if FREEBSD: if OPENBSD or NETBSD: else: pid_exists = _psposix.pid_exists FREEBSD = sys.platform.startswith(("freebsd", "midnightbsd")) OPENBSD = sys.platform.startswith("openbsd") NETBSD = sys.platform.startswith("netbsd") The provided code snippet includes necessary dependencies for implementing the `cpu_stats` function. Write a Python function `def cpu_stats()` to solve the following problem: Return various CPU stats as a named tuple. Here is the function: def cpu_stats(): """Return various CPU stats as a named tuple.""" if FREEBSD: # Note: the C ext is returning some metrics we are not exposing: # traps. ctxsw, intrs, soft_intrs, syscalls, traps = cext.cpu_stats() elif NETBSD: # XXX # Note about intrs: the C extension returns 0. intrs # can be determined via /proc/stat; it has the same value as # soft_intrs thought so the kernel is faking it (?). # # Note about syscalls: the C extension always sets it to 0 (?). # # Note: the C ext is returning some metrics we are not exposing: # traps, faults and forks. ctxsw, intrs, soft_intrs, syscalls, traps, faults, forks = \ cext.cpu_stats() with open('/proc/stat', 'rb') as f: for line in f: if line.startswith(b'intr'): intrs = int(line.split()[1]) elif OPENBSD: # Note: the C ext is returning some metrics we are not exposing: # traps, faults and forks. ctxsw, intrs, soft_intrs, syscalls, traps, faults, forks = \ cext.cpu_stats() return _common.scpustats(ctxsw, intrs, soft_intrs, syscalls)
Return various CPU stats as a named tuple.
176,317
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which def cpu_count_logical(): """Return the number of logical CPUs in the system.""" return cext.cpu_count_logical() The provided code snippet includes necessary dependencies for implementing the `cpu_freq` function. Write a Python function `def cpu_freq()` to solve the following problem: Return frequency metrics for CPUs. As of Dec 2018 only CPU 0 appears to be supported by FreeBSD and all other cores match the frequency of CPU 0. Here is the function: def cpu_freq(): """Return frequency metrics for CPUs. As of Dec 2018 only CPU 0 appears to be supported by FreeBSD and all other cores match the frequency of CPU 0. """ ret = [] num_cpus = cpu_count_logical() for cpu in range(num_cpus): try: current, available_freq = cext.cpu_freq(cpu) except NotImplementedError: continue if available_freq: try: min_freq = int(available_freq.split(" ")[-1].split("/")[0]) except (IndexError, ValueError): min_freq = None try: max_freq = int(available_freq.split(" ")[0].split("/")[0]) except (IndexError, ValueError): max_freq = None ret.append(_common.scpufreq(current, min_freq, max_freq)) return ret
Return frequency metrics for CPUs. As of Dec 2018 only CPU 0 appears to be supported by FreeBSD and all other cores match the frequency of CPU 0.
176,318
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which def cpu_freq(): curr = float(cext.cpu_freq()) return [_common.scpufreq(curr, 0.0, 0.0)]
null
176,319
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which The provided code snippet includes necessary dependencies for implementing the `disk_partitions` function. Write a Python function `def disk_partitions(all=False)` to solve the following problem: Return mounted disk partitions as a list of namedtuples. 'all' argument is ignored, see: https://github.com/giampaolo/psutil/issues/906 Here is the function: def disk_partitions(all=False): """Return mounted disk partitions as a list of namedtuples. 'all' argument is ignored, see: https://github.com/giampaolo/psutil/issues/906 """ retlist = [] partitions = cext.disk_partitions() for partition in partitions: device, mountpoint, fstype, opts = partition maxfile = maxpath = None # set later ntuple = _common.sdiskpart(device, mountpoint, fstype, opts, maxfile, maxpath) retlist.append(ntuple) return retlist
Return mounted disk partitions as a list of namedtuples. 'all' argument is ignored, see: https://github.com/giampaolo/psutil/issues/906
176,320
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which net_io_counters = cext.net_io_counters The provided code snippet includes necessary dependencies for implementing the `net_if_stats` function. Write a Python function `def net_if_stats()` to solve the following problem: Get NIC stats (isup, duplex, speed, mtu). Here is the function: def net_if_stats(): """Get NIC stats (isup, duplex, speed, mtu).""" names = net_io_counters().keys() ret = {} for name in names: try: mtu = cext_posix.net_if_mtu(name) flags = cext_posix.net_if_flags(name) duplex, speed = cext_posix.net_if_duplex_speed(name) except OSError as err: # https://github.com/giampaolo/psutil/issues/1279 if err.errno != errno.ENODEV: raise else: if hasattr(_common, 'NicDuplex'): duplex = _common.NicDuplex(duplex) output_flags = ','.join(flags) isup = 'running' in flags ret[name] = _common.snicstats(isup, duplex, speed, mtu, output_flags) return ret
Get NIC stats (isup, duplex, speed, mtu).
176,321
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which TCP_STATUSES = { cext.TCPS_ESTABLISHED: _common.CONN_ESTABLISHED, cext.TCPS_SYN_SENT: _common.CONN_SYN_SENT, cext.TCPS_SYN_RECEIVED: _common.CONN_SYN_RECV, cext.TCPS_FIN_WAIT_1: _common.CONN_FIN_WAIT1, cext.TCPS_FIN_WAIT_2: _common.CONN_FIN_WAIT2, cext.TCPS_TIME_WAIT: _common.CONN_TIME_WAIT, cext.TCPS_CLOSED: _common.CONN_CLOSE, cext.TCPS_CLOSE_WAIT: _common.CONN_CLOSE_WAIT, cext.TCPS_LAST_ACK: _common.CONN_LAST_ACK, cext.TCPS_LISTEN: _common.CONN_LISTEN, cext.TCPS_CLOSING: _common.CONN_CLOSING, cext.PSUTIL_CONN_NONE: _common.CONN_NONE, } if OPENBSD or NETBSD: else: def pids(): """Returns a list of PIDs currently running on the system.""" ret = cext.pids() if OPENBSD and (0 not in ret) and _pid_0_exists(): # On OpenBSD the kernel does not return PID 0 (neither does # ps) but it's actually querable (Process(0) will succeed). ret.insert(0, 0) return ret if OPENBSD or NETBSD: else: pid_exists = _psposix.pid_exists class Process(object): """Wrapper class around underlying C implementation.""" __slots__ = ["pid", "_name", "_ppid", "_cache"] def __init__(self, pid): self.pid = pid self._name = None self._ppid = None def _assert_alive(self): """Raise NSP if the process disappeared on us.""" # For those C function who do not raise NSP, possibly returning # incorrect or incomplete result. cext.proc_name(self.pid) def oneshot(self): """Retrieves multiple process info in one shot as a raw tuple.""" ret = cext.proc_oneshot_info(self.pid) assert len(ret) == len(kinfo_proc_map) return ret def oneshot_enter(self): self.oneshot.cache_activate(self) def oneshot_exit(self): self.oneshot.cache_deactivate(self) def name(self): name = self.oneshot()[kinfo_proc_map['name']] return name if name is not None else cext.proc_name(self.pid) def exe(self): if FREEBSD: if self.pid == 0: return '' # else NSP return cext.proc_exe(self.pid) elif NETBSD: if self.pid == 0: # /proc/0 dir exists but /proc/0/exe doesn't return "" with wrap_exceptions_procfs(self): return os.readlink("/proc/%s/exe" % self.pid) else: # OpenBSD: exe cannot be determined; references: # https://chromium.googlesource.com/chromium/src/base/+/ # master/base_paths_posix.cc # We try our best guess by using which against the first # cmdline arg (may return None). cmdline = self.cmdline() if cmdline: return which(cmdline[0]) or "" else: return "" def cmdline(self): if OPENBSD and self.pid == 0: return [] # ...else it crashes elif NETBSD: # XXX - most of the times the underlying sysctl() call on Net # and Open BSD returns a truncated string. # Also /proc/pid/cmdline behaves the same so it looks # like this is a kernel bug. try: return cext.proc_cmdline(self.pid) except OSError as err: if err.errno == errno.EINVAL: if is_zombie(self.pid): raise ZombieProcess(self.pid, self._name, self._ppid) elif not pid_exists(self.pid): raise NoSuchProcess(self.pid, self._name, self._ppid) else: # XXX: this happens with unicode tests. It means the C # routine is unable to decode invalid unicode chars. return [] else: raise else: return cext.proc_cmdline(self.pid) def environ(self): return cext.proc_environ(self.pid) def terminal(self): tty_nr = self.oneshot()[kinfo_proc_map['ttynr']] tmap = _psposix.get_terminal_map() try: return tmap[tty_nr] except KeyError: return None def ppid(self): self._ppid = self.oneshot()[kinfo_proc_map['ppid']] return self._ppid def uids(self): rawtuple = self.oneshot() return _common.puids( rawtuple[kinfo_proc_map['real_uid']], rawtuple[kinfo_proc_map['effective_uid']], rawtuple[kinfo_proc_map['saved_uid']]) def gids(self): rawtuple = self.oneshot() return _common.pgids( rawtuple[kinfo_proc_map['real_gid']], rawtuple[kinfo_proc_map['effective_gid']], rawtuple[kinfo_proc_map['saved_gid']]) def cpu_times(self): rawtuple = self.oneshot() return _common.pcputimes( rawtuple[kinfo_proc_map['user_time']], rawtuple[kinfo_proc_map['sys_time']], rawtuple[kinfo_proc_map['ch_user_time']], rawtuple[kinfo_proc_map['ch_sys_time']]) if FREEBSD: def cpu_num(self): return self.oneshot()[kinfo_proc_map['cpunum']] def memory_info(self): rawtuple = self.oneshot() return pmem( rawtuple[kinfo_proc_map['rss']], rawtuple[kinfo_proc_map['vms']], rawtuple[kinfo_proc_map['memtext']], rawtuple[kinfo_proc_map['memdata']], rawtuple[kinfo_proc_map['memstack']]) memory_full_info = memory_info def create_time(self): return self.oneshot()[kinfo_proc_map['create_time']] def num_threads(self): if HAS_PROC_NUM_THREADS: # FreeBSD return cext.proc_num_threads(self.pid) else: return len(self.threads()) def num_ctx_switches(self): rawtuple = self.oneshot() return _common.pctxsw( rawtuple[kinfo_proc_map['ctx_switches_vol']], rawtuple[kinfo_proc_map['ctx_switches_unvol']]) def threads(self): # Note: on OpenSBD this (/dev/mem) requires root access. rawlist = cext.proc_threads(self.pid) retlist = [] for thread_id, utime, stime in rawlist: ntuple = _common.pthread(thread_id, utime, stime) retlist.append(ntuple) if OPENBSD: self._assert_alive() return retlist def connections(self, kind='inet'): if kind not in conn_tmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in conn_tmap]))) if NETBSD: families, types = conn_tmap[kind] ret = [] rawlist = cext.net_connections(self.pid) for item in rawlist: fd, fam, type, laddr, raddr, status, pid = item assert pid == self.pid if fam in families and type in types: nt = conn_to_ntuple(fd, fam, type, laddr, raddr, status, TCP_STATUSES) ret.append(nt) self._assert_alive() return list(ret) families, types = conn_tmap[kind] rawlist = cext.proc_connections(self.pid, families, types) ret = [] for item in rawlist: fd, fam, type, laddr, raddr, status = item nt = conn_to_ntuple(fd, fam, type, laddr, raddr, status, TCP_STATUSES) ret.append(nt) if OPENBSD: self._assert_alive() return ret def wait(self, timeout=None): return _psposix.wait_pid(self.pid, timeout, self._name) def nice_get(self): return cext_posix.getpriority(self.pid) def nice_set(self, value): return cext_posix.setpriority(self.pid, value) def status(self): code = self.oneshot()[kinfo_proc_map['status']] # XXX is '?' legit? (we're not supposed to return it anyway) return PROC_STATUSES.get(code, '?') def io_counters(self): rawtuple = self.oneshot() return _common.pio( rawtuple[kinfo_proc_map['read_io_count']], rawtuple[kinfo_proc_map['write_io_count']], -1, -1) def cwd(self): """Return process current working directory.""" # sometimes we get an empty string, in which case we turn # it into None if OPENBSD and self.pid == 0: return None # ...else it would raise EINVAL elif NETBSD or HAS_PROC_OPEN_FILES: # FreeBSD < 8 does not support functions based on # kinfo_getfile() and kinfo_getvmmap() return cext.proc_cwd(self.pid) or None else: raise NotImplementedError( "supported only starting from FreeBSD 8" if FREEBSD else "") nt_mmap_grouped = namedtuple( 'mmap', 'path rss, private, ref_count, shadow_count') nt_mmap_ext = namedtuple( 'mmap', 'addr, perms path rss, private, ref_count, shadow_count') def _not_implemented(self): raise NotImplementedError # FreeBSD < 8 does not support functions based on kinfo_getfile() # and kinfo_getvmmap() if HAS_PROC_OPEN_FILES: def open_files(self): """Return files opened by process as a list of namedtuples.""" rawlist = cext.proc_open_files(self.pid) return [_common.popenfile(path, fd) for path, fd in rawlist] else: open_files = _not_implemented # FreeBSD < 8 does not support functions based on kinfo_getfile() # and kinfo_getvmmap() if HAS_PROC_NUM_FDS: def num_fds(self): """Return the number of file descriptors opened by this process.""" ret = cext.proc_num_fds(self.pid) if NETBSD: self._assert_alive() return ret else: num_fds = _not_implemented # --- FreeBSD only APIs if FREEBSD: def cpu_affinity_get(self): return cext.proc_cpu_affinity_get(self.pid) def cpu_affinity_set(self, cpus): # Pre-emptively check if CPUs are valid because the C # function has a weird behavior in case of invalid CPUs, # see: https://github.com/giampaolo/psutil/issues/586 allcpus = tuple(range(len(per_cpu_times()))) for cpu in cpus: if cpu not in allcpus: raise ValueError("invalid CPU #%i (choose between %s)" % (cpu, allcpus)) try: cext.proc_cpu_affinity_set(self.pid, cpus) except OSError as err: # 'man cpuset_setaffinity' about EDEADLK: # <<the call would leave a thread without a valid CPU to run # on because the set does not overlap with the thread's # anonymous mask>> if err.errno in (errno.EINVAL, errno.EDEADLK): for cpu in cpus: if cpu not in allcpus: raise ValueError( "invalid CPU #%i (choose between %s)" % ( cpu, allcpus)) raise def memory_maps(self): return cext.proc_memory_maps(self.pid) def rlimit(self, resource, limits=None): if limits is None: return cext.proc_getrlimit(self.pid, resource) else: if len(limits) != 2: raise ValueError( "second argument must be a (soft, hard) tuple, " "got %s" % repr(limits)) soft, hard = limits return cext.proc_setrlimit(self.pid, resource, soft, hard) OPENBSD = sys.platform.startswith("openbsd") NETBSD = sys.platform.startswith("netbsd") conn_tmap = { "all": ([AF_INET, AF_INET6, AF_UNIX], [SOCK_STREAM, SOCK_DGRAM]), "tcp": ([AF_INET, AF_INET6], [SOCK_STREAM]), "tcp4": ([AF_INET], [SOCK_STREAM]), "udp": ([AF_INET, AF_INET6], [SOCK_DGRAM]), "udp4": ([AF_INET], [SOCK_DGRAM]), "inet": ([AF_INET, AF_INET6], [SOCK_STREAM, SOCK_DGRAM]), "inet4": ([AF_INET], [SOCK_STREAM, SOCK_DGRAM]), "inet6": ([AF_INET6], [SOCK_STREAM, SOCK_DGRAM]), } class NoSuchProcess(Error): """Exception raised when a process with a certain PID doesn't or no longer exists. """ __module__ = 'psutil' def __init__(self, pid, name=None, msg=None): Error.__init__(self) self.pid = pid self.name = name self.msg = msg or "process no longer exists" class ZombieProcess(NoSuchProcess): """Exception raised when querying a zombie process. This is raised on macOS, BSD and Solaris only, and not always: depending on the query the OS may be able to succeed anyway. On Linux all zombie processes are querable (hence this is never raised). Windows doesn't have zombie processes. """ __module__ = 'psutil' def __init__(self, pid, name=None, ppid=None, msg=None): NoSuchProcess.__init__(self, pid, name, msg) self.ppid = ppid self.msg = msg or "PID still exists but it's a zombie" def conn_to_ntuple(fd, fam, type_, laddr, raddr, status, status_map, pid=None): """Convert a raw connection tuple to a proper ntuple.""" if fam in (socket.AF_INET, AF_INET6): if laddr: laddr = addr(*laddr) if raddr: raddr = addr(*raddr) if type_ == socket.SOCK_STREAM and fam in (AF_INET, AF_INET6): status = status_map.get(status, CONN_NONE) else: status = CONN_NONE # ignore whatever C returned to us fam = sockfam_to_enum(fam) type_ = socktype_to_enum(type_) if pid is None: return pconn(fd, fam, type_, laddr, raddr, status) else: return sconn(fd, fam, type_, laddr, raddr, status, pid) The provided code snippet includes necessary dependencies for implementing the `net_connections` function. Write a Python function `def net_connections(kind)` to solve the following problem: System-wide network connections. Here is the function: def net_connections(kind): """System-wide network connections.""" if OPENBSD: ret = [] for pid in pids(): try: cons = Process(pid).connections(kind) except (NoSuchProcess, ZombieProcess): continue else: for conn in cons: conn = list(conn) conn.append(pid) ret.append(_common.sconn(*conn)) return ret if kind not in _common.conn_tmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in conn_tmap]))) families, types = conn_tmap[kind] ret = set() if NETBSD: rawlist = cext.net_connections(-1) else: rawlist = cext.net_connections() for item in rawlist: fd, fam, type, laddr, raddr, status, pid = item # TODO: apply filter at C level if fam in families and type in types: nt = conn_to_ntuple(fd, fam, type, laddr, raddr, status, TCP_STATUSES, pid) ret.add(nt) return list(ret)
System-wide network connections.
176,322
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which The provided code snippet includes necessary dependencies for implementing the `sensors_battery` function. Write a Python function `def sensors_battery()` to solve the following problem: Return battery info. Here is the function: def sensors_battery(): """Return battery info.""" try: percent, minsleft, power_plugged = cext.sensors_battery() except NotImplementedError: # See: https://github.com/giampaolo/psutil/issues/1074 return None power_plugged = power_plugged == 1 if power_plugged: secsleft = _common.POWER_TIME_UNLIMITED elif minsleft == -1: secsleft = _common.POWER_TIME_UNKNOWN else: secsleft = minsleft * 60 return _common.sbattery(percent, secsleft, power_plugged)
Return battery info.
176,323
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which def cpu_count_logical(): """Return the number of logical CPUs in the system.""" return cext.cpu_count_logical() class defaultdict(Dict[_KT, _VT], Generic[_KT, _VT]): default_factory: Callable[[], _VT] def __init__(self, **kwargs: _VT) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]]) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT]) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT) -> None: ... def __init__(self, default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]]) -> None: ... def __init__( self, default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT ) -> None: ... def __missing__(self, key: _KT) -> _VT: ... def copy(self: _S) -> _S: ... The provided code snippet includes necessary dependencies for implementing the `sensors_temperatures` function. Write a Python function `def sensors_temperatures()` to solve the following problem: Return CPU cores temperatures if available, else an empty dict. Here is the function: def sensors_temperatures(): """Return CPU cores temperatures if available, else an empty dict.""" ret = defaultdict(list) num_cpus = cpu_count_logical() for cpu in range(num_cpus): try: current, high = cext.sensors_cpu_temperature(cpu) if high <= 0: high = None name = "Core %s" % cpu ret["coretemp"].append( _common.shwtemp(name, current, high, high)) except NotImplementedError: pass return ret
Return CPU cores temperatures if available, else an empty dict.
176,324
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which The provided code snippet includes necessary dependencies for implementing the `boot_time` function. Write a Python function `def boot_time()` to solve the following problem: The system boot time expressed in seconds since the epoch. Here is the function: def boot_time(): """The system boot time expressed in seconds since the epoch.""" return cext.boot_time()
The system boot time expressed in seconds since the epoch.
176,325
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which if OPENBSD or NETBSD: else: if OPENBSD or NETBSD: else: pid_exists = _psposix.pid_exists OPENBSD = sys.platform.startswith("openbsd") The provided code snippet includes necessary dependencies for implementing the `users` function. Write a Python function `def users()` to solve the following problem: Return currently connected users as a list of namedtuples. Here is the function: def users(): """Return currently connected users as a list of namedtuples.""" retlist = [] rawlist = cext.users() for item in rawlist: user, tty, hostname, tstamp, pid = item if pid == -1: assert OPENBSD pid = None if tty == '~': continue # reboot or shutdown nt = _common.suser(user, tty or None, hostname, tstamp, pid) retlist.append(nt) return retlist
Return currently connected users as a list of namedtuples.
176,326
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which def pids(): """Returns a list of PIDs currently running on the system.""" ret = cext.pids() if OPENBSD and (0 not in ret) and _pid_0_exists(): # On OpenBSD the kernel does not return PID 0 (neither does # ps) but it's actually querable (Process(0) will succeed). ret.insert(0, 0) return ret The provided code snippet includes necessary dependencies for implementing the `pid_exists` function. Write a Python function `def pid_exists(pid)` to solve the following problem: Return True if pid exists. Here is the function: def pid_exists(pid): """Return True if pid exists.""" exists = _psposix.pid_exists(pid) if not exists: # We do this because _psposix.pid_exists() lies in case of # zombie processes. return pid in pids() else: return True
Return True if pid exists.
176,327
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which def pids(): """Returns a list of PIDs currently running on the system.""" ret = cext.pids() if OPENBSD and (0 not in ret) and _pid_0_exists(): # On OpenBSD the kernel does not return PID 0 (neither does # ps) but it's actually querable (Process(0) will succeed). ret.insert(0, 0) return ret def is_zombie(pid): try: st = cext.proc_oneshot_info(pid)[kinfo_proc_map['status']] return st == cext.SZOMB except Exception: return False class NoSuchProcess(Error): """Exception raised when a process with a certain PID doesn't or no longer exists. """ __module__ = 'psutil' def __init__(self, pid, name=None, msg=None): Error.__init__(self) self.pid = pid self.name = name self.msg = msg or "process no longer exists" class ZombieProcess(NoSuchProcess): """Exception raised when querying a zombie process. This is raised on macOS, BSD and Solaris only, and not always: depending on the query the OS may be able to succeed anyway. On Linux all zombie processes are querable (hence this is never raised). Windows doesn't have zombie processes. """ __module__ = 'psutil' def __init__(self, pid, name=None, ppid=None, msg=None): NoSuchProcess.__init__(self, pid, name, msg) self.ppid = ppid self.msg = msg or "PID still exists but it's a zombie" class AccessDenied(Error): """Exception raised when permission to perform an action is denied.""" __module__ = 'psutil' def __init__(self, pid=None, name=None, msg=None): Error.__init__(self) self.pid = pid self.name = name self.msg = msg or "" The provided code snippet includes necessary dependencies for implementing the `wrap_exceptions` function. Write a Python function `def wrap_exceptions(fun)` to solve the following problem: Decorator which translates bare OSError exceptions into NoSuchProcess and AccessDenied. Here is the function: def wrap_exceptions(fun): """Decorator which translates bare OSError exceptions into NoSuchProcess and AccessDenied. """ @functools.wraps(fun) def wrapper(self, *args, **kwargs): try: return fun(self, *args, **kwargs) except ProcessLookupError: if is_zombie(self.pid): raise ZombieProcess(self.pid, self._name, self._ppid) else: raise NoSuchProcess(self.pid, self._name) except PermissionError: raise AccessDenied(self.pid, self._name) except OSError: if self.pid == 0: if 0 in pids(): raise AccessDenied(self.pid, self._name) else: raise raise return wrapper
Decorator which translates bare OSError exceptions into NoSuchProcess and AccessDenied.
176,328
import contextlib import errno import functools import os import xml.etree.ElementTree as ET from collections import defaultdict from collections import namedtuple from . import _common from . import _psposix from . import _psutil_bsd as cext from . import _psutil_posix as cext_posix from ._common import FREEBSD from ._common import NETBSD from ._common import OPENBSD from ._common import AccessDenied from ._common import NoSuchProcess from ._common import ZombieProcess from ._common import conn_tmap from ._common import conn_to_ntuple from ._common import memoize from ._common import memoize_when_activated from ._common import usage_percent from ._compat import FileNotFoundError from ._compat import PermissionError from ._compat import ProcessLookupError from ._compat import which def is_zombie(pid): try: st = cext.proc_oneshot_info(pid)[kinfo_proc_map['status']] return st == cext.SZOMB except Exception: return False class NoSuchProcess(Error): """Exception raised when a process with a certain PID doesn't or no longer exists. """ __module__ = 'psutil' def __init__(self, pid, name=None, msg=None): Error.__init__(self) self.pid = pid self.name = name self.msg = msg or "process no longer exists" class ZombieProcess(NoSuchProcess): """Exception raised when querying a zombie process. This is raised on macOS, BSD and Solaris only, and not always: depending on the query the OS may be able to succeed anyway. On Linux all zombie processes are querable (hence this is never raised). Windows doesn't have zombie processes. """ __module__ = 'psutil' def __init__(self, pid, name=None, ppid=None, msg=None): NoSuchProcess.__init__(self, pid, name, msg) self.ppid = ppid self.msg = msg or "PID still exists but it's a zombie" class AccessDenied(Error): """Exception raised when permission to perform an action is denied.""" __module__ = 'psutil' def __init__(self, pid=None, name=None, msg=None): Error.__init__(self) self.pid = pid self.name = name self.msg = msg or "" The provided code snippet includes necessary dependencies for implementing the `wrap_exceptions_procfs` function. Write a Python function `def wrap_exceptions_procfs(inst)` to solve the following problem: Same as above, for routines relying on reading /proc fs. Here is the function: def wrap_exceptions_procfs(inst): """Same as above, for routines relying on reading /proc fs.""" try: yield except (ProcessLookupError, FileNotFoundError): # ENOENT (no such file or directory) gets raised on open(). # ESRCH (no such process) can get raised on read() if # process is gone in meantime. if is_zombie(inst.pid): raise ZombieProcess(inst.pid, inst._name, inst._ppid) else: raise NoSuchProcess(inst.pid, inst._name) except PermissionError: raise AccessDenied(inst.pid, inst._name)
Same as above, for routines relying on reading /proc fs.
176,329
from functools import wraps from copy import deepcopy from traitlets import TraitError from traitlets.config.loader import ( Config, ) from jupyter_core.application import JupyterApp from jupyter_server.serverapp import ServerApp from jupyter_server.extension.application import ExtensionApp from .traits import NotebookAppTraits def NBAPP_AND_SVAPP_SHIM_MSG(trait_name): return ( "'{trait_name}' was found in both NotebookApp " "and ServerApp. This is likely a recent change. " "This config will only be set in NotebookApp. " "Please check if you should also config these traits in " "ServerApp for your purpose.".format( trait_name=trait_name, ) )
null
176,330
from functools import wraps from copy import deepcopy from traitlets import TraitError from traitlets.config.loader import ( Config, ) from jupyter_core.application import JupyterApp from jupyter_server.serverapp import ServerApp from jupyter_server.extension.application import ExtensionApp from .traits import NotebookAppTraits def NBAPP_TO_SVAPP_SHIM_MSG(trait_name): return ( "'{trait_name}' has moved from NotebookApp to " "ServerApp. This config will be passed to ServerApp. " "Be sure to update your config before " "our next release.".format( trait_name=trait_name, ) )
null
176,331
from functools import wraps from copy import deepcopy from traitlets import TraitError from traitlets.config.loader import ( Config, ) from jupyter_core.application import JupyterApp from jupyter_server.serverapp import ServerApp from jupyter_server.extension.application import ExtensionApp from .traits import NotebookAppTraits def EXTAPP_AND_NBAPP_AND_SVAPP_SHIM_MSG(trait_name, extapp_name): return ( "'{trait_name}' is found in {extapp_name}, NotebookApp, " "and ServerApp. This is a recent change. " "This config will only be set in {extapp_name}. " "Please check if you should also config these traits in " "NotebookApp and ServerApp for your purpose.".format( trait_name=trait_name, extapp_name=extapp_name ) )
null
176,332
from functools import wraps from copy import deepcopy from traitlets import TraitError from traitlets.config.loader import ( Config, ) from jupyter_core.application import JupyterApp from jupyter_server.serverapp import ServerApp from jupyter_server.extension.application import ExtensionApp from .traits import NotebookAppTraits def EXTAPP_AND_SVAPP_SHIM_MSG(trait_name, extapp_name): return ( "'{trait_name}' is found in both {extapp_name} " "and ServerApp. This is a recent change. " "This config will only be set in {extapp_name}. " "Please check if you should also config these traits in " "ServerApp for your purpose.".format( trait_name=trait_name, extapp_name=extapp_name ) )
null
176,333
from functools import wraps from copy import deepcopy from traitlets import TraitError from traitlets.config.loader import ( Config, ) from jupyter_core.application import JupyterApp from jupyter_server.serverapp import ServerApp from jupyter_server.extension.application import ExtensionApp from .traits import NotebookAppTraits def EXTAPP_AND_NBAPP_SHIM_MSG(trait_name, extapp_name): return ( "'{trait_name}' is found in both {extapp_name} " "and NotebookApp. This is a recent change. " "This config will only be set in {extapp_name}. " "Please check if you should also config these traits in " "NotebookApp for your purpose.".format( trait_name=trait_name, extapp_name=extapp_name ) )
null
176,334
from functools import wraps from copy import deepcopy from traitlets import TraitError from traitlets.config.loader import ( Config, ) from jupyter_core.application import JupyterApp from jupyter_server.serverapp import ServerApp from jupyter_server.extension.application import ExtensionApp from .traits import NotebookAppTraits def NOT_EXTAPP_NBAPP_AND_SVAPP_SHIM_MSG(trait_name, extapp_name): return ( "'{trait_name}' is not found in {extapp_name}, but " "it was found in both NotebookApp " "and ServerApp. This is likely a recent change. " "This config will only be set in ServerApp. " "Please check if you should also config these traits in " "NotebookApp for your purpose.".format( trait_name=trait_name, extapp_name=extapp_name ) )
null
176,335
from functools import wraps from copy import deepcopy from traitlets import TraitError from traitlets.config.loader import ( Config, ) from jupyter_core.application import JupyterApp from jupyter_server.serverapp import ServerApp from jupyter_server.extension.application import ExtensionApp from .traits import NotebookAppTraits def EXTAPP_TO_SVAPP_SHIM_MSG(trait_name, extapp_name): return ( "'{trait_name}' has moved from {extapp_name} to " "ServerApp. Be sure to update your config before " "our next release.".format( trait_name=trait_name, extapp_name=extapp_name ) )
null
176,336
from functools import wraps from copy import deepcopy from traitlets import TraitError from traitlets.config.loader import ( Config, ) from jupyter_core.application import JupyterApp from jupyter_server.serverapp import ServerApp from jupyter_server.extension.application import ExtensionApp from .traits import NotebookAppTraits def EXTAPP_TO_NBAPP_SHIM_MSG(trait_name, extapp_name): return ( "'{trait_name}' has moved from {extapp_name} to " "NotebookApp. Be sure to update your config before " "our next release.".format( trait_name=trait_name, extapp_name=extapp_name ) )
null
176,337
import os import types import inspect from functools import wraps from jupyter_core.paths import jupyter_config_path from traitlets.traitlets import is_trait from jupyter_server.services.config.manager import ConfigManager from .traits import NotebookAppTraits def proxy(obj1, obj2, name, overwrite=False): def diff_members(obj1, obj2): def get_nbserver_extensions(config_dirs): def jupyter_config_path() -> List[str]: class NotebookAppTraits(HasTraits): def _update_enable_mathjax(self, change): def static_file_path(self): def _default_static_custom_path(self): def template_file_path(self): def nbextensions_path(self): def static_url_prefix(self): def _default_mathjax_url(self): def _update_mathjax_url(self, change): def _update_mathjax_config(self, change): def _link_jupyter_server_extension(serverapp): # Get the extension manager from the server manager = serverapp.extension_manager logger = serverapp.log # Hack that patches the enabled extensions list, prioritizing # jupyter nbclassic. In the future, it would be much better # to incorporate a dependency injection system in the # Extension manager that allows extensions to list # their dependency tree and sort that way. def sorted_extensions(self): """Dictionary with extension package names as keys and an ExtensionPackage objects as values. """ # Sort the keys and keys = sorted(self.extensions.keys()) keys.remove("notebook_shim") keys = ["notebook_shim"] + keys return {key: self.extensions[key] for key in keys} manager.__class__.sorted_extensions = property(sorted_extensions) # Look to see if nbclassic is enabled. if so, # link the nbclassic extension here to load # its config. Then, port its config to the serverapp # for backwards compatibility. try: pkg = manager.extensions["notebook_shim"] pkg.link_point("notebook_shim", serverapp) point = pkg.extension_points["notebook_shim"] nbapp = point.app except Exception: nbapp = NotebookAppTraits() # Proxy NotebookApp traits through serverapp to notebookapp. members = diff_members(serverapp, nbapp) for m in members: proxy(serverapp, nbapp, m) # Find jupyter server extensions listed as notebook server extensions. jupyter_paths = jupyter_config_path() config_dirs = jupyter_paths + [serverapp.config_dir] nbserver_extensions = get_nbserver_extensions(config_dirs) # Link all extensions found in the old locations for # notebook server extensions. for name, enabled in nbserver_extensions.items(): # If the extension is already enabled in the manager, i.e. # because it was discovered already by Jupyter Server # through its jupyter_server_config, then don't re-enable here. if name not in manager.extensions: successful = manager.add_extension(name, enabled=enabled) if successful: logger.info( "{name} | extension was found and enabled by notebook_shim. " "Consider moving the extension to Jupyter Server's " "extension paths.".format(name=name) ) manager.link_extension(name)
null
176,338
import os import types import inspect from functools import wraps from jupyter_core.paths import jupyter_config_path from traitlets.traitlets import is_trait from jupyter_server.services.config.manager import ConfigManager from .traits import NotebookAppTraits def jupyter_config_path() -> List[str]: """Return the search path for Jupyter config files as a list. If the JUPYTER_PREFER_ENV_PATH environment variable is set, the environment-level directories will have priority over user-level directories. If the Python site.ENABLE_USER_SITE variable is True, we also add the appropriate Python user site subdirectory to the user-level directories. """ if os.environ.get("JUPYTER_NO_CONFIG"): # jupyter_config_dir makes a blank config when JUPYTER_NO_CONFIG is set. return [jupyter_config_dir()] paths: List[str] = [] # highest priority is explicit environment variable if os.environ.get("JUPYTER_CONFIG_PATH"): paths.extend(p.rstrip(os.sep) for p in os.environ["JUPYTER_CONFIG_PATH"].split(os.pathsep)) # Next is environment or user, depending on the JUPYTER_PREFER_ENV_PATH flag user = [jupyter_config_dir()] if site.ENABLE_USER_SITE: userbase: Optional[str] # Check if site.getuserbase() exists to be compatible with virtualenv, # which often does not have this method. userbase = site.getuserbase() if hasattr(site, "getuserbase") else site.USER_BASE if userbase: userdir = os.path.join(userbase, "etc", "jupyter") if userdir not in user: user.append(userdir) env = [p for p in ENV_CONFIG_PATH if p not in SYSTEM_CONFIG_PATH] if prefer_environment_over_user(): paths.extend(env) paths.extend(user) else: paths.extend(user) paths.extend(env) # Finally, system path paths.extend(SYSTEM_CONFIG_PATH) return paths def _load_jupyter_server_extension(serverapp): # Patch the config service manager to find the # proper path for old notebook frontend extensions config_manager = serverapp.config_manager read_config_path = config_manager.read_config_path read_config_path += [os.path.join(p, 'nbconfig') for p in jupyter_config_path()] config_manager.read_config_path = read_config_path
null
176,340
from __future__ import absolute_import import binascii import codecs import os from io import BytesIO from .fields import RequestField from .packages import six from .packages.six import b writer = codecs.lookup("utf-8")[3] def choose_boundary(): """ Our embarrassingly-simple replacement for mimetools.choose_boundary. """ boundary = binascii.hexlify(os.urandom(16)) if not six.PY2: boundary = boundary.decode("ascii") return boundary def iter_field_objects(fields): """ Iterate over fields. Supports list of (k, v) tuples and dicts, and lists of :class:`~urllib3.fields.RequestField`. """ if isinstance(fields, dict): i = six.iteritems(fields) else: i = iter(fields) for field in i: if isinstance(field, RequestField): yield field else: yield RequestField.from_tuples(*field) class BytesIO(BufferedIOBase, BinaryIO): def __init__(self, initial_bytes: bytes = ...) -> None: ... # BytesIO does not contain a "name" field. This workaround is necessary # to allow BytesIO sub-classes to add this field, as it is defined # as a read-only property on IO[]. name: Any def __enter__(self: _T) -> _T: ... def getvalue(self) -> bytes: ... def getbuffer(self) -> memoryview: ... if sys.version_info >= (3, 7): def read1(self, __size: Optional[int] = ...) -> bytes: ... else: def read1(self, __size: Optional[int]) -> bytes: ... # type: ignore The provided code snippet includes necessary dependencies for implementing the `encode_multipart_formdata` function. Write a Python function `def encode_multipart_formdata(fields, boundary=None)` to solve the following problem: Encode a dictionary of ``fields`` using the multipart/form-data MIME format. :param fields: Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). :param boundary: If not specified, then a random boundary will be generated using :func:`urllib3.filepost.choose_boundary`. Here is the function: def encode_multipart_formdata(fields, boundary=None): """ Encode a dictionary of ``fields`` using the multipart/form-data MIME format. :param fields: Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). :param boundary: If not specified, then a random boundary will be generated using :func:`urllib3.filepost.choose_boundary`. """ body = BytesIO() if boundary is None: boundary = choose_boundary() for field in iter_field_objects(fields): body.write(b("--%s\r\n" % (boundary))) writer(body).write(field.render_headers()) data = field.data if isinstance(data, int): data = str(data) # Backwards compatibility if isinstance(data, six.text_type): writer(body).write(data) else: body.write(data) body.write(b"\r\n") body.write(b("--%s--\r\n" % (boundary))) content_type = str("multipart/form-data; boundary=%s" % boundary) return body.getvalue(), content_type
Encode a dictionary of ``fields`` using the multipart/form-data MIME format. :param fields: Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`). :param boundary: If not specified, then a random boundary will be generated using :func:`urllib3.filepost.choose_boundary`.
176,396
from __future__ import absolute_import import functools import itertools import operator import sys import types if sys.version_info[0:2] < (3, 4): # This does exactly the same what the :func:`py3:functools.update_wrapper` # function does on Python versions after 3.2. It sets the ``__wrapped__`` # attribute on ``wrapper`` object and it doesn't raise an error if any of # the attributes mentioned in ``assigned`` and ``updated`` are missing on # ``wrapped`` object. def _update_wrapper( wrapper, wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES, ): _update_wrapper.__doc__ = functools.update_wrapper.__doc__ wraps.__doc__ = functools.wraps.__doc__ else: wraps = functools.wraps def wraps( wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, updated=functools.WRAPPER_UPDATES, ): return functools.partial( _update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated )
null
176,408
from __future__ import absolute_import from base64 import b64encode from ..exceptions import UnrewindableBodyError from ..packages.six import b, integer_types ACCEPT_ENCODING = "gzip,deflate" def b64encode(s: _encodable, altchars: Optional[bytes] = ...) -> bytes: ... The provided code snippet includes necessary dependencies for implementing the `make_headers` function. Write a Python function `def make_headers( keep_alive=None, accept_encoding=None, user_agent=None, basic_auth=None, proxy_basic_auth=None, disable_cache=None, )` to solve the following problem: Shortcuts for generating request headers. :param keep_alive: If ``True``, adds 'connection: keep-alive' header. :param accept_encoding: Can be a boolean, list, or string. ``True`` translates to 'gzip,deflate'. List will get joined by comma. String will be used as provided. :param user_agent: String representing the user-agent you want, such as "python-urllib3/0.6" :param basic_auth: Colon-separated username:password string for 'authorization: basic ...' auth header. :param proxy_basic_auth: Colon-separated username:password string for 'proxy-authorization: basic ...' auth header. :param disable_cache: If ``True``, adds 'cache-control: no-cache' header. Example:: >>> make_headers(keep_alive=True, user_agent="Batman/1.0") {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} >>> make_headers(accept_encoding=True) {'accept-encoding': 'gzip,deflate'} Here is the function: def make_headers( keep_alive=None, accept_encoding=None, user_agent=None, basic_auth=None, proxy_basic_auth=None, disable_cache=None, ): """ Shortcuts for generating request headers. :param keep_alive: If ``True``, adds 'connection: keep-alive' header. :param accept_encoding: Can be a boolean, list, or string. ``True`` translates to 'gzip,deflate'. List will get joined by comma. String will be used as provided. :param user_agent: String representing the user-agent you want, such as "python-urllib3/0.6" :param basic_auth: Colon-separated username:password string for 'authorization: basic ...' auth header. :param proxy_basic_auth: Colon-separated username:password string for 'proxy-authorization: basic ...' auth header. :param disable_cache: If ``True``, adds 'cache-control: no-cache' header. Example:: >>> make_headers(keep_alive=True, user_agent="Batman/1.0") {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} >>> make_headers(accept_encoding=True) {'accept-encoding': 'gzip,deflate'} """ headers = {} if accept_encoding: if isinstance(accept_encoding, str): pass elif isinstance(accept_encoding, list): accept_encoding = ",".join(accept_encoding) else: accept_encoding = ACCEPT_ENCODING headers["accept-encoding"] = accept_encoding if user_agent: headers["user-agent"] = user_agent if keep_alive: headers["connection"] = "keep-alive" if basic_auth: headers["authorization"] = "Basic " + b64encode(b(basic_auth)).decode("utf-8") if proxy_basic_auth: headers["proxy-authorization"] = "Basic " + b64encode( b(proxy_basic_auth) ).decode("utf-8") if disable_cache: headers["cache-control"] = "no-cache" return headers
Shortcuts for generating request headers. :param keep_alive: If ``True``, adds 'connection: keep-alive' header. :param accept_encoding: Can be a boolean, list, or string. ``True`` translates to 'gzip,deflate'. List will get joined by comma. String will be used as provided. :param user_agent: String representing the user-agent you want, such as "python-urllib3/0.6" :param basic_auth: Colon-separated username:password string for 'authorization: basic ...' auth header. :param proxy_basic_auth: Colon-separated username:password string for 'proxy-authorization: basic ...' auth header. :param disable_cache: If ``True``, adds 'cache-control: no-cache' header. Example:: >>> make_headers(keep_alive=True, user_agent="Batman/1.0") {'connection': 'keep-alive', 'user-agent': 'Batman/1.0'} >>> make_headers(accept_encoding=True) {'accept-encoding': 'gzip,deflate'}
176,412
from __future__ import absolute_import import hmac import os import sys import warnings from binascii import hexlify, unhexlify from hashlib import md5, sha1, sha256 from ..exceptions import ( InsecurePlatformWarning, ProxySchemeUnsupported, SNIMissingWarning, SSLError, ) from ..packages import six from .url import BRACELESS_IPV6_ADDRZ_RE, IPV4_RE HASHFUNC_MAP = {32: md5, 40: sha1, 64: sha256} _const_compare_digest = getattr(hmac, "compare_digest", _const_compare_digest_backport) def unhexlify(__hexstr: _Ascii) -> bytes: ... class SSLError(HTTPError): """Raised when SSL certificate fails in an HTTPS connection.""" pass The provided code snippet includes necessary dependencies for implementing the `assert_fingerprint` function. Write a Python function `def assert_fingerprint(cert, fingerprint)` to solve the following problem: Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. Here is the function: def assert_fingerprint(cert, fingerprint): """ Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. """ fingerprint = fingerprint.replace(":", "").lower() digest_length = len(fingerprint) hashfunc = HASHFUNC_MAP.get(digest_length) if not hashfunc: raise SSLError("Fingerprint of invalid length: {0}".format(fingerprint)) # We need encode() here for py32; works on py2 and p33. fingerprint_bytes = unhexlify(fingerprint.encode()) cert_digest = hashfunc(cert).digest() if not _const_compare_digest(cert_digest, fingerprint_bytes): raise SSLError( 'Fingerprints did not match. Expected "{0}", got "{1}".'.format( fingerprint, hexlify(cert_digest) ) )
Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons.
176,413
from __future__ import absolute_import import hmac import os import sys import warnings from binascii import hexlify, unhexlify from hashlib import md5, sha1, sha256 from ..exceptions import ( InsecurePlatformWarning, ProxySchemeUnsupported, SNIMissingWarning, SSLError, ) from ..packages import six from .url import BRACELESS_IPV6_ADDRZ_RE, IPV4_RE HAS_SNI = False IS_SECURETRANSPORT = False ALPN_PROTOCOLS = ["http/1.1"] def create_urllib3_context( ssl_version=None, cert_reqs=None, options=None, ciphers=None ): """All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do:: from urllib3.util import ssl_ context = ssl_.create_urllib3_context() context.options &= ~ssl_.OP_NO_SSLv3 You can do the same to enable compression (substituting ``COMPRESSION`` for ``SSLv3`` in the last line above). :param ssl_version: The desired protocol version to use. This will default to PROTOCOL_SSLv23 which will negotiate the highest protocol that both the server and your installation of OpenSSL support. :param cert_reqs: Whether to require the certificate verification. This defaults to ``ssl.CERT_REQUIRED``. :param options: Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``, ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``. :param ciphers: Which cipher suites to allow the server to select. :returns: Constructed SSLContext object with specified options :rtype: SSLContext """ # PROTOCOL_TLS is deprecated in Python 3.10 if not ssl_version or ssl_version == PROTOCOL_TLS: ssl_version = PROTOCOL_TLS_CLIENT context = SSLContext(ssl_version) context.set_ciphers(ciphers or DEFAULT_CIPHERS) # Setting the default here, as we may have no ssl module on import cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs if options is None: options = 0 # SSLv2 is easily broken and is considered harmful and dangerous options |= OP_NO_SSLv2 # SSLv3 has several problems and is now dangerous options |= OP_NO_SSLv3 # Disable compression to prevent CRIME attacks for OpenSSL 1.0+ # (issue #309) options |= OP_NO_COMPRESSION # TLSv1.2 only. Unless set explicitly, do not request tickets. # This may save some bandwidth on wire, and although the ticket is encrypted, # there is a risk associated with it being on wire, # if the server is not rotating its ticketing keys properly. options |= OP_NO_TICKET context.options |= options # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is # necessary for conditional client cert authentication with TLS 1.3. # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older # versions of Python. We only enable on Python 3.7.4+ or if certificate # verification is enabled to work around Python issue #37428 # See: https://bugs.python.org/issue37428 if (cert_reqs == ssl.CERT_REQUIRED or sys.version_info >= (3, 7, 4)) and getattr( context, "post_handshake_auth", None ) is not None: context.post_handshake_auth = True def disable_check_hostname(): if ( getattr(context, "check_hostname", None) is not None ): # Platform-specific: Python 3.2 # We do our own verification, including fingerprints and alternative # hostnames. So disable it here context.check_hostname = False # The order of the below lines setting verify_mode and check_hostname # matter due to safe-guards SSLContext has to prevent an SSLContext with # check_hostname=True, verify_mode=NONE/OPTIONAL. This is made even more # complex because we don't know whether PROTOCOL_TLS_CLIENT will be used # or not so we don't know the initial state of the freshly created SSLContext. if cert_reqs == ssl.CERT_REQUIRED: context.verify_mode = cert_reqs disable_check_hostname() else: disable_check_hostname() context.verify_mode = cert_reqs # Enable logging of TLS session keys via defacto standard environment variable # 'SSLKEYLOGFILE', if the feature is available (Python 3.8+). Skip empty values. if hasattr(context, "keylog_filename"): sslkeylogfile = os.environ.get("SSLKEYLOGFILE") if sslkeylogfile: context.keylog_filename = sslkeylogfile return context def is_ipaddress(hostname): """Detects whether the hostname given is an IPv4 or IPv6 address. Also detects IPv6 addresses with Zone IDs. :param str hostname: Hostname to examine. :return: True if the hostname is an IP address, False otherwise. """ if not six.PY2 and isinstance(hostname, bytes): # IDN A-label bytes are ASCII compatible. hostname = hostname.decode("ascii") return bool(IPV4_RE.match(hostname) or BRACELESS_IPV6_ADDRZ_RE.match(hostname)) def _is_key_file_encrypted(key_file): """Detects if a key file is encrypted or not.""" with open(key_file, "r") as f: for line in f: # Look for Proc-Type: 4,ENCRYPTED if "ENCRYPTED" in line: return True return False def _ssl_wrap_socket_impl(sock, ssl_context, tls_in_tls, server_hostname=None): if tls_in_tls: if not SSLTransport: # Import error, ssl is not available. raise ProxySchemeUnsupported( "TLS in TLS requires support for the 'ssl' module" ) SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context) return SSLTransport(sock, ssl_context, server_hostname) if server_hostname: return ssl_context.wrap_socket(sock, server_hostname=server_hostname) else: return ssl_context.wrap_socket(sock) class SSLError(HTTPError): """Raised when SSL certificate fails in an HTTPS connection.""" pass class SNIMissingWarning(HTTPWarning): """Warned when making a HTTPS request without SNI available.""" pass HAS_SNI: bool The provided code snippet includes necessary dependencies for implementing the `ssl_wrap_socket` function. Write a Python function `def ssl_wrap_socket( sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None, ca_cert_dir=None, key_password=None, ca_cert_data=None, tls_in_tls=False, )` to solve the following problem: All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations(). :param key_password: Optional password if the keyfile is encrypted. :param ca_cert_data: Optional string containing CA certificates in PEM format suitable for passing as the cadata parameter to SSLContext.load_verify_locations() :param tls_in_tls: Use SSLTransport to wrap the existing socket. Here is the function: def ssl_wrap_socket( sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None, ca_cert_dir=None, key_password=None, ca_cert_data=None, tls_in_tls=False, ): """ All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations(). :param key_password: Optional password if the keyfile is encrypted. :param ca_cert_data: Optional string containing CA certificates in PEM format suitable for passing as the cadata parameter to SSLContext.load_verify_locations() :param tls_in_tls: Use SSLTransport to wrap the existing socket. """ context = ssl_context if context is None: # Note: This branch of code and all the variables in it are no longer # used by urllib3 itself. We should consider deprecating and removing # this code. context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers) if ca_certs or ca_cert_dir or ca_cert_data: try: context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data) except (IOError, OSError) as e: raise SSLError(e) elif ssl_context is None and hasattr(context, "load_default_certs"): # try to load OS default certs; works well on Windows (require Python3.4+) context.load_default_certs() # Attempt to detect if we get the goofy behavior of the # keyfile being encrypted and OpenSSL asking for the # passphrase via the terminal and instead error out. if keyfile and key_password is None and _is_key_file_encrypted(keyfile): raise SSLError("Client private key is encrypted, password is required") if certfile: if key_password is None: context.load_cert_chain(certfile, keyfile) else: context.load_cert_chain(certfile, keyfile, key_password) try: if hasattr(context, "set_alpn_protocols"): context.set_alpn_protocols(ALPN_PROTOCOLS) except NotImplementedError: # Defensive: in CI, we always have set_alpn_protocols pass # If we detect server_hostname is an IP address then the SNI # extension should not be used according to RFC3546 Section 3.1 use_sni_hostname = server_hostname and not is_ipaddress(server_hostname) # SecureTransport uses server_hostname in certificate verification. send_sni = (use_sni_hostname and HAS_SNI) or ( IS_SECURETRANSPORT and server_hostname ) # Do not warn the user if server_hostname is an invalid SNI hostname. if not HAS_SNI and use_sni_hostname: warnings.warn( "An HTTPS request has been made, but the SNI (Server Name " "Indication) extension to TLS is not available on this platform. " "This may cause the server to present an incorrect TLS " "certificate, which can cause validation failures. You can upgrade to " "a newer version of Python to solve this. For more information, see " "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html" "#ssl-warnings", SNIMissingWarning, ) if send_sni: ssl_sock = _ssl_wrap_socket_impl( sock, context, tls_in_tls, server_hostname=server_hostname ) else: ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls) return ssl_sock
All arguments except for server_hostname, ssl_context, and ca_cert_dir have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provided, one will be created using :func:`create_urllib3_context`. :param ciphers: A string of ciphers we wish the client to support. :param ca_cert_dir: A directory containing CA certificates in multiple separate files, as supported by OpenSSL's -CApath flag or the capath argument to SSLContext.load_verify_locations(). :param key_password: Optional password if the keyfile is encrypted. :param ca_cert_data: Optional string containing CA certificates in PEM format suitable for passing as the cadata parameter to SSLContext.load_verify_locations() :param tls_in_tls: Use SSLTransport to wrap the existing socket.
176,419
from __future__ import absolute_import import json from collections import OrderedDict from textblob.compat import PY2, csv from textblob.utils import is_filelike _registry = OrderedDict([ ('csv', CSV), ('json', JSON), ('tsv', TSV), ]) def is_filelike(obj): """Return whether ``obj`` is a file-like object.""" return hasattr(obj, 'read') The provided code snippet includes necessary dependencies for implementing the `detect` function. Write a Python function `def detect(fp, max_read=1024)` to solve the following problem: Attempt to detect a file's format, trying each of the supported formats. Return the format class that was detected. If no format is detected, return ``None``. Here is the function: def detect(fp, max_read=1024): """Attempt to detect a file's format, trying each of the supported formats. Return the format class that was detected. If no format is detected, return ``None``. """ if not is_filelike(fp): return None for Format in _registry.values(): if Format.detect(fp.read(max_read)): fp.seek(0) return Format fp.seek(0) return None
Attempt to detect a file's format, trying each of the supported formats. Return the format class that was detected. If no format is detected, return ``None``.
176,420
from __future__ import absolute_import import json from collections import OrderedDict from textblob.compat import PY2, csv from textblob.utils import is_filelike def get_registry(): """Return a dictionary of registered formats.""" return _registry The provided code snippet includes necessary dependencies for implementing the `register` function. Write a Python function `def register(name, format_class)` to solve the following problem: Register a new format. :param str name: The name that will be used to refer to the format, e.g. 'csv' :param type format_class: The format class to register. Here is the function: def register(name, format_class): """Register a new format. :param str name: The name that will be used to refer to the format, e.g. 'csv' :param type format_class: The format class to register. """ get_registry()[name] = format_class
Register a new format. :param str name: The name that will be used to refer to the format, e.g. 'csv' :param type format_class: The format class to register.
176,421
import re import string def strip_punc(s, all=False): """Removes punctuation from a string. :param s: The string. :param all: Remove all punctuation. If False, only removes punctuation from the ends of the string. """ if all: return PUNCTUATION_REGEX.sub('', s.strip()) else: return s.strip().strip(string.punctuation) The provided code snippet includes necessary dependencies for implementing the `lowerstrip` function. Write a Python function `def lowerstrip(s, all=False)` to solve the following problem: Makes text all lowercase and strips punctuation and whitespace. :param s: The string. :param all: Remove all punctuation. If False, only removes punctuation from the ends of the string. Here is the function: def lowerstrip(s, all=False): """Makes text all lowercase and strips punctuation and whitespace. :param s: The string. :param all: Remove all punctuation. If False, only removes punctuation from the ends of the string. """ return strip_punc(s.lower().strip(), all=all)
Makes text all lowercase and strips punctuation and whitespace. :param s: The string. :param all: Remove all punctuation. If False, only removes punctuation from the ends of the string.
176,422
import re import string The provided code snippet includes necessary dependencies for implementing the `tree2str` function. Write a Python function `def tree2str(tree, concat=' ')` to solve the following problem: Convert a nltk.tree.Tree to a string. For example: (NP a/DT beautiful/JJ new/JJ dashboard/NN) -> "a beautiful dashboard" Here is the function: def tree2str(tree, concat=' '): """Convert a nltk.tree.Tree to a string. For example: (NP a/DT beautiful/JJ new/JJ dashboard/NN) -> "a beautiful dashboard" """ return concat.join([word for (word, tag) in tree])
Convert a nltk.tree.Tree to a string. For example: (NP a/DT beautiful/JJ new/JJ dashboard/NN) -> "a beautiful dashboard"
176,423
import re import string The provided code snippet includes necessary dependencies for implementing the `filter_insignificant` function. Write a Python function `def filter_insignificant(chunk, tag_suffixes=('DT', 'CC', 'PRP$', 'PRP'))` to solve the following problem: Filter out insignificant (word, tag) tuples from a chunk of text. Here is the function: def filter_insignificant(chunk, tag_suffixes=('DT', 'CC', 'PRP$', 'PRP')): """Filter out insignificant (word, tag) tuples from a chunk of text.""" good = [] for word, tag in chunk: ok = True for suffix in tag_suffixes: if tag.endswith(suffix): ok = False break if ok: good.append((word, tag)) return good
Filter out insignificant (word, tag) tuples from a chunk of text.
176,424
from __future__ import unicode_literals, absolute_import import sys import json import warnings from collections import defaultdict import nltk from textblob.decorators import cached_property, requires_nltk_corpus from textblob.utils import lowerstrip, PUNCTUATION_REGEX from textblob.inflect import singularize as _singularize, pluralize as _pluralize from textblob.mixins import BlobComparableMixin, StringlikeMixin from textblob.compat import unicode, basestring from textblob.base import (BaseNPExtractor, BaseTagger, BaseTokenizer, BaseSentimentAnalyzer, BaseParser) from textblob.np_extractors import FastNPExtractor from textblob.taggers import NLTKTagger from textblob.tokenizers import WordTokenizer, sent_tokenize, word_tokenize from textblob.sentiments import PatternAnalyzer from textblob.parsers import PatternParser from textblob.translate import Translator from textblob.en import suggest _wordnet = nltk.corpus.wordnet The provided code snippet includes necessary dependencies for implementing the `_penn_to_wordnet` function. Write a Python function `def _penn_to_wordnet(tag)` to solve the following problem: Converts a Penn corpus tag into a Wordnet tag. Here is the function: def _penn_to_wordnet(tag): """Converts a Penn corpus tag into a Wordnet tag.""" if tag in ("NN", "NNS", "NNP", "NNPS"): return _wordnet.NOUN if tag in ("JJ", "JJR", "JJS"): return _wordnet.ADJ if tag in ("VB", "VBD", "VBG", "VBN", "VBP", "VBZ"): return _wordnet.VERB if tag in ("RB", "RBR", "RBS"): return _wordnet.ADV return None
Converts a Penn corpus tag into a Wordnet tag.
176,425
from __future__ import unicode_literals, absolute_import import sys import json import warnings from collections import defaultdict import nltk from textblob.decorators import cached_property, requires_nltk_corpus from textblob.utils import lowerstrip, PUNCTUATION_REGEX from textblob.inflect import singularize as _singularize, pluralize as _pluralize from textblob.mixins import BlobComparableMixin, StringlikeMixin from textblob.compat import unicode, basestring from textblob.base import (BaseNPExtractor, BaseTagger, BaseTokenizer, BaseSentimentAnalyzer, BaseParser) from textblob.np_extractors import FastNPExtractor from textblob.taggers import NLTKTagger from textblob.tokenizers import WordTokenizer, sent_tokenize, word_tokenize from textblob.sentiments import PatternAnalyzer from textblob.parsers import PatternParser from textblob.translate import Translator from textblob.en import suggest def _validated_param(obj, name, base_class, default, base_class_name=None): """Validates a parameter passed to __init__. Makes sure that obj is the correct class. Return obj if it's not None or falls back to default :param obj: The object passed in. :param name: The name of the parameter. :param base_class: The class that obj must inherit from. :param default: The default object to fall back upon if obj is None. """ base_class_name = base_class_name if base_class_name else base_class.__name__ if obj is not None and not isinstance(obj, base_class): raise ValueError('{name} must be an instance of {cls}' .format(name=name, cls=base_class_name)) return obj or default class BaseBlob(StringlikeMixin, BlobComparableMixin): """An abstract base class that all textblob classes will inherit from. Includes words, POS tag, NP, and word count properties. Also includes basic dunder and string methods for making objects like Python strings. :param text: A string. :param tokenizer: (optional) A tokenizer instance. If ``None``, defaults to :class:`WordTokenizer() <textblob.tokenizers.WordTokenizer>`. :param np_extractor: (optional) An NPExtractor instance. If ``None``, defaults to :class:`FastNPExtractor() <textblob.en.np_extractors.FastNPExtractor>`. :param pos_tagger: (optional) A Tagger instance. If ``None``, defaults to :class:`NLTKTagger <textblob.en.taggers.NLTKTagger>`. :param analyzer: (optional) A sentiment analyzer. If ``None``, defaults to :class:`PatternAnalyzer <textblob.en.sentiments.PatternAnalyzer>`. :param parser: A parser. If ``None``, defaults to :class:`PatternParser <textblob.en.parsers.PatternParser>`. :param classifier: A classifier. .. versionchanged:: 0.6.0 ``clean_html`` parameter deprecated, as it was in NLTK. """ np_extractor = FastNPExtractor() pos_tagger = NLTKTagger() tokenizer = WordTokenizer() translator = Translator() analyzer = PatternAnalyzer() parser = PatternParser() def __init__(self, text, tokenizer=None, pos_tagger=None, np_extractor=None, analyzer=None, parser=None, classifier=None, clean_html=False): if not isinstance(text, basestring): raise TypeError('The `text` argument passed to `__init__(text)` ' 'must be a string, not {0}'.format(type(text))) if clean_html: raise NotImplementedError("clean_html has been deprecated. " "To remove HTML markup, use BeautifulSoup's " "get_text() function") self.raw = self.string = text self.stripped = lowerstrip(self.raw, all=True) _initialize_models(self, tokenizer, pos_tagger, np_extractor, analyzer, parser, classifier) def words(self): """Return a list of word tokens. This excludes punctuation characters. If you want to include punctuation characters, access the ``tokens`` property. :returns: A :class:`WordList <WordList>` of word tokens. """ return WordList(word_tokenize(self.raw, include_punc=False)) def tokens(self): """Return a list of tokens, using this blob's tokenizer object (defaults to :class:`WordTokenizer <textblob.tokenizers.WordTokenizer>`). """ return WordList(self.tokenizer.tokenize(self.raw)) def tokenize(self, tokenizer=None): """Return a list of tokens, using ``tokenizer``. :param tokenizer: (optional) A tokenizer object. If None, defaults to this blob's default tokenizer. """ t = tokenizer if tokenizer is not None else self.tokenizer return WordList(t.tokenize(self.raw)) def parse(self, parser=None): """Parse the text. :param parser: (optional) A parser instance. If ``None``, defaults to this blob's default parser. .. versionadded:: 0.6.0 """ p = parser if parser is not None else self.parser return p.parse(self.raw) def classify(self): """Classify the blob using the blob's ``classifier``.""" if self.classifier is None: raise NameError("This blob has no classifier. Train one first!") return self.classifier.classify(self.raw) def sentiment(self): """Return a tuple of form (polarity, subjectivity ) where polarity is a float within the range [-1.0, 1.0] and subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective. :rtype: namedtuple of the form ``Sentiment(polarity, subjectivity)`` """ return self.analyzer.analyze(self.raw) def sentiment_assessments(self): """Return a tuple of form (polarity, subjectivity, assessments ) where polarity is a float within the range [-1.0, 1.0], subjectivity is a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective, and assessments is a list of polarity and subjectivity scores for the assessed tokens. :rtype: namedtuple of the form ``Sentiment(polarity, subjectivity, assessments)`` """ return self.analyzer.analyze(self.raw, keep_assessments=True) def polarity(self): """Return the polarity score as a float within the range [-1.0, 1.0] :rtype: float """ return PatternAnalyzer().analyze(self.raw)[0] def subjectivity(self): """Return the subjectivity score as a float within the range [0.0, 1.0] where 0.0 is very objective and 1.0 is very subjective. :rtype: float """ return PatternAnalyzer().analyze(self.raw)[1] def noun_phrases(self): """Returns a list of noun phrases for this blob.""" return WordList([phrase.strip().lower() for phrase in self.np_extractor.extract(self.raw) if len(phrase) > 1]) def pos_tags(self): """Returns an list of tuples of the form (word, POS tag). Example: :: [('At', 'IN'), ('eight', 'CD'), ("o'clock", 'JJ'), ('on', 'IN'), ('Thursday', 'NNP'), ('morning', 'NN')] :rtype: list of tuples """ if isinstance(self, TextBlob): return [val for sublist in [s.pos_tags for s in self.sentences] for val in sublist] else: return [(Word(unicode(word), pos_tag=t), unicode(t)) for word, t in self.pos_tagger.tag(self) if not PUNCTUATION_REGEX.match(unicode(t))] tags = pos_tags def word_counts(self): """Dictionary of word frequencies in this text. """ counts = defaultdict(int) stripped_words = [lowerstrip(word) for word in self.words] for word in stripped_words: counts[word] += 1 return counts def np_counts(self): """Dictionary of noun phrase frequencies in this text. """ counts = defaultdict(int) for phrase in self.noun_phrases: counts[phrase] += 1 return counts def ngrams(self, n=3): """Return a list of n-grams (tuples of n successive words) for this blob. :rtype: List of :class:`WordLists <WordList>` """ if n <= 0: return [] grams = [WordList(self.words[i:i + n]) for i in range(len(self.words) - n + 1)] return grams def translate(self, from_lang="auto", to="en"): """Translate the blob to another language. Uses the Google Translate API. Returns a new TextBlob. Requires an internet connection. Usage: :: >>> b = TextBlob("Simple is better than complex") >>> b.translate(to="es") TextBlob('Lo simple es mejor que complejo') Language code reference: https://developers.google.com/translate/v2/using_rest#language-params .. deprecated:: 0.16.0 Use the official Google Translate API instead. .. versionadded:: 0.5.0. :param str from_lang: Language to translate from. If ``None``, will attempt to detect the language. :param str to: Language to translate to. :rtype: :class:`BaseBlob <BaseBlob>` """ warnings.warn( 'TextBlob.translate is deprecated and will be removed in a future release. ' 'Use the official Google Translate API instead.', DeprecationWarning ) return self.__class__(self.translator.translate(self.raw, from_lang=from_lang, to_lang=to)) def detect_language(self): """Detect the blob's language using the Google Translate API. Requires an internet connection. Usage: :: >>> b = TextBlob("bonjour") >>> b.detect_language() u'fr' Language code reference: https://developers.google.com/translate/v2/using_rest#language-params .. deprecated:: 0.16.0 Use the official Google Translate API instead. .. versionadded:: 0.5.0 :rtype: str """ warnings.warn( 'TextBlob.detext_translate is deprecated and will be removed in a future release. ' 'Use the official Google Translate API instead.', DeprecationWarning ) return self.translator.detect(self.raw) def correct(self): """Attempt to correct the spelling of a blob. .. versionadded:: 0.6.0 :rtype: :class:`BaseBlob <BaseBlob>` """ # regex matches: word or punctuation or whitespace tokens = nltk.tokenize.regexp_tokenize(self.raw, r"\w+|[^\w\s]|\s") corrected = (Word(w).correct() for w in tokens) ret = ''.join(corrected) return self.__class__(ret) def _cmpkey(self): """Key used by ComparableMixin to implement all rich comparison operators. """ return self.raw def _strkey(self): """Key used by StringlikeMixin to implement string methods.""" return self.raw def __hash__(self): return hash(self._cmpkey()) def __add__(self, other): '''Concatenates two text objects the same way Python strings are concatenated. Arguments: - `other`: a string or a text object ''' if isinstance(other, basestring): return self.__class__(self.raw + other) elif isinstance(other, BaseBlob): return self.__class__(self.raw + other.raw) else: raise TypeError('Operands must be either strings or {0} objects' .format(self.__class__.__name__)) def split(self, sep=None, maxsplit=sys.maxsize): """Behaves like the built-in str.split() except returns a WordList. :rtype: :class:`WordList <WordList>` """ return WordList(self._strkey().split(sep, maxsplit)) class BaseTagger(with_metaclass(ABCMeta)): """Abstract tagger class from which all taggers inherit from. All descendants must implement a ``tag()`` method. """ def tag(self, text, tokenize=True): """Return a list of tuples of the form (word, tag) for a given set of text or BaseBlob instance. """ return class BaseNPExtractor(with_metaclass(ABCMeta)): """Abstract base class from which all NPExtractor classes inherit. Descendant classes must implement an ``extract(text)`` method that returns a list of noun phrases as strings. """ def extract(self, text): """Return a list of noun phrases (strings) for a body of text.""" return class BaseTokenizer(with_metaclass(ABCMeta), nltk.tokenize.api.TokenizerI): """Abstract base class from which all Tokenizer classes inherit. Descendant classes must implement a ``tokenize(text)`` method that returns a list of noun phrases as strings. """ def tokenize(self, text): """Return a list of tokens (strings) for a body of text. :rtype: list """ return def itokenize(self, text, *args, **kwargs): """Return a generator that generates tokens "on-demand". .. versionadded:: 0.6.0 :rtype: generator """ return (t for t in self.tokenize(text, *args, **kwargs)) class BaseSentimentAnalyzer(with_metaclass(ABCMeta)): """Abstract base class from which all sentiment analyzers inherit. Should implement an ``analyze(text)`` method which returns either the results of analysis. """ kind = DISCRETE def __init__(self): self._trained = False def train(self): # Train me self._trained = True def analyze(self, text): """Return the result of of analysis. Typically returns either a tuple, float, or dictionary. """ # Lazily train the classifier if not self._trained: self.train() # Analyze text return None class BaseParser(with_metaclass(ABCMeta)): """Abstract parser class from which all parsers inherit from. All descendants must implement a ``parse()`` method. """ def parse(self, text): """Parses the text.""" return The provided code snippet includes necessary dependencies for implementing the `_initialize_models` function. Write a Python function `def _initialize_models(obj, tokenizer, pos_tagger, np_extractor, analyzer, parser, classifier)` to solve the following problem: Common initialization between BaseBlob and Blobber classes. Here is the function: def _initialize_models(obj, tokenizer, pos_tagger, np_extractor, analyzer, parser, classifier): """Common initialization between BaseBlob and Blobber classes.""" # tokenizer may be a textblob or an NLTK tokenizer obj.tokenizer = _validated_param(tokenizer, "tokenizer", base_class=(BaseTokenizer, nltk.tokenize.api.TokenizerI), default=BaseBlob.tokenizer, base_class_name="BaseTokenizer") obj.np_extractor = _validated_param(np_extractor, "np_extractor", base_class=BaseNPExtractor, default=BaseBlob.np_extractor) obj.pos_tagger = _validated_param(pos_tagger, "pos_tagger", BaseTagger, BaseBlob.pos_tagger) obj.analyzer = _validated_param(analyzer, "analyzer", BaseSentimentAnalyzer, BaseBlob.analyzer) obj.parser = _validated_param(parser, "parser", BaseParser, BaseBlob.parser) obj.classifier = classifier
Common initialization between BaseBlob and Blobber classes.
176,426
from __future__ import absolute_import from itertools import chain import nltk from textblob.compat import basestring from textblob.decorators import cached_property from textblob.exceptions import FormatError from textblob.tokenizers import word_tokenize from textblob.utils import strip_punc, is_filelike import textblob.formats as formats def _get_words_from_dataset(dataset): """Return a set of all words in a dataset. :param dataset: A list of tuples of the form ``(words, label)`` where ``words`` is either a string of a list of tokens. """ # Words may be either a string or a list of tokens. Return an iterator # of tokens accordingly def tokenize(words): if isinstance(words, basestring): return word_tokenize(words, include_punc=False) else: return words all_words = chain.from_iterable(tokenize(words) for words, _ in dataset) return set(all_words) def _get_document_tokens(document): if isinstance(document, basestring): tokens = set((strip_punc(w, all=False) for w in word_tokenize(document, include_punc=False))) else: tokens = set(strip_punc(w, all=False) for w in document) return tokens class chain(Iterator[_T], Generic[_T]): def __init__(self, *iterables: Iterable[_T]) -> None: ... def __next__(self) -> _T: ... def __iter__(self) -> Iterator[_T]: ... def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... The provided code snippet includes necessary dependencies for implementing the `basic_extractor` function. Write a Python function `def basic_extractor(document, train_set)` to solve the following problem: A basic document feature extractor that returns a dict indicating what words in ``train_set`` are contained in ``document``. :param document: The text to extract features from. Can be a string or an iterable. :param list train_set: Training data set, a list of tuples of the form ``(words, label)`` OR an iterable of strings. Here is the function: def basic_extractor(document, train_set): """A basic document feature extractor that returns a dict indicating what words in ``train_set`` are contained in ``document``. :param document: The text to extract features from. Can be a string or an iterable. :param list train_set: Training data set, a list of tuples of the form ``(words, label)`` OR an iterable of strings. """ try: el_zero = next(iter(train_set)) # Infer input from first element. except StopIteration: return {} if isinstance(el_zero, basestring): word_features = [w for w in chain([el_zero], train_set)] else: try: assert(isinstance(el_zero[0], basestring)) word_features = _get_words_from_dataset(chain([el_zero], train_set)) except Exception: raise ValueError('train_set is probably malformed.') tokens = _get_document_tokens(document) features = dict(((u'contains({0})'.format(word), (word in tokens)) for word in word_features)) return features
A basic document feature extractor that returns a dict indicating what words in ``train_set`` are contained in ``document``. :param document: The text to extract features from. Can be a string or an iterable. :param list train_set: Training data set, a list of tuples of the form ``(words, label)`` OR an iterable of strings.
176,427
from __future__ import absolute_import from itertools import chain import nltk from textblob.compat import basestring from textblob.decorators import cached_property from textblob.exceptions import FormatError from textblob.tokenizers import word_tokenize from textblob.utils import strip_punc, is_filelike import textblob.formats as formats def _get_document_tokens(document): if isinstance(document, basestring): tokens = set((strip_punc(w, all=False) for w in word_tokenize(document, include_punc=False))) else: tokens = set(strip_punc(w, all=False) for w in document) return tokens The provided code snippet includes necessary dependencies for implementing the `contains_extractor` function. Write a Python function `def contains_extractor(document)` to solve the following problem: A basic document feature extractor that returns a dict of words that the document contains. Here is the function: def contains_extractor(document): """A basic document feature extractor that returns a dict of words that the document contains. """ tokens = _get_document_tokens(document) features = dict((u'contains({0})'.format(w), True) for w in tokens) return features
A basic document feature extractor that returns a dict of words that the document contains.
176,428
import sys import nltk MIN_CORPORA = [ 'brown', # Required for FastNPExtractor 'punkt', # Required for WordTokenizer 'wordnet', # Required for lemmatization 'averaged_perceptron_tagger', # Required for NLTKTagger ] def download_lite(): for each in MIN_CORPORA: nltk.download(each)
null
176,429
import sys import nltk ALL_CORPORA = MIN_CORPORA + ADDITIONAL_CORPORA def download_all(): for each in ALL_CORPORA: nltk.download(each)
null
176,430
from __future__ import absolute_import from collections import namedtuple import nltk from textblob.en import sentiment as pattern_sentiment from textblob.tokenizers import word_tokenize from textblob.decorators import requires_nltk_corpus from textblob.base import BaseSentimentAnalyzer, DISCRETE, CONTINUOUS The provided code snippet includes necessary dependencies for implementing the `_default_feature_extractor` function. Write a Python function `def _default_feature_extractor(words)` to solve the following problem: Default feature extractor for the NaiveBayesAnalyzer. Here is the function: def _default_feature_extractor(words): """Default feature extractor for the NaiveBayesAnalyzer.""" return dict(((word, True) for word in words))
Default feature extractor for the NaiveBayesAnalyzer.
176,431
import re plural_prepositions = [ "about", "above", "across", "after", "among", "around", "at", "athwart", "before", "behind", "below", "beneath", "beside", "besides", "between", "betwixt", "beyond", "but", "by", "during", "except", "for", "from", "in", "into", "near", "of", "off", "on", "onto", "out", "over", "since", "till", "to", "under", "until", "unto", "upon", "with" ] plural_rules = [ # 0) Indefinite articles and demonstratives. [["^a$|^an$", "some", None, False], ["^this$", "these", None, False], ["^that$", "those", None, False], ["^any$", "all", None, False] ], # 1) Possessive adjectives. # Overlaps with 1/ for "his" and "its". # Overlaps with 2/ for "her". [["^my$", "our", None, False], ["^your$|^thy$", "your", None, False], ["^her$|^his$|^its$|^their$", "their", None, False] ], # 2) Possessive pronouns. [["^mine$", "ours", None, False], ["^yours$|^thine$", "yours", None, False], ["^hers$|^his$|^its$|^theirs$", "theirs", None, False] ], # 3) Personal pronouns. [["^I$", "we", None, False], ["^me$", "us", None, False], ["^myself$", "ourselves", None, False], ["^you$", "you", None, False], ["^thou$|^thee$", "ye", None, False], ["^yourself$|^thyself$", "yourself", None, False], ["^she$|^he$|^it$|^they$", "they", None, False], ["^her$|^him$|^it$|^them$", "them", None, False], ["^herself$|^himself$|^itself$|^themself$", "themselves", None, False], ["^oneself$", "oneselves", None, False] ], # 4) Words that do not inflect. [["$", "", "uninflected", False], ["$", "", "uncountable", False], ["fish$", "fish", None, False], ["([- ])bass$", "\\1bass", None, False], ["ois$", "ois", None, False], ["sheep$", "sheep", None, False], ["deer$", "deer", None, False], ["pox$", "pox", None, False], ["([A-Z].*)ese$", "\\1ese", None, False], ["itis$", "itis", None, False], ["(fruct|gluc|galact|lact|ket|malt|rib|sacchar|cellul)ose$", "\\1ose", None, False] ], # 5) Irregular plurals (mongoose, oxen). [["atlas$", "atlantes", None, True], ["atlas$", "atlases", None, False], ["beef$", "beeves", None, True], ["brother$", "brethren", None, True], ["child$", "children", None, False], ["corpus$", "corpora", None, True], ["corpus$", "corpuses", None, False], ["^cow$", "kine", None, True], ["ephemeris$", "ephemerides", None, False], ["ganglion$", "ganglia", None, True], ["genie$", "genii", None, True], ["genus$", "genera", None, False], ["graffito$", "graffiti", None, False], ["loaf$", "loaves", None, False], ["money$", "monies", None, True], ["mongoose$", "mongooses", None, False], ["mythos$", "mythoi", None, False], ["octopus$", "octopodes", None, True], ["opus$", "opera", None, True], ["opus$", "opuses", None, False], ["^ox$", "oxen", None, False], ["penis$", "penes", None, True], ["penis$", "penises", None, False], ["soliloquy$", "soliloquies", None, False], ["testis$", "testes", None, False], ["trilby$", "trilbys", None, False], ["turf$", "turves", None, True], ["numen$", "numena", None, False], ["occiput$", "occipita", None, True] ], # 6) Irregular inflections for common suffixes (synopses, mice, men). [["man$", "men", None, False], ["person$", "people", None, False], ["([lm])ouse$", "\\1ice", None, False], ["tooth$", "teeth", None, False], ["goose$", "geese", None, False], ["foot$", "feet", None, False], ["zoon$", "zoa", None, False], ["([csx])is$", "\\1es", None, False] ], # 7) Fully assimilated classical inflections (vertebrae, codices). [["ex$", "ices", "ex-ices", False], ["ex$", "ices", "ex-ices-classical", True], ["um$", "a", "um-a", False], ["um$", "a", "um-a-classical", True], ["on$", "a", "on-a", False], ["a$", "ae", "a-ae", False], ["a$", "ae", "a-ae-classical", True] ], # 8) Classical variants of modern inflections (stigmata, soprani). [["trix$", "trices", None, True], ["eau$", "eaux", None, True], ["ieu$", "ieu", None, True], ["([iay])nx$", "\\1nges", None, True], ["en$", "ina", "en-ina-classical", True], ["a$", "ata", "a-ata-classical", True], ["is$", "ides", "is-ides-classical", True], ["us$", "i", "us-i-classical", True], ["us$", "us", "us-us-classical", True], ["o$", "i", "o-i-classical", True], ["$", "i", "-i-classical", True], ["$", "im", "-im-classical", True] ], # 9) -ch, -sh and -ss and the s-singular group take -es in the plural (churches, classes, lenses). [["([cs])h$", "\\1hes", None, False], ["ss$", "sses", None, False], ["x$", "xes", None, False], ["s$", "ses", "s-singular", False] ], # 10) Certain words ending in -f or -fe take -ves in the plural (lives, wolves). [["([aeo]l)f$", "\\1ves", None, False], ["([^d]ea)f$", "\\1ves", None, False], ["arf$", "arves", None, False], ["([nlw]i)fe$", "\\1ves", None, False], ], # 11) -y takes -ys if preceded by a vowel or when a proper noun, # but -ies if preceded by a consonant (storeys, Marys, stories). [["([aeiou])y$", "\\1ys", None, False], ["([A-Z].*)y$", "\\1ys", None, False], ["y$", "ies", None, False] ], # 12) Some words ending in -o take -os, the rest take -oes. # Words in which the -o is preceded by a vowel always take -os (lassos, potatoes, bamboos). [["o$", "os", "o-os", False], ["([aeiou])o$", "\\1os", None, False], ["o$", "oes", None, False] ], # 13) Miltary stuff (Major Generals). [["l$", "ls", "general-generals", False] ], # 14) Otherwise, assume that the plural just adds -s (cats, programmes). [["$", "s", None, False] ], ] for ruleset in plural_rules: for rule in ruleset: rule[0] = re.compile(rule[0]) plural_categories = { "uninflected": [ "aircraft", "antelope", "bison", "bream", "breeches", "britches", "carp", "cattle", "chassis", "clippers", "cod", "contretemps", "corps", "debris", "diabetes", "djinn", "eland", "elk", "flounder", "gallows", "graffiti", "headquarters", "herpes", "high-jinks", "homework", "innings", "jackanapes", "mackerel", "measles", "mews", "moose", "mumps", "offspring", "news", "pincers", "pliers", "proceedings", "rabies", "salmon", "scissors", "series", "shears", "species", "swine", "trout", "tuna", "whiting", "wildebeest"], "uncountable": [ "advice", "bread", "butter", "cannabis", "cheese", "electricity", "equipment", "fruit", "furniture", "garbage", "gravel", "happiness", "information", "ketchup", "knowledge", "love", "luggage", "mathematics", "mayonnaise", "meat", "mustard", "news", "progress", "research", "rice", "sand", "software", "understanding", "water"], "s-singular": [ "acropolis", "aegis", "alias", "asbestos", "bathos", "bias", "bus", "caddis", "canvas", "chaos", "christmas", "cosmos", "dais", "digitalis", "epidermis", "ethos", "gas", "glottis", "ibis", "lens", "mantis", "marquis", "metropolis", "pathos", "pelvis", "polis", "rhinoceros", "sassafras", "trellis"], "ex-ices": ["codex", "murex", "silex"], "ex-ices-classical": [ "apex", "cortex", "index", "latex", "pontifex", "simplex", "vertex", "vortex"], "um-a": [ "agendum", "bacterium", "candelabrum", "datum", "desideratum", "erratum", "extremum", "ovum", "stratum"], "um-a-classical": [ "aquarium", "compendium", "consortium", "cranium", "curriculum", "dictum", "emporium", "enconium", "gymnasium", "honorarium", "interregnum", "lustrum", "maximum", "medium", "memorandum", "millenium", "minimum", "momentum", "optimum", "phylum", "quantum", "rostrum", "spectrum", "speculum", "stadium", "trapezium", "ultimatum", "vacuum", "velum"], "on-a": [ "aphelion", "asyndeton", "criterion", "hyperbaton", "noumenon", "organon", "perihelion", "phenomenon", "prolegomenon"], "a-ae": ["alga", "alumna", "vertebra"], "a-ae-classical": [ "abscissa", "amoeba", "antenna", "aurora", "formula", "hydra", "hyperbola", "lacuna", "medusa", "nebula", "nova", "parabola"], "en-ina-classical": ["foramen", "lumen", "stamen"], "a-ata-classical": [ "anathema", "bema", "carcinoma", "charisma", "diploma", "dogma", "drama", "edema", "enema", "enigma", "gumma", "lemma", "lymphoma", "magma", "melisma", "miasma", "oedema", "sarcoma", "schema", "soma", "stigma", "stoma", "trauma"], "is-ides-classical": ["clitoris", "iris"], "us-i-classical": [ "focus", "fungus", "genius", "incubus", "nimbus", "nucleolus", "radius", "stylus", "succubus", "torus", "umbilicus", "uterus"], "us-us-classical": [ "apparatus", "cantus", "coitus", "hiatus", "impetus", "nexus", "plexus", "prospectus", "sinus", "status"], "o-i-classical": ["alto", "basso", "canto", "contralto", "crescendo", "solo", "soprano", "tempo"], "-i-classical": ["afreet", "afrit", "efreet"], "-im-classical": ["cherub", "goy", "seraph"], "o-os": [ "albino", "archipelago", "armadillo", "commando", "ditto", "dynamo", "embryo", "fiasco", "generalissimo", "ghetto", "guano", "inferno", "jumbo", "lingo", "lumbago", "magneto", "manifesto", "medico", "octavo", "photo", "pro", "quarto", "rhino", "stylo"], "general-generals": [ "Adjutant", "Brigadier", "Lieutenant", "Major", "Quartermaster", "adjutant", "brigadier", "lieutenant", "major", "quartermaster"], } for rule in singular_rules: rule[0] = re.compile(rule[0]) The provided code snippet includes necessary dependencies for implementing the `pluralize` function. Write a Python function `def pluralize(word, pos=NOUN, custom={}, classical=True)` to solve the following problem: Returns the plural of a given word. For example: child -> children. Handles nouns and adjectives, using classical inflection by default (e.g. where "matrix" pluralizes to "matrices" instead of "matrixes"). The custom dictionary is for user-defined replacements. Here is the function: def pluralize(word, pos=NOUN, custom={}, classical=True): """ Returns the plural of a given word. For example: child -> children. Handles nouns and adjectives, using classical inflection by default (e.g. where "matrix" pluralizes to "matrices" instead of "matrixes"). The custom dictionary is for user-defined replacements. """ if word in custom: return custom[word] # Recursion of genitives. # Remove the apostrophe and any trailing -s, # form the plural of the resultant noun, and then append an apostrophe (dog's -> dogs'). if word.endswith("'") or word.endswith("'s"): owner = word.rstrip("'s") owners = pluralize(owner, pos, custom, classical) if owners.endswith("s"): return owners + "'" else: return owners + "'s" # Recursion of compound words # (Postmasters General, mothers-in-law, Roman deities). words = word.replace("-", " ").split(" ") if len(words) > 1: if words[1] == "general" or words[1] == "General" and \ words[0] not in plural_categories["general-generals"]: return word.replace(words[0], pluralize(words[0], pos, custom, classical)) elif words[1] in plural_prepositions: return word.replace(words[0], pluralize(words[0], pos, custom, classical)) else: return word.replace(words[-1], pluralize(words[-1], pos, custom, classical)) # Only a very few number of adjectives inflect. n = list(range(len(plural_rules))) if pos.startswith(ADJECTIVE): n = [0, 1] # Apply pluralization rules. for i in n: ruleset = plural_rules[i] for rule in ruleset: suffix, inflection, category, classic = rule # A general rule, or a classic rule in classical mode. if category == None: if not classic or (classic and classical): if suffix.search(word) is not None: return suffix.sub(inflection, word) # A rule relating to a specific category of words. if category != None: if word in plural_categories[category] and (not classic or (classic and classical)): if suffix.search(word) is not None: return suffix.sub(inflection, word)
Returns the plural of a given word. For example: child -> children. Handles nouns and adjectives, using classical inflection by default (e.g. where "matrix" pluralizes to "matrices" instead of "matrixes"). The custom dictionary is for user-defined replacements.
176,432
import re plural_prepositions = [ "about", "above", "across", "after", "among", "around", "at", "athwart", "before", "behind", "below", "beneath", "beside", "besides", "between", "betwixt", "beyond", "but", "by", "during", "except", "for", "from", "in", "into", "near", "of", "off", "on", "onto", "out", "over", "since", "till", "to", "under", "until", "unto", "upon", "with" ] singular_rules = [ ['(?i)(.)ae$', '\\1a'], ['(?i)(.)itis$', '\\1itis'], ['(?i)(.)eaux$', '\\1eau'], ['(?i)(quiz)zes$', '\\1'], ['(?i)(matr)ices$', '\\1ix'], ['(?i)(ap|vert|ind)ices$', '\\1ex'], ['(?i)^(ox)en', '\\1'], ['(?i)(alias|status)es$', '\\1'], ['(?i)([octop|vir])i$', '\\1us'], ['(?i)(cris|ax|test)es$', '\\1is'], ['(?i)(shoe)s$', '\\1'], ['(?i)(o)es$', '\\1'], ['(?i)(bus)es$', '\\1'], ['(?i)([m|l])ice$', '\\1ouse'], ['(?i)(x|ch|ss|sh)es$', '\\1'], ['(?i)(m)ovies$', '\\1ovie'], ['(?i)(.)ombies$', '\\1ombie'], ['(?i)(s)eries$', '\\1eries'], ['(?i)([^aeiouy]|qu)ies$', '\\1y'], # Certain words ending in -f or -fe take -ves in the plural (lives, wolves). ["([aeo]l)ves$", "\\1f"], ["([^d]ea)ves$", "\\1f"], ["arves$", "arf"], ["erves$", "erve"], ["([nlw]i)ves$", "\\1fe"], ['(?i)([lr])ves$', '\\1f'], ["([aeo])ves$", "\\1ve"], ['(?i)(sive)s$', '\\1'], ['(?i)(tive)s$', '\\1'], ['(?i)(hive)s$', '\\1'], ['(?i)([^f])ves$', '\\1fe'], # -es suffix. ['(?i)(^analy)ses$', '\\1sis'], ['(?i)((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$', '\\1\\2sis'], ['(?i)(.)opses$', '\\1opsis'], ['(?i)(.)yses$', '\\1ysis'], ['(?i)(h|d|r|o|n|b|cl|p)oses$', '\\1ose'], ['(?i)(fruct|gluc|galact|lact|ket|malt|rib|sacchar|cellul)ose$', '\\1ose'], ['(?i)(.)oses$', '\\1osis'], # -a ['(?i)([ti])a$', '\\1um'], ['(?i)(n)ews$', '\\1ews'], ['(?i)s$', ''], ] for rule in singular_rules: rule[0] = re.compile(rule[0]) singular_uninflected = [ "aircraft", "antelope", "bison", "bream", "breeches", "britches", "carp", "cattle", "chassis", "clippers", "cod", "contretemps", "corps", "debris", "diabetes", "djinn", "eland", "elk", "flounder", "gallows", "georgia", "graffiti", "headquarters", "herpes", "high-jinks", "homework", "innings", "jackanapes", "mackerel", "measles", "mews", "moose", "mumps", "news", "offspring", "pincers", "pliers", "proceedings", "rabies", "salmon", "scissors", "series", "shears", "species", "swine", "swiss", "trout", "tuna", "whiting", "wildebeest" ] singular_uncountable = [ "advice", "bread", "butter", "cannabis", "cheese", "electricity", "equipment", "fruit", "furniture", "garbage", "gravel", "happiness", "information", "ketchup", "knowledge", "love", "luggage", "mathematics", "mayonnaise", "meat", "mustard", "news", "progress", "research", "rice", "sand", "software", "understanding", "water" ] singular_ie = [ "algerie", "auntie", "beanie", "birdie", "bogie", "bombie", "bookie", "collie", "cookie", "cutie", "doggie", "eyrie", "freebie", "goonie", "groupie", "hankie", "hippie", "hoagie", "hottie", "indie", "junkie", "laddie", "laramie", "lingerie", "meanie", "nightie", "oldie", "^pie", "pixie", "quickie", "reverie", "rookie", "softie", "sortie", "stoolie", "sweetie", "techie", "^tie", "toughie", "valkyrie", "veggie", "weenie", "yuppie", "zombie" ] singular_s = plural_categories['s-singular'] singular_irregular = { "men": "man", "people": "person", "children": "child", "sexes": "sex", "axes": "axe", "moves": "move", "teeth": "tooth", "geese": "goose", "feet": "foot", "zoa": "zoon", "atlantes": "atlas", "atlases": "atlas", "beeves": "beef", "brethren": "brother", "children": "child", "corpora": "corpus", "corpuses": "corpus", "kine": "cow", "ephemerides": "ephemeris", "ganglia": "ganglion", "genii": "genie", "genera": "genus", "graffiti": "graffito", "helves": "helve", "leaves": "leaf", "loaves": "loaf", "monies": "money", "mongooses": "mongoose", "mythoi": "mythos", "octopodes": "octopus", "opera": "opus", "opuses": "opus", "oxen": "ox", "penes": "penis", "penises": "penis", "soliloquies": "soliloquy", "testes": "testis", "trilbys": "trilby", "turves": "turf", "numena": "numen", "occipita": "occiput", "our": "my", } def singularize(word, pos=NOUN, custom={}): if word in list(custom.keys()): return custom[word] # Recursion of compound words (e.g. mothers-in-law). if "-" in word: words = word.split("-") if len(words) > 1 and words[1] in plural_prepositions: return singularize(words[0], pos, custom)+"-"+"-".join(words[1:]) # dogs' => dog's if word.endswith("'"): return singularize(word[:-1]) + "'s" lower = word.lower() for w in singular_uninflected: if w.endswith(lower): return word for w in singular_uncountable: if w.endswith(lower): return word for w in singular_ie: if lower.endswith(w+"s"): return w for w in singular_s: if lower.endswith(w + 'es'): return w for w in list(singular_irregular.keys()): if lower.endswith(w): return re.sub('(?i)'+w+'$', singular_irregular[w], word) for rule in singular_rules: suffix, inflection = rule match = suffix.search(word) if match: groups = match.groups() for k in range(0, len(groups)): if groups[k] == None: inflection = inflection.replace('\\'+str(k+1), '') return suffix.sub(inflection, word) return word
null
176,433
from __future__ import unicode_literals, absolute_import import nltk from textblob.taggers import PatternTagger from textblob.decorators import requires_nltk_corpus from textblob.utils import tree2str, filter_insignificant from textblob.base import BaseNPExtractor The provided code snippet includes necessary dependencies for implementing the `_normalize_tags` function. Write a Python function `def _normalize_tags(chunk)` to solve the following problem: Normalize the corpus tags. ("NN", "NN-PL", "NNS") -> "NN" Here is the function: def _normalize_tags(chunk): '''Normalize the corpus tags. ("NN", "NN-PL", "NNS") -> "NN" ''' ret = [] for word, tag in chunk: if tag == 'NP-TL' or tag == 'NP': ret.append((word, 'NNP')) continue if tag.endswith('-TL'): ret.append((word, tag[:-3])) continue if tag.endswith('S'): ret.append((word, tag[:-1])) continue ret.append((word, tag)) return ret
Normalize the corpus tags. ("NN", "NN-PL", "NNS") -> "NN"
176,434
from __future__ import unicode_literals, absolute_import import nltk from textblob.taggers import PatternTagger from textblob.decorators import requires_nltk_corpus from textblob.utils import tree2str, filter_insignificant from textblob.base import BaseNPExtractor The provided code snippet includes necessary dependencies for implementing the `_is_match` function. Write a Python function `def _is_match(tagged_phrase, cfg)` to solve the following problem: Return whether or not a tagged phrases matches a context-free grammar. Here is the function: def _is_match(tagged_phrase, cfg): '''Return whether or not a tagged phrases matches a context-free grammar. ''' copy = list(tagged_phrase) # A copy of the list merge = True while merge: merge = False for i in range(len(copy) - 1): first, second = copy[i], copy[i + 1] key = first[1], second[1] # Tuple of tags e.g. ('NN', 'JJ') value = cfg.get(key, None) if value: merge = True copy.pop(i) copy.pop(i) match = '{0} {1}'.format(first[0], second[0]) pos = value copy.insert(i, (match, pos)) break match = any([t[1] in ('NNP', 'NNI') for t in copy]) return match
Return whether or not a tagged phrases matches a context-free grammar.
176,435
from __future__ import absolute_import from functools import wraps from textblob.exceptions import MissingCorpusError def wraps(wrapped: _AnyCallable, assigned: Sequence[str] = ..., updated: Sequence[str] = ...) -> Callable[[_T], _T]: ... class MissingCorpusError(TextBlobError): """Exception thrown when a user tries to use a feature that requires a dataset or model that the user does not have on their system. """ def __init__(self, message=MISSING_CORPUS_MESSAGE, *args, **kwargs): super(MissingCorpusError, self).__init__(message, *args, **kwargs) The provided code snippet includes necessary dependencies for implementing the `requires_nltk_corpus` function. Write a Python function `def requires_nltk_corpus(func)` to solve the following problem: Wraps a function that requires an NLTK corpus. If the corpus isn't found, raise a :exc:`MissingCorpusError`. Here is the function: def requires_nltk_corpus(func): """Wraps a function that requires an NLTK corpus. If the corpus isn't found, raise a :exc:`MissingCorpusError`. """ @wraps(func) def decorated(*args, **kwargs): try: return func(*args, **kwargs) except LookupError as err: print(err) raise MissingCorpusError() return decorated
Wraps a function that requires an NLTK corpus. If the corpus isn't found, raise a :exc:`MissingCorpusError`.
176,436
from __future__ import absolute_import import codecs import json import re from textblob.compat import PY2, request, urlencode from textblob.exceptions import TranslatorError, NotTranslated The provided code snippet includes necessary dependencies for implementing the `_unescape` function. Write a Python function `def _unescape(text)` to solve the following problem: Unescape unicode character codes within a string. Here is the function: def _unescape(text): """Unescape unicode character codes within a string. """ pattern = r'\\{1,2}u[0-9a-fA-F]{4}' return re.sub(pattern, lambda x: codecs.getdecoder('unicode_escape')(x.group())[0], text)
Unescape unicode character codes within a string.
176,437
from __future__ import absolute_import import codecs import json import re from textblob.compat import PY2, request, urlencode from textblob.exceptions import TranslatorError, NotTranslated PY2 = int(sys.version[0]) == 2 if PY2: from itertools import imap, izip import urllib2 as request from urllib import quote as urlquote from urllib import urlencode text_type = unicode binary_type = str string_types = (str, unicode) unicode = unicode basestring = basestring imap = imap izip = izip import unicodecsv as csv def implements_to_string(cls): """Class decorator that renames __str__ to __unicode__ and modifies __str__ that returns utf-8. """ cls.__unicode__ = cls.__str__ cls.__str__ = lambda x: x.__unicode__().encode('utf-8') return cls else: # PY3 from urllib import request from urllib.parse import quote as urlquote from urllib.parse import urlencode text_type = str binary_type = bytes string_types = (str,) unicode = str basestring = (str, bytes) imap = map izip = zip import csv implements_to_string = lambda x: x The provided code snippet includes necessary dependencies for implementing the `_calculate_tk` function. Write a Python function `def _calculate_tk(source)` to solve the following problem: Reverse engineered cross-site request protection. Here is the function: def _calculate_tk(source): """Reverse engineered cross-site request protection.""" # Source: https://github.com/soimort/translate-shell/issues/94#issuecomment-165433715 # Source: http://www.liuxiatool.com/t.php def c_int(x, nbits=32): """ C cast to int32, int16, int8... """ return (x & ((1 << (nbits - 1)) - 1)) - (x & (1 << (nbits - 1))) def c_uint(x, nbits=32): """ C cast to uint32, uint16, uint8... """ return x & ((1 << nbits) - 1) tkk = [406398, 561666268 + 1526272306] b = tkk[0] if PY2: d = map(ord, source) else: d = source.encode('utf-8') def RL(a, b): for c in range(0, len(b) - 2, 3): d = b[c + 2] d = ord(d) - 87 if d >= 'a' else int(d) xa = c_uint(a) d = xa >> d if b[c + 1] == '+' else xa << d a = a + d & 4294967295 if b[c] == '+' else a ^ d return c_int(a) a = b for di in d: a = RL(a + di, "+-a^+6") a = RL(a, "+-3^+b+-f") a ^= tkk[1] a = a if a >= 0 else ((a & 2147483647) + 2147483648) a %= pow(10, 6) tk = '{0:d}.{1:d}'.format(a, a ^ b) return tk
Reverse engineered cross-site request protection.
176,438
import sys The provided code snippet includes necessary dependencies for implementing the `implements_to_string` function. Write a Python function `def implements_to_string(cls)` to solve the following problem: Class decorator that renames __str__ to __unicode__ and modifies __str__ that returns utf-8. Here is the function: def implements_to_string(cls): """Class decorator that renames __str__ to __unicode__ and modifies __str__ that returns utf-8. """ cls.__unicode__ = cls.__str__ cls.__str__ = lambda x: x.__unicode__().encode('utf-8') return cls
Class decorator that renames __str__ to __unicode__ and modifies __str__ that returns utf-8.
176,439
import sys The provided code snippet includes necessary dependencies for implementing the `with_metaclass` function. Write a Python function `def with_metaclass(meta, *bases)` to solve the following problem: Create a base class with a metaclass. Here is the function: def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(meta): # noqa def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
Create a base class with a metaclass.
176,440
from __future__ import unicode_literals import string import codecs from itertools import chain import types import os import re from xml.etree import cElementTree from .compat import text_type, basestring, imap, unicode, binary_type, PY2 The provided code snippet includes necessary dependencies for implementing the `decode_string` function. Write a Python function `def decode_string(v, encoding="utf-8")` to solve the following problem: Returns the given value as a Unicode string (if possible). Here is the function: def decode_string(v, encoding="utf-8"): """ Returns the given value as a Unicode string (if possible). """ if isinstance(encoding, basestring): encoding = ((encoding,),) + (("windows-1252",), ("utf-8", "ignore")) if isinstance(v, binary_type): for e in encoding: try: return v.decode(*e) except: pass return v return unicode(v)
Returns the given value as a Unicode string (if possible).
176,441
from __future__ import unicode_literals import string import codecs from itertools import chain import types import os import re from xml.etree import cElementTree from .compat import text_type, basestring, imap, unicode, binary_type, PY2 The provided code snippet includes necessary dependencies for implementing the `encode_string` function. Write a Python function `def encode_string(v, encoding="utf-8")` to solve the following problem: Returns the given value as a Python byte string (if possible). Here is the function: def encode_string(v, encoding="utf-8"): """ Returns the given value as a Python byte string (if possible). """ if isinstance(encoding, basestring): encoding = ((encoding,),) + (("windows-1252",), ("utf-8", "ignore")) if isinstance(v, unicode): for e in encoding: try: return v.encode(*e) except: pass return v return str(v)
Returns the given value as a Python byte string (if possible).
176,442
from __future__ import unicode_literals import string import codecs from itertools import chain import types import os import re from xml.etree import cElementTree from .compat import text_type, basestring, imap, unicode, binary_type, PY2 def isnumeric(strg): try: float(strg) except ValueError: return False return True
null
176,443
from __future__ import unicode_literals import string import codecs from itertools import chain import types import os import re from xml.etree import cElementTree from .compat import text_type, basestring, imap, unicode, binary_type, PY2 NOUN, VERB, ADJ, ADV, PRON, DET, PREP, ADP, NUM, CONJ, INTJ, PRT, PUNC, X = \ "NN", "VB", "JJ", "RB", "PR", "DT", "PP", "PP", "NO", "CJ", "UH", "PT", ".", "X" NOUN, VERB, ADJECTIVE, ADVERB = \ "NN", "VB", "JJ", "RB" The provided code snippet includes necessary dependencies for implementing the `penntreebank2universal` function. Write a Python function `def penntreebank2universal(token, tag)` to solve the following problem: Returns a (token, tag)-tuple with a simplified universal part-of-speech tag. Here is the function: def penntreebank2universal(token, tag): """ Returns a (token, tag)-tuple with a simplified universal part-of-speech tag. """ if tag.startswith(("NNP-", "NNPS-")): return (token, "%s-%s" % (NOUN, tag.split("-")[-1])) if tag in ("NN", "NNS", "NNP", "NNPS", "NP"): return (token, NOUN) if tag in ("MD", "VB", "VBD", "VBG", "VBN", "VBP", "VBZ"): return (token, VERB) if tag in ("JJ", "JJR", "JJS"): return (token, ADJ) if tag in ("RB", "RBR", "RBS", "WRB"): return (token, ADV) if tag in ("PRP", "PRP$", "WP", "WP$"): return (token, PRON) if tag in ("DT", "PDT", "WDT", "EX"): return (token, DET) if tag in ("IN",): return (token, PREP) if tag in ("CD",): return (token, NUM) if tag in ("CC",): return (token, CONJ) if tag in ("UH",): return (token, INTJ) if tag in ("POS", "RP", "TO"): return (token, PRT) if tag in ("SYM", "LS", ".", "!", "?", ",", ":", "(", ")", "\"", "#", "$"): return (token, PUNC) return (token, X)
Returns a (token, tag)-tuple with a simplified universal part-of-speech tag.
176,444
from __future__ import unicode_literals import string import codecs from itertools import chain import types import os import re from xml.etree import cElementTree from .compat import text_type, basestring, imap, unicode, binary_type, PY2 TOKEN = re.compile(r"(\S+)\s") PUNCTUATION = \ punctuation = ".,;:!?()[]{}`''\"@#$^&*+-|=~_" ABBREVIATIONS = abbreviations = set(( "a.", "adj.", "adv.", "al.", "a.m.", "c.", "cf.", "comp.", "conf.", "def.", "ed.", "e.g.", "esp.", "etc.", "ex.", "f.", "fig.", "gen.", "id.", "i.e.", "int.", "l.", "m.", "Med.", "Mil.", "Mr.", "n.", "n.q.", "orig.", "pl.", "pred.", "pres.", "p.m.", "ref.", "v.", "vs.", "w/" )) RE_ABBR1 = re.compile("^[A-Za-z]\.$") RE_ABBR2 = re.compile("^([A-Za-z]\.)+$") RE_ABBR3 = re.compile("^[A-Z][" + "|".join( # capital followed by consonants, "Mr." "bcdfghjklmnpqrstvwxz") + "]+.$") RE_EMOTICONS = [r" ?".join([re.escape(each) for each in e]) for v in EMOTICONS.values() for e in v] RE_EMOTICONS = re.compile(r"(%s)($|\s)" % "|".join(RE_EMOTICONS)) RE_SARCASM = re.compile(r"\( ?\! ?\)") replacements = { "'d": " 'd", "'m": " 'm", "'s": " 's", "'ll": " 'll", "'re": " 're", "'ve": " 've", "n't": " n't" } EOS = "END-OF-SENTENCE" The provided code snippet includes necessary dependencies for implementing the `find_tokens` function. Write a Python function `def find_tokens(string, punctuation=PUNCTUATION, abbreviations=ABBREVIATIONS, replace=replacements, linebreak=r"\n{2,}")` to solve the following problem: Returns a list of sentences. Each sentence is a space-separated string of tokens (words). Handles common cases of abbreviations (e.g., etc., ...). Punctuation marks are split from other words. Periods (or ?!) mark the end of a sentence. Headings without an ending period are inferred by line breaks. Here is the function: def find_tokens(string, punctuation=PUNCTUATION, abbreviations=ABBREVIATIONS, replace=replacements, linebreak=r"\n{2,}"): """ Returns a list of sentences. Each sentence is a space-separated string of tokens (words). Handles common cases of abbreviations (e.g., etc., ...). Punctuation marks are split from other words. Periods (or ?!) mark the end of a sentence. Headings without an ending period are inferred by line breaks. """ # Handle periods separately. punctuation = tuple(punctuation.replace(".", "")) # Handle replacements (contractions). for a, b in list(replace.items()): string = re.sub(a, b, string) # Handle Unicode quotes. if isinstance(string, unicode): string = unicode(string).replace("“", " “ ")\ .replace("”", " ” ")\ .replace("‘", " ‘ ")\ .replace("’", " ’ ")\ .replace("'", " ' ")\ .replace('"', ' " ') # Collapse whitespace. string = re.sub("\r\n", "\n", string) string = re.sub(linebreak, " %s " % EOS, string) string = re.sub(r"\s+", " ", string) tokens = [] for t in TOKEN.findall(string+" "): if len(t) > 0: tail = [] while t.startswith(punctuation) and \ not t in replace: # Split leading punctuation. if t.startswith(punctuation): tokens.append(t[0]); t=t[1:] while t.endswith(punctuation+(".",)) and \ not t in replace: # Split trailing punctuation. if t.endswith(punctuation): tail.append(t[-1]); t=t[:-1] # Split ellipsis (...) before splitting period. if t.endswith("..."): tail.append("..."); t=t[:-3].rstrip(".") # Split period (if not an abbreviation). if t.endswith("."): if t in abbreviations or \ RE_ABBR1.match(t) is not None or \ RE_ABBR2.match(t) is not None or \ RE_ABBR3.match(t) is not None: break else: tail.append(t[-1]); t=t[:-1] if t != "": tokens.append(t) tokens.extend(reversed(tail)) sentences, i, j = [[]], 0, 0 while j < len(tokens): if tokens[j] in ("...", ".", "!", "?", EOS): # Handle citations, trailing parenthesis, repeated punctuation (!?). while j < len(tokens) \ and tokens[j] in ("'", "\"", u"”", u"’", "...", ".", "!", "?", ")", EOS): if tokens[j] in ("'", "\"") and sentences[-1].count(tokens[j]) % 2 == 0: break # Balanced quotes. j += 1 sentences[-1].extend(t for t in tokens[i:j] if t != EOS) sentences.append([]) i = j j += 1 sentences[-1].extend(tokens[i:j]) sentences = (" ".join(s) for s in sentences if len(s) > 0) sentences = (RE_SARCASM.sub("(!)", s) for s in sentences) sentences = [RE_EMOTICONS.sub( lambda m: m.group(1).replace(" ", "") + m.group(2), s) for s in sentences] return sentences
Returns a list of sentences. Each sentence is a space-separated string of tokens (words). Handles common cases of abbreviations (e.g., etc., ...). Punctuation marks are split from other words. Periods (or ?!) mark the end of a sentence. Headings without an ending period are inferred by line breaks.
176,445
from __future__ import unicode_literals import string import codecs from itertools import chain import types import os import re from xml.etree import cElementTree from .compat import text_type, basestring, imap, unicode, binary_type, PY2 decode_utf8 = decode_string PY2 = int(sys.version[0]) == 2 if PY2: from itertools import imap, izip import urllib2 as request from urllib import quote as urlquote from urllib import urlencode text_type = unicode binary_type = str string_types = (str, unicode) unicode = unicode basestring = basestring imap = imap izip = izip import unicodecsv as csv def implements_to_string(cls): """Class decorator that renames __str__ to __unicode__ and modifies __str__ that returns utf-8. """ cls.__unicode__ = cls.__str__ cls.__str__ = lambda x: x.__unicode__().encode('utf-8') return cls else: # PY3 from urllib import request from urllib.parse import quote as urlquote from urllib.parse import urlencode text_type = str binary_type = bytes string_types = (str,) unicode = str basestring = (str, bytes) imap = map izip = zip import csv implements_to_string = lambda x: x The provided code snippet includes necessary dependencies for implementing the `_read` function. Write a Python function `def _read(path, encoding="utf-8", comment=";;;")` to solve the following problem: Returns an iterator over the lines in the file at the given path, stripping comments and decoding each line to Unicode. Here is the function: def _read(path, encoding="utf-8", comment=";;;"): """ Returns an iterator over the lines in the file at the given path, stripping comments and decoding each line to Unicode. """ if path: if isinstance(path, basestring) and os.path.exists(path): # From file path. if PY2: f = codecs.open(path, 'r', encoding='utf-8') else: f = open(path, 'r', encoding='utf-8') elif isinstance(path, basestring): # From string. f = path.splitlines() elif hasattr(path, "read"): # From string buffer. f = path.read().splitlines() else: f = path for i, line in enumerate(f): line = line.strip(codecs.BOM_UTF8) if i == 0 and isinstance(line, binary_type) else line line = line.strip() line = decode_utf8(line) if not line or (comment and line.startswith(comment)): continue yield line return
Returns an iterator over the lines in the file at the given path, stripping comments and decoding each line to Unicode.
176,446
from __future__ import unicode_literals import string import codecs from itertools import chain import types import os import re from xml.etree import cElementTree from .compat import text_type, basestring, imap, unicode, binary_type, PY2 def avg(list): return sum(list) / float(len(list) or 1)
null
176,447
from __future__ import unicode_literals import string import codecs from itertools import chain import types import os import re from xml.etree import cElementTree from .compat import text_type, basestring, imap, unicode, binary_type, PY2 CD = re.compile(r"^[0-9\-\,\.\:\/\%\$]+$") def _suffix_rules(token, tag="NN"): """ Default morphological tagging rules for English, based on word suffixes. """ if isinstance(token, (list, tuple)): token, tag = token if token.endswith("ing"): tag = "VBG" if token.endswith("ly"): tag = "RB" if token.endswith("s") and not token.endswith(("is", "ous", "ss")): tag = "NNS" if token.endswith(("able", "al", "ful", "ible", "ient", "ish", "ive", "less", "tic", "ous")) or "-" in token: tag = "JJ" if token.endswith("ed"): tag = "VBN" if token.endswith(("ate", "ify", "ise", "ize")): tag = "VBP" return [token, tag] The provided code snippet includes necessary dependencies for implementing the `find_tags` function. Write a Python function `def find_tags(tokens, lexicon={}, model=None, morphology=None, context=None, entities=None, default=("NN", "NNP", "CD"), language="en", map=None, **kwargs)` to solve the following problem: Returns a list of [token, tag]-items for the given list of tokens: ["The", "cat", "purs"] => [["The", "DT"], ["cat", "NN"], ["purs", "VB"]] Words are tagged using the given lexicon of (word, tag)-items. Unknown words are tagged NN by default. Unknown words that start with a capital letter are tagged NNP (unless language="de"). Unknown words that consist only of digits and punctuation marks are tagged CD. Unknown words are then improved with morphological rules. All words are improved with contextual rules. If a model is given, uses model for unknown words instead of morphology and context. If map is a function, it is applied to each (token, tag) after applying all rules. Here is the function: def find_tags(tokens, lexicon={}, model=None, morphology=None, context=None, entities=None, default=("NN", "NNP", "CD"), language="en", map=None, **kwargs): """ Returns a list of [token, tag]-items for the given list of tokens: ["The", "cat", "purs"] => [["The", "DT"], ["cat", "NN"], ["purs", "VB"]] Words are tagged using the given lexicon of (word, tag)-items. Unknown words are tagged NN by default. Unknown words that start with a capital letter are tagged NNP (unless language="de"). Unknown words that consist only of digits and punctuation marks are tagged CD. Unknown words are then improved with morphological rules. All words are improved with contextual rules. If a model is given, uses model for unknown words instead of morphology and context. If map is a function, it is applied to each (token, tag) after applying all rules. """ tagged = [] # Tag known words. for i, token in enumerate(tokens): tagged.append([token, lexicon.get(token, i == 0 and lexicon.get(token.lower()) or None)]) # Tag unknown words. for i, (token, tag) in enumerate(tagged): prev, next = (None, None), (None, None) if i > 0: prev = tagged[i-1] if i < len(tagged) - 1: next = tagged[i+1] if tag is None or token in (model is not None and model.unknown or ()): # Use language model (i.e., SLP). if model is not None: tagged[i] = model.apply([token, None], prev, next) # Use NNP for capitalized words (except in German). elif token.istitle() and language != "de": tagged[i] = [token, default[1]] # Use CD for digits and numbers. elif CD.match(token) is not None: tagged[i] = [token, default[2]] # Use suffix rules (e.g., -ly = RB). elif morphology is not None: tagged[i] = morphology.apply([token, default[0]], prev, next) # Use suffix rules (English default). elif language == "en": tagged[i] = _suffix_rules([token, default[0]]) # Use most frequent tag (NN). else: tagged[i] = [token, default[0]] # Tag words by context. if context is not None and model is None: tagged = context.apply(tagged) # Tag named entities. if entities is not None: tagged = entities.apply(tagged) # Map tags with a custom function. if map is not None: tagged = [list(map(token, tag)) or [token, default[0]] for token, tag in tagged] return tagged
Returns a list of [token, tag]-items for the given list of tokens: ["The", "cat", "purs"] => [["The", "DT"], ["cat", "NN"], ["purs", "VB"]] Words are tagged using the given lexicon of (word, tag)-items. Unknown words are tagged NN by default. Unknown words that start with a capital letter are tagged NNP (unless language="de"). Unknown words that consist only of digits and punctuation marks are tagged CD. Unknown words are then improved with morphological rules. All words are improved with contextual rules. If a model is given, uses model for unknown words instead of morphology and context. If map is a function, it is applied to each (token, tag) after applying all rules.
176,448
from __future__ import unicode_literals import string import codecs from itertools import chain import types import os import re from xml.etree import cElementTree from .compat import text_type, basestring, imap, unicode, binary_type, PY2 SEPARATOR = "/" CHUNKS = [[ # Germanic languages: en, de, nl, ... ( "NP", re.compile(r"(("+NN+")/)*((DT|CD|CC|CJ)/)*(("+RB+"|"+JJ+")/)*(("+NN+")/)+")), ( "VP", re.compile(r"(((MD|"+RB+")/)*(("+VB+")/)+)+")), ( "VP", re.compile(r"((MD)/)")), ( "PP", re.compile(r"((IN|PP|TO)/)+")), ("ADJP", re.compile(r"((CC|CJ|"+RB+"|"+JJ+")/)*(("+JJ+")/)+")), ("ADVP", re.compile(r"(("+RB+"|WRB)/)+")), ], [ # Romance languages: es, fr, it, ... ( "NP", re.compile(r"(("+NN+")/)*((DT|CD|CC|CJ)/)*(("+RB+"|"+JJ+")/)*(("+NN+")/)+(("+RB+"|"+JJ+")/)*")), ( "VP", re.compile(r"(((MD|"+RB+")/)*(("+VB+")/)+(("+RB+")/)*)+")), ( "VP", re.compile(r"((MD)/)")), ( "PP", re.compile(r"((IN|PP|TO)/)+")), ("ADJP", re.compile(r"((CC|CJ|"+RB+"|"+JJ+")/)*(("+JJ+")/)+")), ("ADVP", re.compile(r"(("+RB+"|WRB)/)+")), ]] CHUNKS[0].insert(1, CHUNKS[0].pop(3)) CHUNKS[1].insert(1, CHUNKS[1].pop(3)) The provided code snippet includes necessary dependencies for implementing the `find_chunks` function. Write a Python function `def find_chunks(tagged, language="en")` to solve the following problem: The input is a list of [token, tag]-items. The output is a list of [token, tag, chunk]-items: The/DT nice/JJ fish/NN is/VBZ dead/JJ ./. => The/DT/B-NP nice/JJ/I-NP fish/NN/I-NP is/VBZ/B-VP dead/JJ/B-ADJP ././O Here is the function: def find_chunks(tagged, language="en"): """ The input is a list of [token, tag]-items. The output is a list of [token, tag, chunk]-items: The/DT nice/JJ fish/NN is/VBZ dead/JJ ./. => The/DT/B-NP nice/JJ/I-NP fish/NN/I-NP is/VBZ/B-VP dead/JJ/B-ADJP ././O """ chunked = [x for x in tagged] tags = "".join("%s%s" % (tag, SEPARATOR) for token, tag in tagged) # Use Germanic or Romance chunking rules according to given language. for tag, rule in CHUNKS[int(language in ("ca", "es", "pt", "fr", "it", "pt", "ro"))]: for m in rule.finditer(tags): # Find the start of chunks inside the tags-string. # Number of preceding separators = number of preceding tokens. i = m.start() j = tags[:i].count(SEPARATOR) n = m.group(0).count(SEPARATOR) for k in range(j, j+n): if len(chunked[k]) == 3: continue if len(chunked[k]) < 3: # A conjunction can not be start of a chunk. if k == j and chunked[k][1] in ("CC", "CJ", "KON", "Conj(neven)"): j += 1 # Mark first token in chunk with B-. elif k == j: chunked[k].append("B-"+tag) # Mark other tokens in chunk with I-. else: chunked[k].append("I-"+tag) # Mark chinks (tokens outside of a chunk) with O-. for chink in filter(lambda x: len(x) < 3, chunked): chink.append("O") # Post-processing corrections. for i, (word, tag, chunk) in enumerate(chunked): if tag.startswith("RB") and chunk == "B-NP": # "Very nice work" (NP) <=> "Perhaps" (ADVP) + "you" (NP). if i < len(chunked)-1 and not chunked[i+1][1].startswith("JJ"): chunked[i+0][2] = "B-ADVP" chunked[i+1][2] = "B-NP" return chunked
The input is a list of [token, tag]-items. The output is a list of [token, tag, chunk]-items: The/DT nice/JJ fish/NN is/VBZ dead/JJ ./. => The/DT/B-NP nice/JJ/I-NP fish/NN/I-NP is/VBZ/B-VP dead/JJ/B-ADJP ././O
176,449
from __future__ import unicode_literals import string import codecs from itertools import chain import types import os import re from xml.etree import cElementTree from .compat import text_type, basestring, imap, unicode, binary_type, PY2 The provided code snippet includes necessary dependencies for implementing the `find_prepositions` function. Write a Python function `def find_prepositions(chunked)` to solve the following problem: The input is a list of [token, tag, chunk]-items. The output is a list of [token, tag, chunk, preposition]-items. PP-chunks followed by NP-chunks make up a PNP-chunk. Here is the function: def find_prepositions(chunked): """ The input is a list of [token, tag, chunk]-items. The output is a list of [token, tag, chunk, preposition]-items. PP-chunks followed by NP-chunks make up a PNP-chunk. """ # Tokens that are not part of a preposition just get the O-tag. for ch in chunked: ch.append("O") for i, chunk in enumerate(chunked): if chunk[2].endswith("PP") and chunk[-1] == "O": # Find PP followed by other PP, NP with nouns and pronouns, VP with a gerund. if i < len(chunked)-1 and \ (chunked[i+1][2].endswith(("NP", "PP")) or \ chunked[i+1][1] in ("VBG", "VBN")): chunk[-1] = "B-PNP" pp = True for ch in chunked[i+1:]: if not (ch[2].endswith(("NP", "PP")) or ch[1] in ("VBG", "VBN")): break if ch[2].endswith("PP") and pp: ch[-1] = "I-PNP" if not ch[2].endswith("PP"): ch[-1] = "I-PNP" pp = False return chunked
The input is a list of [token, tag, chunk]-items. The output is a list of [token, tag, chunk, preposition]-items. PP-chunks followed by NP-chunks make up a PNP-chunk.
176,451
import typing as t from . import Markup def escape(s: t.Any) -> Markup: """Replace the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in the string with HTML-safe sequences. Use this if you need to display text that might contain such characters in HTML. If the object has an ``__html__`` method, it is called and the return value is assumed to already be safe for HTML. :param s: An object to be converted to a string and escaped. :return: A :class:`Markup` string with the escaped text. """ if hasattr(s, "__html__"): return Markup(s.__html__()) return Markup( str(s) .replace("&", "&amp;") .replace(">", "&gt;") .replace("<", "&lt;") .replace("'", "&#39;") .replace('"', "&#34;") ) The provided code snippet includes necessary dependencies for implementing the `escape_silent` function. Write a Python function `def escape_silent(s: t.Optional[t.Any]) -> Markup` to solve the following problem: Like :func:`escape` but treats ``None`` as the empty string. Useful with optional values, as otherwise you get the string ``'None'`` when the value is ``None``. >>> escape(None) Markup('None') >>> escape_silent(None) Markup('') Here is the function: def escape_silent(s: t.Optional[t.Any]) -> Markup: """Like :func:`escape` but treats ``None`` as the empty string. Useful with optional values, as otherwise you get the string ``'None'`` when the value is ``None``. >>> escape(None) Markup('None') >>> escape_silent(None) Markup('') """ if s is None: return Markup() return escape(s)
Like :func:`escape` but treats ``None`` as the empty string. Useful with optional values, as otherwise you get the string ``'None'`` when the value is ``None``. >>> escape(None) Markup('None') >>> escape_silent(None) Markup('')
176,452
import typing as t from . import Markup The provided code snippet includes necessary dependencies for implementing the `soft_str` function. Write a Python function `def soft_str(s: t.Any) -> str` to solve the following problem: Convert an object to a string if it isn't already. This preserves a :class:`Markup` string rather than converting it back to a basic string, so it will still be marked as safe and won't be escaped again. >>> value = escape("<User 1>") >>> value Markup('&lt;User 1&gt;') >>> escape(str(value)) Markup('&amp;lt;User 1&amp;gt;') >>> escape(soft_str(value)) Markup('&lt;User 1&gt;') Here is the function: def soft_str(s: t.Any) -> str: """Convert an object to a string if it isn't already. This preserves a :class:`Markup` string rather than converting it back to a basic string, so it will still be marked as safe and won't be escaped again. >>> value = escape("<User 1>") >>> value Markup('&lt;User 1&gt;') >>> escape(str(value)) Markup('&amp;lt;User 1&amp;gt;') >>> escape(soft_str(value)) Markup('&lt;User 1&gt;') """ if not isinstance(s, str): return str(s) return s
Convert an object to a string if it isn't already. This preserves a :class:`Markup` string rather than converting it back to a basic string, so it will still be marked as safe and won't be escaped again. >>> value = escape("<User 1>") >>> value Markup('&lt;User 1&gt;') >>> escape(str(value)) Markup('&amp;lt;User 1&amp;gt;') >>> escape(soft_str(value)) Markup('&lt;User 1&gt;')
176,453
from textwrap import dedent from parso import split_lines from jedi import debug from jedi.api.exceptions import RefactoringError from jedi.api.refactoring import Refactoring, EXPRESSION_PARTS from jedi.common import indent_block from jedi.parser_utils import function_is_classmethod, function_is_staticmethod def _is_expression_with_error(nodes): """ Returns a tuple (is_expression, error_string). """ if any(node.type == 'name' and node.is_definition() for node in nodes): return False, 'Cannot extract a name that defines something' if nodes[0].type not in _VARIABLE_EXCTRACTABLE: return False, 'Cannot extract a "%s"' % nodes[0].type return True, '' def _find_nodes(module_node, pos, until_pos): """ Looks up a module and tries to find the appropriate amount of nodes that are in there. """ start_node = module_node.get_leaf_for_position(pos, include_prefixes=True) if until_pos is None: if start_node.type == 'operator': next_leaf = start_node.get_next_leaf() if next_leaf is not None and next_leaf.start_pos == pos: start_node = next_leaf if _is_not_extractable_syntax(start_node): start_node = start_node.parent if start_node.parent.type == 'trailer': start_node = start_node.parent.parent while start_node.parent.type in EXPRESSION_PARTS: start_node = start_node.parent nodes = [start_node] else: # Get the next leaf if we are at the end of a leaf if start_node.end_pos == pos: next_leaf = start_node.get_next_leaf() if next_leaf is not None: start_node = next_leaf # Some syntax is not exactable, just use its parent if _is_not_extractable_syntax(start_node): start_node = start_node.parent # Find the end end_leaf = module_node.get_leaf_for_position(until_pos, include_prefixes=True) if end_leaf.start_pos > until_pos: end_leaf = end_leaf.get_previous_leaf() if end_leaf is None: raise RefactoringError('Cannot extract anything from that') parent_node = start_node while parent_node.end_pos < end_leaf.end_pos: parent_node = parent_node.parent nodes = _remove_unwanted_expression_nodes(parent_node, pos, until_pos) # If the user marks just a return statement, we return the expression # instead of the whole statement, because the user obviously wants to # extract that part. if len(nodes) == 1 and start_node.type in ('return_stmt', 'yield_expr'): return [nodes[0].children[1]] return nodes def _replace(nodes, expression_replacement, extracted, pos, insert_before_leaf=None, remaining_prefix=None): # Now try to replace the nodes found with a variable and move the code # before the current statement. definition = _get_parent_definition(nodes[0]) if insert_before_leaf is None: insert_before_leaf = definition.get_first_leaf() first_node_leaf = nodes[0].get_first_leaf() lines = split_lines(insert_before_leaf.prefix, keepends=True) if first_node_leaf is insert_before_leaf: if remaining_prefix is not None: # The remaining prefix has already been calculated. lines[:-1] = remaining_prefix lines[-1:-1] = [indent_block(extracted, lines[-1]) + '\n'] extracted_prefix = ''.join(lines) replacement_dct = {} if first_node_leaf is insert_before_leaf: replacement_dct[nodes[0]] = extracted_prefix + expression_replacement else: if remaining_prefix is None: p = first_node_leaf.prefix else: p = remaining_prefix + _get_indentation(nodes[0]) replacement_dct[nodes[0]] = p + expression_replacement replacement_dct[insert_before_leaf] = extracted_prefix + insert_before_leaf.value for node in nodes[1:]: replacement_dct[node] = '' return replacement_dct def _expression_nodes_to_string(nodes): return ''.join(n.get_code(include_prefix=i != 0) for i, n in enumerate(nodes)) class RefactoringError(_JediError): """ Refactorings can fail for various reasons. So if you work with refactorings like :meth:`.Script.rename`, :meth:`.Script.inline`, :meth:`.Script.extract_variable` and :meth:`.Script.extract_function`, make sure to catch these. The descriptions in the errors are usually valuable for end users. A typical ``RefactoringError`` would tell the user that inlining is not possible if no name is under the cursor. """ class Refactoring: def __init__(self, inference_state, file_to_node_changes, renames=()): self._inference_state = inference_state self._renames = renames self._file_to_node_changes = file_to_node_changes def get_changed_files(self) -> Dict[Path, ChangedFile]: def calculate_to_path(p): if p is None: return p p = str(p) for from_, to in renames: if p.startswith(str(from_)): p = str(to) + p[len(str(from_)):] return Path(p) renames = self.get_renames() return { path: ChangedFile( self._inference_state, from_path=path, to_path=calculate_to_path(path), module_node=next(iter(map_)).get_root_node(), node_to_str_map=map_ ) for path, map_ in sorted(self._file_to_node_changes.items()) } def get_renames(self) -> Iterable[Tuple[Path, Path]]: """ Files can be renamed in a refactoring. """ return sorted(self._renames) def get_diff(self): text = '' project_path = self._inference_state.project.path for from_, to in self.get_renames(): text += 'rename from %s\nrename to %s\n' \ % (from_.relative_to(project_path), to.relative_to(project_path)) return text + ''.join(f.get_diff() for f in self.get_changed_files().values()) def apply(self): """ Applies the whole refactoring to the files, which includes renames. """ for f in self.get_changed_files().values(): f.apply() for old, new in self.get_renames(): old.rename(new) def extract_variable(inference_state, path, module_node, name, pos, until_pos): nodes = _find_nodes(module_node, pos, until_pos) debug.dbg('Extracting nodes: %s', nodes) is_expression, message = _is_expression_with_error(nodes) if not is_expression: raise RefactoringError(message) generated_code = name + ' = ' + _expression_nodes_to_string(nodes) file_to_node_changes = {path: _replace(nodes, name, generated_code, pos)} return Refactoring(inference_state, file_to_node_changes)
null
176,454
from textwrap import dedent from parso import split_lines from jedi import debug from jedi.api.exceptions import RefactoringError from jedi.api.refactoring import Refactoring, EXPRESSION_PARTS from jedi.common import indent_block from jedi.parser_utils import function_is_classmethod, function_is_staticmethod def _is_expression_with_error(nodes): """ Returns a tuple (is_expression, error_string). """ if any(node.type == 'name' and node.is_definition() for node in nodes): return False, 'Cannot extract a name that defines something' if nodes[0].type not in _VARIABLE_EXCTRACTABLE: return False, 'Cannot extract a "%s"' % nodes[0].type return True, '' def _find_nodes(module_node, pos, until_pos): """ Looks up a module and tries to find the appropriate amount of nodes that are in there. """ start_node = module_node.get_leaf_for_position(pos, include_prefixes=True) if until_pos is None: if start_node.type == 'operator': next_leaf = start_node.get_next_leaf() if next_leaf is not None and next_leaf.start_pos == pos: start_node = next_leaf if _is_not_extractable_syntax(start_node): start_node = start_node.parent if start_node.parent.type == 'trailer': start_node = start_node.parent.parent while start_node.parent.type in EXPRESSION_PARTS: start_node = start_node.parent nodes = [start_node] else: # Get the next leaf if we are at the end of a leaf if start_node.end_pos == pos: next_leaf = start_node.get_next_leaf() if next_leaf is not None: start_node = next_leaf # Some syntax is not exactable, just use its parent if _is_not_extractable_syntax(start_node): start_node = start_node.parent # Find the end end_leaf = module_node.get_leaf_for_position(until_pos, include_prefixes=True) if end_leaf.start_pos > until_pos: end_leaf = end_leaf.get_previous_leaf() if end_leaf is None: raise RefactoringError('Cannot extract anything from that') parent_node = start_node while parent_node.end_pos < end_leaf.end_pos: parent_node = parent_node.parent nodes = _remove_unwanted_expression_nodes(parent_node, pos, until_pos) # If the user marks just a return statement, we return the expression # instead of the whole statement, because the user obviously wants to # extract that part. if len(nodes) == 1 and start_node.type in ('return_stmt', 'yield_expr'): return [nodes[0].children[1]] return nodes def _replace(nodes, expression_replacement, extracted, pos, insert_before_leaf=None, remaining_prefix=None): # Now try to replace the nodes found with a variable and move the code # before the current statement. definition = _get_parent_definition(nodes[0]) if insert_before_leaf is None: insert_before_leaf = definition.get_first_leaf() first_node_leaf = nodes[0].get_first_leaf() lines = split_lines(insert_before_leaf.prefix, keepends=True) if first_node_leaf is insert_before_leaf: if remaining_prefix is not None: # The remaining prefix has already been calculated. lines[:-1] = remaining_prefix lines[-1:-1] = [indent_block(extracted, lines[-1]) + '\n'] extracted_prefix = ''.join(lines) replacement_dct = {} if first_node_leaf is insert_before_leaf: replacement_dct[nodes[0]] = extracted_prefix + expression_replacement else: if remaining_prefix is None: p = first_node_leaf.prefix else: p = remaining_prefix + _get_indentation(nodes[0]) replacement_dct[nodes[0]] = p + expression_replacement replacement_dct[insert_before_leaf] = extracted_prefix + insert_before_leaf.value for node in nodes[1:]: replacement_dct[node] = '' return replacement_dct def _expression_nodes_to_string(nodes): return ''.join(n.get_code(include_prefix=i != 0) for i, n in enumerate(nodes)) def _suite_nodes_to_string(nodes, pos): n = nodes[0] prefix, part_of_code = _split_prefix_at(n.get_first_leaf(), pos[0] - 1) code = part_of_code + n.get_code(include_prefix=False) \ + ''.join(n.get_code() for n in nodes[1:]) return prefix, code def _split_prefix_at(leaf, until_line): """ Returns a tuple of the leaf's prefix, split at the until_line position. """ # second means the second returned part second_line_count = leaf.start_pos[0] - until_line lines = split_lines(leaf.prefix, keepends=True) return ''.join(lines[:-second_line_count]), ''.join(lines[-second_line_count:]) def _check_for_non_extractables(nodes): for n in nodes: try: children = n.children except AttributeError: if n.value == 'return': raise RefactoringError( 'Can only extract return statements if they are at the end.') if n.value == 'yield': raise RefactoringError('Cannot extract yield statements.') else: _check_for_non_extractables(children) def _find_inputs_and_outputs(module_context, context, nodes): first = nodes[0].start_pos last = nodes[-1].end_pos inputs = [] outputs = [] for name in _find_non_global_names(nodes): if name.is_definition(): if name not in outputs: outputs.append(name.value) else: if name.value not in inputs: name_definitions = context.goto(name, name.start_pos) if not name_definitions \ or _is_name_input(module_context, name_definitions, first, last): inputs.append(name.value) # Check if outputs are really needed: return inputs, outputs def _get_code_insertion_node(node, is_bound_method): if not is_bound_method or function_is_staticmethod(node): while node.parent.type != 'file_input': node = node.parent while node.parent.type in ('async_funcdef', 'decorated', 'async_stmt'): node = node.parent return node def _find_needed_output_variables(context, search_node, at_least_pos, return_variables): """ Searches everything after at_least_pos in a node and checks if any of the return_variables are used in there and returns those. """ for node in search_node.children: if node.start_pos < at_least_pos: continue return_variables = set(return_variables) for name in _find_non_global_names([node]): if not name.is_definition() and name.value in return_variables: return_variables.remove(name.value) yield name.value def _is_node_ending_return_stmt(node): t = node.type if t == 'simple_stmt': return _is_node_ending_return_stmt(node.children[0]) return t == 'return_stmt' def dedent(text: str) -> str: ... class Refactoring: def __init__(self, inference_state, file_to_node_changes, renames=()): self._inference_state = inference_state self._renames = renames self._file_to_node_changes = file_to_node_changes def get_changed_files(self) -> Dict[Path, ChangedFile]: def calculate_to_path(p): if p is None: return p p = str(p) for from_, to in renames: if p.startswith(str(from_)): p = str(to) + p[len(str(from_)):] return Path(p) renames = self.get_renames() return { path: ChangedFile( self._inference_state, from_path=path, to_path=calculate_to_path(path), module_node=next(iter(map_)).get_root_node(), node_to_str_map=map_ ) for path, map_ in sorted(self._file_to_node_changes.items()) } def get_renames(self) -> Iterable[Tuple[Path, Path]]: """ Files can be renamed in a refactoring. """ return sorted(self._renames) def get_diff(self): text = '' project_path = self._inference_state.project.path for from_, to in self.get_renames(): text += 'rename from %s\nrename to %s\n' \ % (from_.relative_to(project_path), to.relative_to(project_path)) return text + ''.join(f.get_diff() for f in self.get_changed_files().values()) def apply(self): """ Applies the whole refactoring to the files, which includes renames. """ for f in self.get_changed_files().values(): f.apply() for old, new in self.get_renames(): old.rename(new) def indent_block(text, indention=' '): """This function indents a text block with a default of four spaces.""" temp = '' while text and text[-1] == '\n': temp += text[-1] text = text[:-1] lines = text.split('\n') return '\n'.join(map(lambda s: indention + s, lines)) + temp function_is_staticmethod = _function_is_x_method('staticmethod') function_is_classmethod = _function_is_x_method('classmethod') def extract_function(inference_state, path, module_context, name, pos, until_pos): nodes = _find_nodes(module_context.tree_node, pos, until_pos) assert len(nodes) is_expression, _ = _is_expression_with_error(nodes) context = module_context.create_context(nodes[0]) is_bound_method = context.is_bound_method() params, return_variables = list(_find_inputs_and_outputs(module_context, context, nodes)) # Find variables # Is a class method / method if context.is_module(): insert_before_leaf = None # Leaf will be determined later else: node = _get_code_insertion_node(context.tree_node, is_bound_method) insert_before_leaf = node.get_first_leaf() if is_expression: code_block = 'return ' + _expression_nodes_to_string(nodes) + '\n' remaining_prefix = None has_ending_return_stmt = False else: has_ending_return_stmt = _is_node_ending_return_stmt(nodes[-1]) if not has_ending_return_stmt: # Find the actually used variables (of the defined ones). If none are # used (e.g. if the range covers the whole function), return the last # defined variable. return_variables = list(_find_needed_output_variables( context, nodes[0].parent, nodes[-1].end_pos, return_variables )) or [return_variables[-1]] if return_variables else [] remaining_prefix, code_block = _suite_nodes_to_string(nodes, pos) after_leaf = nodes[-1].get_next_leaf() first, second = _split_prefix_at(after_leaf, until_pos[0]) code_block += first code_block = dedent(code_block) if not has_ending_return_stmt: output_var_str = ', '.join(return_variables) code_block += 'return ' + output_var_str + '\n' # Check if we have to raise RefactoringError _check_for_non_extractables(nodes[:-1] if has_ending_return_stmt else nodes) decorator = '' self_param = None if is_bound_method: if not function_is_staticmethod(context.tree_node): function_param_names = context.get_value().get_param_names() if len(function_param_names): self_param = function_param_names[0].string_name params = [p for p in params if p != self_param] if function_is_classmethod(context.tree_node): decorator = '@classmethod\n' else: code_block += '\n' function_code = '%sdef %s(%s):\n%s' % ( decorator, name, ', '.join(params if self_param is None else [self_param] + params), indent_block(code_block) ) function_call = '%s(%s)' % ( ('' if self_param is None else self_param + '.') + name, ', '.join(params) ) if is_expression: replacement = function_call else: if has_ending_return_stmt: replacement = 'return ' + function_call + '\n' else: replacement = output_var_str + ' = ' + function_call + '\n' replacement_dct = _replace(nodes, replacement, function_code, pos, insert_before_leaf, remaining_prefix) if not is_expression: replacement_dct[after_leaf] = second + after_leaf.value file_to_node_changes = {path: replacement_dct} return Refactoring(inference_state, file_to_node_changes)
null
176,455
import pydoc from contextlib import suppress from typing import Dict, Optional from jedi.inference.names import AbstractArbitraryName The provided code snippet includes necessary dependencies for implementing the `imitate_pydoc` function. Write a Python function `def imitate_pydoc(string)` to solve the following problem: It's not possible to get the pydoc's without starting the annoying pager stuff. Here is the function: def imitate_pydoc(string): """ It's not possible to get the pydoc's without starting the annoying pager stuff. """ if pydoc_topics is None: return '' h = pydoc.help with suppress(KeyError): # try to access symbols string = h.symbols[string] string, _, related = string.partition(' ') def get_target(s): return h.topics.get(s, h.keywords.get(s)) while isinstance(string, str): string = get_target(string) try: # is a tuple now label, related = string except TypeError: return '' try: return pydoc_topics[label].strip() if pydoc_topics else '' except KeyError: return ''
It's not possible to get the pydoc's without starting the annoying pager stuff.
176,456
from jedi.inference import compiled from jedi.inference.base_value import ValueSet from jedi.inference.filters import ParserTreeFilter, MergedFilter from jedi.inference.names import TreeNameDefinition from jedi.inference.compiled import mixed from jedi.inference.compiled.access import create_access_path from jedi.inference.context import ModuleContext def create_access_path(inference_state, obj): def _create(inference_state, obj): return compiled.create_from_access_path( inference_state, create_access_path(inference_state, obj) )
null
176,457
from typing import Dict, Tuple, Callable CacheValuesCallback = Callable[[], CacheValues] _cache: Dict[str, Dict[str, CacheValues]] = {} def save_entry(module_name: str, name: str, cache: CacheValues) -> None: try: module_cache = _cache[module_name] except KeyError: module_cache = _cache[module_name] = {} module_cache[name] = cache class Callable(BaseTypingInstance): def py__call__(self, arguments): """ def x() -> Callable[[Callable[..., _T]], _T]: ... """ # The 0th index are the arguments. try: param_values = self._generics_manager[0] result_values = self._generics_manager[1] except IndexError: debug.warning('Callable[...] defined without two arguments') return NO_VALUES else: from jedi.inference.gradual.annotation import infer_return_for_callable return infer_return_for_callable(arguments, param_values, result_values) def py__get__(self, instance, class_value): return ValueSet([self]) def _create_get_from_cache(number: int) -> Callable[[str, str, CacheValuesCallback], str]: def _get_from_cache(module_name: str, name: str, get_cache_values: CacheValuesCallback) -> str: try: return _cache[module_name][name][number] except KeyError: v = get_cache_values() save_entry(module_name, name, v) return v[number] return _get_from_cache
null
176,458
import os import sys import hashlib import filecmp from collections import namedtuple from shutil import which from jedi.cache import memoize_method, time_cache from jedi.inference.compiled.subprocess import CompiledSubprocess, \ InferenceStateSameProcess, InferenceStateSubprocess import parso import sys if sys.version_info >= (3, 8): # pragma: no branch from typing import Literal # pragma: no cover def _get_info(): return ( sys.executable, sys.prefix, sys.version_info[:3], )
null
176,459
import os import sys import hashlib import filecmp from collections import namedtuple from shutil import which from jedi.cache import memoize_method, time_cache from jedi.inference.compiled.subprocess import CompiledSubprocess, \ InferenceStateSameProcess, InferenceStateSubprocess import parso _CONDA_VAR = 'CONDA_PREFIX' def _get_cached_default_environment(): try: return get_default_environment() except InvalidPythonEnvironment: # It's possible that `sys.executable` is wrong. Typically happens # when Jedi is used in an executable that embeds Python. For further # information, have a look at: # https://github.com/davidhalter/jedi/issues/1531 return InterpreterEnvironment() def get_cached_default_environment(): var = os.environ.get('VIRTUAL_ENV') or os.environ.get(_CONDA_VAR) environment = _get_cached_default_environment() # Under macOS in some cases - notably when using Pipenv - the # sys.prefix of the virtualenv is /path/to/env/bin/.. instead of # /path/to/env so we need to fully resolve the paths in order to # compare them. if var and os.path.realpath(var) != os.path.realpath(environment.path): _get_cached_default_environment.clear_cache() return _get_cached_default_environment() return environment
null
176,460
import os import sys import hashlib import filecmp from collections import namedtuple from shutil import which from jedi.cache import memoize_method, time_cache from jedi.inference.compiled.subprocess import CompiledSubprocess, \ InferenceStateSameProcess, InferenceStateSubprocess import parso _CONDA_VAR = 'CONDA_PREFIX' class InvalidPythonEnvironment(Exception): """ If you see this exception, the Python executable or Virtualenv you have been trying to use is probably not a correct Python version. """ class Environment(_BaseEnvironment): """ This class is supposed to be created by internal Jedi architecture. You should not create it directly. Please use create_environment or the other functions instead. It is then returned by that function. """ _subprocess = None def __init__(self, executable, env_vars=None): self._start_executable = executable self._env_vars = env_vars # Initialize the environment self._get_subprocess() def _get_subprocess(self): if self._subprocess is not None and not self._subprocess.is_crashed: return self._subprocess try: self._subprocess = CompiledSubprocess(self._start_executable, env_vars=self._env_vars) info = self._subprocess._send(None, _get_info) except Exception as exc: raise InvalidPythonEnvironment( "Could not get version information for %r: %r" % ( self._start_executable, exc)) # Since it could change and might not be the same(?) as the one given, # set it here. self.executable = info[0] """ The Python executable, matches ``sys.executable``. """ self.path = info[1] """ The path to an environment, matches ``sys.prefix``. """ self.version_info = _VersionInfo(*info[2]) """ Like :data:`sys.version_info`: a tuple to show the current Environment's Python version. """ return self._subprocess def __repr__(self): version = '.'.join(str(i) for i in self.version_info) return '<%s: %s in %s>' % (self.__class__.__name__, version, self.path) def get_inference_state_subprocess(self, inference_state): return InferenceStateSubprocess(inference_state, self._get_subprocess()) def get_sys_path(self): """ The sys path for this environment. Does not include potential modifications from e.g. appending to :data:`sys.path`. :returns: list of str """ # It's pretty much impossible to generate the sys path without actually # executing Python. The sys path (when starting with -S) itself depends # on how the Python version was compiled (ENV variables). # If you omit -S when starting Python (normal case), additionally # site.py gets executed. return self._get_subprocess().get_sys_path() def _get_virtual_env_from_var(env_var='VIRTUAL_ENV'): """Get virtualenv environment from VIRTUAL_ENV environment variable. It uses `safe=False` with ``create_environment``, because the environment variable is considered to be safe / controlled by the user solely. """ var = os.environ.get(env_var) if var: # Under macOS in some cases - notably when using Pipenv - the # sys.prefix of the virtualenv is /path/to/env/bin/.. instead of # /path/to/env so we need to fully resolve the paths in order to # compare them. if os.path.realpath(var) == os.path.realpath(sys.prefix): return _try_get_same_env() try: return create_environment(var, safe=False) except InvalidPythonEnvironment: pass def _get_executable_path(path, safe=True): """ Returns None if it's not actually a virtual env. """ if os.name == 'nt': python = os.path.join(path, 'Scripts', 'python.exe') else: python = os.path.join(path, 'bin', 'python') if not os.path.exists(python): raise InvalidPythonEnvironment("%s seems to be missing." % python) _assert_safe(python, safe) return python The provided code snippet includes necessary dependencies for implementing the `find_virtualenvs` function. Write a Python function `def find_virtualenvs(paths=None, *, safe=True, use_environment_vars=True)` to solve the following problem: :param paths: A list of paths in your file system to be scanned for Virtualenvs. It will search in these paths and potentially execute the Python binaries. :param safe: Default True. In case this is False, it will allow this function to execute potential `python` environments. An attacker might be able to drop an executable in a path this function is searching by default. If the executable has not been installed by root, it will not be executed. :param use_environment_vars: Default True. If True, the VIRTUAL_ENV variable will be checked if it contains a valid VirtualEnv. CONDA_PREFIX will be checked to see if it contains a valid conda environment. :yields: :class:`.Environment` Here is the function: def find_virtualenvs(paths=None, *, safe=True, use_environment_vars=True): """ :param paths: A list of paths in your file system to be scanned for Virtualenvs. It will search in these paths and potentially execute the Python binaries. :param safe: Default True. In case this is False, it will allow this function to execute potential `python` environments. An attacker might be able to drop an executable in a path this function is searching by default. If the executable has not been installed by root, it will not be executed. :param use_environment_vars: Default True. If True, the VIRTUAL_ENV variable will be checked if it contains a valid VirtualEnv. CONDA_PREFIX will be checked to see if it contains a valid conda environment. :yields: :class:`.Environment` """ if paths is None: paths = [] _used_paths = set() if use_environment_vars: # Using this variable should be safe, because attackers might be # able to drop files (via git) but not environment variables. virtual_env = _get_virtual_env_from_var() if virtual_env is not None: yield virtual_env _used_paths.add(virtual_env.path) conda_env = _get_virtual_env_from_var(_CONDA_VAR) if conda_env is not None: yield conda_env _used_paths.add(conda_env.path) for directory in paths: if not os.path.isdir(directory): continue directory = os.path.abspath(directory) for path in os.listdir(directory): path = os.path.join(directory, path) if path in _used_paths: # A path shouldn't be inferred twice. continue _used_paths.add(path) try: executable = _get_executable_path(path, safe=safe) yield Environment(executable) except InvalidPythonEnvironment: pass
:param paths: A list of paths in your file system to be scanned for Virtualenvs. It will search in these paths and potentially execute the Python binaries. :param safe: Default True. In case this is False, it will allow this function to execute potential `python` environments. An attacker might be able to drop an executable in a path this function is searching by default. If the executable has not been installed by root, it will not be executed. :param use_environment_vars: Default True. If True, the VIRTUAL_ENV variable will be checked if it contains a valid VirtualEnv. CONDA_PREFIX will be checked to see if it contains a valid conda environment. :yields: :class:`.Environment`
176,461
class SyntaxError: """ Syntax errors are generated by :meth:`.Script.get_syntax_errors`. """ def __init__(self, parso_error): self._parso_error = parso_error def line(self): """The line where the error starts (starting with 1).""" return self._parso_error.start_pos[0] def column(self): """The column where the error starts (starting with 0).""" return self._parso_error.start_pos[1] def until_line(self): """The line where the error ends (starting with 1).""" return self._parso_error.end_pos[0] def until_column(self): """The column where the error ends (starting with 0).""" return self._parso_error.end_pos[1] def get_message(self): return self._parso_error.message def __repr__(self): return '<%s from=%s to=%s>' % ( self.__class__.__name__, self._parso_error.start_pos, self._parso_error.end_pos, ) def parso_to_jedi_errors(grammar, module_node): return [SyntaxError(e) for e in grammar.iter_errors(module_node)]
null
176,462
import os from jedi.api import classes from jedi.api.strings import StringName, get_quote_ending from jedi.api.helpers import match from jedi.inference.helpers import get_str_or_none class PathName(StringName): def _get_string_additions(module_context, start_leaf): def _add_os_path_join(module_context, start_leaf, bracket_start): def get_quote_ending(string, code_lines, position, invert_result=False): def match(string, like_name, fuzzy=False): def complete_file_name(inference_state, module_context, start_leaf, quote, string, like_name, signatures_callback, code_lines, position, fuzzy): # First we want to find out what can actually be changed as a name. like_name_length = len(os.path.basename(string)) addition = _get_string_additions(module_context, start_leaf) if string.startswith('~'): string = os.path.expanduser(string) if addition is None: return string = addition + string # Here we use basename again, because if strings are added like # `'foo' + 'bar`, it should complete to `foobar/`. must_start_with = os.path.basename(string) string = os.path.dirname(string) sigs = signatures_callback(*position) is_in_os_path_join = sigs and all(s.full_name == 'os.path.join' for s in sigs) if is_in_os_path_join: to_be_added = _add_os_path_join(module_context, start_leaf, sigs[0].bracket_start) if to_be_added is None: is_in_os_path_join = False else: string = to_be_added + string base_path = os.path.join(inference_state.project.path, string) try: listed = sorted(os.scandir(base_path), key=lambda e: e.name) # OSError: [Errno 36] File name too long: '...' except (FileNotFoundError, OSError): return quote_ending = get_quote_ending(quote, code_lines, position) for entry in listed: name = entry.name if match(name, must_start_with, fuzzy=fuzzy): if is_in_os_path_join or not entry.is_dir(): name += quote_ending else: name += os.path.sep yield classes.Completion( inference_state, PathName(inference_state, name[len(must_start_with) - like_name_length:]), stack=None, like_name_length=like_name_length, is_fuzzy=fuzzy, )
null
176,463
import json from pathlib import Path from itertools import chain from jedi import debug from jedi.api.environment import get_cached_default_environment, create_environment from jedi.api.exceptions import WrongVersion from jedi.api.completion import search_in_module from jedi.api.helpers import split_search_string, get_module_names from jedi.inference.imports import load_module_from_path, \ load_namespace_from_path, iter_module_names from jedi.inference.sys_path import discover_buildout_paths from jedi.inference.cache import inference_state_as_method_param_cache from jedi.inference.references import recurse_find_python_folders_and_files, search_in_file_ios from jedi.file_io import FolderIO def _try_to_skip_duplicates(func): def wrapper(*args, **kwargs): found_tree_nodes = [] found_modules = [] for definition in func(*args, **kwargs): tree_node = definition._name.tree_name if tree_node is not None and tree_node in found_tree_nodes: continue if definition.type == 'module' and definition.module_path is not None: if definition.module_path in found_modules: continue found_modules.append(definition.module_path) yield definition found_tree_nodes.append(tree_node) return wrapper
null
176,464
import json from pathlib import Path from itertools import chain from jedi import debug from jedi.api.environment import get_cached_default_environment, create_environment from jedi.api.exceptions import WrongVersion from jedi.api.completion import search_in_module from jedi.api.helpers import split_search_string, get_module_names from jedi.inference.imports import load_module_from_path, \ load_namespace_from_path, iter_module_names from jedi.inference.sys_path import discover_buildout_paths from jedi.inference.cache import inference_state_as_method_param_cache from jedi.inference.references import recurse_find_python_folders_and_files, search_in_file_ios from jedi.file_io import FolderIO def _remove_duplicates_from_path(path): used = set() for p in path: if p in used: continue used.add(p) yield p
null
176,465
import json from pathlib import Path from itertools import chain from jedi import debug from jedi.api.environment import get_cached_default_environment, create_environment from jedi.api.exceptions import WrongVersion from jedi.api.completion import search_in_module from jedi.api.helpers import split_search_string, get_module_names from jedi.inference.imports import load_module_from_path, \ load_namespace_from_path, iter_module_names from jedi.inference.sys_path import discover_buildout_paths from jedi.inference.cache import inference_state_as_method_param_cache from jedi.inference.references import recurse_find_python_folders_and_files, search_in_file_ios from jedi.file_io import FolderIO class Project: """ Projects are a simple way to manage Python folders and define how Jedi does import resolution. It is mostly used as a parameter to :class:`.Script`. Additionally there are functions to search a whole project. """ _environment = None def _get_config_folder_path(base_path): return base_path.joinpath(_CONFIG_FOLDER) def _get_json_path(base_path): return Project._get_config_folder_path(base_path).joinpath('project.json') def load(cls, path): """ Loads a project from a specific path. You should not provide the path to ``.jedi/project.json``, but rather the path to the project folder. :param path: The path of the directory you want to use as a project. """ if isinstance(path, str): path = Path(path) with open(cls._get_json_path(path)) as f: version, data = json.load(f) if version == 1: return cls(**data) else: raise WrongVersion( "The Jedi version of this project seems newer than what we can handle." ) def save(self): """ Saves the project configuration in the project in ``.jedi/project.json``. """ data = dict(self.__dict__) data.pop('_environment', None) data.pop('_django', None) # TODO make django setting public? data = {k.lstrip('_'): v for k, v in data.items()} data['path'] = str(data['path']) self._get_config_folder_path(self._path).mkdir(parents=True, exist_ok=True) with open(self._get_json_path(self._path), 'w') as f: return json.dump((_SERIALIZER_VERSION, data), f) def __init__( self, path, *, environment_path=None, load_unsafe_extensions=False, sys_path=None, added_sys_path=(), smart_sys_path=True, ) -> None: """ :param path: The base path for this project. :param environment_path: The Python executable path, typically the path of a virtual environment. :param load_unsafe_extensions: Default False, Loads extensions that are not in the sys path and in the local directories. With this option enabled, this is potentially unsafe if you clone a git repository and analyze it's code, because those compiled extensions will be important and therefore have execution privileges. :param sys_path: list of str. You can override the sys path if you want. By default the ``sys.path.`` is generated by the environment (virtualenvs, etc). :param added_sys_path: list of str. Adds these paths at the end of the sys path. :param smart_sys_path: If this is enabled (default), adds paths from local directories. Otherwise you will have to rely on your packages being properly configured on the ``sys.path``. """ if isinstance(path, str): path = Path(path).absolute() self._path = path self._environment_path = environment_path if sys_path is not None: # Remap potential pathlib.Path entries sys_path = list(map(str, sys_path)) self._sys_path = sys_path self._smart_sys_path = smart_sys_path self._load_unsafe_extensions = load_unsafe_extensions self._django = False # Remap potential pathlib.Path entries self.added_sys_path = list(map(str, added_sys_path)) """The sys path that is going to be added at the end of the """ def path(self): """ The base path for this project. """ return self._path def sys_path(self): """ The sys path provided to this project. This can be None and in that case will be auto generated. """ return self._sys_path def smart_sys_path(self): """ If the sys path is going to be calculated in a smart way, where additional paths are added. """ return self._smart_sys_path def load_unsafe_extensions(self): """ Wheter the project loads unsafe extensions. """ return self._load_unsafe_extensions def _get_base_sys_path(self, inference_state): # The sys path has not been set explicitly. sys_path = list(inference_state.environment.get_sys_path()) try: sys_path.remove('') except ValueError: pass return sys_path def _get_sys_path(self, inference_state, add_parent_paths=True, add_init_paths=False): """ Keep this method private for all users of jedi. However internally this one is used like a public method. """ suffixed = list(self.added_sys_path) prefixed = [] if self._sys_path is None: sys_path = list(self._get_base_sys_path(inference_state)) else: sys_path = list(self._sys_path) if self._smart_sys_path: prefixed.append(str(self._path)) if inference_state.script_path is not None: suffixed += map(str, discover_buildout_paths( inference_state, inference_state.script_path )) if add_parent_paths: # Collect directories in upward search by: # 1. Skipping directories with __init__.py # 2. Stopping immediately when above self._path traversed = [] for parent_path in inference_state.script_path.parents: if parent_path == self._path \ or self._path not in parent_path.parents: break if not add_init_paths \ and parent_path.joinpath("__init__.py").is_file(): continue traversed.append(str(parent_path)) # AFAIK some libraries have imports like `foo.foo.bar`, which # leads to the conclusion to by default prefer longer paths # rather than shorter ones by default. suffixed += reversed(traversed) if self._django: prefixed.append(str(self._path)) path = prefixed + sys_path + suffixed return list(_remove_duplicates_from_path(path)) def get_environment(self): if self._environment is None: if self._environment_path is not None: self._environment = create_environment(self._environment_path, safe=False) else: self._environment = get_cached_default_environment() return self._environment def search(self, string, *, all_scopes=False): """ Searches a name in the whole project. If the project is very big, at some point Jedi will stop searching. However it's also very much recommended to not exhaust the generator. Just display the first ten results to the user. There are currently three different search patterns: - ``foo`` to search for a definition foo in any file or a file called ``foo.py`` or ``foo.pyi``. - ``foo.bar`` to search for the ``foo`` and then an attribute ``bar`` in it. - ``class foo.bar.Bar`` or ``def foo.bar.baz`` to search for a specific API type. :param bool all_scopes: Default False; searches not only for definitions on the top level of a module level, but also in functions and classes. :yields: :class:`.Name` """ return self._search_func(string, all_scopes=all_scopes) def complete_search(self, string, **kwargs): """ Like :meth:`.Script.search`, but completes that string. An empty string lists all definitions in a project, so be careful with that. :param bool all_scopes: Default False; searches not only for definitions on the top level of a module level, but also in functions and classes. :yields: :class:`.Completion` """ return self._search_func(string, complete=True, **kwargs) def _search_func(self, string, complete=False, all_scopes=False): # Using a Script is they easiest way to get an empty module context. from jedi import Script s = Script('', project=self) inference_state = s._inference_state empty_module_context = s._get_module_context() debug.dbg('Search for string %s, complete=%s', string, complete) wanted_type, wanted_names = split_search_string(string) name = wanted_names[0] stub_folder_name = name + '-stubs' ios = recurse_find_python_folders_and_files(FolderIO(str(self._path))) file_ios = [] # 1. Search for modules in the current project for folder_io, file_io in ios: if file_io is None: file_name = folder_io.get_base_name() if file_name == name or file_name == stub_folder_name: f = folder_io.get_file_io('__init__.py') try: m = load_module_from_path(inference_state, f).as_context() except FileNotFoundError: f = folder_io.get_file_io('__init__.pyi') try: m = load_module_from_path(inference_state, f).as_context() except FileNotFoundError: m = load_namespace_from_path(inference_state, folder_io).as_context() else: continue else: file_ios.append(file_io) if Path(file_io.path).name in (name + '.py', name + '.pyi'): m = load_module_from_path(inference_state, file_io).as_context() else: continue debug.dbg('Search of a specific module %s', m) yield from search_in_module( inference_state, m, names=[m.name], wanted_type=wanted_type, wanted_names=wanted_names, complete=complete, convert=True, ignore_imports=True, ) # 2. Search for identifiers in the project. for module_context in search_in_file_ios(inference_state, file_ios, name, complete=complete): names = get_module_names(module_context.tree_node, all_scopes=all_scopes) names = [module_context.create_name(n) for n in names] names = _remove_imports(names) yield from search_in_module( inference_state, module_context, names=names, wanted_type=wanted_type, wanted_names=wanted_names, complete=complete, ignore_imports=True, ) # 3. Search for modules on sys.path sys_path = [ p for p in self._get_sys_path(inference_state) # Exclude the current folder which is handled by recursing the folders. if p != self._path ] names = list(iter_module_names(inference_state, empty_module_context, sys_path)) yield from search_in_module( inference_state, empty_module_context, names=names, wanted_type=wanted_type, wanted_names=wanted_names, complete=complete, convert=True, ) def __repr__(self): return '<%s: %s>' % (self.__class__.__name__, self._path) def _is_potential_project(path): for name in _CONTAINS_POTENTIAL_PROJECT: try: if path.joinpath(name).exists(): return True except OSError: continue return False def _is_django_path(directory): """ Detects the path of the very well known Django library (if used) """ try: with open(directory.joinpath('manage.py'), 'rb') as f: return b"DJANGO_SETTINGS_MODULE" in f.read() except (FileNotFoundError, IsADirectoryError, PermissionError): return False class Path(PurePath): def __new__(cls: Type[_P], *args: Union[str, _PathLike], **kwargs: Any) -> _P: ... def __enter__(self: _P) -> _P: ... def __exit__( self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType] ) -> Optional[bool]: ... def cwd(cls: Type[_P]) -> _P: ... def stat(self) -> os.stat_result: ... def chmod(self, mode: int) -> None: ... def exists(self) -> bool: ... def glob(self: _P, pattern: str) -> Generator[_P, None, None]: ... def group(self) -> str: ... def is_dir(self) -> bool: ... def is_file(self) -> bool: ... if sys.version_info >= (3, 7): def is_mount(self) -> bool: ... def is_symlink(self) -> bool: ... def is_socket(self) -> bool: ... def is_fifo(self) -> bool: ... def is_block_device(self) -> bool: ... def is_char_device(self) -> bool: ... def iterdir(self: _P) -> Generator[_P, None, None]: ... def lchmod(self, mode: int) -> None: ... def lstat(self) -> os.stat_result: ... def mkdir(self, mode: int = ..., parents: bool = ..., exist_ok: bool = ...) -> None: ... # Adapted from builtins.open # Text mode: always returns a TextIOWrapper def open( self, mode: OpenTextMode = ..., buffering: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., newline: Optional[str] = ..., ) -> TextIOWrapper: ... # Unbuffered binary mode: returns a FileIO def open( self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = ..., errors: None = ..., newline: None = ... ) -> FileIO: ... # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter def open( self, mode: OpenBinaryModeUpdating, buffering: Literal[-1, 1] = ..., encoding: None = ..., errors: None = ..., newline: None = ..., ) -> BufferedRandom: ... def open( self, mode: OpenBinaryModeWriting, buffering: Literal[-1, 1] = ..., encoding: None = ..., errors: None = ..., newline: None = ..., ) -> BufferedWriter: ... def open( self, mode: OpenBinaryModeReading, buffering: Literal[-1, 1] = ..., encoding: None = ..., errors: None = ..., newline: None = ..., ) -> BufferedReader: ... # Buffering cannot be determined: fall back to BinaryIO def open( self, mode: OpenBinaryMode, buffering: int, encoding: None = ..., errors: None = ..., newline: None = ... ) -> BinaryIO: ... # Fallback if mode is not specified def open( self, mode: str, buffering: int = ..., encoding: Optional[str] = ..., errors: Optional[str] = ..., newline: Optional[str] = ..., ) -> IO[Any]: ... def owner(self) -> str: ... if sys.version_info >= (3, 9): def readlink(self: _P) -> _P: ... if sys.version_info >= (3, 8): def rename(self: _P, target: Union[str, PurePath]) -> _P: ... def replace(self: _P, target: Union[str, PurePath]) -> _P: ... else: def rename(self, target: Union[str, PurePath]) -> None: ... def replace(self, target: Union[str, PurePath]) -> None: ... def resolve(self: _P, strict: bool = ...) -> _P: ... def rglob(self: _P, pattern: str) -> Generator[_P, None, None]: ... def rmdir(self) -> None: ... def symlink_to(self, target: Union[str, Path], target_is_directory: bool = ...) -> None: ... def touch(self, mode: int = ..., exist_ok: bool = ...) -> None: ... if sys.version_info >= (3, 8): def unlink(self, missing_ok: bool = ...) -> None: ... else: def unlink(self) -> None: ... def home(cls: Type[_P]) -> _P: ... def absolute(self: _P) -> _P: ... def expanduser(self: _P) -> _P: ... def read_bytes(self) -> bytes: ... def read_text(self, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> str: ... def samefile(self, other_path: Union[str, bytes, int, Path]) -> bool: ... def write_bytes(self, data: bytes) -> int: ... def write_text(self, data: str, encoding: Optional[str] = ..., errors: Optional[str] = ...) -> int: ... if sys.version_info >= (3, 8): def link_to(self, target: Union[str, bytes, os.PathLike[str]]) -> None: ... class chain(Iterator[_T], Generic[_T]): def __init__(self, *iterables: Iterable[_T]) -> None: ... def __next__(self) -> _T: ... def __iter__(self) -> Iterator[_T]: ... def from_iterable(iterable: Iterable[Iterable[_S]]) -> Iterator[_S]: ... The provided code snippet includes necessary dependencies for implementing the `get_default_project` function. Write a Python function `def get_default_project(path=None)` to solve the following problem: If a project is not defined by the user, Jedi tries to define a project by itself as well as possible. Jedi traverses folders until it finds one of the following: 1. A ``.jedi/config.json`` 2. One of the following files: ``setup.py``, ``.git``, ``.hg``, ``requirements.txt`` and ``MANIFEST.in``. Here is the function: def get_default_project(path=None): """ If a project is not defined by the user, Jedi tries to define a project by itself as well as possible. Jedi traverses folders until it finds one of the following: 1. A ``.jedi/config.json`` 2. One of the following files: ``setup.py``, ``.git``, ``.hg``, ``requirements.txt`` and ``MANIFEST.in``. """ if path is None: path = Path.cwd() elif isinstance(path, str): path = Path(path) check = path.absolute() probable_path = None first_no_init_file = None for dir in chain([check], check.parents): try: return Project.load(dir) except (FileNotFoundError, IsADirectoryError, PermissionError): pass except NotADirectoryError: continue if first_no_init_file is None: if dir.joinpath('__init__.py').exists(): # In the case that a __init__.py exists, it's in 99% just a # Python package and the project sits at least one level above. continue elif not dir.is_file(): first_no_init_file = dir if _is_django_path(dir): project = Project(dir) project._django = True return project if probable_path is None and _is_potential_project(dir): probable_path = dir if probable_path is not None: return Project(probable_path) if first_no_init_file is not None: return Project(first_no_init_file) curdir = path if path.is_dir() else path.parent return Project(curdir)
If a project is not defined by the user, Jedi tries to define a project by itself as well as possible. Jedi traverses folders until it finds one of the following: 1. A ``.jedi/config.json`` 2. One of the following files: ``setup.py``, ``.git``, ``.hg``, ``requirements.txt`` and ``MANIFEST.in``.
176,466
import json from pathlib import Path from itertools import chain from jedi import debug from jedi.api.environment import get_cached_default_environment, create_environment from jedi.api.exceptions import WrongVersion from jedi.api.completion import search_in_module from jedi.api.helpers import split_search_string, get_module_names from jedi.inference.imports import load_module_from_path, \ load_namespace_from_path, iter_module_names from jedi.inference.sys_path import discover_buildout_paths from jedi.inference.cache import inference_state_as_method_param_cache from jedi.inference.references import recurse_find_python_folders_and_files, search_in_file_ios from jedi.file_io import FolderIO def _remove_imports(names): return [ n for n in names if n.tree_name is None or n.api_type not in ('module', 'namespace') ]
null
176,467
import re from pathlib import Path from typing import Optional from parso.tree import search_ancestor from jedi import settings from jedi import debug from jedi.inference.utils import unite from jedi.cache import memoize_method from jedi.inference.compiled.mixed import MixedName from jedi.inference.names import ImportName, SubModuleName from jedi.inference.gradual.stub_value import StubModuleValue from jedi.inference.gradual.conversion import convert_names, convert_values from jedi.inference.base_value import ValueSet, HasNoContext from jedi.api.keywords import KeywordName from jedi.api import completion_cache from jedi.api.helpers import filter_follow_imports class Name(BaseName): def __init__(self, inference_state, definition): def defined_names(self): def is_definition(self): def __eq__(self, other): def __ne__(self, other): def __hash__(self): def _values_to_definitions(values): return [Name(c.inference_state, c.name) for c in values]
null
176,468
import re from jedi.inference.names import AbstractArbitraryName from jedi.inference.helpers import infer_call_of_leaf from jedi.api.classes import Completion from jedi.parser_utils import cut_value_at_position def _completions_for_dicts(inference_state, dicts, literal_string, cut_end_quote, fuzzy): for dict_key in sorted(_get_python_keys(dicts), key=lambda x: repr(x)): dict_key_str = _create_repr_string(literal_string, dict_key) if dict_key_str.startswith(literal_string): name = StringName(inference_state, dict_key_str[:-len(cut_end_quote) or None]) yield Completion( inference_state, name, stack=None, like_name_length=len(literal_string), is_fuzzy=fuzzy ) def get_quote_ending(string, code_lines, position, invert_result=False): _, quote = _get_string_prefix_and_quote(string) if quote is None: return '' # Add a quote only if it's not already there. if _matches_quote_at_position(code_lines, quote, position) != invert_result: return '' return quote def infer_call_of_leaf(context, leaf, cut_own_trailer=False): """ Creates a "call" node that consist of all ``trailer`` and ``power`` objects. E.g. if you call it with ``append``:: list([]).append(3) or None You would get a node with the content ``list([]).append`` back. This generates a copy of the original ast node. If you're using the leaf, e.g. the bracket `)` it will return ``list([])``. We use this function for two purposes. Given an expression ``bar.foo``, we may want to - infer the type of ``foo`` to offer completions after foo - infer the type of ``bar`` to be able to jump to the definition of foo The option ``cut_own_trailer`` must be set to true for the second purpose. """ trailer = leaf.parent if trailer.type == 'fstring': from jedi.inference import compiled return compiled.get_string_value_set(context.inference_state) # The leaf may not be the last or first child, because there exist three # different trailers: `( x )`, `[ x ]` and `.x`. In the first two examples # we should not match anything more than x. if trailer.type != 'trailer' or leaf not in (trailer.children[0], trailer.children[-1]): if leaf == ':': # Basically happens with foo[:] when the cursor is on the colon from jedi.inference.base_value import NO_VALUES return NO_VALUES if trailer.type == 'atom': return context.infer_node(trailer) return context.infer_node(leaf) power = trailer.parent index = power.children.index(trailer) if cut_own_trailer: cut = index else: cut = index + 1 if power.type == 'error_node': start = index while True: start -= 1 base = power.children[start] if base.type != 'trailer': break trailers = power.children[start + 1:cut] else: base = power.children[0] trailers = power.children[1:cut] if base == 'await': base = trailers[0] trailers = trailers[1:] values = context.infer_node(base) from jedi.inference.syntax_tree import infer_trailer for trailer in trailers: values = infer_trailer(context, values, trailer) return values def cut_value_at_position(leaf, position): """ Cuts of the value of the leaf at position """ lines = split_lines(leaf.value, keepends=True)[:position[0] - leaf.line + 1] column = position[1] if leaf.line == position[0]: column -= leaf.column if not lines: return '' lines[-1] = lines[-1][:column] return ''.join(lines) def complete_dict(module_context, code_lines, leaf, position, string, fuzzy): bracket_leaf = leaf if bracket_leaf != '[': bracket_leaf = leaf.get_previous_leaf() cut_end_quote = '' if string: cut_end_quote = get_quote_ending(string, code_lines, position, invert_result=True) if bracket_leaf == '[': if string is None and leaf is not bracket_leaf: string = cut_value_at_position(leaf, position) context = module_context.create_context(bracket_leaf) before_bracket_leaf = bracket_leaf.get_previous_leaf() if before_bracket_leaf.type in ('atom', 'trailer', 'name'): values = infer_call_of_leaf(context, before_bracket_leaf) return list(_completions_for_dicts( module_context.inference_state, values, '' if string is None else string, cut_end_quote, fuzzy=fuzzy, )) return []
null
176,469
import re from collections import namedtuple from textwrap import dedent from itertools import chain from functools import wraps from inspect import Parameter from parso.python.parser import Parser from parso.python import tree from jedi.inference.base_value import NO_VALUES from jedi.inference.syntax_tree import infer_atom from jedi.inference.helpers import infer_call_of_leaf from jedi.inference.compiled import get_string_value_set from jedi.cache import signature_time_cache, memoize_method from jedi.parser_utils import get_parent_scope def sorted_definitions(defs): # Note: `or ''` below is required because `module_path` could be return sorted(defs, key=lambda x: (str(x.module_path or ''), x.line or 0, x.column or 0, x.name))
null
176,470
import re from collections import namedtuple from textwrap import dedent from itertools import chain from functools import wraps from inspect import Parameter from parso.python.parser import Parser from parso.python import tree from jedi.inference.base_value import NO_VALUES from jedi.inference.syntax_tree import infer_atom from jedi.inference.helpers import infer_call_of_leaf from jedi.inference.compiled import get_string_value_set from jedi.cache import signature_time_cache, memoize_method from jedi.parser_utils import get_parent_scope def get_on_completion_name(module_node, lines, position): leaf = module_node.get_leaf_for_position(position) if leaf is None or leaf.type in ('string', 'error_leaf'): # Completions inside strings are a bit special, we need to parse the # string. The same is true for comments and error_leafs. line = lines[position[0] - 1] # The first step of completions is to get the name return re.search(r'(?!\d)\w+$|$', line[:position[1]]).group(0) elif leaf.type not in ('name', 'keyword'): return '' return leaf.value[:position[1] - leaf.start_pos[1]]
null