Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def sign_file(self, filename, signer, sign_password, keystore=None): cmd, sig_file = self.get_sign_command(filename, signer, sign_password, keystore) rc, stdout, stderr = self.run_command(cmd, ...
[ "\n Sign a file.\n\n :param filename: The pathname to the file to be signed.\n :param signer: The identifier of the signer of the file.\n :param sign_password: The passphrase for the signer's\n private key used for signing.\n :param keystore: The path ...
Please provide a description of the function:def upload_documentation(self, metadata, doc_dir): self.check_credentials() if not os.path.isdir(doc_dir): raise DistlibException('not a directory: %r' % doc_dir) fn = os.path.join(doc_dir, 'index.html') if not os.path.exi...
[ "\n Upload documentation to the index.\n\n :param metadata: A :class:`Metadata` instance defining at least a name\n and version number for the documentation to be\n uploaded.\n :param doc_dir: The pathname of the directory which contains the\n ...
Please provide a description of the function:def get_verify_command(self, signature_filename, data_filename, keystore=None): cmd = [self.gpg, '--status-fd', '2', '--no-tty'] if keystore is None: keystore = self.gpg_home if keystore: cmd...
[ "\n Return a suitable command for verifying a file.\n\n :param signature_filename: The pathname to the file containing the\n signature.\n :param data_filename: The pathname to the file containing the\n signed data.\n :param k...
Please provide a description of the function:def verify_signature(self, signature_filename, data_filename, keystore=None): if not self.gpg: raise DistlibException('verification unavailable because gpg ' 'unavailable') cmd =...
[ "\n Verify a signature for a file.\n\n :param signature_filename: The pathname to the file containing the\n signature.\n :param data_filename: The pathname to the file containing the\n signed data.\n :param keystore: The path...
Please provide a description of the function:def download_file(self, url, destfile, digest=None, reporthook=None): if digest is None: digester = None logger.debug('No digest specified') else: if isinstance(digest, (list, tuple)): hasher, diges...
[ "\n This is a convenience method for downloading a file from an URL.\n Normally, this will be a file from the index, though currently\n no check is made for this (i.e. a file can be downloaded from\n anywhere).\n\n The method is just like the :func:`urlretrieve` function in the\n ...
Please provide a description of the function:def send_request(self, req): handlers = [] if self.password_handler: handlers.append(self.password_handler) if self.ssl_verifier: handlers.append(self.ssl_verifier) opener = build_opener(*handlers) retu...
[ "\n Send a standard library :class:`Request` to PyPI and return its\n response.\n\n :param req: The request to send.\n :return: The HTTP response from PyPI (a standard library HTTPResponse).\n " ]
Please provide a description of the function:def encode_request(self, fields, files): # Adapted from packaging, which in turn was adapted from # http://code.activestate.com/recipes/146306 parts = [] boundary = self.boundary for k, values in fields: if not is...
[ "\n Encode fields and files for posting to an HTTP server.\n\n :param fields: The fields to send as a list of (fieldname, value)\n tuples.\n :param files: The files to send as a list of (fieldname, filename,\n file_bytes) tuple.\n " ]
Please provide a description of the function:def do_bash_complete(cli, prog_name): comp_words = os.environ['COMP_WORDS'] try: cwords = shlex.split(comp_words) quoted = False except ValueError: # No closing quotation cwords = split_args(comp_words) quoted = True cwor...
[ "Do the completion for bash\n\n Parameters\n ----------\n cli : click.Command\n The main click Command of the program\n prog_name : str\n The program name on the command line\n\n Returns\n -------\n bool\n True if the completion was successful, False otherwise\n ", "([...
Please provide a description of the function:def do_fish_complete(cli, prog_name): commandline = os.environ['COMMANDLINE'] args = split_args(commandline)[1:] if args and not commandline.endswith(' '): incomplete = args[-1] args = args[:-1] else: incomplete = '' for item...
[ "Do the fish completion\n\n Parameters\n ----------\n cli : click.Command\n The main click Command of the program\n prog_name : str\n The program name on the command line\n\n Returns\n -------\n bool\n True if the completion was successful, False otherwise\n " ]
Please provide a description of the function:def do_powershell_complete(cli, prog_name): commandline = os.environ['COMMANDLINE'] args = split_args(commandline)[1:] quote = single_quote incomplete = '' if args and not commandline.endswith(' '): incomplete = args[-1] args = args[:...
[ "Do the powershell completion\n\n Parameters\n ----------\n cli : click.Command\n The main click Command of the program\n prog_name : str\n The program name on the command line\n\n Returns\n -------\n bool\n True if the completion was successful, False otherwise\n " ]
Please provide a description of the function:def get_code(shell=None, prog_name=None, env_name=None, extra_env=None): from jinja2 import Environment, FileSystemLoader if shell in [None, 'auto']: shell = get_auto_shell() if not isinstance(shell, Shell): shell = Shell[shell] prog_name...
[ "Returns the completion code to be evaluated by the shell\n\n Parameters\n ----------\n shell : Shell\n The shell type (Default value = None)\n prog_name : str\n The program name on the command line (Default value = None)\n env_name : str\n The environment variable used to contro...
Please provide a description of the function:def install(shell=None, prog_name=None, env_name=None, path=None, append=None, extra_env=None): prog_name = prog_name or click.get_current_context().find_root().info_name shell = shell or get_auto_shell() if append is None and path is not None: appen...
[ "Install the completion\n\n Parameters\n ----------\n shell : Shell\n The shell type targeted. It will be guessed with get_auto_shell() if the value is None (Default value = None)\n prog_name : str\n The program name on the command line. It will be automatically computed if the value is No...
Please provide a description of the function:def getTreeBuilder(treeType, implementation=None, **kwargs): treeType = treeType.lower() if treeType not in treeBuilderCache: if treeType == "dom": from . import dom # Come up with a sane default (pref. from the stdlib) ...
[ "Get a TreeBuilder class for various types of trees with built-in support\n\n :arg treeType: the name of the tree type required (case-insensitive). Supported\n values are:\n\n * \"dom\" - A generic builder for DOM implementations, defaulting to a\n xml.dom.minidom based implementation.\n ...
Please provide a description of the function:def choose_boundary(): boundary = binascii.hexlify(os.urandom(16)) if six.PY3: boundary = boundary.decode('ascii') return boundary
[ "\n Our embarrassingly-simple replacement for mimetools.choose_boundary.\n " ]
Please provide a description of the function:def iter_field_objects(fields): 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.fr...
[ "\n Iterate over fields.\n\n Supports list of (k, v) tuples and dicts, and lists of\n :class:`~urllib3.fields.RequestField`.\n\n " ]
Please provide a description of the function:def iter_fields(fields): if isinstance(fields, dict): return ((k, v) for k, v in six.iteritems(fields)) return ((k, v) for k, v in fields)
[ "\n .. deprecated:: 1.6\n\n Iterate over fields.\n\n The addition of :class:`~urllib3.fields.RequestField` makes this function\n obsolete. Instead, use :func:`iter_field_objects`, which returns\n :class:`~urllib3.fields.RequestField` objects.\n\n Supports list of (k, v) tuples and dicts.\n " ]
Please provide a description of the function:def encode_multipart_formdata(fields, boundary=None): 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...
[ "\n Encode a dictionary of ``fields`` using the multipart/form-data MIME format.\n\n :param fields:\n Dictionary of fields or list of (key, :class:`~urllib3.fields.RequestField`).\n\n :param boundary:\n If not specified, then a random boundary will be generated using\n :func:`urllib3.f...
Please provide a description of the function:def finder(package): if package in _finder_cache: result = _finder_cache[package] else: if package not in sys.modules: __import__(package) module = sys.modules[package] path = getattr(module, '__path__', None) ...
[ "\n Return a resource finder for a package.\n :param package: The name of the package.\n :return: A :class:`ResourceFinder` instance for the package.\n " ]
Please provide a description of the function:def finder_for_path(path): result = None # calls any path hooks, gets importer into cache pkgutil.get_importer(path) loader = sys.path_importer_cache.get(path) finder = _finder_registry.get(type(loader)) if finder: module = _dummy_module ...
[ "\n Return a resource finder for a path, which should represent a container.\n\n :param path: The path.\n :return: A :class:`ResourceFinder` instance for the path.\n " ]
Please provide a description of the function:def get(self, resource): prefix, path = resource.finder.get_cache_info(resource) if prefix is None: result = path else: result = os.path.join(self.base, self.prefix_to_dir(prefix), path) dirname = os.path.d...
[ "\n Get a resource into the cache,\n\n :param resource: A :class:`Resource` instance.\n :return: The pathname of the resource in the cache.\n " ]
Please provide a description of the function:def to_sax(walker, handler): handler.startDocument() for prefix, namespace in prefix_mapping.items(): handler.startPrefixMapping(prefix, namespace) for token in walker: type = token["type"] if type == "Doctype": continue ...
[ "Call SAX-like content handler based on treewalker walker\n\n :arg walker: the treewalker to use to walk the tree to convert it\n\n :arg handler: SAX handler to use\n\n " ]
Please provide a description of the function:def retry(*dargs, **dkw): # support both @retry and @retry() as valid syntax if len(dargs) == 1 and callable(dargs[0]): def wrap_simple(f): @six.wraps(f) def wrapped_f(*args, **kw): return Retrying().call(f, *args...
[ "\n Decorator function that instantiates the Retrying object\n @param *dargs: positional arguments passed to Retrying object\n @param **dkw: keyword arguments passed to the Retrying object\n " ]
Please provide a description of the function:def random_sleep(self, previous_attempt_number, delay_since_first_attempt_ms): return random.randint(self._wait_random_min, self._wait_random_max)
[ "Sleep a random amount of time between wait_random_min and wait_random_max" ]
Please provide a description of the function:def incrementing_sleep(self, previous_attempt_number, delay_since_first_attempt_ms): result = self._wait_incrementing_start + (self._wait_incrementing_increment * (previous_attempt_number - 1)) if result < 0: result = 0 return res...
[ "\n Sleep an incremental amount of time after each attempt, starting at\n wait_incrementing_start and incrementing by wait_incrementing_increment\n " ]
Please provide a description of the function:def get(self, wrap_exception=False): if self.has_exception: if wrap_exception: raise RetryError(self) else: six.reraise(self.value[0], self.value[1], self.value[2]) else: return self...
[ "\n Return the return value of this Attempt instance or raise an Exception.\n If wrap_exception is true, this Attempt is wrapped inside of a\n RetryError before being raised.\n " ]
Please provide a description of the function:def safe_range(*args): rng = range(*args) if len(rng) > MAX_RANGE: raise OverflowError('range too big, maximum size for range is %d' % MAX_RANGE) return rng
[ "A range that can't generate ranges with a length of more than\n MAX_RANGE items.\n " ]
Please provide a description of the function:def is_internal_attribute(obj, attr): if isinstance(obj, types.FunctionType): if attr in UNSAFE_FUNCTION_ATTRIBUTES: return True elif isinstance(obj, types.MethodType): if attr in UNSAFE_FUNCTION_ATTRIBUTES or \ attr in UNS...
[ "Test if the attribute given is an internal python attribute. For\n example this function returns `True` for the `func_code` attribute of\n python objects. This is useful if the environment method\n :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.\n\n >>> from jinja2.sandbox import is_in...
Please provide a description of the function:def modifies_known_mutable(obj, attr): for typespec, unsafe in _mutable_spec: if isinstance(obj, typespec): return attr in unsafe return False
[ "This function checks if an attribute on a builtin mutable object\n (list, dict, set or deque) would modify it if called. It also supports\n the \"user\"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and\n with Python 2.6 onwards the abstract base classes `MutableSet`,\n `MutableMapping`, and...
Please provide a description of the function:def is_safe_attribute(self, obj, attr, value): return not (attr.startswith('_') or is_internal_attribute(obj, attr))
[ "The sandboxed environment will call this method to check if the\n attribute of an object is safe to access. Per default all attributes\n starting with an underscore are considered private as well as the\n special attributes of internal python objects as returned by the\n :func:`is_inte...
Please provide a description of the function:def call_binop(self, context, operator, left, right): return self.binop_table[operator](left, right)
[ "For intercepted binary operator calls (:meth:`intercepted_binops`)\n this function is executed instead of the builtin operator. This can\n be used to fine tune the behavior of certain operators.\n\n .. versionadded:: 2.6\n " ]
Please provide a description of the function:def getattr(self, obj, attribute): try: value = getattr(obj, attribute) except AttributeError: try: return obj[attribute] except (TypeError, LookupError): pass else: ...
[ "Subscribe an object from sandboxed code and prefer the\n attribute. The attribute passed *must* be a bytestring.\n " ]
Please provide a description of the function:def unsafe_undefined(self, obj, attribute): return self.undefined('access to attribute %r of %r ' 'object is unsafe.' % ( attribute, obj.__class__.__name__ ), name=attribute, obj=obj, exc=Security...
[ "Return an undefined object for unsafe attributes." ]
Please provide a description of the function:def format_string(self, s, args, kwargs): if isinstance(s, Markup): formatter = SandboxedEscapeFormatter(self, s.escape) else: formatter = SandboxedFormatter(self) kwargs = _MagicFormatMapping(args, kwargs) rv ...
[ "If a format call is detected, then this is routed through this\n method so that our safety sandbox can be used for it.\n " ]
Please provide a description of the function:def call(__self, __context, __obj, *args, **kwargs): fmt = inspect_format_method(__obj) if fmt is not None: return __self.format_string(fmt, args, kwargs) # the double prefixes are to avoid double keyword argument # error...
[ "Call an object from sandboxed code." ]
Please provide a description of the function:def attrib( default=NOTHING, validator=None, repr=True, cmp=True, hash=None, init=True, convert=None, metadata=None, type=None, converter=None, factory=None, kw_only=False, ): if hash is not None and hash is not True a...
[ "\n Create a new attribute on a class.\n\n .. warning::\n\n Does *not* do anything unless the class is also decorated with\n :func:`attr.s`!\n\n :param default: A value that is used if an ``attrs``-generated ``__init__``\n is used and no value is passed while instantiating or the attr...
Please provide a description of the function:def _make_attr_tuple_class(cls_name, attr_names): attr_class_name = "{}Attributes".format(cls_name) attr_class_template = [ "class {}(tuple):".format(attr_class_name), " __slots__ = ()", ] if attr_names: for i, attr_name in enu...
[ "\n Create a tuple subclass to hold `Attribute`s for an `attrs` class.\n\n The subclass is a bare tuple with properties for names.\n\n class MyClassAttributes(tuple):\n __slots__ = ()\n x = property(itemgetter(0))\n " ]
Please provide a description of the function:def _get_annotations(cls): anns = getattr(cls, "__annotations__", None) if anns is None: return {} # Verify that the annotations aren't merely inherited. for base_cls in cls.__mro__[1:]: if anns is getattr(base_cls, "__annotations__", No...
[ "\n Get annotations for *cls*.\n " ]
Please provide a description of the function:def _transform_attrs(cls, these, auto_attribs, kw_only): cd = cls.__dict__ anns = _get_annotations(cls) if these is not None: ca_list = [(name, ca) for name, ca in iteritems(these)] if not isinstance(these, ordered_dict): ca_lis...
[ "\n Transform all `_CountingAttr`s on a class into `Attribute`s.\n\n If *these* is passed, use that and don't look for them on the class.\n\n Return an `_Attributes`.\n " ]
Please provide a description of the function:def attrs( maybe_cls=None, these=None, repr_ns=None, repr=True, cmp=True, hash=None, init=True, slots=False, frozen=False, weakref_slot=True, str=False, auto_attribs=False, kw_only=False, cache_hash=False, auto_exc=...
[ "\n A class decorator that adds `dunder\n <https://wiki.python.org/moin/DunderAlias>`_\\ -methods according to the\n specified attributes using :func:`attr.ib` or the *these* argument.\n\n :param these: A dictionary of name to :func:`attr.ib` mappings. This is\n useful to avoid the definition of...
Please provide a description of the function:def _attrs_to_tuple(obj, attrs): return tuple(getattr(obj, a.name) for a in attrs)
[ "\n Create a tuple of all values of *obj*'s *attrs*.\n " ]
Please provide a description of the function:def _add_hash(cls, attrs): cls.__hash__ = _make_hash(attrs, frozen=False, cache_hash=False) return cls
[ "\n Add a hash method to *cls*.\n " ]
Please provide a description of the function:def _add_cmp(cls, attrs=None): if attrs is None: attrs = cls.__attrs_attrs__ cls.__eq__, cls.__ne__, cls.__lt__, cls.__le__, cls.__gt__, cls.__ge__ = _make_cmp( # noqa attrs ) return cls
[ "\n Add comparison methods to *cls*.\n " ]
Please provide a description of the function:def _make_repr(attrs, ns): attr_names = tuple(a.name for a in attrs if a.repr) def __repr__(self): try: working_set = _already_repring.working_set except AttributeError: working_set = set() _already_r...
[ "\n Make a repr method for *attr_names* adding *ns* to the full name.\n ", "\n Automatically created by attrs.\n " ]
Please provide a description of the function:def _add_repr(cls, ns=None, attrs=None): if attrs is None: attrs = cls.__attrs_attrs__ cls.__repr__ = _make_repr(attrs, ns) return cls
[ "\n Add a repr method to *cls*.\n " ]
Please provide a description of the function:def fields(cls): if not isclass(cls): raise TypeError("Passed object must be a class.") attrs = getattr(cls, "__attrs_attrs__", None) if attrs is None: raise NotAnAttrsClassError( "{cls!r} is not an attrs-decorated class.".format(...
[ "\n Return the tuple of ``attrs`` attributes for a class.\n\n The tuple also allows accessing the fields by their names (see below for\n examples).\n\n :param type cls: Class to introspect.\n\n :raise TypeError: If *cls* is not a class.\n :raise attr.exceptions.NotAnAttrsClassError: If *cls* is no...
Please provide a description of the function:def fields_dict(cls): if not isclass(cls): raise TypeError("Passed object must be a class.") attrs = getattr(cls, "__attrs_attrs__", None) if attrs is None: raise NotAnAttrsClassError( "{cls!r} is not an attrs-decorated class.".fo...
[ "\n Return an ordered dictionary of ``attrs`` attributes for a class, whose\n keys are the attribute names.\n\n :param type cls: Class to introspect.\n\n :raise TypeError: If *cls* is not a class.\n :raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``\n class.\n\n :rtyp...
Please provide a description of the function:def validate(inst): if _config._run_validators is False: return for a in fields(inst.__class__): v = a.validator if v is not None: v(inst, a, getattr(inst, a.name))
[ "\n Validate all attributes on *inst* that have a validator.\n\n Leaves all exceptions through.\n\n :param inst: Instance of a class with ``attrs`` attributes.\n " ]
Please provide a description of the function:def _attrs_to_init_script( attrs, frozen, slots, post_init, cache_hash, base_attr_map, is_exc ): lines = [] any_slot_ancestors = any( _is_slot_attr(a.name, base_attr_map) for a in attrs ) if frozen is True: if slots is True: ...
[ "\n Return a script of an initializer for *attrs* and a dict of globals.\n\n The globals are expected by the generated script.\n\n If *frozen* is True, we cannot set the attributes directly so we use\n a cached ``object.__setattr__``.\n ", "\\\ndef __init__(self, {args}):\n {lines}\n" ]
Please provide a description of the function:def make_class(name, attrs, bases=(object,), **attributes_arguments): if isinstance(attrs, dict): cls_dict = attrs elif isinstance(attrs, (list, tuple)): cls_dict = dict((a, attrib()) for a in attrs) else: raise TypeError("attrs argum...
[ "\n A quick way to create a new class called *name* with *attrs*.\n\n :param name: The name for the new class.\n :type name: str\n\n :param attrs: A list of names or a dictionary of mappings of names to\n attributes.\n\n If *attrs* is a list or an ordered dict (:class:`dict` on Python 3.6+...
Please provide a description of the function:def and_(*validators): vals = [] for validator in validators: vals.extend( validator._validators if isinstance(validator, _AndValidator) else [validator] ) return _AndValidator(tuple(vals))
[ "\n A validator that composes multiple validators into one.\n\n When called on a value, it runs all wrapped validators.\n\n :param validators: Arbitrary number of validators.\n :type validators: callables\n\n .. versionadded:: 17.1.0\n " ]
Please provide a description of the function:def _patch_original_class(self): cls = self._cls base_names = self._base_names # Clean class of attribute definitions (`attr.ib()`s). if self._delete_attribs: for name in self._attr_names: if ( ...
[ "\n Apply accumulated methods and return the class.\n " ]
Please provide a description of the function:def _create_slots_class(self): base_names = self._base_names cd = { k: v for k, v in iteritems(self._cls_dict) if k not in tuple(self._attr_names) + ("__dict__", "__weakref__") } weakref_inherited ...
[ "\n Build and return a new class with a `__slots__` attribute.\n ", "\n Automatically created by attrs.\n ", "\n Automatically created by attrs.\n " ]
Please provide a description of the function:def _add_method_dunders(self, method): try: method.__module__ = self._cls.__module__ except AttributeError: pass try: method.__qualname__ = ".".join( (self._cls.__qualname__, method.__name_...
[ "\n Add __module__ and __qualname__ to a *method* if possible.\n " ]
Please provide a description of the function:def _assoc(self, **changes): new = copy.copy(self) new._setattrs(changes.items()) return new
[ "\n Copy *self* and apply *changes*.\n " ]
Please provide a description of the function:def validator(self, meth): if self._validator is None: self._validator = meth else: self._validator = and_(self._validator, meth) return meth
[ "\n Decorator that adds *meth* to the list of validators.\n\n Returns *meth* unchanged.\n\n .. versionadded:: 17.1.0\n " ]
Please provide a description of the function:def default(self, meth): if self._default is not NOTHING: raise DefaultAlreadySetError() self._default = Factory(meth, takes_self=True) return meth
[ "\n Decorator that allows to set the default for an attribute.\n\n Returns *meth* unchanged.\n\n :raises DefaultAlreadySetError: If default has been set before.\n\n .. versionadded:: 17.1.0\n " ]
Please provide a description of the function:def _expand_args(command): # Prepare arguments. if isinstance(command, STR_TYPES): if sys.version_info[0] == 2: splitter = shlex.shlex(command.encode("utf-8")) elif sys.version_info[0] == 3: splitter = shlex.shlex(command...
[ "Parses command strings and returns a Popen-ready list." ]
Please provide a description of the function:def out(self): if self.__out is not None: return self.__out if self._uses_subprocess: self.__out = self.std_out.read() else: self.__out = self._pexpect_out return self.__out
[ "Std/out output (cached)" ]
Please provide a description of the function:def expect(self, pattern, timeout=-1): if self.blocking: raise RuntimeError("expect can only be used on non-blocking commands.") try: self.subprocess.expect(pattern=pattern, timeout=timeout) except pexpect.EOF: ...
[ "Waits on the given pattern to appear in std_out" ]
Please provide a description of the function:def block(self): if self._uses_subprocess: # consume stdout and stderr if self.blocking: try: stdout, stderr = self.subprocess.communicate() self.__out = stdout ...
[ "Blocks until process is complete." ]
Please provide a description of the function:def pipe(self, command, timeout=None, cwd=None): if not timeout: timeout = self.timeout if not self.was_run: self.run(block=False, cwd=cwd) data = self.out if timeout: c = Command(command, timeou...
[ "Runs the current command and passes its output to the next\n given process.\n " ]
Please provide a description of the function:def backport_makefile(self, mode="r", buffering=None, encoding=None, errors=None, newline=None): if not set(mode) <= {"r", "w", "b"}: raise ValueError( "invalid mode %r (only r, w, b allowed)" % (mode,) ) writing...
[ "\n Backport of ``socket.makefile`` from Python 3.5.\n " ]
Please provide a description of the function:def make_traceback(exc_info, source_hint=None): exc_type, exc_value, tb = exc_info if isinstance(exc_value, TemplateSyntaxError): exc_info = translate_syntax_error(exc_value, source_hint) initial_skip = 0 else: initial_skip = 1 re...
[ "Creates a processed traceback object from the exc_info." ]
Please provide a description of the function:def translate_syntax_error(error, source=None): error.source = source error.translated = True exc_info = (error.__class__, error, None) filename = error.filename if filename is None: filename = '<unknown>' return fake_exc_info(exc_info, f...
[ "Rewrites a syntax error to please traceback systems." ]
Please provide a description of the function:def render_as_text(self, limit=None): lines = traceback.format_exception(self.exc_type, self.exc_value, self.frames[0], limit=limit) return ''.join(lines).rstrip()
[ "Return a string with the traceback." ]
Please provide a description of the function:def render_as_html(self, full=False): from jinja2.debugrenderer import render_traceback return u'%s\n\n<!--\n%s\n-->' % ( render_traceback(self, full=full), self.render_as_text().decode('utf-8', 'replace') )
[ "Return a unicode string with the traceback as rendered HTML." ]
Please provide a description of the function:def standard_exc_info(self): tb = self.frames[0] # the frame will be an actual traceback (or transparent proxy) if # we are on pypy or a python implementation with support for tproxy if type(tb) is not TracebackType: tb = ...
[ "Standard python exc_info for re-raising" ]
Please provide a description of the function:def resolve_command(self, ctx, args): original_cmd_name = click.utils.make_str(args[0]) try: return super(DYMMixin, self).resolve_command(ctx, args) except click.exceptions.UsageError as error: error_msg = str(error) ...
[ "\n Overrides clicks ``resolve_command`` method\n and appends *Did you mean ...* suggestions\n to the raised exception message.\n " ]
Please provide a description of the function:def cmdify(self, extra_args=None): parts = list(self._parts) if extra_args: parts.extend(extra_args) return " ".join( arg if not next(re.finditer(r'\s', arg), None) else '"{0}"'.format(re.sub(r'(\\*)"', r'\...
[ "Encode into a cmd-executable string.\n\n This re-implements CreateProcess's quoting logic to turn a list of\n arguments into one single string for the shell to interpret.\n\n * All double quotes are escaped with a backslash.\n * Existing backslashes before a quote are doubled, so they a...
Please provide a description of the function:def make_abstract_dist(req): # type: (InstallRequirement) -> DistAbstraction if req.editable: return IsSDist(req) elif req.link and req.link.is_wheel: return IsWheel(req) else: return IsSDist(req)
[ "Factory to make an abstract dist object.\n\n Preconditions: Either an editable req with a source_dir, or satisfied_by or\n a wheel link, or a non-editable req with a source_dir.\n\n :return: A concrete DistAbstraction.\n " ]
Please provide a description of the function:def prepare_linked_requirement( self, req, # type: InstallRequirement session, # type: PipSession finder, # type: PackageFinder upgrade_allowed, # type: bool require_hashes # type: bool ): # type: (...) -> Dist...
[ "Prepare a requirement that would be obtained from req.link\n " ]
Please provide a description of the function:def prepare_editable_requirement( self, req, # type: InstallRequirement require_hashes, # type: bool use_user_site, # type: bool finder # type: PackageFinder ): # type: (...) -> DistAbstraction assert r...
[ "Prepare an editable requirement\n " ]
Please provide a description of the function:def prepare_installed_requirement(self, req, require_hashes, skip_reason): # type: (InstallRequirement, bool, Optional[str]) -> DistAbstraction assert req.satisfied_by, "req should have been satisfied but isn't" assert skip_reason is not None...
[ "Prepare an already-installed requirement\n " ]
Please provide a description of the function:def install_given_reqs( to_install, # type: List[InstallRequirement] install_options, # type: List[str] global_options=(), # type: Sequence[str] *args, **kwargs ): # type: (...) -> List[InstallRequirement] if to_install: logger.info( ...
[ "\n Install everything in the given list.\n\n (to be called after having downloaded and unpacked the packages)\n " ]
Please provide a description of the function:def cprint(text, color=None, on_color=None, attrs=None, **kwargs): print((colored(text, color, on_color, attrs)), **kwargs)
[ "Print colorize text.\n\n It accepts arguments of print function.\n " ]
Please provide a description of the function:def get_provider(moduleOrReq): if isinstance(moduleOrReq, Requirement): return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0] try: module = sys.modules[moduleOrReq] except KeyError: __import__(moduleOrReq) modul...
[ "Return an IResourceProvider for the named module or requirement" ]
Please provide a description of the function:def get_build_platform(): from sysconfig import get_platform plat = get_platform() if sys.platform == "darwin" and not plat.startswith('macosx-'): try: version = _macosx_vers() machine = os.uname()[4].replace(" ", "_") ...
[ "Return this platform's string for platform-specific distributions\n\n XXX Currently this is the same as ``distutils.util.get_platform()``, but it\n needs some hacks for Linux and Mac OS X.\n " ]
Please provide a description of the function:def compatible_platforms(provided, required): if provided is None or required is None or provided == required: # easy case return True # Mac OS X special cases reqMac = macosVersionString.match(required) if reqMac: provMac = maco...
[ "Can code for the `provided` platform run on the `required` platform?\n\n Returns true if either platform is ``None``, or the platforms are equal.\n\n XXX Needs compatibility checks for Linux and other unixy OSes.\n " ]
Please provide a description of the function:def run_script(dist_spec, script_name): ns = sys._getframe(1).f_globals name = ns['__name__'] ns.clear() ns['__name__'] = name require(dist_spec)[0].run_script(script_name, ns)
[ "Locate distribution `dist_spec` and run its `script_name` script" ]
Please provide a description of the function:def get_distribution(dist): if isinstance(dist, six.string_types): dist = Requirement.parse(dist) if isinstance(dist, Requirement): dist = get_provider(dist) if not isinstance(dist, Distribution): raise TypeError("Expected string, Req...
[ "Return a current distribution object for a Requirement or string" ]
Please provide a description of the function:def safe_version(version): try: # normalize the version return str(packaging.version.Version(version)) except packaging.version.InvalidVersion: version = version.replace(' ', '.') return re.sub('[^A-Za-z0-9.]+', '-', version)
[ "\n Convert an arbitrary string to a standard version string\n " ]
Please provide a description of the function:def invalid_marker(text): try: evaluate_marker(text) except SyntaxError as e: e.filename = None e.lineno = None return e return False
[ "\n Validate text as a PEP 508 environment marker; return an exception\n if invalid or False otherwise.\n " ]
Please provide a description of the function:def evaluate_marker(text, extra=None): try: marker = packaging.markers.Marker(text) return marker.evaluate() except packaging.markers.InvalidMarker as e: raise SyntaxError(e)
[ "\n Evaluate a PEP 508 environment marker.\n Return a boolean indicating the marker result in this environment.\n Raise SyntaxError if marker is invalid.\n\n This implementation uses the 'pyparsing' module.\n " ]
Please provide a description of the function:def find_distributions(path_item, only=False): importer = get_importer(path_item) finder = _find_adapter(_distribution_finders, importer) return finder(importer, path_item, only)
[ "Yield distributions accessible via `path_item`" ]
Please provide a description of the function:def find_eggs_in_zip(importer, path_item, only=False): if importer.archive.endswith('.whl'): # wheels are not supported with this finder # they don't have PKG-INFO metadata, and won't ever contain eggs return metadata = EggMetadata(import...
[ "\n Find eggs in zip files; possibly multiple nested eggs.\n " ]
Please provide a description of the function:def _by_version_descending(names): def _by_version(name): name, ext = os.path.splitext(name) parts = itertools.chain(name.split('-'), [ext]) return [packaging.version.parse(part) for part in parts] return sorted(names, key=_by_v...
[ "\n Given a list of filenames, return them in descending order\n by version number.\n\n >>> names = 'bar', 'foo', 'Python-2.7.10.egg', 'Python-2.7.2.egg'\n >>> _by_version_descending(names)\n ['Python-2.7.10.egg', 'Python-2.7.2.egg', 'foo', 'bar']\n >>> names = 'Setuptools-1.2.3b1.egg', 'Setuptool...
Please provide a description of the function:def find_on_path(importer, path_item, only=False): path_item = _normalize_cached(path_item) if _is_unpacked_egg(path_item): yield Distribution.from_filename( path_item, metadata=PathMetadata( path_item, os.path.join(path_item...
[ "Yield distributions accessible on a sys.path directory" ]
Please provide a description of the function:def dist_factory(path_item, entry, only): lower = entry.lower() is_meta = any(map(lower.endswith, ('.egg-info', '.dist-info'))) return ( distributions_from_metadata if is_meta else find_distributions if not only and _is_egg_pa...
[ "\n Return a dist_factory for a path_item and entry\n " ]
Please provide a description of the function:def safe_listdir(path): try: return os.listdir(path) except (PermissionError, NotADirectoryError): pass except OSError as e: # Ignore the directory if does not exist, not a directory or # permission denied ignorable = ...
[ "\n Attempt to list contents of path, but suppress some exceptions.\n " ]
Please provide a description of the function:def non_empty_lines(path): with open(path) as f: for line in f: line = line.strip() if line: yield line
[ "\n Yield non-empty lines from file at path\n " ]
Please provide a description of the function:def resolve_egg_link(path): referenced_paths = non_empty_lines(path) resolved_paths = ( os.path.join(os.path.dirname(path), ref) for ref in referenced_paths ) dist_groups = map(find_distributions, resolved_paths) return next(dist_grou...
[ "\n Given a path to an .egg-link, resolve distributions\n present in the referenced path.\n " ]
Please provide a description of the function:def _handle_ns(packageName, path_item): importer = get_importer(path_item) if importer is None: return None # capture warnings due to #1111 with warnings.catch_warnings(): warnings.simplefilter("ignore") loader = importer.find_m...
[ "Ensure that named package includes a subpath of path_item (if needed)" ]
Please provide a description of the function:def _rebuild_mod_path(orig_path, package_name, module): sys_path = [_normalize_cached(p) for p in sys.path] def safe_sys_path_index(entry): try: return sys_path.index(entry) except ValueError: return float('inf')...
[ "\n Rebuild module.__path__ ensuring that all entries are ordered\n corresponding to their sys.path order\n ", "\n Workaround for #520 and #513.\n ", "\n Return the ordinal of the path based on its position in sys.path\n " ]
Please provide a description of the function:def declare_namespace(packageName): _imp.acquire_lock() try: if packageName in _namespace_packages: return path = sys.path parent, _, _ = packageName.rpartition('.') if parent: declare_namespace(parent) ...
[ "Declare that package 'packageName' is a namespace package" ]
Please provide a description of the function:def fixup_namespace_packages(path_item, parent=None): _imp.acquire_lock() try: for package in _namespace_packages.get(parent, ()): subpath = _handle_ns(package, path_item) if subpath: fixup_namespace_packages(subpa...
[ "Ensure that previously-declared namespace packages include path_item" ]
Please provide a description of the function:def file_ns_handler(importer, path_item, packageName, module): subpath = os.path.join(path_item, packageName.split('.')[-1]) normalized = _normalize_cached(subpath) for item in module.__path__: if _normalize_cached(item) == normalized: b...
[ "Compute an ns-package subpath for a filesystem or zipfile importer" ]
Please provide a description of the function:def normalize_path(filename): return os.path.normcase(os.path.realpath(os.path.normpath(_cygwin_patch(filename))))
[ "Normalize a file/dir name for comparison purposes" ]
Please provide a description of the function:def _is_unpacked_egg(path): return ( _is_egg_path(path) and os.path.isfile(os.path.join(path, 'EGG-INFO', 'PKG-INFO')) )
[ "\n Determine if given path appears to be an unpacked egg.\n " ]
Please provide a description of the function:def _version_from_file(lines): def is_version_line(line): return line.lower().startswith('version:') version_lines = filter(is_version_line, lines) line = next(iter(version_lines), '') _, _, value = line.partition(':') return safe_version(val...
[ "\n Given an iterable of lines from a Metadata file, return\n the value of the Version field, if present, or None otherwise.\n " ]
Please provide a description of the function:def parse_requirements(strs): # create a steppable iterator, so we can handle \-continuations lines = iter(yield_lines(strs)) for line in lines: # Drop comments -- a hash without a space may be in a URL. if ' #' in line: line = l...
[ "Yield ``Requirement`` objects for each specification in `strs`\n\n `strs` must be a string, or a (possibly-nested) iterable thereof.\n " ]