Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def copy( self ): cpy = copy.copy( self ) cpy.parseAction = self.parseAction[:] cpy.ignoreExprs = self.ignoreExprs[:] if self.copyDefaultWhiteChars: cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS return cpy
[ "\n Make a copy of this :class:`ParserElement`. Useful for defining\n different parse actions for the same parsing pattern, using copies of\n the original parse element.\n\n Example::\n\n integer = Word(nums).setParseAction(lambda toks: int(toks[0]))\n integerK = i...
Please provide a description of the function:def setName( self, name ): self.name = name self.errmsg = "Expected " + self.name if hasattr(self,"exception"): self.exception.msg = self.errmsg return self
[ "\n Define name for this expression, makes debugging and exception messages clearer.\n\n Example::\n\n Word(nums).parseString(\"ABC\") # -> Exception: Expected W:(0123...) (at char 0), (line:1, col:1)\n Word(nums).setName(\"integer\").parseString(\"ABC\") # -> Exception: Expect...
Please provide a description of the function:def setResultsName( self, name, listAllMatches=False ): newself = self.copy() if name.endswith("*"): name = name[:-1] listAllMatches=True newself.resultsName = name newself.modalResults = not listAllMatches ...
[ "\n Define name for referencing matching tokens as a nested attribute\n of the returned parse results.\n NOTE: this returns a *copy* of the original :class:`ParserElement` object;\n this is so that the client can define a basic element, such as an\n integer, and reference it in mu...
Please provide a description of the function:def addCondition(self, *fns, **kwargs): msg = kwargs.get("message", "failed user-defined condition") exc_type = ParseFatalException if kwargs.get("fatal", False) else ParseException for fn in fns: fn = _trim_arity(fn) ...
[ "Add a boolean predicate function to expression's list of parse actions. See\n :class:`setParseAction` for function call signatures. Unlike ``setParseAction``,\n functions passed to ``addCondition`` need to return boolean success/fail of the condition.\n\n Optional keyword arguments:\n -...
Please provide a description of the function:def enablePackrat(cache_size_limit=128): if not ParserElement._packratEnabled: ParserElement._packratEnabled = True if cache_size_limit is None: ParserElement.packrat_cache = ParserElement._UnboundedCache() ...
[ "Enables \"packrat\" parsing, which adds memoizing to the parsing logic.\n Repeated parse attempts at the same string location (which happens\n often in many complex grammars) can immediately return a cached value,\n instead of re-executing parsing/validating code. Memoizing is done o...
Please provide a description of the function:def parseString( self, instring, parseAll=False ): ParserElement.resetCache() if not self.streamlined: self.streamline() #~ self.saveAsList = True for e in self.ignoreExprs: e.streamline() if not se...
[ "\n Execute the parse expression with the given string.\n This is the main interface to the client code, once the complete\n expression has been built.\n\n If you want the grammar to require that the entire input string be\n successfully parsed, then set ``parseAll`` to True (equi...
Please provide a description of the function:def searchString( self, instring, maxMatches=_MAX_INT ): try: return ParseResults([ t for t,s,e in self.scanString( instring, maxMatches ) ]) except ParseBaseException as exc: if ParserElement.verbose_stacktrace: ...
[ "\n Another extension to :class:`scanString`, simplifying the access to the tokens found\n to match the given parse expression. May be called with optional\n ``maxMatches`` argument, to clip searching after 'n' matches are found.\n\n Example::\n\n # a capitalized word starts ...
Please provide a description of the function:def split(self, instring, maxsplit=_MAX_INT, includeSeparators=False): splits = 0 last = 0 for t,s,e in self.scanString(instring, maxMatches=maxsplit): yield instring[last:s] if includeSeparators: yield...
[ "\n Generator method to split a string using the given expression as a separator.\n May be called with optional ``maxsplit`` argument, to limit the number of splits;\n and the optional ``includeSeparators`` argument (default= ``False``), if the separating\n matching text should be includ...
Please provide a description of the function:def setWhitespaceChars( self, chars ): self.skipWhitespace = True self.whiteChars = chars self.copyDefaultWhiteChars = False return self
[ "\n Overrides the default whitespace chars\n " ]
Please provide a description of the function:def ignore( self, other ): if isinstance(other, basestring): other = Suppress(other) if isinstance( other, Suppress ): if other not in self.ignoreExprs: self.ignoreExprs.append(other) else: ...
[ "\n Define expression to be ignored (e.g., comments) while doing pattern\n matching; may be called repeatedly, to define multiple comment or other\n ignorable patterns.\n\n Example::\n\n patt = OneOrMore(Word(alphas))\n patt.parseString('ablaj /* comment */ lskjd') ...
Please provide a description of the function:def setDebugActions( self, startAction, successAction, exceptionAction ): self.debugActions = (startAction or _defaultStartDebugAction, successAction or _defaultSuccessDebugAction, exceptionAction or ...
[ "\n Enable display of debugging messages while doing pattern matching.\n " ]
Please provide a description of the function:def setDebug( self, flag=True ): if flag: self.setDebugActions( _defaultStartDebugAction, _defaultSuccessDebugAction, _defaultExceptionDebugAction ) else: self.debug = False return self
[ "\n Enable display of debugging messages while doing pattern matching.\n Set ``flag`` to True to enable, False to disable.\n\n Example::\n\n wd = Word(alphas).setName(\"alphaword\")\n integer = Word(nums).setName(\"numword\")\n term = wd | integer\n\n ...
Please provide a description of the function:def parseFile( self, file_or_filename, parseAll=False ): try: file_contents = file_or_filename.read() except AttributeError: with open(file_or_filename, "r") as f: file_contents = f.read() try: ...
[ "\n Execute the parse expression on the given file or filename.\n If a filename is specified (instead of a file object),\n the entire file is opened, read, and closed before parsing.\n " ]
Please provide a description of the function:def sub(self, repl): if self.asGroupList: warnings.warn("cannot use sub() with Regex(asGroupList=True)", SyntaxWarning, stacklevel=2) raise SyntaxError() if self.asMatch and callable(repl): ...
[ "\n Return Regex with an attached parse action to transform the parsed\n result as if called using `re.sub(expr, repl, string) <https://docs.python.org/3/library/re.html#re.sub>`_.\n\n Example::\n\n make_html = Regex(r\"(\\w+):(.*?):\").sub(r\"<\\1>\\2</\\1>\")\n print(mak...
Please provide a description of the function:def leaveWhitespace( self ): self.skipWhitespace = False self.exprs = [ e.copy() for e in self.exprs ] for e in self.exprs: e.leaveWhitespace() return self
[ "Extends ``leaveWhitespace`` defined in base class, and also invokes ``leaveWhitespace`` on\n all contained expressions." ]
Please provide a description of the function:def convertToDate(fmt="%Y-%m-%d"): def cvt_fn(s,l,t): try: return datetime.strptime(t[0], fmt).date() except ValueError as ve: raise ParseException(s, l, str(ve)) return cvt_fn
[ "\n Helper to create a parse action for converting parsed date string to Python datetime.date\n\n Params -\n - fmt - format to be passed to datetime.strptime (default= ``\"%Y-%m-%d\"``)\n\n Example::\n\n date_expr = pyparsing_common.iso8601_date.copy()\n date_expr....
Please provide a description of the function:def convertToDatetime(fmt="%Y-%m-%dT%H:%M:%S.%f"): def cvt_fn(s,l,t): try: return datetime.strptime(t[0], fmt) except ValueError as ve: raise ParseException(s, l, str(ve)) return cvt_fn
[ "Helper to create a parse action for converting parsed\n datetime string to Python datetime.datetime\n\n Params -\n - fmt - format to be passed to datetime.strptime (default= ``\"%Y-%m-%dT%H:%M:%S.%f\"``)\n\n Example::\n\n dt_expr = pyparsing_common.iso8601_datetime.copy()\n ...
Please provide a description of the function:def _match_vcs_scheme(url): # type: (str) -> Optional[str] from pipenv.patched.notpip._internal.vcs import VcsSupport for scheme in VcsSupport.schemes: if url.lower().startswith(scheme) and url[len(scheme)] in '+:': return scheme retu...
[ "Look for VCS schemes in the URL.\n\n Returns the matched VCS scheme, or None if there's no match.\n " ]
Please provide a description of the function:def _is_url_like_archive(url): # type: (str) -> bool filename = Link(url).filename for bad_ext in ARCHIVE_EXTENSIONS: if filename.endswith(bad_ext): return True return False
[ "Return whether the URL looks like an archive.\n " ]
Please provide a description of the function:def _ensure_html_header(response): # type: (Response) -> None content_type = response.headers.get("Content-Type", "") if not content_type.lower().startswith("text/html"): raise _NotHTML(content_type, response.request.method)
[ "Check the Content-Type header to ensure the response contains HTML.\n\n Raises `_NotHTML` if the content type is not text/html.\n " ]
Please provide a description of the function:def _ensure_html_response(url, session): # type: (str, PipSession) -> None scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url) if scheme not in {'http', 'https'}: raise _NotHTTP() resp = session.head(url, allow_redirects=True) ...
[ "Send a HEAD request to the URL, and ensure the response contains HTML.\n\n Raises `_NotHTTP` if the URL is not available for a HEAD request, or\n `_NotHTML` if the content type is not text/html.\n " ]
Please provide a description of the function:def _get_html_response(url, session): # type: (str, PipSession) -> Response if _is_url_like_archive(url): _ensure_html_response(url, session=session) logger.debug('Getting page %s', url) resp = session.get( url, headers={ ...
[ "Access an HTML page with GET, and return the response.\n\n This consists of three parts:\n\n 1. If the URL looks suspiciously like an archive, send a HEAD first to\n check the Content-Type is HTML, to avoid downloading a large file.\n Raise `_NotHTTP` if the content type cannot be determined, or\...
Please provide a description of the function:def _find_name_version_sep(egg_info, canonical_name): # type: (str, str) -> int # Project name and version must be separated by one single dash. Find all # occurrences of dashes; if the string in front of it matches the canonical # name, this is the one ...
[ "Find the separator's index based on the package's canonical name.\n\n `egg_info` must be an egg info string for the given package, and\n `canonical_name` must be the package's canonical name.\n\n This function is needed since the canonicalized name does not necessarily\n have the same length as the egg...
Please provide a description of the function:def _egg_info_matches(egg_info, canonical_name): # type: (str, str) -> Optional[str] try: version_start = _find_name_version_sep(egg_info, canonical_name) + 1 except ValueError: return None version = egg_info[version_start:] if not ve...
[ "Pull the version part out of a string.\n\n :param egg_info: The string to parse. E.g. foo-2.1\n :param canonical_name: The canonicalized name of the package this\n belongs to.\n " ]
Please provide a description of the function:def _determine_base_url(document, page_url): for base in document.findall(".//base"): href = base.get("href") if href is not None: return href return page_url
[ "Determine the HTML document's base URL.\n\n This looks for a ``<base>`` tag in the HTML document. If present, its href\n attribute denotes the base URL of anchor tags in the document. If there is\n no such tag (or if it does not have a valid href attribute), the HTML\n file's URL is used as the base UR...
Please provide a description of the function:def _get_encoding_from_headers(headers): if headers and "Content-Type" in headers: content_type, params = cgi.parse_header(headers["Content-Type"]) if "charset" in params: return params['charset'] return None
[ "Determine if we have any encoding information in our headers.\n " ]
Please provide a description of the function:def _candidate_sort_key(self, candidate, ignore_compatibility=True): # type: (InstallationCandidate, bool) -> CandidateSortingKey support_num = len(self.valid_tags) build_tag = tuple() # type: BuildTag binary_preference = 0 i...
[ "\n Function used to generate link sort key for link tuples.\n The greater the return value, the more preferred it is.\n If not finding wheels, then sorted by version only.\n If finding wheels, then the sort order is by version, then:\n 1. existing installs\n 2. wheels ...
Please provide a description of the function:def _get_index_urls_locations(self, project_name): # type: (str) -> List[str] def mkurl_pypi_url(url): loc = posixpath.join( url, urllib_parse.quote(canonicalize_name(project_name))) # For maxi...
[ "Returns the locations found via self.index_urls\n\n Checks the url_name on the main (first in the list) index and\n use this url_name to produce all locations\n " ]
Please provide a description of the function:def find_all_candidates(self, project_name): # type: (str) -> List[Optional[InstallationCandidate]] index_locations = self._get_index_urls_locations(project_name) index_file_loc, index_url_loc = self._sort_locations(index_locations) f...
[ "Find all available InstallationCandidate for project_name\n\n This checks index_urls and find_links.\n All versions found are returned as an InstallationCandidate list.\n\n See _link_package_versions for details on which files are accepted\n " ]
Please provide a description of the function:def find_requirement(self, req, upgrade, ignore_compatibility=False): # type: (InstallRequirement, bool, bool) -> Optional[Link] all_candidates = self.find_all_candidates(req.name) # Filter out anything which doesn't match our specifier ...
[ "Try to find a Link matching req\n\n Expects req, an InstallRequirement and upgrade, a boolean\n Returns a Link if found,\n Raises DistributionNotFound or BestVersionAlreadyInstalled otherwise\n " ]
Please provide a description of the function:def _get_pages(self, locations, project_name): # type: (Iterable[Link], str) -> Iterable[HTMLPage] seen = set() # type: Set[Link] for location in locations: if location in seen: continue seen.add(locat...
[ "\n Yields (page, page_url) from the given locations, skipping\n locations that have errors.\n " ]
Please provide a description of the function:def _link_package_versions(self, link, search, ignore_compatibility=True): # type: (Link, Search, bool) -> Optional[InstallationCandidate] version = None if link.egg_fragment: egg_info = link.egg_fragment ext = link.ex...
[ "Return an InstallationCandidate or None" ]
Please provide a description of the function:def iter_links(self): # type: () -> Iterable[Link] document = html5lib.parse( self.content, transport_encoding=_get_encoding_from_headers(self.headers), namespaceHTMLElements=False, ) base_url = _de...
[ "Yields all links in the page" ]
Please provide a description of the function:def run(command, timeout=30, withexitstatus=False, events=None, extra_args=None, logfile=None, cwd=None, env=None, **kwargs): ''' This function runs the given command; waits for it to finish; then returns all output as a string. STDERR is included in out...
[]
Please provide a description of the function:def runu(command, timeout=30, withexitstatus=False, events=None, extra_args=None, logfile=None, cwd=None, env=None, **kwargs): kwargs.setdefault('encoding', 'utf-8') return run(command, timeout=timeout, withexitstatus=withexitstatus, even...
[ "Deprecated: pass encoding to run() instead.\n " ]
Please provide a description of the function:def get_process_mapping(): output = subprocess.check_output([ 'ps', '-ww', '-o', 'pid=', '-o', 'ppid=', '-o', 'args=', ]) if not isinstance(output, str): output = output.decode(sys.stdout.encoding) processes = {} for line in output.sp...
[ "Try to look up the process tree via the output of `ps`.\n " ]
Please provide a description of the function:def path_url(self): url = [] p = urlsplit(self.url) path = p.path if not path: path = '/' url.append(path) query = p.query if query: url.append('?') url.append(query) ...
[ "Build the path URL to use." ]
Please provide a description of the function:def _encode_params(data): if isinstance(data, (str, bytes)): return data elif hasattr(data, 'read'): return data elif hasattr(data, '__iter__'): result = [] for k, vs in to_key_val_list(data): ...
[ "Encode parameters in a piece of data.\n\n Will successfully encode parameters when passed as a dict or a list of\n 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary\n if parameters are supplied as a dict.\n " ]
Please provide a description of the function:def _encode_files(files, data): if (not files): raise ValueError("Files must be provided.") elif isinstance(data, basestring): raise ValueError("Data must not be a string.") new_fields = [] fields = to_key_val...
[ "Build the body for a multipart/form-data request.\n\n Will successfully encode files when passed as a dict or a list of\n tuples. Order is retained if data is a list of tuples but arbitrary\n if parameters are supplied as a dict.\n The tuples may be 2-tuples (filename, fileobj), 3-tuple...
Please provide a description of the function:def register_hook(self, event, hook): if event not in self.hooks: raise ValueError('Unsupported event specified, with event name "%s"' % (event)) if isinstance(hook, Callable): self.hooks[event].append(hook) elif has...
[ "Properly register a hook." ]
Please provide a description of the function:def deregister_hook(self, event, hook): try: self.hooks[event].remove(hook) return True except ValueError: return False
[ "Deregister a previously registered hook.\n Returns True if the hook existed, False if not.\n " ]
Please provide a description of the function:def prepare(self, method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None): self.prepare_method(method) self.prepare_url(url, params) self.prepare_header...
[ "Prepares the entire request with the given parameters." ]
Please provide a description of the function:def prepare_body(self, data, files, json=None): # Check if file, fo, generator, iterator. # If not, run through normal process. # Nottin' on you. body = None content_type = None if not data and json is not None: ...
[ "Prepares the given HTTP body data." ]
Please provide a description of the function:def prepare_content_length(self, body): if body is not None: length = super_len(body) if length: # If length exists, set it. Otherwise, we fallback # to Transfer-Encoding: chunked. self....
[ "Prepare Content-Length header based on request method and body" ]
Please provide a description of the function:def prepare_auth(self, auth, url=''): # If no Auth is explicitly provided, extract it from the URL first. if auth is None: url_auth = get_auth_from_url(self.url) auth = url_auth if any(url_auth) else None if auth: ...
[ "Prepares the given HTTP auth data." ]
Please provide a description of the function:def prepare_cookies(self, cookies): if isinstance(cookies, cookielib.CookieJar): self._cookies = cookies else: self._cookies = cookiejar_from_dict(cookies) cookie_header = get_cookie_header(self._cookies, self) ...
[ "Prepares the given HTTP cookie data.\n\n This function eventually generates a ``Cookie`` header from the\n given cookies using cookielib. Due to cookielib's design, the header\n will not be regenerated if it already exists, meaning this function\n can only be called once for the life of...
Please provide a description of the function:def prepare_hooks(self, hooks): # hooks can be passed as None to the prepare method and to this # method. To prevent iterating over None, simply use an empty list # if hooks is False-y hooks = hooks or [] for event in hooks: ...
[ "Prepares the given hooks." ]
Please provide a description of the function:def is_permanent_redirect(self): return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))
[ "True if this Response one of the permanent versions of redirect." ]
Please provide a description of the function:def text(self): # Try charset from content-type content = None encoding = self.encoding if not self.content: return str('') # Fallback to auto-detected encoding. if self.encoding is None: enc...
[ "Content of the response, in unicode.\n\n If Response.encoding is None, encoding will be guessed using\n ``chardet``.\n\n The encoding of the response content is determined based solely on HTTP\n headers, following RFC 2616 to the letter. If you can take advantage of\n non-HTTP kn...
Please provide a description of the function:def raise_for_status(self): http_error_msg = '' if isinstance(self.reason, bytes): # We attempt to decode utf-8 first because some servers # choose to localize their reason strings. If the string # isn't utf-8, we...
[ "Raises stored :class:`HTTPError`, if one occurred." ]
Please provide a description of the function:def close(self): if not self._content_consumed: self.raw.close() release_conn = getattr(self.raw, 'release_conn', None) if release_conn is not None: release_conn()
[ "Releases the connection back to the pool. Once this method has been\n called the underlying ``raw`` object must not be accessed again.\n\n *Note: Should not normally need to be called explicitly.*\n " ]
Please provide a description of the function:def create_env_error_message(error, show_traceback, using_user_site): parts = [] # Mention the error if we are not going to show a traceback parts.append("Could not install packages due to an EnvironmentError") if not show_traceback: parts.appen...
[ "Format an error message for an EnvironmentError\n\n It may occur anytime during the execution of the install command.\n " ]
Please provide a description of the function:def _ipv6_host(host, scheme): # httplib doesn't like it when we include brackets in IPv6 addresses # Specifically, if we include brackets but also pass the port then # httplib crazily doubles up the square brackets on the Host header. # Instead, we need...
[ "\n Process IPv6 address literals\n " ]
Please provide a description of the function:def _get_conn(self, timeout=None): conn = None try: conn = self.pool.get(block=self.block, timeout=timeout) except AttributeError: # self.pool is None raise ClosedPoolError(self, "Pool is closed.") except qu...
[ "\n Get a connection. Will return a pooled connection if one is available.\n\n If no connections are available and :prop:`.block` is ``False``, then a\n fresh connection is returned.\n\n :param timeout:\n Seconds to wait before giving up and raising\n :class:`urllib...
Please provide a description of the function:def _get_timeout(self, timeout): if timeout is _Default: return self.timeout.clone() if isinstance(timeout, Timeout): return timeout.clone() else: # User passed us an int/float. This is for backwards compa...
[ " Helper that always returns a :class:`urllib3.util.Timeout` " ]
Please provide a description of the function:def _raise_timeout(self, err, url, timeout_value): if isinstance(err, SocketTimeout): raise ReadTimeoutError(self, url, "Read timed out. (read timeout=%s)" % timeout_value) # See the above comment about EAGAIN in Python 3. In Python 2 w...
[ "Is the error actually a timeout? Will raise a ReadTimeout or pass" ]
Please provide a description of the function:def urlopen(self, method, url, body=None, headers=None, retries=None, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, chunked=False, body_pos=None, **response_kw): ...
[ "\n Get a connection from the pool and perform an HTTP request. This is the\n lowest level call for making a request, so you'll need to specify all\n the raw details.\n\n .. note::\n\n More commonly, it's appropriate to use a convenience method provided\n by :class:`....
Please provide a description of the function:def _prepare_conn(self, conn): if isinstance(conn, VerifiedHTTPSConnection): conn.set_cert(key_file=self.key_file, cert_file=self.cert_file, cert_reqs=self.cert_reqs, ...
[ "\n Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket`\n and establish the tunnel if proxy is used.\n " ]
Please provide a description of the function:def _prepare_proxy(self, conn): conn.set_tunnel(self._proxy_host, self.port, self.proxy_headers) conn.connect()
[ "\n Establish tunnel connection early, because otherwise httplib\n would improperly set Host: header to proxy's IP:port.\n " ]
Please provide a description of the function:def reload_system_path(self): # type: () -> None if self._system_path is not None: self._system_path.clear_caches() self._system_path = None six.moves.reload_module(pyfinder_path) self._system_path = self.create_s...
[ "\n Rebuilds the base system path and all of the contained finders within it.\n\n This will re-apply any changes to the environment or any version changes on the system.\n " ]
Please provide a description of the function:def find_python_version( self, major=None, minor=None, patch=None, pre=None, dev=None, arch=None, name=None ): # type: (Optional[Union[str, int]], Optional[int], Optional[int], Optional[bool], Optional[bool], Optional[str], Optional[str]) -> PathEntry ...
[ "\n Find the python version which corresponds most closely to the version requested.\n\n :param Union[str, int] major: The major version to look for, or the full version, or the name of the target version.\n :param Optional[int] minor: The minor version. If provided, disables string-based looku...
Please provide a description of the function:def get_shell(pid=None, max_depth=6): pid = str(pid or os.getpid()) mapping = _get_process_mapping() login_shell = os.environ.get('SHELL', '') for _ in range(max_depth): try: proc = mapping[pid] except KeyError: br...
[ "Get the shell that the supplied pid or os.getpid() is running in.\n " ]
Please provide a description of the function:def _make_class_unpicklable(cls): def _break_on_call_reduce(self, protocol=None): raise TypeError('%r cannot be pickled' % self) cls.__reduce_ex__ = _break_on_call_reduce cls.__module__ = '<unknown>'
[ "Make the given class un-picklable." ]
Please provide a description of the function:def _convert(cls, name, module, filter, source=None): # convert all constants from source (or module) that pass filter() to # a new Enum called name, and export the enum and its members back to # module; # also, replace the __reduce_ex__ method so unpick...
[ "\n Create a new Enum subclass that replaces a collection of global constants\n " ]
Please provide a description of the function:def unique(enumeration): duplicates = [] for name, member in enumeration.__members__.items(): if name != member.name: duplicates.append((name, member.name)) if duplicates: duplicate_names = ', '.join( ["%s -> %s" %...
[ "Class decorator that ensures only unique members exist in an enumeration." ]
Please provide a description of the function:def _create_(cls, class_name, names=None, module=None, type=None, start=1): if pyver < 3.0: # if class_name is unicode, attempt a conversion to ASCII if isinstance(class_name, unicode): try: class_n...
[ "Convenience method to create a new Enum class.\n\n `names` can be:\n\n * A string containing member names, separated either with spaces or\n commas. Values are auto-numbered from 1.\n * An iterable of member names. Values are auto-numbered from 1.\n * An iterable of (member n...
Please provide a description of the function:def _get_mixins_(bases): if not bases or Enum is None: return object, Enum # double check that we are not subclassing a class with existing # enumeration members; while we're at it, see if any other data # type has been ...
[ "Returns the type for creating enum members, and the first inherited\n enum class.\n\n bases: the tuple of bases that was given to __new__\n\n " ]
Please provide a description of the function:def _basic_auth_str(username, password): # "I want us to put a big-ol' comment on top of it that # says that this behaviour is dumb but we need to preserve # it because people are relying on it." # - Lukasa # # These are here solely to mainta...
[ "Returns a Basic Auth string." ]
Please provide a description of the function:def format_for_columns(pkgs, options): running_outdated = options.outdated # Adjust the header for the `pip list --outdated` case. if running_outdated: header = ["Package", "Version", "Latest", "Type"] else: header = ["Package", "Version"...
[ "\n Convert the package data into something usable\n by output_package_listing_columns.\n " ]
Please provide a description of the function:def _build_package_finder(self, options, index_urls, session): return PackageFinder( find_links=options.find_links, index_urls=index_urls, allow_all_prereleases=options.pre, trusted_hosts=options.trusted_hosts,...
[ "\n Create a package finder appropriate to this list command.\n " ]
Please provide a description of the function:def _build_shebang(self, executable, post_interp): if os.name != 'posix': simple_shebang = True else: # Add 3 for '#!' prefix and newline suffix. shebang_length = len(executable) + len(post_interp) + 3 ...
[ "\n Build a shebang line. In the simple case (on Windows, or a shebang line\n which is not too long or contains spaces) use a simple formulation for\n the shebang. Otherwise, use /bin/sh as the executable, with a contrived\n shebang which allows the script to run either under Python or s...
Please provide a description of the function:def make(self, specification, options=None): filenames = [] entry = get_export_entry(specification) if entry is None: self._copy_script(specification, filenames) else: self._make_script(entry, filenames, option...
[ "\n Make a script.\n\n :param specification: The specification, which is either a valid export\n entry specification (to make a script from a\n callable) or a filename (to make a script by\n copying from a source lo...
Please provide a description of the function:def make_multiple(self, specifications, options=None): filenames = [] for specification in specifications: filenames.extend(self.make(specification, options)) return filenames
[ "\n Take a list of specifications and make scripts from them,\n :param specifications: A list of specifications.\n :return: A list of all absolute pathnames written to,\n " ]
Please provide a description of the function:def iter_find_files(directory, patterns, ignored=None): if isinstance(patterns, basestring): patterns = [patterns] pats_re = re.compile('|'.join([fnmatch.translate(p) for p in patterns])) if not ignored: ignored = [] elif isinstance(igno...
[ "Returns a generator that yields file paths under a *directory*,\n matching *patterns* using `glob`_ syntax (e.g., ``*.txt``). Also\n supports *ignored* patterns.\n\n Args:\n directory (str): Path that serves as the root of the\n search. Yielded paths will include this as a prefix.\n ...
Please provide a description of the function:def from_int(cls, i): i &= FULL_PERMS key = ('', 'x', 'w', 'xw', 'r', 'rx', 'rw', 'rwx') parts = [] while i: parts.append(key[i & _SINGLE_FULL_PERM]) i >>= 3 parts.reverse() return cls(*parts)
[ "Create a :class:`FilePerms` object from an integer.\n\n >>> FilePerms.from_int(0o644) # note the leading zero-oh for octal\n FilePerms(user='rw', group='r', other='r')\n " ]
Please provide a description of the function:def from_path(cls, path): stat_res = os.stat(path) return cls.from_int(stat.S_IMODE(stat_res.st_mode))
[ "Make a new :class:`FilePerms` object based on the permissions\n assigned to the file or directory at *path*.\n\n Args:\n path (str): Filesystem path of the target file.\n\n >>> from os.path import expanduser\n >>> 'r' in FilePerms.from_path(expanduser('~')).user # probably\n...
Please provide a description of the function:def setup(self): if os.path.lexists(self.dest_path): if not self.overwrite: raise OSError(errno.EEXIST, 'Overwrite disabled and file already exists', self.dest_path) ...
[ "Called on context manager entry (the :keyword:`with` statement),\n the ``setup()`` method creates the temporary file in the same\n directory as the destination file.\n\n ``setup()`` tests for a writable directory with rename permissions\n early, as the part file may not be written to im...
Please provide a description of the function:def load(pipfile_path=None, inject_env=True): if pipfile_path is None: pipfile_path = Pipfile.find() return Pipfile.load(filename=pipfile_path, inject_env=inject_env)
[ "Loads a pipfile from a given path.\n If none is provided, one will try to be found.\n " ]
Please provide a description of the function:def inject_environment_variables(self, d): if not d: return d if isinstance(d, six.string_types): return os.path.expandvars(d) for k, v in d.items(): if isinstance(v, six.string_types): d[k...
[ "\n Recursively injects environment variables into TOML values\n " ]
Please provide a description of the function:def find(max_depth=3): i = 0 for c, d, f in walk_up(os.getcwd()): i += 1 if i < max_depth: if 'Pipfile': p = os.path.join(c, 'Pipfile') if os.path.isfile(p): ...
[ "Returns the path of a Pipfile in parent directories." ]
Please provide a description of the function:def load(klass, filename, inject_env=True): p = PipfileParser(filename=filename) pipfile = klass(filename=filename) pipfile.data = p.parse(inject_env=inject_env) return pipfile
[ "Load a Pipfile from a given filename." ]
Please provide a description of the function:def hash(self): content = json.dumps(self.data, sort_keys=True, separators=(",", ":")) return hashlib.sha256(content.encode("utf8")).hexdigest()
[ "Returns the SHA256 of the pipfile's data." ]
Please provide a description of the function:def lock(self): data = self.data data['_meta']['hash'] = {"sha256": self.hash} data['_meta']['pipfile-spec'] = 6 return json.dumps(data, indent=4, separators=(',', ': '))
[ "Returns a JSON representation of the Pipfile." ]
Please provide a description of the function:def assert_requirements(self): # Support for 508's implementation_version. if hasattr(sys, 'implementation'): implementation_version = format_full_version(sys.implementation.version) else: implementation_version = "0"...
[ "\"Asserts PEP 508 specifiers." ]
Please provide a description of the function:def copyfileobj(fsrc, fdst, length=16*1024): while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf)
[ "copy data from file-like object fsrc to file-like object fdst" ]
Please provide a description of the function:def copyfile(src, dst): if _samefile(src, dst): raise Error("`%s` and `%s` are the same file" % (src, dst)) for fn in [src, dst]: try: st = os.stat(fn) except OSError: # File most likely does not exist ...
[ "Copy data from src to dst" ]
Please provide a description of the function:def copymode(src, dst): if hasattr(os, 'chmod'): st = os.stat(src) mode = stat.S_IMODE(st.st_mode) os.chmod(dst, mode)
[ "Copy mode bits from src to dst" ]
Please provide a description of the function:def copystat(src, dst): st = os.stat(src) mode = stat.S_IMODE(st.st_mode) if hasattr(os, 'utime'): os.utime(dst, (st.st_atime, st.st_mtime)) if hasattr(os, 'chmod'): os.chmod(dst, mode) if hasattr(os, 'chflags') and hasattr(st, 'st_fl...
[ "Copy all stat info (mode bits, atime, mtime, flags) from src to dst" ]
Please provide a description of the function:def copy(src, dst): if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copymode(src, dst)
[ "Copy data and mode bits (\"cp src dst\").\n\n The destination may be a directory.\n\n " ]
Please provide a description of the function:def copy2(src, dst): if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) copyfile(src, dst) copystat(src, dst)
[ "Copy data and all stat info (\"cp -p src dst\").\n\n The destination may be a directory.\n\n " ]
Please provide a description of the function:def rmtree(path, ignore_errors=False, onerror=None): if ignore_errors: def onerror(*args): pass elif onerror is None: def onerror(*args): raise try: if os.path.islink(path): # symlinks to directorie...
[ "Recursively delete a directory tree.\n\n If ignore_errors is set, errors are ignored; otherwise, if onerror\n is set, it is called to handle the error with arguments (func,\n path, exc_info) where func is os.listdir, os.remove, or os.rmdir;\n path is the argument to that function that caused it to fail...
Please provide a description of the function:def move(src, dst): real_dst = dst if os.path.isdir(dst): if _samefile(src, dst): # We might be on a case insensitive filesystem, # perform the rename anyway. os.rename(src, dst) return real_dst = ...
[ "Recursively move a file or directory to another location. This is\n similar to the Unix \"mv\" command.\n\n If the destination is a directory or a symlink to a directory, the source\n is moved inside the directory. The destination path must not already\n exist.\n\n If the destination already exists ...
Please provide a description of the function:def _get_gid(name): if getgrnam is None or name is None: return None try: result = getgrnam(name) except KeyError: result = None if result is not None: return result[2] return None
[ "Returns a gid, given a group name." ]
Please provide a description of the function:def _get_uid(name): if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None
[ "Returns an uid, given a user name." ]
Please provide a description of the function:def _make_tarball(base_name, base_dir, compress="gzip", verbose=0, dry_run=0, owner=None, group=None, logger=None): tar_compression = {'gzip': 'gz', None: ''} compress_ext = {'gzip': '.gz'} if _BZ2_SUPPORTED: tar_compression['bzip2...
[ "Create a (possibly compressed) tar file from all the files under\n 'base_dir'.\n\n 'compress' must be \"gzip\" (the default), \"bzip2\", or None.\n\n 'owner' and 'group' can be used to define an owner and a group for the\n archive that is being built. If not provided, the current owner and group\n w...
Please provide a description of the function:def _make_zipfile(base_name, base_dir, verbose=0, dry_run=0, logger=None): zip_filename = base_name + ".zip" archive_dir = os.path.dirname(base_name) if not os.path.exists(archive_dir): if logger is not None: logger.info("creating %s", a...
[ "Create a zip file from all the files under 'base_dir'.\n\n The output zip file will be named 'base_name' + \".zip\". Uses either the\n \"zipfile\" Python module (if available) or the InfoZIP \"zip\" utility\n (if installed and found on the default search path). If neither tool is\n available, raises ...
Please provide a description of the function:def get_archive_formats(): formats = [(name, registry[2]) for name, registry in _ARCHIVE_FORMATS.items()] formats.sort() return formats
[ "Returns a list of supported formats for archiving and unarchiving.\n\n Each element of the returned sequence is a tuple (name, description)\n " ]
Please provide a description of the function:def register_archive_format(name, function, extra_args=None, description=''): if extra_args is None: extra_args = [] if not isinstance(function, collections.Callable): raise TypeError('The %s object is not callable' % function) if not isinsta...
[ "Registers an archive format.\n\n name is the name of the format. function is the callable that will be\n used to create archives. If provided, extra_args is a sequence of\n (name, value) tuples that will be passed as arguments to the callable.\n description can be provided to describe the format, and w...
Please provide a description of the function:def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, dry_run=0, owner=None, group=None, logger=None): save_cwd = os.getcwd() if root_dir is not None: if logger is not None: logger.debug("changing into ...
[ "Create an archive file (eg. zip or tar).\n\n 'base_name' is the name of the file to create, minus any format-specific\n extension; 'format' is the archive format: one of \"zip\", \"tar\", \"bztar\"\n or \"gztar\".\n\n 'root_dir' is a directory that will be the root directory of the\n archive; ie. we...
Please provide a description of the function:def get_unpack_formats(): formats = [(name, info[0], info[3]) for name, info in _UNPACK_FORMATS.items()] formats.sort() return formats
[ "Returns a list of supported formats for unpacking.\n\n Each element of the returned sequence is a tuple\n (name, extensions, description)\n " ]