_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q276400
_transform_result
test
def _transform_result(typ, result): """Convert the result back into the input type. """ if issubclass(typ, bytes): return tostring(result, encoding='utf-8') elif issubclass(typ,
python
{ "resource": "" }
q276401
html_to_xhtml
test
def html_to_xhtml(html): """Convert all tags in an HTML tree to XHTML by moving them to the XHTML namespace. """ try: html = html.getroot()
python
{ "resource": "" }
q276402
xhtml_to_html
test
def xhtml_to_html(xhtml): """Convert all tags in an XHTML tree to HTML by removing their XHTML namespace. """ try: xhtml = xhtml.getroot() except AttributeError: pass
python
{ "resource": "" }
q276403
tostring
test
def tostring(doc, pretty_print=False, include_meta_content_type=False, encoding=None, method="html", with_tail=True, doctype=None): """Return an HTML string representation of the document. Note: if include_meta_content_type is true this will create a ``<meta http-equiv="Content-Type" ...>`` tag in the head; regardless of the value of include_meta_content_type any existing ``<meta http-equiv="Content-Type" ...>`` tag will be removed The ``encoding`` argument controls the output encoding (defauts to ASCII, with &#...; character references for any characters outside of ASCII). Note that you can pass the name ``'unicode'`` as ``encoding`` argument to serialise to a Unicode string. The ``method`` argument defines the output method. It defaults to 'html', but can also be 'xml' for xhtml output, or 'text' to serialise to plain text without markup. To leave out the tail text of the top-level element that is being serialised, pass ``with_tail=False``. The ``doctype`` option allows passing in a plain string that will be serialised before the XML tree. Note that passing in non well-formed content here will make the XML output non well-formed. Also, an existing doctype in the document tree will not be removed when serialising an ElementTree instance. Example:: >>> from lxml import html >>> root = html.fragment_fromstring('<p>Hello<br>world!</p>') >>> html.tostring(root) b'<p>Hello<br>world!</p>' >>> html.tostring(root, method='html') b'<p>Hello<br>world!</p>' >>> html.tostring(root, method='xml') b'<p>Hello<br/>world!</p>' >>> html.tostring(root, method='text') b'Helloworld!' >>> html.tostring(root, method='text', encoding='unicode')
python
{ "resource": "" }
q276404
open_in_browser
test
def open_in_browser(doc, encoding=None): """ Open the HTML document in a web browser, saving it to a temporary file to open it. Note that this does not delete the file after use. This is mainly meant for debugging. """ import os import webbrowser import tempfile if not isinstance(doc, etree._ElementTree): doc = etree.ElementTree(doc) handle, fn = tempfile.mkstemp(suffix='.html') f = os.fdopen(handle, 'wb') try:
python
{ "resource": "" }
q276405
HtmlMixin.drop_tree
test
def drop_tree(self): """ Removes this element from the tree, including its children and text. The tail text is joined to the previous element or parent. """ parent = self.getparent()
python
{ "resource": "" }
q276406
HtmlMixin.drop_tag
test
def drop_tag(self): """ Remove the tag, but not its children or text. The children and text are merged into the parent. Example:: >>> h = fragment_fromstring('<div>Hello <b>World!</b></div>') >>> h.find('.//b').drop_tag() >>> print(tostring(h, encoding='unicode')) <div>Hello World!</div> """ parent = self.getparent() assert parent is not None previous = self.getprevious()
python
{ "resource": "" }
q276407
HtmlMixin.get_element_by_id
test
def get_element_by_id(self, id, *default): """ Get the first element in a document with the given id. If none is found, return the default argument if provided or raise KeyError otherwise. Note that there can be more than one element with the same id, and this isn't uncommon in HTML documents found in the wild. Browsers return only the first match, and this function does the same. """ try: # FIXME: should this check for
python
{ "resource": "" }
q276408
HtmlMixin.cssselect
test
def cssselect(self, expr, translator='html'): """ Run the CSS expression on this element and its children, returning a list of the results. Equivalent to lxml.cssselect.CSSSelect(expr, translator='html')(self) -- note that pre-compiling the expression can provide a substantial speedup.
python
{ "resource": "" }
q276409
loghandler_members
test
def loghandler_members(): """iterate through the attributes of every logger's handler this is used to switch out stderr and stdout in tests when buffer is True :returns: generator of tuples, each tuple has (name, handler, member_name, member_val) """ Members = namedtuple("Members", ["name", "handler", "member_name", "member"]) log_manager = logging.Logger.manager loggers = [] ignore = set([modname()]) if log_manager.root: loggers = list(log_manager.loggerDict.items())
python
{ "resource": "" }
q276410
get_counts
test
def get_counts(): """return test counts that are set via pyt environment variables when pyt runs the test :returns: dict, 3 keys (classes, tests, modules) and how many tests of each were found by pyt """ counts = {} ks = [
python
{ "resource": "" }
q276411
is_single_class
test
def is_single_class(): """Returns True if only a single class is being run or some tests within a single class""" ret = False counts = get_counts() if counts["classes"] < 1 and counts["modules"] < 1:
python
{ "resource": "" }
q276412
is_single_module
test
def is_single_module(): """Returns True if only a module is being run""" ret = False counts = get_counts() if counts["modules"] == 1:
python
{ "resource": "" }
q276413
validate_params
test
def validate_params(request): """Validate request params.""" if 'params' in request:
python
{ "resource": "" }
q276414
validate_id
test
def validate_id(request): """Validate request id.""" if 'id' in request: correct_id = isinstance(
python
{ "resource": "" }
q276415
filesys_decode
test
def filesys_decode(path): """ Ensure that the given path is decoded, NONE when no expected encoding works """ fs_enc = sys.getfilesystemencoding() if isinstance(path, decoded_string): return path
python
{ "resource": "" }
q276416
_escape_argspec
test
def _escape_argspec(obj, iterable, escape): """Helper for various string-wrapped functions.""" for
python
{ "resource": "" }
q276417
codecName
test
def codecName(encoding): """Return the python codec name corresponding to an encoding or None if the string doesn't correspond to a valid encoding.""" if isinstance(encoding, bytes): try: encoding = encoding.decode("ascii") except UnicodeDecodeError:
python
{ "resource": "" }
q276418
HTMLBinaryInputStream.detectBOM
test
def detectBOM(self): """Attempts to detect at BOM at the start of the stream. If an encoding can be determined from the BOM return the name of the encoding otherwise return None""" bomDict = { codecs.BOM_UTF8: 'utf-8', codecs.BOM_UTF16_LE: 'utf-16-le', codecs.BOM_UTF16_BE: 'utf-16-be', codecs.BOM_UTF32_LE: 'utf-32-le', codecs.BOM_UTF32_BE: 'utf-32-be' } # Go to beginning of file and read in 4 bytes string = self.rawStream.read(4) assert isinstance(string, bytes) # Try detecting the BOM using bytes from the string encoding = bomDict.get(string[:3]) # UTF-8
python
{ "resource": "" }
q276419
ProxyFix.get_remote_addr
test
def get_remote_addr(self, forwarded_for): """Selects the new remote addr from the given list of ips in X-Forwarded-For. By default it picks the one that the
python
{ "resource": "" }
q276420
amount_converter
test
def amount_converter(obj): """Converts amount value from several types into Decimal.""" if isinstance(obj, Decimal): return obj elif isinstance(obj, (str, int,
python
{ "resource": "" }
q276421
fromstring
test
def fromstring(data, beautifulsoup=None, makeelement=None, **bsargs): """Parse a string of HTML data into an Element tree using the BeautifulSoup parser. Returns the root ``<html>`` Element of the tree. You can pass a different BeautifulSoup parser through the `beautifulsoup` keyword, and a diffent Element
python
{ "resource": "" }
q276422
parse
test
def parse(file, beautifulsoup=None, makeelement=None, **bsargs): """Parse a file into an ElemenTree using the BeautifulSoup parser. You can pass a different BeautifulSoup parser through the `beautifulsoup` keyword, and a diffent
python
{ "resource": "" }
q276423
convert_tree
test
def convert_tree(beautiful_soup_tree, makeelement=None): """Convert a BeautifulSoup tree to a list of Element trees. Returns a list instead of a single root Element to support HTML-like soup with more than one root element. You can pass a different Element factory through the `makeelement` keyword. """ if makeelement is None:
python
{ "resource": "" }
q276424
get_current_traceback
test
def get_current_traceback(ignore_system_exceptions=False, show_hidden_frames=False, skip=0): """Get the current exception info as `Traceback` object. Per default calling this method will reraise system exceptions such as generator exit, system exit or others. This behavior can be disabled by passing `False` to the function as first parameter. """ exc_type, exc_value, tb = sys.exc_info()
python
{ "resource": "" }
q276425
Traceback.exception
test
def exception(self): """String representation of the exception.""" buf = traceback.format_exception_only(self.exc_type, self.exc_value)
python
{ "resource": "" }
q276426
Traceback.render_summary
test
def render_summary(self, include_title=True): """Render the traceback for the interactive console.""" title = '' frames = [] classes = ['traceback'] if not self.frames: classes.append('noframe-traceback') if include_title: if self.is_syntax_error: title = u'Syntax Error' else: title = u'Traceback <em>(most recent call last)</em>:'
python
{ "resource": "" }
q276427
Traceback.generate_plaintext_traceback
test
def generate_plaintext_traceback(self): """Like the plaintext attribute but returns a generator""" yield u'Traceback (most recent call last):' for frame in self.frames: yield u' File "%s", line %s, in %s' % (
python
{ "resource": "" }
q276428
Frame.get_annotated_lines
test
def get_annotated_lines(self): """Helper function that returns lines with extra information.""" lines = [Line(idx + 1, x) for idx, x in enumerate(self.sourcelines)] # find function definition and mark lines if hasattr(self.code, 'co_firstlineno'): lineno = self.code.co_firstlineno - 1 while lineno > 0: if _funcdef_re.match(lines[lineno].code):
python
{ "resource": "" }
q276429
Frame.render_source
test
def render_source(self): """Render the sourcecode.""" return SOURCE_TABLE_HTML %
python
{ "resource": "" }
q276430
egg_info_matches
test
def egg_info_matches( egg_info, search_name, link, _egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)): """Pull the version part out of a string. :param egg_info: The string to parse. E.g. foo-2.1 :param search_name: The name of the package this belongs to. None to infer the name. Note that this cannot unambiguously parse strings like foo-2-2 which might be foo, 2-2 or foo-2, 2. :param link: The link the string came from, for logging on failure. """ match = _egg_info_re.search(egg_info) if not match: logger.debug('Could not parse version from link: %s', link) return None if search_name is None: full_match
python
{ "resource": "" }
q276431
PackageFinder._get_index_urls_locations
test
def _get_index_urls_locations(self, project_name): """Returns the locations found via self.index_urls Checks the url_name on the main (first in the list) index and use this url_name to produce all locations """ def mkurl_pypi_url(url): loc = posixpath.join(url, project_url_name) # For maximum compatibility with easy_install, ensure the path # ends in a trailing slash. Although this isn't in the spec # (and PyPI can handle it without the slash) some other index # implementations might break if they relied on easy_install's # behavior. if not loc.endswith('/'): loc = loc + '/' return loc project_url_name = urllib_parse.quote(project_name.lower()) if self.index_urls: # Check that we have the url_name correctly spelled: # Only check main index if index URL is given main_index_url = Link( mkurl_pypi_url(self.index_urls[0]), trusted=True, ) page = self._get_page(main_index_url)
python
{ "resource": "" }
q276432
PackageFinder._find_all_versions
test
def _find_all_versions(self, project_name): """Find all available versions for project_name This checks index_urls, find_links and dependency_links All versions found are returned See _link_package_versions for details on which files are accepted """ index_locations = self._get_index_urls_locations(project_name) index_file_loc, index_url_loc = self._sort_locations(index_locations) fl_file_loc, fl_url_loc = self._sort_locations( self.find_links, expand_dir=True) dep_file_loc, dep_url_loc = self._sort_locations(self.dependency_links) file_locations = ( Link(url) for url in itertools.chain( index_file_loc, fl_file_loc, dep_file_loc) ) # We trust every url that the user has given us whether it was given # via --index-url or --find-links # We explicitly do not trust links that came from dependency_links # We want to filter out any thing which does not have a secure origin. url_locations = [ link for link in itertools.chain( (Link(url, trusted=True) for url in index_url_loc), (Link(url, trusted=True) for url in fl_url_loc), (Link(url) for url in dep_url_loc), ) if self._validate_secure_origin(logger, link) ] logger.debug('%d location(s) to search for versions of %s:', len(url_locations), project_name) for location in url_locations: logger.debug('* %s', location) canonical_name = pkg_resources.safe_name(project_name).lower() formats = fmt_ctl_formats(self.format_control, canonical_name) search = Search(project_name.lower(), canonical_name, formats) find_links_versions = self._package_versions( # We trust every directly linked archive in find_links (Link(url, '-f', trusted=True) for url in self.find_links), search ) page_versions = [] for page in self._get_pages(url_locations, project_name): logger.debug('Analyzing links from page %s', page.url) with indent_log(): page_versions.extend(
python
{ "resource": "" }
q276433
PackageFinder.find_requirement
test
def find_requirement(self, req, upgrade): """Try to find an InstallationCandidate for req Expects req, an InstallRequirement and upgrade, a boolean Returns an InstallationCandidate or None May raise DistributionNotFound or BestVersionAlreadyInstalled """ all_versions = self._find_all_versions(req.name) # Filter out anything which doesn't match our specifier _versions = set( req.specifier.filter( [x.version for x in all_versions], prereleases=( self.allow_all_prereleases if self.allow_all_prereleases else None ), ) ) applicable_versions = [ x for x in all_versions if x.version in _versions ] if req.satisfied_by is not None: # Finally add our existing versions to the front of our versions. applicable_versions.insert( 0, InstallationCandidate( req.name, req.satisfied_by.version, INSTALLED_VERSION, ) ) existing_applicable = True else: existing_applicable = False applicable_versions = self._sort_versions(applicable_versions) if not upgrade and existing_applicable: if applicable_versions[0].location is INSTALLED_VERSION: logger.debug( 'Existing installed version (%s) is most up-to-date and ' 'satisfies requirement', req.satisfied_by.version, ) else: logger.debug( 'Existing installed version (%s) satisfies requirement ' '(most up-to-date version is %s)', req.satisfied_by.version, applicable_versions[0][2], ) return None if not applicable_versions: logger.critical( 'Could not find a version that satisfies the requirement %s ' '(from versions: %s)', req, ', '.join( sorted( set(str(i.version) for i in all_versions), key=parse_version, ) ) ) if self.need_warn_external: logger.warning( "Some externally hosted files were ignored as access to " "them may be unreliable (use --allow-external %s to " "allow).", req.name, ) if self.need_warn_unverified:
python
{ "resource": "" }
q276434
PackageFinder._sort_links
test
def _sort_links(self, links): """ Returns elements of links in order, non-egg links first, egg links second, while eliminating duplicates """ eggs, no_eggs = [], [] seen = set() for link in links: if link not in seen: seen.add(link)
python
{ "resource": "" }
q276435
HTMLPage._get_content_type
test
def _get_content_type(url, session): """Get the Content-Type of the given url, using a HEAD request""" scheme, netloc, path, query, fragment = urllib_parse.urlsplit(url) if scheme not in ('http', 'https'): # FIXME: some warning or something?
python
{ "resource": "" }
q276436
HTMLPage.links
test
def links(self): """Yields all links in the page""" for anchor in self.parsed.findall(".//a"): if anchor.get("href"): href = anchor.get("href") url = self.clean_link( urllib_parse.urljoin(self.base_url, href) ) # Determine if this link is internal. If that distinction # doesn't make sense in this context, then we don't make # any distinction. internal = None
python
{ "resource": "" }
q276437
Link.verifiable
test
def verifiable(self): """ Returns True if this link can be verified after download, False if it cannot, and None if we cannot determine. """ trusted = self.trusted or getattr(self.comes_from, "trusted", None) if trusted is not None and trusted: # This link came from a trusted source. It *may* be verifiable but # first we need to see if this page is operating under the new # API version. try: api_version = getattr(self.comes_from, "api_version", None) api_version = int(api_version) except (ValueError, TypeError): api_version = None if api_version is None or api_version <= 1: # This link is either trusted, or it came from a trusted, # however it is not operating under the API version 2 so # we can't make any claims about if it's safe or not
python
{ "resource": "" }
q276438
build_py.find_data_files
test
def find_data_files(self, package, src_dir): """Return filenames for package's data files in 'src_dir'""" globs = (self.package_data.get('', []) + self.package_data.get(package, [])) files = self.manifest_files.get(package, [])[:] for pattern in globs:
python
{ "resource": "" }
q276439
build_py.exclude_data_files
test
def exclude_data_files(self, package, src_dir, files): """Filter filenames for package's data files in 'src_dir'""" globs = (self.exclude_package_data.get('', []) + self.exclude_package_data.get(package, [])) bad = [] for pattern in globs: bad.extend( fnmatch.filter( files, os.path.join(src_dir, convert_path(pattern))
python
{ "resource": "" }
q276440
parse_requirements
test
def parse_requirements(filename, finder=None, comes_from=None, options=None, session=None, wheel_cache=None): """ Parse a requirements file and yield InstallRequirement instances. :param filename: Path or url of requirements file. :param finder: Instance of pip.index.PackageFinder. :param comes_from: Origin description of requirements. :param options: Global options. :param session: Instance of pip.download.PipSession. :param wheel_cache: Instance of pip.wheel.WheelCache """ if session is None: raise TypeError( "parse_requirements() missing 1 required keyword argument: " "'session'" )
python
{ "resource": "" }
q276441
join_lines
test
def join_lines(iterator): """ Joins a line ending in '\' with the previous line. """ lines = [] for line in iterator: if not line.endswith('\\'): if lines: lines.append(line)
python
{ "resource": "" }
q276442
ignore_comments
test
def ignore_comments(iterator): """ Strips and filters empty or commented lines. """ for line in iterator: line
python
{ "resource": "" }
q276443
compile
test
def compile(marker): """Return compiled marker as a function accepting an environment dict.""" try: return _cache[marker] except KeyError: pass if not marker.strip(): def marker_fn(environment=None, override=None): """""" return True else: compiled_marker = compile_marker(parse_marker(marker)) def marker_fn(environment=None, override=None): """override updates environment""" if override is None: override = {}
python
{ "resource": "" }
q276444
ASTWhitelist.visit
test
def visit(self, node): """Ensure statement only contains allowed nodes.""" if not isinstance(node, self.ALLOWED): raise SyntaxError('Not allowed in environment markers.\n%s\n%s' %
python
{ "resource": "" }
q276445
ASTWhitelist.visit_Attribute
test
def visit_Attribute(self, node): """Flatten one level of attribute access.""" new_node
python
{ "resource": "" }
q276446
coerce
test
def coerce(value): """ coerce takes a value and attempts to convert it to a float, or int. If none of the conversions are successful, the original value is returned. >>> coerce('3')
python
{ "resource": "" }
q276447
copy_current_request_context
test
def copy_current_request_context(f): """A helper function that decorates a function to retain the current request context. This is useful when working with greenlets. The moment the function is decorated a copy of the request context is created and then pushed when the function is called. Example:: import gevent from flask import copy_current_request_context @app.route('/') def index(): @copy_current_request_context
python
{ "resource": "" }
q276448
AppContext.push
test
def push(self): """Binds the app context to the current context.""" self._refcnt += 1
python
{ "resource": "" }
q276449
AppContext.pop
test
def pop(self, exc=None): """Pops the app context.""" self._refcnt -= 1 if self._refcnt <= 0: if exc is None: exc = sys.exc_info()[1] self.app.do_teardown_appcontext(exc) rv = _app_ctx_stack.pop() assert rv
python
{ "resource": "" }
q276450
RequestContext.copy
test
def copy(self): """Creates a copy of this request context with the same request object. This can be used to move a request context to a different greenlet. Because the actual request object is the same this cannot be used to move a request context to a different thread unless access to the
python
{ "resource": "" }
q276451
RequestContext.match_request
test
def match_request(self): """Can be overridden by a subclass to hook into the matching of the request. """ try: url_rule, self.request.view_args = \ self.url_adapter.match(return_rule=True)
python
{ "resource": "" }
q276452
RequestContext.push
test
def push(self): """Binds the request context to the current context.""" # If an exception occurs in debug mode or if context preservation is # activated under exception situations exactly one context stays # on the stack. The rationale is that you want to access that # information under debug situations. However if someone forgets to # pop that context again we want to make sure that on the next push # it's invalidated, otherwise we run at risk that something leaks # memory. This is usually only a problem in testsuite since this # functionality is not active in production environments. top = _request_ctx_stack.top if top is not None and top.preserved: top.pop(top._preserved_exc) # Before we push the request context we have to ensure that there # is an application context. app_ctx = _app_ctx_stack.top if app_ctx is None or app_ctx.app != self.app: app_ctx = self.app.app_context() app_ctx.push() self._implicit_app_ctx_stack.append(app_ctx)
python
{ "resource": "" }
q276453
make_path_relative
test
def make_path_relative(path, rel_to): """ Make a filename relative, where the filename path, and it is relative to rel_to >>> make_path_relative('/usr/share/something/a-file.pth', ... '/usr/share/another-place/src/Directory') '../../../something/a-file.pth' >>> make_path_relative('/usr/share/something/a-file.pth', ... '/home/user/src/Directory') '../../../usr/share/something/a-file.pth'
python
{ "resource": "" }
q276454
dist_is_editable
test
def dist_is_editable(dist): """Is distribution an editable install?""" # TODO: factor out determining editableness out of FrozenRequirement from
python
{ "resource": "" }
q276455
Blueprint.url_value_preprocessor
test
def url_value_preprocessor(self, f): """Registers a function as URL value preprocessor for this blueprint. It's called before the view functions are called and can modify the url values provided. """
python
{ "resource": "" }
q276456
Blueprint.url_defaults
test
def url_defaults(self, f): """Callback function for URL defaults for this blueprint. It's called with the endpoint and values and
python
{ "resource": "" }
q276457
Blueprint.errorhandler
test
def errorhandler(self, code_or_exception): """Registers an error handler that becomes active for this blueprint only. Please be aware that routing does not happen local to a blueprint so an error handler for 404 usually is not handled by a blueprint unless it is caused inside a view function. Another special case is the 500 internal server error which is always looked up from the
python
{ "resource": "" }
q276458
stream_with_context
test
def stream_with_context(generator_or_function): """Request contexts disappear when the response is started on the server. This is done for efficiency reasons and to make it less likely to encounter memory leaks with badly written WSGI middlewares. The downside is that if you are using streamed responses, the generator cannot access request bound information any more. This function however can help you keep the context around for longer:: from flask import stream_with_context, request, Response @app.route('/stream') def streamed_response(): @stream_with_context def generate(): yield 'Hello ' yield request.args['name'] yield '!' return Response(generate()) Alternatively it can also be used around a specific generator:: from flask import stream_with_context, request, Response @app.route('/stream') def streamed_response(): def generate(): yield 'Hello ' yield request.args['name']
python
{ "resource": "" }
q276459
make_response
test
def make_response(*args): """Sometimes it is necessary to set additional headers in a view. Because views do not have to return response objects but can return a value that is converted into a response object by Flask itself, it becomes tricky to add headers to it. This function can be called instead of using a return and you will get a response object which you can use to attach headers. If view looked like this and you want to add a new header:: def index(): return render_template('index.html', foo=42) You can now do something like this:: def index(): response = make_response(render_template('index.html', foo=42)) response.headers['X-Parachutes'] = 'parachutes are cool'
python
{ "resource": "" }
q276460
url_for
test
def url_for(endpoint, **values): """Generates a URL to the given endpoint with the method provided. Variable arguments that are unknown to the target endpoint are appended to the generated URL as query arguments. If the value of a query argument is `None`, the whole pair is skipped. In case blueprints are active you can shortcut references to the same blueprint by prefixing the local endpoint with a dot (``.``). This will reference the index function local to the current blueprint:: url_for('.index') For more information, head over to the :ref:`Quickstart <url-building>`. To integrate applications, :class:`Flask` has a hook to intercept URL build errors through :attr:`Flask.build_error_handler`. The `url_for` function results in a :exc:`~werkzeug.routing.BuildError` when the current app does not have a URL for the given endpoint and values. When it does, the :data:`~flask.current_app` calls its :attr:`~Flask.build_error_handler` if it is not `None`, which can return a string to use as the result of `url_for` (instead of `url_for`'s default to raise the :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception. An example:: def external_url_handler(error, endpoint, **values): "Looks up an external URL when `url_for` cannot build a URL." # This is an example of hooking the build_error_handler. # Here, lookup_url is some utility function you've built # which looks up the endpoint in some external URL registry. url = lookup_url(endpoint, **values) if url is None: # External lookup did not have a URL. # Re-raise the BuildError, in context of original traceback. exc_type, exc_value, tb = sys.exc_info() if exc_value is error: raise exc_type, exc_value, tb else: raise error # url_for will use this result, instead of raising BuildError. return url app.build_error_handler = external_url_handler Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and `endpoint` and `**values` are the arguments passed into `url_for`. Note that this is for building URLs outside the current application, and not for handling 404 NotFound errors. .. versionadded:: 0.10 The `_scheme` parameter was added. .. versionadded:: 0.9 The `_anchor` and `_method` parameters were added. .. versionadded:: 0.9 Calls :meth:`Flask.handle_build_error` on :exc:`~werkzeug.routing.BuildError`. :param endpoint: the endpoint of the URL (name of the function) :param values: the variable arguments of the URL rule :param _external: if set to `True`, an absolute URL is generated. Server address can be changed via `SERVER_NAME` configuration variable which defaults to `localhost`. :param _scheme: a string specifying the desired URL scheme. The `_external` parameter must be set to `True` or a `ValueError` is raised. :param _anchor: if provided this is added as anchor to the URL. :param _method: if provided this explicitly specifies an HTTP method. """ appctx = _app_ctx_stack.top reqctx = _request_ctx_stack.top if appctx is None: raise RuntimeError('Attempted to generate a URL without the ' 'application context being pushed. This has to be '
python
{ "resource": "" }
q276461
safe_join
test
def safe_join(directory, filename): """Safely join `directory` and `filename`. Example usage:: @app.route('/wiki/<path:filename>') def wiki_page(filename): filename = safe_join(app.config['WIKI_FOLDER'], filename) with open(filename, 'rb') as fd: content = fd.read() # Read and process the file content... :param directory: the base directory. :param filename: the untrusted filename relative to that directory. :raises: :class:`~werkzeug.exceptions.NotFound` if the resulting path
python
{ "resource": "" }
q276462
get_root_path
test
def get_root_path(import_name): """Returns the path to a package or cwd if that cannot be found. This returns the path of a package or the folder that contains a module. Not to be confused with the package path returned by :func:`find_package`. """ # Module already imported and has a file attribute. Use that first. mod = sys.modules.get(import_name) if mod is not None and hasattr(mod, '__file__'): return os.path.dirname(os.path.abspath(mod.__file__)) # Next attempt: check the loader. loader = pkgutil.get_loader(import_name) # Loader does not exist or we're referring to an unloaded main module # or a main module without path (interactive sessions), go with the # current working directory. if loader is None or import_name == '__main__': return os.getcwd()
python
{ "resource": "" }
q276463
_PackageBoundObject.jinja_loader
test
def jinja_loader(self): """The Jinja loader for this package bound object. .. versionadded:: 0.5 """ if self.template_folder is not None:
python
{ "resource": "" }
q276464
CompletionCommand.run
test
def run(self, options, args): """Prints the completion code of the given shell""" shells = COMPLETION_SCRIPTS.keys() shell_options = ['--' + shell for shell in sorted(shells)] if options.shell in shells: script = COMPLETION_SCRIPTS.get(options.shell, '')
python
{ "resource": "" }
q276465
SessionInterface.get_cookie_domain
test
def get_cookie_domain(self, app): """Helpful helper method that returns the cookie domain that should be used for the session cookie if session cookies are used. """ if app.config['SESSION_COOKIE_DOMAIN'] is not None: return app.config['SESSION_COOKIE_DOMAIN'] if app.config['SERVER_NAME'] is not None: # chop of the port which is usually not supported by browsers rv = '.' + app.config['SERVER_NAME'].rsplit(':', 1)[0] # Google chrome does not like cookies set to .localhost, so # we just go with no domain then. Flask documents anyways that # cross domain cookies need a fully qualified domain name
python
{ "resource": "" }
q276466
_cache_for_link
test
def _cache_for_link(cache_dir, link): """ Return a directory to store cached wheels in for link. Because there are M wheels for any one sdist, we provide a directory to cache them in, and then consult that directory when looking up cache hits. We only insert things into the cache if they have plausible version numbers, so that we don't contaminate the cache with things that were not unique. E.g. ./package might have dozens of installs done for it and build a version of 0.0...and if we built and cached a wheel, we'd end up using the same wheel even if the source has been edited. :param cache_dir: The cache_dir being used by pip. :param link: The link of the sdist for which this will cache wheels. """
python
{ "resource": "" }
q276467
root_is_purelib
test
def root_is_purelib(name, wheeldir): """ Return True if the extracted wheel in wheeldir should go into purelib. """ name_folded = name.replace("-", "_") for item in os.listdir(wheeldir): match = dist_info_re.match(item) if match and match.group('name') == name_folded: with open(os.path.join(wheeldir, item, 'WHEEL')) as wheel:
python
{ "resource": "" }
q276468
uninstallation_paths
test
def uninstallation_paths(dist): """ Yield all the uninstallation paths for dist based on RECORD-without-.pyc Yield paths to all the files in RECORD. For each .py file in RECORD, add the .pyc in the same directory. UninstallPathSet.add() takes care of the __pycache__ .pyc. """ from pip.utils import FakeFile # circular import r = csv.reader(FakeFile(dist.get_metadata_lines('RECORD'))) for row in r:
python
{ "resource": "" }
q276469
check_compatibility
test
def check_compatibility(version, name): """ Raises errors or warns if called with an incompatible Wheel-Version. Pip should refuse to install a Wheel-Version that's a major series ahead of what it's compatible with (e.g 2.0 > 1.1); and warn when installing a version only minor version ahead (e.g 1.2 > 1.1). version: a 2-tuple representing a Wheel-Version (Major, Minor) name: name of wheel or package to raise exception about :raises UnsupportedWheel: when an incompatible Wheel-Version is given """ if not version: raise UnsupportedWheel( "%s is in an unsupported or invalid wheel" % name )
python
{ "resource": "" }
q276470
WheelBuilder._build_one
test
def _build_one(self, req, output_dir): """Build one wheel. :return: The filename of the built wheel, or None if the build failed. """ tempd = tempfile.mkdtemp('pip-wheel-') try: if self.__build_one(req, tempd): try: wheel_name = os.listdir(tempd)[0] wheel_path = os.path.join(output_dir, wheel_name) shutil.move(os.path.join(tempd, wheel_name), wheel_path)
python
{ "resource": "" }
q276471
iter_symbols
test
def iter_symbols(code): """Yield names and strings used by `code` and its nested code objects""" for name in code.co_names: yield name for const in code.co_consts: if isinstance(const, basestring): yield const
python
{ "resource": "" }
q276472
ensure_fresh_rates
test
def ensure_fresh_rates(func): """Decorator for Backend that ensures rates are fresh within last 5 mins""" def wrapper(self, *args,
python
{ "resource": "" }
q276473
manifest_maker._add_egg_info
test
def _add_egg_info(self, cmd): """ Add paths for egg-info files for an external egg-base. The egg-info files are written to egg-base. If egg-base is outside the current working directory, this method searchs the egg-base directory for files to include in the manifest. Uses distutils.filelist.findall (which is really the version monkeypatched in by setuptools/__init__.py) to perform the search. Since findall records relative paths, prefix the returned paths with cmd.egg_base, so add_default's include_pattern call (which is looking for the absolute cmd.egg_info) will match them.
python
{ "resource": "" }
q276474
write_delete_marker_file
test
def write_delete_marker_file(directory): """ Write the pip delete marker file into this directory.
python
{ "resource": "" }
q276475
running_under_virtualenv
test
def running_under_virtualenv(): """ Return True if we're running inside a virtualenv, False otherwise. """ if hasattr(sys, 'real_prefix'):
python
{ "resource": "" }
q276476
__get_username
test
def __get_username(): """ Returns the effective username of the current process. """ if WINDOWS: return getpass.getuser()
python
{ "resource": "" }
q276477
distutils_scheme
test
def distutils_scheme(dist_name, user=False, home=None, root=None, isolated=False): """ Return a distutils install scheme """ from distutils.dist import Distribution scheme = {} if isolated: extra_dist_args = {"script_args": ["--no-user-cfg"]} else: extra_dist_args = {} dist_args = {'name': dist_name} dist_args.update(extra_dist_args) d = Distribution(dist_args) d.parse_config_files() i = d.get_command_obj('install', create=True) # NOTE: setting user or home has the side-effect of creating the home dir # or user base for installations during finalize_options() # ideally, we'd prefer a scheme class that has no side-effects. i.user = user or i.user i.home = home or i.home i.root = root or i.root i.finalize_options() for key in SCHEME_KEYS:
python
{ "resource": "" }
q276478
CacheController.parse_cache_control
test
def parse_cache_control(self, headers): """ Parse the cache control headers returning a dictionary with values for the different directives. """ retval = {} cc_header = 'cache-control' if 'Cache-Control' in headers: cc_header = 'Cache-Control' if cc_header in headers: parts = headers[cc_header].split(',') parts_with_args = [ tuple([x.strip().lower() for x in part.split("=", 1)])
python
{ "resource": "" }
q276479
CacheController.cached_request
test
def cached_request(self, request): """ Return a cached response if it exists in the cache, otherwise return False. """ cache_url = self.cache_url(request.url) cc = self.parse_cache_control(request.headers) # non-caching states no_cache = True if 'no-cache' in cc else False if 'max-age' in cc and cc['max-age'] == 0: no_cache = True # Bail out if no-cache was set if no_cache: return False # It is in the cache, so lets see if it is going to be # fresh enough resp = self.serializer.loads(request, self.cache.get(cache_url)) # Check to see if we have a cached object if not resp: return False # If we have a cached 301, return it immediately. We don't # need to test our response for other headers b/c it is # intrinsically "cacheable" as it is Permanent. # See: # https://tools.ietf.org/html/rfc7231#section-6.4.2 # # Client can try to refresh the value by repeating the request # with cache busting headers as usual (ie no-cache). if resp.status == 301: return resp headers = CaseInsensitiveDict(resp.headers) if not headers or 'date' not in headers: # With date or etag, the cached response can never be used # and should be deleted. if 'etag' not in headers: self.cache.delete(cache_url) return False now = time.time() date = calendar.timegm( parsedate_tz(headers['date']) ) current_age = max(0, now - date) # TODO: There is an assumption that the result will be a # urllib3 response object. This may not be best since we # could probably avoid instantiating or constructing the # response until we know we need it. resp_cc = self.parse_cache_control(headers) # determine freshness freshness_lifetime = 0 # Check the max-age pragma in the cache control header if 'max-age' in resp_cc and resp_cc['max-age'].isdigit():
python
{ "resource": "" }
q276480
CacheController.cache_response
test
def cache_response(self, request, response, body=None): """ Algorithm for caching requests. This assumes a requests Response object. """ # From httplib2: Don't cache 206's since we aren't going to # handle byte range requests if response.status not in [200, 203, 300, 301]: return response_headers = CaseInsensitiveDict(response.headers) cc_req = self.parse_cache_control(request.headers) cc = self.parse_cache_control(response_headers) cache_url = self.cache_url(request.url) # Delete it from the cache if we happen to have it stored there no_store = cc.get('no-store') or cc_req.get('no-store') if no_store and self.cache.get(cache_url): self.cache.delete(cache_url) # If we've been given an etag, then keep the response if self.cache_etags and 'etag' in response_headers: self.cache.set( cache_url, self.serializer.dumps(request, response, body=body), ) # Add to the cache any 301s. We do this before looking that # the Date headers. elif response.status == 301: self.cache.set(
python
{ "resource": "" }
q276481
_update_zipimporter_cache
test
def _update_zipimporter_cache(normalized_path, cache, updater=None): """ Update zipimporter cache data for a given normalized path. Any sub-path entries are processed as well, i.e. those corresponding to zip archives embedded in other zip archives. Given updater is a callable taking a cache entry key and the original entry (after already removing the entry from the cache), and expected to update the entry and possibly return a new one to be inserted in its place. Returning None indicates that the entry should not be replaced with a new one. If no updater is given, the cache entries are simply removed without any additional processing, the same as if the updater simply returned
python
{ "resource": "" }
q276482
easy_install._load_template
test
def _load_template(dev_path): """ There are a couple of template scripts in the package. This function loads one of them and prepares it for use. """ # See https://bitbucket.org/pypa/setuptools/issue/134 for info # on script file naming and downstream issues with SVR4 name = 'script.tmpl'
python
{ "resource": "" }
q276483
easy_install.install_site_py
test
def install_site_py(self): """Make sure there's a site.py in the target dir, if needed""" if self.sitepy_installed: return # already did it, or don't need to sitepy = os.path.join(self.install_dir, "site.py") source = resource_string("setuptools", "site-patch.py") current = "" if os.path.exists(sitepy): log.debug("Checking existing site.py in %s", self.install_dir) f = open(sitepy, 'rb') current = f.read() # we want str, not bytes if PY3: current = current.decode() f.close() if not current.startswith('def __boot():'): raise DistutilsError( "%s is not a setuptools-generated site.py; please"
python
{ "resource": "" }
q276484
PthDistributions.save
test
def save(self): """Write changed .pth file back to disk""" if not self.dirty: return data = '\n'.join(map(self.make_relative, self.paths)) if data: log.debug("Saving %s", self.filename) data = ( "import sys; sys.__plen = len(sys.path)\n" "%s\n" "import sys; new=sys.path[sys.__plen:];" " del sys.path[sys.__plen:];" " p=getattr(sys,'__egginsert',0); sys.path[p:p]=new;" " sys.__egginsert = p+len(new)\n" ) %
python
{ "resource": "" }
q276485
BaseConfigurator.convert
test
def convert(self, value): """ Convert values to an appropriate type. dicts, lists and tuples are replaced by their converting alternatives. Strings are checked to see if they have a conversion format and are converted if they do. """ if not isinstance(value, ConvertingDict) and isinstance(value, dict): value = ConvertingDict(value) value.configurator = self elif not isinstance(value, ConvertingList) and isinstance(value, list): value = ConvertingList(value) value.configurator = self elif not isinstance(value, ConvertingTuple) and\ isinstance(value, tuple):
python
{ "resource": "" }
q276486
DictConfigurator.add_filters
test
def add_filters(self, filterer, filters): """Add filters to a filterer from a list of names.""" for f in filters: try: filterer.addFilter(self.config['filters'][f])
python
{ "resource": "" }
q276487
DictConfigurator.configure_handler
test
def configure_handler(self, config): """Configure a handler from a dictionary.""" formatter = config.pop('formatter', None) if formatter: try: formatter = self.config['formatters'][formatter] except StandardError as e: raise ValueError('Unable to set formatter ' '%r: %s' % (formatter, e)) level = config.pop('level', None) filters = config.pop('filters', None) if '()' in config: c = config.pop('()') if not hasattr(c, '__call__') and hasattr(types, 'ClassType') and type(c) != types.ClassType: c = self.resolve(c) factory = c else: klass = self.resolve(config.pop('class')) # Special case for handler which refers to another handler if issubclass(klass, logging.handlers.MemoryHandler) and\ 'target' in config:
python
{ "resource": "" }
q276488
DictConfigurator.add_handlers
test
def add_handlers(self, logger, handlers): """Add handlers to a logger from a list of names.""" for h in handlers: try: logger.addHandler(self.config['handlers'][h])
python
{ "resource": "" }
q276489
DictConfigurator.common_logger_config
test
def common_logger_config(self, logger, config, incremental=False): """ Perform configuration which is common to root and non-root loggers. """ level = config.get('level', None) if level is not None: logger.setLevel(_checkLevel(level)) if not incremental: # Remove any existing handlers for h in logger.handlers[:]: logger.removeHandler(h)
python
{ "resource": "" }
q276490
_execfile
test
def _execfile(filename, globals, locals=None): """ Python 3 implementation of execfile. """ mode = 'rb' with open(filename, mode) as stream: script = stream.read() # compile() function in Python 2.6 and 3.1 requires LF
python
{ "resource": "" }
q276491
override_temp
test
def override_temp(replacement): """ Monkey-patch tempfile.tempdir with replacement, ensuring it exists """ if not os.path.isdir(replacement): os.makedirs(replacement) saved = tempfile.tempdir
python
{ "resource": "" }
q276492
Git.get_url_rev
test
def get_url_rev(self): """ Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'. That's required because although they use SSH they sometimes doesn't work with a ssh:// scheme (e.g. Github). But we need a scheme for parsing. Hence we remove it
python
{ "resource": "" }
q276493
Environment.getitem
test
def getitem(self, obj, argument): """Get an item or attribute of an object but prefer the item.""" try: return obj[argument] except (TypeError, LookupError): if isinstance(argument, string_types): try: attr = str(argument) except Exception:
python
{ "resource": "" }
q276494
Environment._generate
test
def _generate(self, source, name, filename, defer_init=False): """Internal hook that can be overridden to hook a
python
{ "resource": "" }
q276495
Environment.compile_templates
test
def compile_templates(self, target, extensions=None, filter_func=None, zip='deflated', log_function=None, ignore_errors=True, py_compile=False): """Finds all the templates the loader can find, compiles them and stores them in `target`. If `zip` is `None`, instead of in a zipfile, the templates will be will be stored in a directory. By default a deflate zip algorithm is used, to switch to the stored algorithm, `zip` can be set to ``'stored'``. `extensions` and `filter_func` are passed to :meth:`list_templates`. Each template returned will be compiled to the target folder or zipfile. By default template compilation errors are ignored. In case a log function is provided, errors are logged. If you want template syntax errors to abort the compilation you can set `ignore_errors` to `False` and you will get an exception on syntax errors. If `py_compile` is set to `True` .pyc files will be written to the target instead of standard .py files. This flag does not do anything on pypy and Python 3 where pyc files are not picked up by itself and don't give much benefit. .. versionadded:: 2.4 """ from jinja2.loaders import ModuleLoader if log_function is None: log_function = lambda x: None if py_compile: if not PY2 or PYPY: from warnings import warn warn(Warning('py_compile has no effect on pypy or Python 3')) py_compile = False else:
python
{ "resource": "" }
q276496
get_default_cache
test
def get_default_cache(): """Determine the default cache location This returns the ``PYTHON_EGG_CACHE`` environment variable, if set. Otherwise, on Windows, it returns a "Python-Eggs" subdirectory of the "Application Data" directory. On all other systems, it's "~/.python-eggs". """ try: return os.environ['PYTHON_EGG_CACHE'] except KeyError: pass if os.name!='nt': return os.path.expanduser('~/.python-eggs') # XXX this may be locale-specific! app_data = 'Application Data' app_homes = [
python
{ "resource": "" }
q276497
find_eggs_in_zip
test
def find_eggs_in_zip(importer, path_item, only=False): """ Find eggs in zip files; possibly multiple nested eggs. """ 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(importer) if metadata.has_metadata('PKG-INFO'): yield Distribution.from_filename(path_item, metadata=metadata) if only:
python
{ "resource": "" }
q276498
find_on_path
test
def find_on_path(importer, path_item, only=False): """Yield distributions accessible on a sys.path directory""" path_item = _normalize_cached(path_item) if os.path.isdir(path_item) and os.access(path_item, os.R_OK): if path_item.lower().endswith('.egg'): # unpacked egg yield Distribution.from_filename( path_item, metadata=PathMetadata( path_item, os.path.join(path_item,'EGG-INFO') ) ) else: # scan for .egg and .egg-info in directory for entry in os.listdir(path_item): lower = entry.lower() if lower.endswith('.egg-info') or lower.endswith('.dist-info'): fullpath = os.path.join(path_item, entry)
python
{ "resource": "" }
q276499
declare_namespace
test
def declare_namespace(packageName): """Declare that package 'packageName' is a namespace package""" imp.acquire_lock() try: if packageName in _namespace_packages: return path, parent = sys.path, None if '.' in packageName: parent = '.'.join(packageName.split('.')[:-1]) declare_namespace(parent) if parent not in _namespace_packages: __import__(parent) try: path = sys.modules[parent].__path__ except AttributeError: raise TypeError("Not a package:", parent)
python
{ "resource": "" }