INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
If the executable given isn't an absolute path, search $PATH for the interpreter
def resolve_interpreter(exe): """ If the executable given isn't an absolute path, search $PATH for the interpreter """ # If the "executable" is a version number, get the installed executable for # that version python_versions = get_installed_pythons() if exe in python_versions: exe =...
Makes the already-existing environment use relative paths, and takes out the #!-based environment selection in scripts.
def make_environment_relocatable(home_dir): """ Makes the already-existing environment use relative paths, and takes out the #!-based environment selection in scripts. """ home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir) activate_this = os.path.join(bin_dir, 'activate_this.py') ...
Return a script that'll work in a relocatable environment.
def relative_script(lines): "Return a script that'll work in a relocatable environment." activate = "import os; activate_this=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'activate_this.py'); exec(compile(open(activate_this).read(), activate_this, 'exec'), dict(__file__=activate_this)); del os, act...
Makes .pth and .egg-link files use relative paths
def fixup_pth_and_egg_link(home_dir, sys_path=None): """Makes .pth and .egg-link files use relative paths""" home_dir = os.path.normcase(os.path.abspath(home_dir)) if sys_path is None: sys_path = sys.path for path in sys_path: if not path: path = '.' if not os.path.is...
Make a filename relative, where the filename is dest, and it is being referred to from the filename source. >>> make_relative_path('/usr/share/something/a-file.pth', ... '/usr/share/another-place/src/Directory') '../another-place/src/Directory' >>> make_relative_p...
def make_relative_path(source, dest, dest_is_directory=True): """ Make a filename relative, where the filename is dest, and it is being referred to from the filename source. >>> make_relative_path('/usr/share/something/a-file.pth', ... '/usr/share/another-place/src/Direct...
Creates a bootstrap script, which is like this script but with extend_parser, adjust_options, and after_install hooks. This returns a string that (written to disk of course) can be used as a bootstrap script with your own customizations. The script will be the standard virtualenv.py script, with your ...
def create_bootstrap_script(extra_text, python_version=''): """ Creates a bootstrap script, which is like this script but with extend_parser, adjust_options, and after_install hooks. This returns a string that (written to disk of course) can be used as a bootstrap script with your own customization...
Read a given number of 32-bits unsigned integers from the given file with the given endianness.
def read_data(file, endian, num=1): """ Read a given number of 32-bits unsigned integers from the given file with the given endianness. """ res = struct.unpack(endian + 'L' * num, file.read(num * 4)) if len(res) == 1: return res[0] return res
If we are in a progress scope, and no log messages have been shown, write out another '.
def show_progress(self): """If we are in a progress scope, and no log messages have been shown, write out another '.'""" if self.in_progress_hanging: sys.stdout.write('.') sys.stdout.flush()
Returns the level that stdout runs at
def _stdout_level(self): """Returns the level that stdout runs at""" for level, consumer in self.consumers: if consumer is sys.stdout: return level return self.FATAL
>>> l = Logger([]) >>> l.level_matches(3, 4) False >>> l.level_matches(3, 2) True >>> l.level_matches(slice(None, 3), 3) False >>> l.level_matches(slice(None, 3), 2) True >>> l.level_matches(slice(1, 3), 1) True >>> l.level_matches(...
def level_matches(self, level, consumer_level): """ >>> l = Logger([]) >>> l.level_matches(3, 4) False >>> l.level_matches(3, 2) True >>> l.level_matches(slice(None, 3), 3) False >>> l.level_matches(slice(None, 3), 2) True >>> l.lev...
Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists).
def update_defaults(self, defaults): """ Updates the given defaults with values from the config files and the environ. Does a little special handling for certain types of options (lists). """ # Then go and look for the other sources of configuration: config = {} ...
Get a section of a configuration
def get_config_section(self, name): """ Get a section of a configuration """ if self.config.has_section(name): return self.config.items(name) return []
Returns a generator with all environmental vars with prefix VIRTUALENV
def get_environ_vars(self, prefix='VIRTUALENV_'): """ Returns a generator with all environmental vars with prefix VIRTUALENV """ for key, val in os.environ.items(): if key.startswith(prefix): yield (key.replace(prefix, '').lower(), val)
Overridding to make updating the defaults after instantiation of the option parser possible, update_defaults() does the dirty work.
def get_default_values(self): """ Overridding to make updating the defaults after instantiation of the option parser possible, update_defaults() does the dirty work. """ if not self.process_default_values: # Old, pre-Optik 1.5 behaviour. return optparse.Va...
Read the next method from the source, once one complete method has been assembled it is placed in the internal queue.
def _next_method(self): """Read the next method from the source, once one complete method has been assembled it is placed in the internal queue.""" queue = self.queue put = self._quick_put read_frame = self.source.read_frame while not queue: try: ...
Process Content Header frames
def _process_content_header(self, channel, payload): """Process Content Header frames""" partial = self.partial_messages[channel] partial.add_header(payload) if partial.complete: # # a bodyless message, we're done # self._quick_put((channe...
Process Content Body frames
def _process_content_body(self, channel, payload): """Process Content Body frames""" partial = self.partial_messages[channel] partial.add_payload(payload) if partial.complete: # # Stick the message in the queue and go back to # waiting for method frame...
Read a method from the peer.
def read_method(self): """Read a method from the peer.""" self._next_method() m = self._quick_get() if isinstance(m, Exception): raise m if isinstance(m, tuple) and isinstance(m[1], AMQPError): raise m[1] return m
Since argparse doesn't support much introspection, we monkey-patch it to replace the parse_known_args method and all actions with hooks that tell us which action was last taken or about to be taken, and let us have the parser figure out which subparsers need to be activated (then recursively monkey-patc...
def _patch_argument_parser(self): ''' Since argparse doesn't support much introspection, we monkey-patch it to replace the parse_known_args method and all actions with hooks that tell us which action was last taken or about to be taken, and let us have the parser figure out which subpars...
Visits the active parsers and their actions, executes their completers or introspects them to collect their option strings. Returns the resulting completions as a list of strings. This method is exposed for overriding in subclasses; there is no need to use it directly.
def collect_completions(self, active_parsers, parsed_args, cword_prefix, debug): ''' Visits the active parsers and their actions, executes their completers or introspects them to collect their option strings. Returns the resulting completions as a list of strings. This method is exposed...
Ensures collected completions are Unicode text, de-duplicates them, and excludes those specified by ``exclude``. Returns the filtered completions as an iterable. This method is exposed for overriding in subclasses; there is no need to use it directly.
def filter_completions(self, completions): ''' Ensures collected completions are Unicode text, de-duplicates them, and excludes those specified by ``exclude``. Returns the filtered completions as an iterable. This method is exposed for overriding in subclasses; there is no need to use i...
If the word under the cursor started with a quote (as indicated by a nonempty ``cword_prequote``), escapes occurrences of that quote character in the completions, and adds the quote to the beginning of each completion. Otherwise, escapes all characters that bash splits words on (``COMP_WORDBREAKS``), an...
def quote_completions(self, completions, cword_prequote, first_colon_pos): ''' If the word under the cursor started with a quote (as indicated by a nonempty ``cword_prequote``), escapes occurrences of that quote character in the completions, and adds the quote to the beginning of each completion...
Alternate entry point for using the argcomplete completer in a readline-based REPL. See also `rlcompleter <https://docs.python.org/2/library/rlcompleter.html#completer-objects>`_. Usage: .. code-block:: python import argcomplete, argparse, readline parser = argparse.Ar...
def complete(self, text, state): ''' Alternate entry point for using the argcomplete completer in a readline-based REPL. See also `rlcompleter <https://docs.python.org/2/library/rlcompleter.html#completer-objects>`_. Usage: .. code-block:: python import argcomplete...
This is called to create a connection instance. Normally you'd pass a connection class to do_open, but it doesn't actually check for a class, and just expects a callable. As long as we behave just as a constructor would have, we should be OK. If it ever changes so that we *must* pass a c...
def _conn_maker(self, *args, **kwargs): """ This is called to create a connection instance. Normally you'd pass a connection class to do_open, but it doesn't actually check for a class, and just expects a callable. As long as we behave just as a constructor would have, we should ...
Expands any strings within `data` such as '{system.user}'.
def expand_system_vars(data): """Expands any strings within `data` such as '{system.user}'.""" def _expanded(value): if isinstance(value, basestring): value = expandvars(value) value = expanduser(value) return scoped_format(value, system=system) elif isinstanc...
Create a separate copy of this config.
def copy(self, overrides=None, locked=False): """Create a separate copy of this config.""" other = copy.copy(self) if overrides is not None: other.overrides = overrides other.locked = locked other._uncache() return other
Set a setting to the given value. Note that `key` can be in dotted form, eg 'plugins.release_hook.emailer.sender'.
def override(self, key, value): """Set a setting to the given value. Note that `key` can be in dotted form, eg 'plugins.release_hook.emailer.sender'. """ keys = key.split('.') if len(keys) > 1: if keys[0] != "plugins": raise AttributeError("no...
Remove a setting override, if one exists.
def remove_override(self, key): """Remove a setting override, if one exists.""" keys = key.split('.') if len(keys) > 1: raise NotImplementedError elif key in self.overrides: del self.overrides[key] self._uncache(key)
Returns True if the warning setting is enabled.
def warn(self, key): """Returns True if the warning setting is enabled.""" return (not self.quiet and not self.warn_none and (self.warn_all or getattr(self, "warn_%s" % key)))
Returns True if the debug setting is enabled.
def debug(self, key): """Returns True if the debug setting is enabled.""" return (not self.quiet and not self.debug_none and (self.debug_all or getattr(self, "debug_%s" % key)))
Returns the entire configuration as a dict. Note that this will force all plugins to be loaded.
def data(self): """Returns the entire configuration as a dict. Note that this will force all plugins to be loaded. """ d = {} for key in self._data: if key == "plugins": d[key] = self.plugins.data() else: try: ...
Returns package search paths with local path removed.
def nonlocal_packages_path(self): """Returns package search paths with local path removed.""" paths = self.packages_path[:] if self.local_packages_path in paths: paths.remove(self.local_packages_path) return paths
Swap this config with another. This is used by the unit tests to swap the config to one that is shielded from any user config updates. Do not use this method unless you have good reason.
def _swap(self, other): """Swap this config with another. This is used by the unit tests to swap the config to one that is shielded from any user config updates. Do not use this method unless you have good reason. """ self.__dict__, other.__dict__ = other.__dict__, self....
See comment block at top of 'rezconfig' describing how the main config is assembled.
def _create_main_config(cls, overrides=None): """See comment block at top of 'rezconfig' describing how the main config is assembled.""" filepaths = [] filepaths.append(get_module_root_config()) filepath = os.getenv("REZ_CONFIG_FILE") if filepath: filepaths.ex...
Decorates functions for lookups within a config.platform_map dictionary. The first level key is mapped to the func.__name__ of the decorated function. Regular expressions are used on the second level key, values. Note that there is no guaranteed order within the dictionary evaluation. Only the first matchi...
def platform_mapped(func): """Decorates functions for lookups within a config.platform_map dictionary. The first level key is mapped to the func.__name__ of the decorated function. Regular expressions are used on the second level key, values. Note that there is no guaranteed order within the dictionary...
Compute and return the PageRank in an directed graph. @type graph: digraph @param graph: Digraph. @type damping_factor: number @param damping_factor: PageRank dumping factor. @type max_iterations: number @param max_iterations: Maximum number of iterations. @type ...
def pagerank(graph, damping_factor=0.85, max_iterations=100, min_delta=0.00001): """ Compute and return the PageRank in an directed graph. @type graph: digraph @param graph: Digraph. @type damping_factor: number @param damping_factor: PageRank dumping factor. @type max_...
Expands a requirement string like 'python-2.*', 'foo-2.*+<*', etc. Wildcards are expanded to the latest version that matches. There is also a special wildcard '**' that will expand to the full version, but it cannot be used in combination with '*'. Wildcards MUST placehold a whole version token, not p...
def expand_requirement(request, paths=None): """Expands a requirement string like 'python-2.*', 'foo-2.*+<*', etc. Wildcards are expanded to the latest version that matches. There is also a special wildcard '**' that will expand to the full version, but it cannot be used in combination with '*'. W...
Runs a subproc to calculate a package attribute.
def exec_command(attr, cmd): """Runs a subproc to calculate a package attribute. """ import subprocess p = popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate() if p.returncode: from rez.exceptions import InvalidPackageError raise InvalidPackageE...
Runs a python subproc to calculate a package attribute. Args: attr (str): Name of package attribute being created. src (list of str): Python code to execute, will be converted into semicolon-delimited single line of code. Returns: str: Output of python process.
def exec_python(attr, src, executable="python"): """Runs a python subproc to calculate a package attribute. Args: attr (str): Name of package attribute being created. src (list of str): Python code to execute, will be converted into semicolon-delimited single line of code. Retu...
Find the rez native python package that contains the given module. This function is used by python 'native' rez installers to find the native rez python package that represents the python installation that this module is installed into. Note: This function is dependent on the behavior found in...
def find_site_python(module_name, paths=None): """Find the rez native python package that contains the given module. This function is used by python 'native' rez installers to find the native rez python package that represents the python installation that this module is installed into. Note: ...
:exc:`socket.error` and :exc:`IOError` first got the ``.errno`` attribute in Py2.7
def get_errno(exc): """:exc:`socket.error` and :exc:`IOError` first got the ``.errno`` attribute in Py2.7""" try: return exc.errno except AttributeError: try: # e.args = (errno, reason) if isinstance(exc.args, tuple) and len(exc.args) == 2: return ...
A simple function to find an intersection between two arrays. @type A: List @param A: First List @type B: List @param B: Second List @rtype: List @return: List of Intersections
def _intersection(A,B): """ A simple function to find an intersection between two arrays. @type A: List @param A: First List @type B: List @param B: Second List @rtype: List @return: List of Intersections """ intersection = [] for i in A: if i in B: ...
Return a list of transitive edges. Example of transitivity within graphs: A -> B, B -> C, A -> C in this case the transitive edge is: A -> C @attention: This function is only meaningful for directed acyclic graphs. @type graph: digraph @param graph: Digraph @rtype: List ...
def transitive_edges(graph): """ Return a list of transitive edges. Example of transitivity within graphs: A -> B, B -> C, A -> C in this case the transitive edge is: A -> C @attention: This function is only meaningful for directed acyclic graphs. @type graph: digraph @param ...
Compute and return the critical path in an acyclic directed weighted graph. @attention: This function is only meaningful for directed weighted acyclic graphs @type graph: digraph @param graph: Digraph @rtype: List @return: List containing all the nodes in the path (or an empty array ...
def critical_path(graph): """ Compute and return the critical path in an acyclic directed weighted graph. @attention: This function is only meaningful for directed weighted acyclic graphs @type graph: digraph @param graph: Digraph @rtype: List @return: List containing all the...
Uses a 'parse_build_args.py' file to add options, if found.
def bind_cli(cls, parser, group): """ Uses a 'parse_build_args.py' file to add options, if found. """ try: with open("./parse_build_args.py") as f: source = f.read() except Exception as e: return # detect what extra args have been ...
Perform the build. Note that most of the func args aren't used here - that's because this info is already passed to the custom build command via environment variables.
def build(self, context, variant, build_path, install_path, install=False, build_type=BuildType.local): """Perform the build. Note that most of the func args aren't used here - that's because this info is already passed to the custom build command via environment variables...
Escape the <, >, ^, and & special characters reserved by Windows. Args: value (str/EscapedString): String or already escaped string. Returns: str: The value escaped for Windows.
def escape_string(self, value): """Escape the <, >, ^, and & special characters reserved by Windows. Args: value (str/EscapedString): String or already escaped string. Returns: str: The value escaped for Windows. """ if isinstance(value, EscapedString):...
Create a tag on the toplevel repo if there is no patch repo, or a tag on the patch repo and bookmark on the top repo if there is a patch repo Returns a list where each entry is a dict for each bookmark or tag created, which looks like {'type': ('bookmark' or 'tag'), 'patch': bool}
def _create_tag_highlevel(self, tag_name, message=None): """Create a tag on the toplevel repo if there is no patch repo, or a tag on the patch repo and bookmark on the top repo if there is a patch repo Returns a list where each entry is a dict for each bookmark or tag created, w...
Create a tag on the toplevel or patch repo If the tag exists, and force is False, no tag is made. If force is True, and a tag exists, but it is a direct ancestor of the current commit, and there is no difference in filestate between the current commit and the tagged commit, no tag is ma...
def _create_tag_lowlevel(self, tag_name, message=None, force=True, patch=False): """Create a tag on the toplevel or patch repo If the tag exists, and force is False, no tag is made. If force is True, and a tag exists, but it is a direct ancestor of the current commi...
Returns True if commit1 is a direct ancestor of commit2, or False otherwise. This method considers a commit to be a direct ancestor of itself
def is_ancestor(self, commit1, commit2, patch=False): """Returns True if commit1 is a direct ancestor of commit2, or False otherwise. This method considers a commit to be a direct ancestor of itself""" result = self.hg("log", "-r", "first(%s::%s)" % (commit1, commit2), ...
Apply patch args to a request. For example, consider: >>> print get_patched_request(["foo-5", "bah-8.1"], ["foo-6"]) ["foo-6", "bah-8.1"] >>> print get_patched_request(["foo-5", "bah-8.1"], ["^bah"]) ["foo-5"] The following rules apply wrt how normal/conflict/weak patches over...
def get_patched_request(requires, patchlist): """Apply patch args to a request. For example, consider: >>> print get_patched_request(["foo-5", "bah-8.1"], ["foo-6"]) ["foo-6", "bah-8.1"] >>> print get_patched_request(["foo-5", "bah-8.1"], ["^bah"]) ["foo-5"] The following ...
The execute functon of the hook will be called to start the required application :param app_path: (str) The path of the application executable :param app_args: (str) Any arguments the application may require :param version: (str) version of the application being run if set in the "versions" set...
def execute(self, app_path, app_args, version, **kwargs): """ The execute functon of the hook will be called to start the required application :param app_path: (str) The path of the application executable :param app_args: (str) Any arguments the application may require :param ve...
Checks to see if a Rez package is available in the current environment. If it is available, add it to the system path, exposing the Rez Python API :param strict: (bool) If True, raise an error if Rez is not available as a package. This will prevent the app from being launc...
def check_rez(self, strict=True): """ Checks to see if a Rez package is available in the current environment. If it is available, add it to the system path, exposing the Rez Python API :param strict: (bool) If True, raise an error if Rez is not available as a package. ...
util func, get last revision of url
def get_last_changed_revision(client, url): """ util func, get last revision of url """ try: svn_entries = client.info2(url, pysvn.Revision(pysvn.opt_revision_kind.head), recurse=False) if not svn_entries: ...
provide svn with permissions. @TODO this will have to be updated to take into account automated releases etc.
def get_svn_login(realm, username, may_save): """ provide svn with permissions. @TODO this will have to be updated to take into account automated releases etc. """ import getpass print "svn requires a password for the user %s:" % username pwd = '' while not pwd.strip(): pwd = ge...
Return a string specifying the given graph as a XML document. @type G: graph @param G: Graph. @rtype: string @return: String specifying the graph as a XML document.
def write(G): """ Return a string specifying the given graph as a XML document. @type G: graph @param G: Graph. @rtype: string @return: String specifying the graph as a XML document. """ # Document root grxml = Document() if (type(G) == graph): grxmlr = grxml...
Read a graph from a XML document and return it. Nodes and edges specified in the input will be added to the current graph. @type string: string @param string: Input string in XML format specifying a graph. @rtype: graph @return: Graph
def read(string): """ Read a graph from a XML document and return it. Nodes and edges specified in the input will be added to the current graph. @type string: string @param string: Input string in XML format specifying a graph. @rtype: graph @return: Graph """ dom = parseS...
Return a string specifying the given hypergraph as a XML document. @type hgr: hypergraph @param hgr: Hypergraph. @rtype: string @return: String specifying the graph as a XML document.
def write_hypergraph(hgr): """ Return a string specifying the given hypergraph as a XML document. @type hgr: hypergraph @param hgr: Hypergraph. @rtype: string @return: String specifying the graph as a XML document. """ # Document root grxml = Document() grxmlr = grxml.cr...
Read a graph from a XML document. Nodes and hyperedges specified in the input will be added to the current graph. @type string: string @param string: Input string in XML format specifying a graph. @rtype: hypergraph @return: Hypergraph
def read_hypergraph(string): """ Read a graph from a XML document. Nodes and hyperedges specified in the input will be added to the current graph. @type string: string @param string: Input string in XML format specifying a graph. @rtype: hypergraph @return: Hypergraph """ ...
Invoke a diff editor to show the difference between the source of two packages. Args: pkg1 (`Package`): Package to diff. pkg2 (`Package`): Package to diff against. If None, the next most recent package version is used.
def diff_packages(pkg1, pkg2=None): """Invoke a diff editor to show the difference between the source of two packages. Args: pkg1 (`Package`): Package to diff. pkg2 (`Package`): Package to diff against. If None, the next most recent package version is used. """ if pkg2 i...
Exit gracefully on ctrl-C.
def sigint_handler(signum, frame): """Exit gracefully on ctrl-C.""" global _handled_int if not _handled_int: _handled_int = True if not _env_var_true("_REZ_QUIET_ON_SIG"): print >> sys.stderr, "Interrupted by user" sigbase_handler(signum, frame)
Exit gracefully on terminate.
def sigterm_handler(signum, frame): """Exit gracefully on terminate.""" global _handled_term if not _handled_term: _handled_term = True if not _env_var_true("_REZ_QUIET_ON_SIG"): print >> sys.stderr, "Terminated by user" sigbase_handler(signum, frame)
Sets up all sub-parsers when help is requested.
def format_help(self): """Sets up all sub-parsers when help is requested.""" if self._subparsers: for action in self._subparsers._actions: if isinstance(action, LazySubParsersAction): for parser_name, parser in action._name_parser_map.iteritems(): ...
Test the validity of a package name string. Args: name (str): Name to test. raise_error (bool): If True, raise an exception on failure Returns: bool.
def is_valid_package_name(name, raise_error=False): """Test the validity of a package name string. Args: name (str): Name to test. raise_error (bool): If True, raise an exception on failure Returns: bool. """ is_valid = PACKAGE_NAME_REGEX.match(name) if raise_error and ...
Expand abbreviations in a format string. If an abbreviation does not match a field, or matches multiple fields, it is left unchanged. Example: >>> fields = ("hey", "there", "dude") >>> expand_abbreviations("hello {d}", fields) 'hello dude' Args: txt (str): Format stri...
def expand_abbreviations(txt, fields): """Expand abbreviations in a format string. If an abbreviation does not match a field, or matches multiple fields, it is left unchanged. Example: >>> fields = ("hey", "there", "dude") >>> expand_abbreviations("hello {d}", fields) 'hello d...
Expand shell variables of form $var and ${var}. Unknown variables are left unchanged. Args: text (str): String to expand. environ (dict): Environ dict to use for expansions, defaults to os.environ. Returns: The expanded string.
def expandvars(text, environ=None): """Expand shell variables of form $var and ${var}. Unknown variables are left unchanged. Args: text (str): String to expand. environ (dict): Environ dict to use for expansions, defaults to os.environ. Returns: The expanded string...
Given a nested dict, generate a python code equivalent. Example: >>> d = {'foo': 'bah', 'colors': {'red': 1, 'blue': 2}} >>> print dict_to_attributes_code(d) foo = 'bah' colors.red = 1 colors.blue = 2 Returns: str.
def dict_to_attributes_code(dict_): """Given a nested dict, generate a python code equivalent. Example: >>> d = {'foo': 'bah', 'colors': {'red': 1, 'blue': 2}} >>> print dict_to_attributes_code(d) foo = 'bah' colors.red = 1 colors.blue = 2 Returns: str. ...
Print rows of entries in aligned columns.
def columnise(rows, padding=2): """Print rows of entries in aligned columns.""" strs = [] maxwidths = {} for row in rows: for i, e in enumerate(row): se = str(e) nse = len(se) w = maxwidths.get(i, -1) if nse > w: maxwidths[i] = nse...
Like `columnise`, but with colored rows. Args: printer (`colorize.Printer`): Printer object. Note: The last entry in each row is the row color, or None for no coloring.
def print_colored_columns(printer, rows, padding=2): """Like `columnise`, but with colored rows. Args: printer (`colorize.Printer`): Printer object. Note: The last entry in each row is the row color, or None for no coloring. """ rows_ = [x[:-1] for x in rows] colors = [x[-1] fo...
Convert a string into epoch time. Examples of valid strings: 1418350671 # already epoch time -12s # 12 seconds ago -5.4m # 5.4 minutes ago
def get_epoch_time_from_str(s): """Convert a string into epoch time. Examples of valid strings: 1418350671 # already epoch time -12s # 12 seconds ago -5.4m # 5.4 minutes ago """ try: return int(s) except: pass try: if s.startswith('-'):...
Print the position string equivalent of a positive integer. Examples: 0: zeroeth 1: first 2: second 14: 14th 21: 21st
def positional_number_string(n): """Print the position string equivalent of a positive integer. Examples: 0: zeroeth 1: first 2: second 14: 14th 21: 21st """ if n > 20: suffix = positional_suffix[n % 10] return "%d%s" % (n, suffix) elif n > 3: ...
Expand '~' to home directory in the given string. Note that this function deliberately differs from the builtin os.path.expanduser() on Linux systems, which expands strings such as '~sclaus' to that user's homedir. This is problematic in rez because the string '~packagename' may inadvertently convert t...
def expanduser(path): """Expand '~' to home directory in the given string. Note that this function deliberately differs from the builtin os.path.expanduser() on Linux systems, which expands strings such as '~sclaus' to that user's homedir. This is problematic in rez because the string '~packagename...
Return a string formatted as a python block comment string, like the one you're currently reading. Special characters are escaped if necessary.
def as_block_string(txt): """Return a string formatted as a python block comment string, like the one you're currently reading. Special characters are escaped if necessary. """ import json lines = [] for line in txt.split('\n'): line_ = json.dumps(line) line_ = line_[1:-1].rstri...
Format a string. Args: s (str): String to format, eg "hello {name}" pretty (bool): If True, references to non-string attributes such as lists are converted to basic form, with characters such as brackets and parenthesis removed. If None, defaults to the ...
def format(self, s, pretty=None, expand=None): """Format a string. Args: s (str): String to format, eg "hello {name}" pretty (bool): If True, references to non-string attributes such as lists are converted to basic form, with characters such as br...
Publish an AMQP message. Returns: bool: True if message was sent successfully.
def publish_message(host, amqp_settings, routing_key, data, async=False): """Publish an AMQP message. Returns: bool: True if message was sent successfully. """ global _thread global _num_pending kwargs = { "host": host, "amqp_settings": amqp_settings, "routing_k...
Publish an AMQP message. Returns: bool: True if message was sent successfully.
def _publish_message(host, amqp_settings, routing_key, data): """Publish an AMQP message. Returns: bool: True if message was sent successfully. """ if host == "stdout": print("Published to %s: %s" % (routing_key, data)) return True try: conn = Connection(**remove_no...
Returns a copy of the version.
def copy(self): """Returns a copy of the version.""" other = Version(None) other.tokens = self.tokens[:] other.seps = self.seps[:] return other
Return a copy of the version, possibly with less tokens. Args: len_ (int): New version length. If >= current length, an unchanged copy of the version is returned.
def trim(self, len_): """Return a copy of the version, possibly with less tokens. Args: len_ (int): New version length. If >= current length, an unchanged copy of the version is returned. """ other = Version(None) other.tokens = self.tokens[:len_] ...
Return 'next' version. Eg, next(1.2) is 1.2_
def next(self): """Return 'next' version. Eg, next(1.2) is 1.2_""" if self.tokens: other = self.copy() tok = other.tokens.pop() other.tokens.append(tok.next()) return other else: return Version.inf
OR together version ranges. Calculates the union of this range with one or more other ranges. Args: other: VersionRange object (or list of) to OR with. Returns: New VersionRange object representing the union.
def union(self, other): """OR together version ranges. Calculates the union of this range with one or more other ranges. Args: other: VersionRange object (or list of) to OR with. Returns: New VersionRange object representing the union. """ if no...
AND together version ranges. Calculates the intersection of this range with one or more other ranges. Args: other: VersionRange object (or list of) to AND with. Returns: New VersionRange object representing the intersection, or None if no ranges intersect.
def intersection(self, other): """AND together version ranges. Calculates the intersection of this range with one or more other ranges. Args: other: VersionRange object (or list of) to AND with. Returns: New VersionRange object representing the intersection, or...
Calculate the inverse of the range. Returns: New VersionRange object representing the inverse of this range, or None if there is no inverse (ie, this range is the any range).
def inverse(self): """Calculate the inverse of the range. Returns: New VersionRange object representing the inverse of this range, or None if there is no inverse (ie, this range is the any range). """ if self.is_any(): return None else: ...
Split into separate contiguous ranges. Returns: A list of VersionRange objects. For example, the range "3|5+" will be split into ["3", "5+"].
def split(self): """Split into separate contiguous ranges. Returns: A list of VersionRange objects. For example, the range "3|5+" will be split into ["3", "5+"]. """ ranges = [] for bound in self.bounds: range = VersionRange(None) ...
Create a range from lower_version..upper_version. Args: lower_version: Version object representing lower bound of the range. upper_version: Version object representing upper bound of the range. Returns: `VersionRange` object.
def as_span(cls, lower_version=None, upper_version=None, lower_inclusive=True, upper_inclusive=True): """Create a range from lower_version..upper_version. Args: lower_version: Version object representing lower bound of the range. upper_version: Version object rep...
Create a range from a version. Args: version: Version object. This is used as the upper/lower bound of the range. op: Operation as a string. One of 'gt'/'>', 'gte'/'>=', lt'/'<', 'lte'/'<=', 'eq'/'=='. If None, a bounded range will be created ...
def from_version(cls, version, op=None): """Create a range from a version. Args: version: Version object. This is used as the upper/lower bound of the range. op: Operation as a string. One of 'gt'/'>', 'gte'/'>=', lt'/'<', 'lte'/'<=', 'eq'/'=='. I...
Create a range from a list of versions. This method creates a range that contains only the given versions and no other. Typically the range looks like (for eg) "==3|==4|==5.1". Args: versions: List of Version objects. Returns: `VersionRange` object.
def from_versions(cls, versions): """Create a range from a list of versions. This method creates a range that contains only the given versions and no other. Typically the range looks like (for eg) "==3|==4|==5.1". Args: versions: List of Version objects. Returns: ...
Returns exact version ranges as Version objects, or None if there are no exact version ranges present.
def to_versions(self): """Returns exact version ranges as Version objects, or None if there are no exact version ranges present. """ versions = [] for bound in self.bounds: if bound.lower.inclusive and bound.upper.inclusive \ and (bound.lower.versi...
Returns True if version is contained in this range.
def contains_version(self, version): """Returns True if version is contained in this range.""" if len(self.bounds) < 5: # not worth overhead of binary search for bound in self.bounds: i = bound.version_containment(version) if i == 0: ...
Like `iter_intersect_test`, but returns intersections only. Returns: An iterator that returns items from `iterable` that intersect.
def iter_intersecting(self, iterable, key=None, descending=False): """Like `iter_intersect_test`, but returns intersections only. Returns: An iterator that returns items from `iterable` that intersect. """ return _ContainsVersionIterator(self, iterable, key, descending, ...
Like `iter_intersect_test`, but returns non-intersections only. Returns: An iterator that returns items from `iterable` that don't intersect.
def iter_non_intersecting(self, iterable, key=None, descending=False): """Like `iter_intersect_test`, but returns non-intersections only. Returns: An iterator that returns items from `iterable` that don't intersect. """ return _ContainsVersionIterator(self, iterable, key, de...
Return a contiguous range that is a superset of this range. Returns: A VersionRange object representing the span of this range. For example, the span of "2+<4|6+<8" would be "2+<8".
def span(self): """Return a contiguous range that is a superset of this range. Returns: A VersionRange object representing the span of this range. For example, the span of "2+<4|6+<8" would be "2+<8". """ other = VersionRange(None) bound = _Bound(self.bou...
Visit each version in the range, and apply a function to each. This is for advanced usage only. If `func` returns a `Version`, this call will change the versions in place. It is possible to change versions in a way that is nonsensical - for example setting an upper bound to a ...
def visit_versions(self, func): """Visit each version in the range, and apply a function to each. This is for advanced usage only. If `func` returns a `Version`, this call will change the versions in place. It is possible to change versions in a way that is nonsensical - for ...
Spawn an async request to a remote webserver.
def async_send(self, url, data, headers, success_cb, failure_cb): """ Spawn an async request to a remote webserver. """ # this can be optimized by making a custom self.send that does not # read the response since we don't use it. self._lock.acquire() return gevent...
Sends a request to a remote webserver using HTTP POST.
def send(self, url, data, headers): """ Sends a request to a remote webserver using HTTP POST. """ req = urllib2.Request(url, headers=headers) try: response = urlopen( url=req, data=data, timeout=self.timeout, ...
raven-js will pass both Authorization and X-Sentry-Auth depending on the browser and server configurations.
def extract_auth_vars(request): """ raven-js will pass both Authorization and X-Sentry-Auth depending on the browser and server configurations. """ if request.META.get('HTTP_X_SENTRY_AUTH', '').startswith('Sentry'): return request.META['HTTP_X_SENTRY_AUTH'] elif request.META.get('HTTP_AU...
Convert exception info to a value for the values list.
def _get_value(self, exc_type, exc_value, exc_traceback): """ Convert exception info to a value for the values list. """ stack_info = get_stack_info( iter_traceback_frames(exc_traceback), transformer=self.transform, capture_locals=self.client.capture_l...
Records a breadcrumb for all active clients. This is what integration code should use rather than invoking the `captureBreadcrumb` method on a specific client.
def record(message=None, timestamp=None, level=None, category=None, data=None, type=None, processor=None): """Records a breadcrumb for all active clients. This is what integration code should use rather than invoking the `captureBreadcrumb` method on a specific client. """ if timestamp i...
Ignores a logger during breadcrumb recording.
def ignore_logger(name_or_logger, allow_level=None): """Ignores a logger during breadcrumb recording. """ def handler(logger, level, msg, args, kwargs): if allow_level is not None and \ level >= allow_level: return False return True register_special_log_handler(nam...
Registers a callback for log handling. The callback is invoked with given arguments: `logger`, `level`, `msg`, `args` and `kwargs` which are the values passed to the logging system. If the callback returns true value the default handling is disabled. Only one callback can be registered per one logger na...
def register_special_log_handler(name_or_logger, callback): """Registers a callback for log handling. The callback is invoked with given arguments: `logger`, `level`, `msg`, `args` and `kwargs` which are the values passed to the logging system. If the callback returns true value the default handling is ...
If installed this causes Django's queries to be captured.
def install_sql_hook(): """If installed this causes Django's queries to be captured.""" try: from django.db.backends.utils import CursorWrapper except ImportError: from django.db.backends.util import CursorWrapper try: real_execute = CursorWrapper.execute real_executeman...