id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
246,300
nerdvegas/rez
src/rez/wrapper.py
Wrapper.print_about
def print_about(self): """Print an info message about the tool.""" filepath = os.path.join(self.suite_path, "bin", self.tool_name) print "Tool: %s" % self.tool_name print "Path: %s" % filepath print "Suite: %s" % self.suite_path msg = "%s (%r)" % (self.context.load_path, self.context_name) print "Context: %s" % msg variants = self.context.get_tool_variants(self.tool_name) if variants: if len(variants) > 1: self._print_conflicting(variants) else: variant = iter(variants).next() print "Package: %s" % variant.qualified_package_name return 0
python
def print_about(self): filepath = os.path.join(self.suite_path, "bin", self.tool_name) print "Tool: %s" % self.tool_name print "Path: %s" % filepath print "Suite: %s" % self.suite_path msg = "%s (%r)" % (self.context.load_path, self.context_name) print "Context: %s" % msg variants = self.context.get_tool_variants(self.tool_name) if variants: if len(variants) > 1: self._print_conflicting(variants) else: variant = iter(variants).next() print "Package: %s" % variant.qualified_package_name return 0
[ "def", "print_about", "(", "self", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "suite_path", ",", "\"bin\"", ",", "self", ".", "tool_name", ")", "print", "\"Tool: %s\"", "%", "self", ".", "tool_name", "print", "\"Path...
Print an info message about the tool.
[ "Print", "an", "info", "message", "about", "the", "tool", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/wrapper.py#L202-L219
246,301
nerdvegas/rez
src/rez/wrapper.py
Wrapper.print_package_versions
def print_package_versions(self): """Print a list of versions of the package this tool comes from, and indicate which version this tool is from.""" variants = self.context.get_tool_variants(self.tool_name) if variants: if len(variants) > 1: self._print_conflicting(variants) return 1 else: from rez.packages_ import iter_packages variant = iter(variants).next() it = iter_packages(name=variant.name) rows = [] colors = [] for pkg in sorted(it, key=lambda x: x.version, reverse=True): if pkg.version == variant.version: name = "* %s" % pkg.qualified_name col = heading else: name = " %s" % pkg.qualified_name col = local if pkg.is_local else None label = "(local)" if pkg.is_local else "" rows.append((name, pkg.path, label)) colors.append(col) _pr = Printer() for col, line in zip(colors, columnise(rows)): _pr(line, col) return 0
python
def print_package_versions(self): variants = self.context.get_tool_variants(self.tool_name) if variants: if len(variants) > 1: self._print_conflicting(variants) return 1 else: from rez.packages_ import iter_packages variant = iter(variants).next() it = iter_packages(name=variant.name) rows = [] colors = [] for pkg in sorted(it, key=lambda x: x.version, reverse=True): if pkg.version == variant.version: name = "* %s" % pkg.qualified_name col = heading else: name = " %s" % pkg.qualified_name col = local if pkg.is_local else None label = "(local)" if pkg.is_local else "" rows.append((name, pkg.path, label)) colors.append(col) _pr = Printer() for col, line in zip(colors, columnise(rows)): _pr(line, col) return 0
[ "def", "print_package_versions", "(", "self", ")", ":", "variants", "=", "self", ".", "context", ".", "get_tool_variants", "(", "self", ".", "tool_name", ")", "if", "variants", ":", "if", "len", "(", "variants", ")", ">", "1", ":", "self", ".", "_print_c...
Print a list of versions of the package this tool comes from, and indicate which version this tool is from.
[ "Print", "a", "list", "of", "versions", "of", "the", "package", "this", "tool", "comes", "from", "and", "indicate", "which", "version", "this", "tool", "is", "from", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/wrapper.py#L221-L251
246,302
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/generators.py
generate_hypergraph
def generate_hypergraph(num_nodes, num_edges, r = 0): """ Create a random hyper graph. @type num_nodes: number @param num_nodes: Number of nodes. @type num_edges: number @param num_edges: Number of edges. @type r: number @param r: Uniform edges of size r. """ # Graph creation random_graph = hypergraph() # Nodes nodes = list(map(str, list(range(num_nodes)))) random_graph.add_nodes(nodes) # Base edges edges = list(map(str, list(range(num_nodes, num_nodes+num_edges)))) random_graph.add_hyperedges(edges) # Connect the edges if 0 == r: # Add each edge with 50/50 probability for e in edges: for n in nodes: if choice([True, False]): random_graph.link(n, e) else: # Add only uniform edges for e in edges: # First shuffle the nodes shuffle(nodes) # Then take the first r nodes for i in range(r): random_graph.link(nodes[i], e) return random_graph
python
def generate_hypergraph(num_nodes, num_edges, r = 0): # Graph creation random_graph = hypergraph() # Nodes nodes = list(map(str, list(range(num_nodes)))) random_graph.add_nodes(nodes) # Base edges edges = list(map(str, list(range(num_nodes, num_nodes+num_edges)))) random_graph.add_hyperedges(edges) # Connect the edges if 0 == r: # Add each edge with 50/50 probability for e in edges: for n in nodes: if choice([True, False]): random_graph.link(n, e) else: # Add only uniform edges for e in edges: # First shuffle the nodes shuffle(nodes) # Then take the first r nodes for i in range(r): random_graph.link(nodes[i], e) return random_graph
[ "def", "generate_hypergraph", "(", "num_nodes", ",", "num_edges", ",", "r", "=", "0", ")", ":", "# Graph creation", "random_graph", "=", "hypergraph", "(", ")", "# Nodes", "nodes", "=", "list", "(", "map", "(", "str", ",", "list", "(", "range", "(", "num...
Create a random hyper graph. @type num_nodes: number @param num_nodes: Number of nodes. @type num_edges: number @param num_edges: Number of edges. @type r: number @param r: Uniform edges of size r.
[ "Create", "a", "random", "hyper", "graph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/generators.py#L90-L132
246,303
nerdvegas/rez
src/rez/bind/_utils.py
check_version
def check_version(version, range_=None): """Check that the found software version is within supplied range. Args: version: Version of the package as a Version object. range_: Allowable version range as a VersionRange object. """ if range_ and version not in range_: raise RezBindError("found version %s is not within range %s" % (str(version), str(range_)))
python
def check_version(version, range_=None): if range_ and version not in range_: raise RezBindError("found version %s is not within range %s" % (str(version), str(range_)))
[ "def", "check_version", "(", "version", ",", "range_", "=", "None", ")", ":", "if", "range_", "and", "version", "not", "in", "range_", ":", "raise", "RezBindError", "(", "\"found version %s is not within range %s\"", "%", "(", "str", "(", "version", ")", ",", ...
Check that the found software version is within supplied range. Args: version: Version of the package as a Version object. range_: Allowable version range as a VersionRange object.
[ "Check", "that", "the", "found", "software", "version", "is", "within", "supplied", "range", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/bind/_utils.py#L45-L54
246,304
nerdvegas/rez
src/rez/bind/_utils.py
extract_version
def extract_version(exepath, version_arg, word_index=-1, version_rank=3): """Run an executable and get the program version. Args: exepath: Filepath to executable. version_arg: Arg to pass to program, eg "-V". Can also be a list. word_index: Expect the Nth word of output to be the version. version_rank: Cap the version to this many tokens. Returns: `Version` object. """ if isinstance(version_arg, basestring): version_arg = [version_arg] args = [exepath] + version_arg stdout, stderr, returncode = _run_command(args) if returncode: raise RezBindError("failed to execute %s: %s\n(error code %d)" % (exepath, stderr, returncode)) stdout = stdout.strip().split('\n')[0].strip() log("extracting version from output: '%s'" % stdout) try: strver = stdout.split()[word_index] toks = strver.replace('.', ' ').replace('-', ' ').split() strver = '.'.join(toks[:version_rank]) version = Version(strver) except Exception as e: raise RezBindError("failed to parse version from output '%s': %s" % (stdout, str(e))) log("extracted version: '%s'" % str(version)) return version
python
def extract_version(exepath, version_arg, word_index=-1, version_rank=3): if isinstance(version_arg, basestring): version_arg = [version_arg] args = [exepath] + version_arg stdout, stderr, returncode = _run_command(args) if returncode: raise RezBindError("failed to execute %s: %s\n(error code %d)" % (exepath, stderr, returncode)) stdout = stdout.strip().split('\n')[0].strip() log("extracting version from output: '%s'" % stdout) try: strver = stdout.split()[word_index] toks = strver.replace('.', ' ').replace('-', ' ').split() strver = '.'.join(toks[:version_rank]) version = Version(strver) except Exception as e: raise RezBindError("failed to parse version from output '%s': %s" % (stdout, str(e))) log("extracted version: '%s'" % str(version)) return version
[ "def", "extract_version", "(", "exepath", ",", "version_arg", ",", "word_index", "=", "-", "1", ",", "version_rank", "=", "3", ")", ":", "if", "isinstance", "(", "version_arg", ",", "basestring", ")", ":", "version_arg", "=", "[", "version_arg", "]", "args...
Run an executable and get the program version. Args: exepath: Filepath to executable. version_arg: Arg to pass to program, eg "-V". Can also be a list. word_index: Expect the Nth word of output to be the version. version_rank: Cap the version to this many tokens. Returns: `Version` object.
[ "Run", "an", "executable", "and", "get", "the", "program", "version", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/bind/_utils.py#L80-L114
246,305
nerdvegas/rez
src/rez/vendor/version/requirement.py
VersionedObject.construct
def construct(cls, name, version=None): """Create a VersionedObject directly from an object name and version. Args: name: Object name string. version: Version object. """ other = VersionedObject(None) other.name_ = name other.version_ = Version() if version is None else version return other
python
def construct(cls, name, version=None): other = VersionedObject(None) other.name_ = name other.version_ = Version() if version is None else version return other
[ "def", "construct", "(", "cls", ",", "name", ",", "version", "=", "None", ")", ":", "other", "=", "VersionedObject", "(", "None", ")", "other", ".", "name_", "=", "name", "other", ".", "version_", "=", "Version", "(", ")", "if", "version", "is", "Non...
Create a VersionedObject directly from an object name and version. Args: name: Object name string. version: Version object.
[ "Create", "a", "VersionedObject", "directly", "from", "an", "object", "name", "and", "version", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/requirement.py#L37-L47
246,306
nerdvegas/rez
src/rez/vendor/version/requirement.py
Requirement.construct
def construct(cls, name, range=None): """Create a requirement directly from an object name and VersionRange. Args: name: Object name string. range: VersionRange object. If None, an unversioned requirement is created. """ other = Requirement(None) other.name_ = name other.range_ = VersionRange() if range is None else range return other
python
def construct(cls, name, range=None): other = Requirement(None) other.name_ = name other.range_ = VersionRange() if range is None else range return other
[ "def", "construct", "(", "cls", ",", "name", ",", "range", "=", "None", ")", ":", "other", "=", "Requirement", "(", "None", ")", "other", ".", "name_", "=", "name", "other", ".", "range_", "=", "VersionRange", "(", ")", "if", "range", "is", "None", ...
Create a requirement directly from an object name and VersionRange. Args: name: Object name string. range: VersionRange object. If None, an unversioned requirement is created.
[ "Create", "a", "requirement", "directly", "from", "an", "object", "name", "and", "VersionRange", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/requirement.py#L152-L163
246,307
nerdvegas/rez
src/rez/vendor/version/requirement.py
Requirement.conflicts_with
def conflicts_with(self, other): """Returns True if this requirement conflicts with another `Requirement` or `VersionedObject`.""" if isinstance(other, Requirement): if (self.name_ != other.name_) or (self.range is None) \ or (other.range is None): return False elif self.conflict: return False if other.conflict \ else self.range_.issuperset(other.range_) elif other.conflict: return other.range_.issuperset(self.range_) else: return not self.range_.intersects(other.range_) else: # VersionedObject if (self.name_ != other.name_) or (self.range is None): return False if self.conflict: return (other.version_ in self.range_) else: return (other.version_ not in self.range_)
python
def conflicts_with(self, other): if isinstance(other, Requirement): if (self.name_ != other.name_) or (self.range is None) \ or (other.range is None): return False elif self.conflict: return False if other.conflict \ else self.range_.issuperset(other.range_) elif other.conflict: return other.range_.issuperset(self.range_) else: return not self.range_.intersects(other.range_) else: # VersionedObject if (self.name_ != other.name_) or (self.range is None): return False if self.conflict: return (other.version_ in self.range_) else: return (other.version_ not in self.range_)
[ "def", "conflicts_with", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "Requirement", ")", ":", "if", "(", "self", ".", "name_", "!=", "other", ".", "name_", ")", "or", "(", "self", ".", "range", "is", "None", ")", "or...
Returns True if this requirement conflicts with another `Requirement` or `VersionedObject`.
[ "Returns", "True", "if", "this", "requirement", "conflicts", "with", "another", "Requirement", "or", "VersionedObject", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/requirement.py#L196-L216
246,308
nerdvegas/rez
src/rez/vendor/version/requirement.py
Requirement.merged
def merged(self, other): """Returns the merged result of two requirements. Two requirements can be in conflict and if so, this function returns None. For example, requests for "foo-4" and "foo-6" are in conflict, since both cannot be satisfied with a single version of foo. Some example successful requirements merges are: - "foo-3+" and "!foo-5+" == "foo-3+<5" - "foo-1" and "foo-1.5" == "foo-1.5" - "!foo-2" and "!foo-5" == "!foo-2|5" """ if self.name_ != other.name_: return None # cannot merge across object names def _r(r_): r = Requirement(None) r.name_ = r_.name_ r.negate_ = r_.negate_ r.conflict_ = r_.conflict_ r.sep_ = r_.sep_ return r if self.range is None: return other elif other.range is None: return self elif self.conflict: if other.conflict: r = _r(self) r.range_ = self.range_ | other.range_ r.negate_ = (self.negate_ and other.negate_ and not r.range_.is_any()) return r else: range_ = other.range - self.range if range_ is None: return None else: r = _r(other) r.range_ = range_ return r elif other.conflict: range_ = self.range_ - other.range_ if range_ is None: return None else: r = _r(self) r.range_ = range_ return r else: range_ = self.range_ & other.range_ if range_ is None: return None else: r = _r(self) r.range_ = range_ return r
python
def merged(self, other): if self.name_ != other.name_: return None # cannot merge across object names def _r(r_): r = Requirement(None) r.name_ = r_.name_ r.negate_ = r_.negate_ r.conflict_ = r_.conflict_ r.sep_ = r_.sep_ return r if self.range is None: return other elif other.range is None: return self elif self.conflict: if other.conflict: r = _r(self) r.range_ = self.range_ | other.range_ r.negate_ = (self.negate_ and other.negate_ and not r.range_.is_any()) return r else: range_ = other.range - self.range if range_ is None: return None else: r = _r(other) r.range_ = range_ return r elif other.conflict: range_ = self.range_ - other.range_ if range_ is None: return None else: r = _r(self) r.range_ = range_ return r else: range_ = self.range_ & other.range_ if range_ is None: return None else: r = _r(self) r.range_ = range_ return r
[ "def", "merged", "(", "self", ",", "other", ")", ":", "if", "self", ".", "name_", "!=", "other", ".", "name_", ":", "return", "None", "# cannot merge across object names", "def", "_r", "(", "r_", ")", ":", "r", "=", "Requirement", "(", "None", ")", "r"...
Returns the merged result of two requirements. Two requirements can be in conflict and if so, this function returns None. For example, requests for "foo-4" and "foo-6" are in conflict, since both cannot be satisfied with a single version of foo. Some example successful requirements merges are: - "foo-3+" and "!foo-5+" == "foo-3+<5" - "foo-1" and "foo-1.5" == "foo-1.5" - "!foo-2" and "!foo-5" == "!foo-2|5"
[ "Returns", "the", "merged", "result", "of", "two", "requirements", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/version/requirement.py#L218-L275
246,309
nerdvegas/rez
src/rez/utils/graph_utils.py
read_graph_from_string
def read_graph_from_string(txt): """Read a graph from a string, either in dot format, or our own compressed format. Returns: `pygraph.digraph`: Graph object. """ if not txt.startswith('{'): return read_dot(txt) # standard dot format def conv(value): if isinstance(value, basestring): return '"' + value + '"' else: return value # our compacted format doc = literal_eval(txt) g = digraph() for attrs, values in doc.get("nodes", []): attrs = [(k, conv(v)) for k, v in attrs] for value in values: if isinstance(value, basestring): node_name = value attrs_ = attrs else: node_name, label = value attrs_ = attrs + [("label", conv(label))] g.add_node(node_name, attrs=attrs_) for attrs, values in doc.get("edges", []): attrs_ = [(k, conv(v)) for k, v in attrs] for value in values: if len(value) == 3: edge = value[:2] label = value[-1] else: edge = value label = '' g.add_edge(edge, label=label, attrs=attrs_) return g
python
def read_graph_from_string(txt): if not txt.startswith('{'): return read_dot(txt) # standard dot format def conv(value): if isinstance(value, basestring): return '"' + value + '"' else: return value # our compacted format doc = literal_eval(txt) g = digraph() for attrs, values in doc.get("nodes", []): attrs = [(k, conv(v)) for k, v in attrs] for value in values: if isinstance(value, basestring): node_name = value attrs_ = attrs else: node_name, label = value attrs_ = attrs + [("label", conv(label))] g.add_node(node_name, attrs=attrs_) for attrs, values in doc.get("edges", []): attrs_ = [(k, conv(v)) for k, v in attrs] for value in values: if len(value) == 3: edge = value[:2] label = value[-1] else: edge = value label = '' g.add_edge(edge, label=label, attrs=attrs_) return g
[ "def", "read_graph_from_string", "(", "txt", ")", ":", "if", "not", "txt", ".", "startswith", "(", "'{'", ")", ":", "return", "read_dot", "(", "txt", ")", "# standard dot format", "def", "conv", "(", "value", ")", ":", "if", "isinstance", "(", "value", "...
Read a graph from a string, either in dot format, or our own compressed format. Returns: `pygraph.digraph`: Graph object.
[ "Read", "a", "graph", "from", "a", "string", "either", "in", "dot", "format", "or", "our", "own", "compressed", "format", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/graph_utils.py#L20-L66
246,310
nerdvegas/rez
src/rez/utils/graph_utils.py
write_compacted
def write_compacted(g): """Write a graph in our own compacted format. Returns: str. """ d_nodes = {} d_edges = {} def conv(value): if isinstance(value, basestring): return value.strip('"') else: return value for node in g.nodes(): label = None attrs = [] for k, v in sorted(g.node_attributes(node)): v_ = conv(v) if k == "label": label = v_ else: attrs.append((k, v_)) value = (node, label) if label else node d_nodes.setdefault(tuple(attrs), []).append(value) for edge in g.edges(): attrs = [(k, conv(v)) for k, v in sorted(g.edge_attributes(edge))] label = str(g.edge_label(edge)) value = tuple(list(edge) + [label]) if label else edge d_edges.setdefault(tuple(attrs), []).append(tuple(value)) doc = dict(nodes=d_nodes.items(), edges=d_edges.items()) contents = str(doc) return contents
python
def write_compacted(g): d_nodes = {} d_edges = {} def conv(value): if isinstance(value, basestring): return value.strip('"') else: return value for node in g.nodes(): label = None attrs = [] for k, v in sorted(g.node_attributes(node)): v_ = conv(v) if k == "label": label = v_ else: attrs.append((k, v_)) value = (node, label) if label else node d_nodes.setdefault(tuple(attrs), []).append(value) for edge in g.edges(): attrs = [(k, conv(v)) for k, v in sorted(g.edge_attributes(edge))] label = str(g.edge_label(edge)) value = tuple(list(edge) + [label]) if label else edge d_edges.setdefault(tuple(attrs), []).append(tuple(value)) doc = dict(nodes=d_nodes.items(), edges=d_edges.items()) contents = str(doc) return contents
[ "def", "write_compacted", "(", "g", ")", ":", "d_nodes", "=", "{", "}", "d_edges", "=", "{", "}", "def", "conv", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "basestring", ")", ":", "return", "value", ".", "strip", "(", "'\"'", ")...
Write a graph in our own compacted format. Returns: str.
[ "Write", "a", "graph", "in", "our", "own", "compacted", "format", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/graph_utils.py#L69-L106
246,311
nerdvegas/rez
src/rez/utils/graph_utils.py
write_dot
def write_dot(g): """Replacement for pygraph.readwrite.dot.write, which is dog slow. Note: This isn't a general replacement. It will work for the graphs that Rez generates, but there are no guarantees beyond that. Args: g (`pygraph.digraph`): Input graph. Returns: str: Graph in dot format. """ lines = ["digraph g {"] def attrs_txt(items): if items: txt = ", ".join(('%s="%s"' % (k, str(v).strip('"'))) for k, v in items) return '[' + txt + ']' else: return '' for node in g.nodes(): atxt = attrs_txt(g.node_attributes(node)) txt = "%s %s;" % (node, atxt) lines.append(txt) for e in g.edges(): edge_from, edge_to = e attrs = g.edge_attributes(e) label = str(g.edge_label(e)) if label: attrs.append(("label", label)) atxt = attrs_txt(attrs) txt = "%s -> %s %s;" % (edge_from, edge_to, atxt) lines.append(txt) lines.append("}") return '\n'.join(lines)
python
def write_dot(g): lines = ["digraph g {"] def attrs_txt(items): if items: txt = ", ".join(('%s="%s"' % (k, str(v).strip('"'))) for k, v in items) return '[' + txt + ']' else: return '' for node in g.nodes(): atxt = attrs_txt(g.node_attributes(node)) txt = "%s %s;" % (node, atxt) lines.append(txt) for e in g.edges(): edge_from, edge_to = e attrs = g.edge_attributes(e) label = str(g.edge_label(e)) if label: attrs.append(("label", label)) atxt = attrs_txt(attrs) txt = "%s -> %s %s;" % (edge_from, edge_to, atxt) lines.append(txt) lines.append("}") return '\n'.join(lines)
[ "def", "write_dot", "(", "g", ")", ":", "lines", "=", "[", "\"digraph g {\"", "]", "def", "attrs_txt", "(", "items", ")", ":", "if", "items", ":", "txt", "=", "\", \"", ".", "join", "(", "(", "'%s=\"%s\"'", "%", "(", "k", ",", "str", "(", "v", ")...
Replacement for pygraph.readwrite.dot.write, which is dog slow. Note: This isn't a general replacement. It will work for the graphs that Rez generates, but there are no guarantees beyond that. Args: g (`pygraph.digraph`): Input graph. Returns: str: Graph in dot format.
[ "Replacement", "for", "pygraph", ".", "readwrite", ".", "dot", ".", "write", "which", "is", "dog", "slow", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/graph_utils.py#L109-L150
246,312
nerdvegas/rez
src/rez/utils/graph_utils.py
prune_graph
def prune_graph(graph_str, package_name): """Prune a package graph so it only contains nodes accessible from the given package. Args: graph_str (str): Dot-language graph string. package_name (str): Name of package of interest. Returns: Pruned graph, as a string. """ # find nodes of interest g = read_dot(graph_str) nodes = set() for node, attrs in g.node_attr.iteritems(): attr = [x for x in attrs if x[0] == "label"] if attr: label = attr[0][1] try: req_str = _request_from_label(label) request = PackageRequest(req_str) except PackageRequestError: continue if request.name == package_name: nodes.add(node) if not nodes: raise ValueError("The package %r does not appear in the graph." % package_name) # find nodes upstream from these nodes g_rev = g.reverse() accessible_nodes = set() access = accessibility(g_rev) for node in nodes: nodes_ = access.get(node, []) accessible_nodes |= set(nodes_) # remove inaccessible nodes inaccessible_nodes = set(g.nodes()) - accessible_nodes for node in inaccessible_nodes: g.del_node(node) return write_dot(g)
python
def prune_graph(graph_str, package_name): # find nodes of interest g = read_dot(graph_str) nodes = set() for node, attrs in g.node_attr.iteritems(): attr = [x for x in attrs if x[0] == "label"] if attr: label = attr[0][1] try: req_str = _request_from_label(label) request = PackageRequest(req_str) except PackageRequestError: continue if request.name == package_name: nodes.add(node) if not nodes: raise ValueError("The package %r does not appear in the graph." % package_name) # find nodes upstream from these nodes g_rev = g.reverse() accessible_nodes = set() access = accessibility(g_rev) for node in nodes: nodes_ = access.get(node, []) accessible_nodes |= set(nodes_) # remove inaccessible nodes inaccessible_nodes = set(g.nodes()) - accessible_nodes for node in inaccessible_nodes: g.del_node(node) return write_dot(g)
[ "def", "prune_graph", "(", "graph_str", ",", "package_name", ")", ":", "# find nodes of interest", "g", "=", "read_dot", "(", "graph_str", ")", "nodes", "=", "set", "(", ")", "for", "node", ",", "attrs", "in", "g", ".", "node_attr", ".", "iteritems", "(", ...
Prune a package graph so it only contains nodes accessible from the given package. Args: graph_str (str): Dot-language graph string. package_name (str): Name of package of interest. Returns: Pruned graph, as a string.
[ "Prune", "a", "package", "graph", "so", "it", "only", "contains", "nodes", "accessible", "from", "the", "given", "package", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/graph_utils.py#L153-L198
246,313
nerdvegas/rez
src/rez/utils/graph_utils.py
save_graph
def save_graph(graph_str, dest_file, fmt=None, image_ratio=None): """Render a graph to an image file. Args: graph_str (str): Dot-language graph string. dest_file (str): Filepath to save the graph to. fmt (str): Format, eg "png", "jpg". image_ratio (float): Image ratio. Returns: String representing format that was written, such as 'png'. """ g = pydot.graph_from_dot_data(graph_str) # determine the dest format if fmt is None: fmt = os.path.splitext(dest_file)[1].lower().strip('.') or "png" if hasattr(g, "write_" + fmt): write_fn = getattr(g, "write_" + fmt) else: raise Exception("Unsupported graph format: '%s'" % fmt) if image_ratio: g.set_ratio(str(image_ratio)) write_fn(dest_file) return fmt
python
def save_graph(graph_str, dest_file, fmt=None, image_ratio=None): g = pydot.graph_from_dot_data(graph_str) # determine the dest format if fmt is None: fmt = os.path.splitext(dest_file)[1].lower().strip('.') or "png" if hasattr(g, "write_" + fmt): write_fn = getattr(g, "write_" + fmt) else: raise Exception("Unsupported graph format: '%s'" % fmt) if image_ratio: g.set_ratio(str(image_ratio)) write_fn(dest_file) return fmt
[ "def", "save_graph", "(", "graph_str", ",", "dest_file", ",", "fmt", "=", "None", ",", "image_ratio", "=", "None", ")", ":", "g", "=", "pydot", ".", "graph_from_dot_data", "(", "graph_str", ")", "# determine the dest format", "if", "fmt", "is", "None", ":", ...
Render a graph to an image file. Args: graph_str (str): Dot-language graph string. dest_file (str): Filepath to save the graph to. fmt (str): Format, eg "png", "jpg". image_ratio (float): Image ratio. Returns: String representing format that was written, such as 'png'.
[ "Render", "a", "graph", "to", "an", "image", "file", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/graph_utils.py#L201-L226
246,314
nerdvegas/rez
src/rez/utils/graph_utils.py
view_graph
def view_graph(graph_str, dest_file=None): """View a dot graph in an image viewer.""" from rez.system import system from rez.config import config if (system.platform == "linux") and (not os.getenv("DISPLAY")): print >> sys.stderr, "Unable to open display." sys.exit(1) dest_file = _write_graph(graph_str, dest_file=dest_file) # view graph viewed = False prog = config.image_viewer or 'browser' print "loading image viewer (%s)..." % prog if config.image_viewer: proc = popen([config.image_viewer, dest_file]) proc.wait() viewed = not bool(proc.returncode) if not viewed: import webbrowser webbrowser.open_new("file://" + dest_file)
python
def view_graph(graph_str, dest_file=None): from rez.system import system from rez.config import config if (system.platform == "linux") and (not os.getenv("DISPLAY")): print >> sys.stderr, "Unable to open display." sys.exit(1) dest_file = _write_graph(graph_str, dest_file=dest_file) # view graph viewed = False prog = config.image_viewer or 'browser' print "loading image viewer (%s)..." % prog if config.image_viewer: proc = popen([config.image_viewer, dest_file]) proc.wait() viewed = not bool(proc.returncode) if not viewed: import webbrowser webbrowser.open_new("file://" + dest_file)
[ "def", "view_graph", "(", "graph_str", ",", "dest_file", "=", "None", ")", ":", "from", "rez", ".", "system", "import", "system", "from", "rez", ".", "config", "import", "config", "if", "(", "system", ".", "platform", "==", "\"linux\"", ")", "and", "(", ...
View a dot graph in an image viewer.
[ "View", "a", "dot", "graph", "in", "an", "image", "viewer", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/graph_utils.py#L229-L252
246,315
nerdvegas/rez
src/rez/utils/platform_.py
Platform.physical_cores
def physical_cores(self): """Return the number of physical cpu cores on the system.""" try: return self._physical_cores_base() except Exception as e: from rez.utils.logging_ import print_error print_error("Error detecting physical core count, defaulting to 1: %s" % str(e)) return 1
python
def physical_cores(self): try: return self._physical_cores_base() except Exception as e: from rez.utils.logging_ import print_error print_error("Error detecting physical core count, defaulting to 1: %s" % str(e)) return 1
[ "def", "physical_cores", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_physical_cores_base", "(", ")", "except", "Exception", "as", "e", ":", "from", "rez", ".", "utils", ".", "logging_", "import", "print_error", "print_error", "(", "\"Error de...
Return the number of physical cpu cores on the system.
[ "Return", "the", "number", "of", "physical", "cpu", "cores", "on", "the", "system", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/platform_.py#L82-L90
246,316
nerdvegas/rez
src/rez/utils/platform_.py
Platform.logical_cores
def logical_cores(self): """Return the number of cpu cores as reported to the os. May be different from physical_cores if, ie, intel's hyperthreading is enabled. """ try: return self._logical_cores() except Exception as e: from rez.utils.logging_ import print_error print_error("Error detecting logical core count, defaulting to 1: %s" % str(e)) return 1
python
def logical_cores(self): try: return self._logical_cores() except Exception as e: from rez.utils.logging_ import print_error print_error("Error detecting logical core count, defaulting to 1: %s" % str(e)) return 1
[ "def", "logical_cores", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_logical_cores", "(", ")", "except", "Exception", "as", "e", ":", "from", "rez", ".", "utils", ".", "logging_", "import", "print_error", "print_error", "(", "\"Error detecting...
Return the number of cpu cores as reported to the os. May be different from physical_cores if, ie, intel's hyperthreading is enabled.
[ "Return", "the", "number", "of", "cpu", "cores", "as", "reported", "to", "the", "os", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/platform_.py#L93-L105
246,317
nerdvegas/rez
src/rez/vendor/colorama/ansitowin32.py
AnsiToWin32.write_and_convert
def write_and_convert(self, text): ''' Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls. ''' cursor = 0 for match in self.ANSI_RE.finditer(text): start, end = match.span() self.write_plain_text(text, cursor, start) self.convert_ansi(*match.groups()) cursor = end self.write_plain_text(text, cursor, len(text))
python
def write_and_convert(self, text): ''' Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls. ''' cursor = 0 for match in self.ANSI_RE.finditer(text): start, end = match.span() self.write_plain_text(text, cursor, start) self.convert_ansi(*match.groups()) cursor = end self.write_plain_text(text, cursor, len(text))
[ "def", "write_and_convert", "(", "self", ",", "text", ")", ":", "cursor", "=", "0", "for", "match", "in", "self", ".", "ANSI_RE", ".", "finditer", "(", "text", ")", ":", "start", ",", "end", "=", "match", ".", "span", "(", ")", "self", ".", "write_...
Write the given text to our wrapped stream, stripping any ANSI sequences from the text, and optionally converting them into win32 calls.
[ "Write", "the", "given", "text", "to", "our", "wrapped", "stream", "stripping", "any", "ANSI", "sequences", "from", "the", "text", "and", "optionally", "converting", "them", "into", "win32", "calls", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/colorama/ansitowin32.py#L131-L143
246,318
nerdvegas/rez
src/rezgui/models/ContextModel.py
ContextModel.copy
def copy(self): """Returns a copy of the context.""" other = ContextModel(self._context, self.parent()) other._stale = self._stale other._modified = self._modified other.request = self.request[:] other.packages_path = self.packages_path other.implicit_packages = self.implicit_packages other.package_filter = self.package_filter other.caching = self.caching other.default_patch_lock = self.default_patch_lock other.patch_locks = copy.deepcopy(self.patch_locks) return other
python
def copy(self): other = ContextModel(self._context, self.parent()) other._stale = self._stale other._modified = self._modified other.request = self.request[:] other.packages_path = self.packages_path other.implicit_packages = self.implicit_packages other.package_filter = self.package_filter other.caching = self.caching other.default_patch_lock = self.default_patch_lock other.patch_locks = copy.deepcopy(self.patch_locks) return other
[ "def", "copy", "(", "self", ")", ":", "other", "=", "ContextModel", "(", "self", ".", "_context", ",", "self", ".", "parent", "(", ")", ")", "other", ".", "_stale", "=", "self", ".", "_stale", "other", ".", "_modified", "=", "self", ".", "_modified",...
Returns a copy of the context.
[ "Returns", "a", "copy", "of", "the", "context", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/models/ContextModel.py#L51-L63
246,319
nerdvegas/rez
src/rezgui/models/ContextModel.py
ContextModel.get_lock_requests
def get_lock_requests(self): """Take the current context, and the current patch locks, and determine the effective requests that will be added to the main request. Returns: A dict of (PatchLock, [Requirement]) tuples. Each requirement will be a weak package reference. If there is no current context, an empty dict will be returned. """ d = defaultdict(list) if self._context: for variant in self._context.resolved_packages: name = variant.name version = variant.version lock = self.patch_locks.get(name) if lock is None: lock = self.default_patch_lock request = get_lock_request(name, version, lock) if request is not None: d[lock].append(request) return d
python
def get_lock_requests(self): d = defaultdict(list) if self._context: for variant in self._context.resolved_packages: name = variant.name version = variant.version lock = self.patch_locks.get(name) if lock is None: lock = self.default_patch_lock request = get_lock_request(name, version, lock) if request is not None: d[lock].append(request) return d
[ "def", "get_lock_requests", "(", "self", ")", ":", "d", "=", "defaultdict", "(", "list", ")", "if", "self", ".", "_context", ":", "for", "variant", "in", "self", ".", "_context", ".", "resolved_packages", ":", "name", "=", "variant", ".", "name", "versio...
Take the current context, and the current patch locks, and determine the effective requests that will be added to the main request. Returns: A dict of (PatchLock, [Requirement]) tuples. Each requirement will be a weak package reference. If there is no current context, an empty dict will be returned.
[ "Take", "the", "current", "context", "and", "the", "current", "patch", "locks", "and", "determine", "the", "effective", "requests", "that", "will", "be", "added", "to", "the", "main", "request", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/models/ContextModel.py#L113-L134
246,320
nerdvegas/rez
src/rezgui/models/ContextModel.py
ContextModel.resolve_context
def resolve_context(self, verbosity=0, max_fails=-1, timestamp=None, callback=None, buf=None, package_load_callback=None): """Update the current context by performing a re-resolve. The newly resolved context is only applied if it is a successful solve. Returns: `ResolvedContext` object, which may be a successful or failed solve. """ package_filter = PackageFilterList.from_pod(self.package_filter) context = ResolvedContext( self.request, package_paths=self.packages_path, package_filter=package_filter, verbosity=verbosity, max_fails=max_fails, timestamp=timestamp, buf=buf, callback=callback, package_load_callback=package_load_callback, caching=self.caching) if context.success: if self._context and self._context.load_path: context.set_load_path(self._context.load_path) self._set_context(context) self._modified = True return context
python
def resolve_context(self, verbosity=0, max_fails=-1, timestamp=None, callback=None, buf=None, package_load_callback=None): package_filter = PackageFilterList.from_pod(self.package_filter) context = ResolvedContext( self.request, package_paths=self.packages_path, package_filter=package_filter, verbosity=verbosity, max_fails=max_fails, timestamp=timestamp, buf=buf, callback=callback, package_load_callback=package_load_callback, caching=self.caching) if context.success: if self._context and self._context.load_path: context.set_load_path(self._context.load_path) self._set_context(context) self._modified = True return context
[ "def", "resolve_context", "(", "self", ",", "verbosity", "=", "0", ",", "max_fails", "=", "-", "1", ",", "timestamp", "=", "None", ",", "callback", "=", "None", ",", "buf", "=", "None", ",", "package_load_callback", "=", "None", ")", ":", "package_filter...
Update the current context by performing a re-resolve. The newly resolved context is only applied if it is a successful solve. Returns: `ResolvedContext` object, which may be a successful or failed solve.
[ "Update", "the", "current", "context", "by", "performing", "a", "re", "-", "resolve", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/models/ContextModel.py#L175-L203
246,321
nerdvegas/rez
src/rezgui/models/ContextModel.py
ContextModel.set_context
def set_context(self, context): """Replace the current context with another.""" self._set_context(context, emit=False) self._modified = (not context.load_path) self.dataChanged.emit(self.CONTEXT_CHANGED | self.REQUEST_CHANGED | self.PACKAGES_PATH_CHANGED | self.LOCKS_CHANGED | self.LOADPATH_CHANGED | self.PACKAGE_FILTER_CHANGED | self.CACHING_CHANGED)
python
def set_context(self, context): self._set_context(context, emit=False) self._modified = (not context.load_path) self.dataChanged.emit(self.CONTEXT_CHANGED | self.REQUEST_CHANGED | self.PACKAGES_PATH_CHANGED | self.LOCKS_CHANGED | self.LOADPATH_CHANGED | self.PACKAGE_FILTER_CHANGED | self.CACHING_CHANGED)
[ "def", "set_context", "(", "self", ",", "context", ")", ":", "self", ".", "_set_context", "(", "context", ",", "emit", "=", "False", ")", "self", ".", "_modified", "=", "(", "not", "context", ".", "load_path", ")", "self", ".", "dataChanged", ".", "emi...
Replace the current context with another.
[ "Replace", "the", "current", "context", "with", "another", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/models/ContextModel.py#L214-L224
246,322
nerdvegas/rez
src/rez/vendor/distlib/util.py
get_resources_dests
def get_resources_dests(resources_root, rules): """Find destinations for resources files""" def get_rel_path(base, path): # normalizes and returns a lstripped-/-separated path base = base.replace(os.path.sep, '/') path = path.replace(os.path.sep, '/') assert path.startswith(base) return path[len(base):].lstrip('/') destinations = {} for base, suffix, dest in rules: prefix = os.path.join(resources_root, base) for abs_base in iglob(prefix): abs_glob = os.path.join(abs_base, suffix) for abs_path in iglob(abs_glob): resource_file = get_rel_path(resources_root, abs_path) if dest is None: # remove the entry if it was here destinations.pop(resource_file, None) else: rel_path = get_rel_path(abs_base, abs_path) rel_dest = dest.replace(os.path.sep, '/').rstrip('/') destinations[resource_file] = rel_dest + '/' + rel_path return destinations
python
def get_resources_dests(resources_root, rules): def get_rel_path(base, path): # normalizes and returns a lstripped-/-separated path base = base.replace(os.path.sep, '/') path = path.replace(os.path.sep, '/') assert path.startswith(base) return path[len(base):].lstrip('/') destinations = {} for base, suffix, dest in rules: prefix = os.path.join(resources_root, base) for abs_base in iglob(prefix): abs_glob = os.path.join(abs_base, suffix) for abs_path in iglob(abs_glob): resource_file = get_rel_path(resources_root, abs_path) if dest is None: # remove the entry if it was here destinations.pop(resource_file, None) else: rel_path = get_rel_path(abs_base, abs_path) rel_dest = dest.replace(os.path.sep, '/').rstrip('/') destinations[resource_file] = rel_dest + '/' + rel_path return destinations
[ "def", "get_resources_dests", "(", "resources_root", ",", "rules", ")", ":", "def", "get_rel_path", "(", "base", ",", "path", ")", ":", "# normalizes and returns a lstripped-/-separated path", "base", "=", "base", ".", "replace", "(", "os", ".", "path", ".", "se...
Find destinations for resources files
[ "Find", "destinations", "for", "resources", "files" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/distlib/util.py#L123-L147
246,323
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/cycles.py
find_cycle
def find_cycle(graph): """ Find a cycle in the given graph. This function will return a list of nodes which form a cycle in the graph or an empty list if no cycle exists. @type graph: graph, digraph @param graph: Graph. @rtype: list @return: List of nodes. """ if (isinstance(graph, graph_class)): directed = False elif (isinstance(graph, digraph_class)): directed = True else: raise InvalidGraphType def find_cycle_to_ancestor(node, ancestor): """ Find a cycle containing both node and ancestor. """ path = [] while (node != ancestor): if (node is None): return [] path.append(node) node = spanning_tree[node] path.append(node) path.reverse() return path def dfs(node): """ Depth-first search subfunction. """ visited[node] = 1 # Explore recursively the connected component for each in graph[node]: if (cycle): return if (each not in visited): spanning_tree[each] = node dfs(each) else: if (directed or spanning_tree[node] != each): cycle.extend(find_cycle_to_ancestor(node, each)) recursionlimit = getrecursionlimit() setrecursionlimit(max(len(graph.nodes())*2,recursionlimit)) visited = {} # List for marking visited and non-visited nodes spanning_tree = {} # Spanning tree cycle = [] # Algorithm outer-loop for each in graph: # Select a non-visited node if (each not in visited): spanning_tree[each] = None # Explore node's connected component dfs(each) if (cycle): setrecursionlimit(recursionlimit) return cycle setrecursionlimit(recursionlimit) return []
python
def find_cycle(graph): if (isinstance(graph, graph_class)): directed = False elif (isinstance(graph, digraph_class)): directed = True else: raise InvalidGraphType def find_cycle_to_ancestor(node, ancestor): """ Find a cycle containing both node and ancestor. """ path = [] while (node != ancestor): if (node is None): return [] path.append(node) node = spanning_tree[node] path.append(node) path.reverse() return path def dfs(node): """ Depth-first search subfunction. """ visited[node] = 1 # Explore recursively the connected component for each in graph[node]: if (cycle): return if (each not in visited): spanning_tree[each] = node dfs(each) else: if (directed or spanning_tree[node] != each): cycle.extend(find_cycle_to_ancestor(node, each)) recursionlimit = getrecursionlimit() setrecursionlimit(max(len(graph.nodes())*2,recursionlimit)) visited = {} # List for marking visited and non-visited nodes spanning_tree = {} # Spanning tree cycle = [] # Algorithm outer-loop for each in graph: # Select a non-visited node if (each not in visited): spanning_tree[each] = None # Explore node's connected component dfs(each) if (cycle): setrecursionlimit(recursionlimit) return cycle setrecursionlimit(recursionlimit) return []
[ "def", "find_cycle", "(", "graph", ")", ":", "if", "(", "isinstance", "(", "graph", ",", "graph_class", ")", ")", ":", "directed", "=", "False", "elif", "(", "isinstance", "(", "graph", ",", "digraph_class", ")", ")", ":", "directed", "=", "True", "els...
Find a cycle in the given graph. This function will return a list of nodes which form a cycle in the graph or an empty list if no cycle exists. @type graph: graph, digraph @param graph: Graph. @rtype: list @return: List of nodes.
[ "Find", "a", "cycle", "in", "the", "given", "graph", ".", "This", "function", "will", "return", "a", "list", "of", "nodes", "which", "form", "a", "cycle", "in", "the", "graph", "or", "an", "empty", "list", "if", "no", "cycle", "exists", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/cycles.py#L38-L108
246,324
nerdvegas/rez
src/rez/release_vcs.py
create_release_vcs
def create_release_vcs(path, vcs_name=None): """Return a new release VCS that can release from this source path.""" from rez.plugin_managers import plugin_manager vcs_types = get_release_vcs_types() if vcs_name: if vcs_name not in vcs_types: raise ReleaseVCSError("Unknown version control system: %r" % vcs_name) cls = plugin_manager.get_plugin_class('release_vcs', vcs_name) return cls(path) classes_by_level = {} for vcs_name in vcs_types: cls = plugin_manager.get_plugin_class('release_vcs', vcs_name) result = cls.find_vcs_root(path) if not result: continue vcs_path, levels_up = result classes_by_level.setdefault(levels_up, []).append((cls, vcs_path)) if not classes_by_level: raise ReleaseVCSError("No version control system for package " "releasing is associated with the path %s" % path) # it's ok to have multiple results, as long as there is only one at the # "closest" directory up from this dir - ie, if we start at: # /blah/foo/pkg_root # and these dirs exist: # /blah/.hg # /blah/foo/.git # ...then this is ok, because /blah/foo/.git is "closer" to the original # dir, and will be picked. However, if these two directories exist: # /blah/foo/.git # /blah/foo/.hg # ...then we error, because we can't decide which to use lowest_level = sorted(classes_by_level)[0] clss = classes_by_level[lowest_level] if len(clss) > 1: clss_str = ", ".join(x[0].name() for x in clss) raise ReleaseVCSError("Several version control systems are associated " "with the path %s: %s. Use rez-release --vcs to " "choose." % (path, clss_str)) else: cls, vcs_root = clss[0] return cls(pkg_root=path, vcs_root=vcs_root)
python
def create_release_vcs(path, vcs_name=None): from rez.plugin_managers import plugin_manager vcs_types = get_release_vcs_types() if vcs_name: if vcs_name not in vcs_types: raise ReleaseVCSError("Unknown version control system: %r" % vcs_name) cls = plugin_manager.get_plugin_class('release_vcs', vcs_name) return cls(path) classes_by_level = {} for vcs_name in vcs_types: cls = plugin_manager.get_plugin_class('release_vcs', vcs_name) result = cls.find_vcs_root(path) if not result: continue vcs_path, levels_up = result classes_by_level.setdefault(levels_up, []).append((cls, vcs_path)) if not classes_by_level: raise ReleaseVCSError("No version control system for package " "releasing is associated with the path %s" % path) # it's ok to have multiple results, as long as there is only one at the # "closest" directory up from this dir - ie, if we start at: # /blah/foo/pkg_root # and these dirs exist: # /blah/.hg # /blah/foo/.git # ...then this is ok, because /blah/foo/.git is "closer" to the original # dir, and will be picked. However, if these two directories exist: # /blah/foo/.git # /blah/foo/.hg # ...then we error, because we can't decide which to use lowest_level = sorted(classes_by_level)[0] clss = classes_by_level[lowest_level] if len(clss) > 1: clss_str = ", ".join(x[0].name() for x in clss) raise ReleaseVCSError("Several version control systems are associated " "with the path %s: %s. Use rez-release --vcs to " "choose." % (path, clss_str)) else: cls, vcs_root = clss[0] return cls(pkg_root=path, vcs_root=vcs_root)
[ "def", "create_release_vcs", "(", "path", ",", "vcs_name", "=", "None", ")", ":", "from", "rez", ".", "plugin_managers", "import", "plugin_manager", "vcs_types", "=", "get_release_vcs_types", "(", ")", "if", "vcs_name", ":", "if", "vcs_name", "not", "in", "vcs...
Return a new release VCS that can release from this source path.
[ "Return", "a", "new", "release", "VCS", "that", "can", "release", "from", "this", "source", "path", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/release_vcs.py#L17-L61
246,325
nerdvegas/rez
src/rez/release_vcs.py
ReleaseVCS.find_vcs_root
def find_vcs_root(cls, path): """Try to find a version control root directory of this type for the given path. If successful, returns (vcs_root, levels_up), where vcs_root is the path to the version control root directory it found, and levels_up is an integer indicating how many parent directories it had to search through to find it, where 0 means it was found in the indicated path, 1 means it was found in that path's parent, etc. If not sucessful, returns None """ if cls.search_parents_for_root(): valid_dirs = walk_up_dirs(path) else: valid_dirs = [path] for i, current_path in enumerate(valid_dirs): if cls.is_valid_root(current_path): return current_path, i return None
python
def find_vcs_root(cls, path): if cls.search_parents_for_root(): valid_dirs = walk_up_dirs(path) else: valid_dirs = [path] for i, current_path in enumerate(valid_dirs): if cls.is_valid_root(current_path): return current_path, i return None
[ "def", "find_vcs_root", "(", "cls", ",", "path", ")", ":", "if", "cls", ".", "search_parents_for_root", "(", ")", ":", "valid_dirs", "=", "walk_up_dirs", "(", "path", ")", "else", ":", "valid_dirs", "=", "[", "path", "]", "for", "i", ",", "current_path",...
Try to find a version control root directory of this type for the given path. If successful, returns (vcs_root, levels_up), where vcs_root is the path to the version control root directory it found, and levels_up is an integer indicating how many parent directories it had to search through to find it, where 0 means it was found in the indicated path, 1 means it was found in that path's parent, etc. If not sucessful, returns None
[ "Try", "to", "find", "a", "version", "control", "root", "directory", "of", "this", "type", "for", "the", "given", "path", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/release_vcs.py#L115-L132
246,326
nerdvegas/rez
src/rez/release_vcs.py
ReleaseVCS._cmd
def _cmd(self, *nargs): """Convenience function for executing a program such as 'git' etc.""" cmd_str = ' '.join(map(quote, nargs)) if self.package.config.debug("package_release"): print_debug("Running command: %s" % cmd_str) p = popen(nargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.pkg_root) out, err = p.communicate() if p.returncode: print_debug("command stdout:") print_debug(out) print_debug("command stderr:") print_debug(err) raise ReleaseVCSError("command failed: %s\n%s" % (cmd_str, err)) out = out.strip() if out: return [x.rstrip() for x in out.split('\n')] else: return []
python
def _cmd(self, *nargs): cmd_str = ' '.join(map(quote, nargs)) if self.package.config.debug("package_release"): print_debug("Running command: %s" % cmd_str) p = popen(nargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.pkg_root) out, err = p.communicate() if p.returncode: print_debug("command stdout:") print_debug(out) print_debug("command stderr:") print_debug(err) raise ReleaseVCSError("command failed: %s\n%s" % (cmd_str, err)) out = out.strip() if out: return [x.rstrip() for x in out.split('\n')] else: return []
[ "def", "_cmd", "(", "self", ",", "*", "nargs", ")", ":", "cmd_str", "=", "' '", ".", "join", "(", "map", "(", "quote", ",", "nargs", ")", ")", "if", "self", ".", "package", ".", "config", ".", "debug", "(", "\"package_release\"", ")", ":", "print_d...
Convenience function for executing a program such as 'git' etc.
[ "Convenience", "function", "for", "executing", "a", "program", "such", "as", "git", "etc", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/release_vcs.py#L203-L224
246,327
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._close
def _close(self, args): """Request a channel close This method indicates that the sender wants to close the channel. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. an exception. When a close is due to an exception, the sender provides the class and method id of the method which caused the exception. RULE: After sending this method any received method except Channel.Close-OK MUST be discarded. RULE: The peer sending this method MAY use a counter or timeout to detect failure of the other peer to respond correctly with Channel.Close-OK.. PARAMETERS: reply_code: short The reply code. The AMQ reply codes are defined in AMQ RFC 011. reply_text: shortstr The localised reply text. This text can be logged as an aid to resolving issues. class_id: short failing method class When the close is provoked by a method exception, this is the class of the method. method_id: short failing method ID When the close is provoked by a method exception, this is the ID of the method. """ reply_code = args.read_short() reply_text = args.read_shortstr() class_id = args.read_short() method_id = args.read_short() self._send_method((20, 41)) self._do_revive() raise error_for_code( reply_code, reply_text, (class_id, method_id), ChannelError, )
python
def _close(self, args): reply_code = args.read_short() reply_text = args.read_shortstr() class_id = args.read_short() method_id = args.read_short() self._send_method((20, 41)) self._do_revive() raise error_for_code( reply_code, reply_text, (class_id, method_id), ChannelError, )
[ "def", "_close", "(", "self", ",", "args", ")", ":", "reply_code", "=", "args", ".", "read_short", "(", ")", "reply_text", "=", "args", ".", "read_shortstr", "(", ")", "class_id", "=", "args", ".", "read_short", "(", ")", "method_id", "=", "args", ".",...
Request a channel close This method indicates that the sender wants to close the channel. This may be due to internal conditions (e.g. a forced shut-down) or due to an error handling a specific method, i.e. an exception. When a close is due to an exception, the sender provides the class and method id of the method which caused the exception. RULE: After sending this method any received method except Channel.Close-OK MUST be discarded. RULE: The peer sending this method MAY use a counter or timeout to detect failure of the other peer to respond correctly with Channel.Close-OK.. PARAMETERS: reply_code: short The reply code. The AMQ reply codes are defined in AMQ RFC 011. reply_text: shortstr The localised reply text. This text can be logged as an aid to resolving issues. class_id: short failing method class When the close is provoked by a method exception, this is the class of the method. method_id: short failing method ID When the close is provoked by a method exception, this is the ID of the method.
[ "Request", "a", "channel", "close" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L186-L244
246,328
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._x_flow_ok
def _x_flow_ok(self, active): """Confirm a flow method Confirms to the peer that a flow command was received and processed. PARAMETERS: active: boolean current flow setting Confirms the setting of the processed flow method: True means the peer will start sending or continue to send content frames; False means it will not. """ args = AMQPWriter() args.write_bit(active) self._send_method((20, 21), args)
python
def _x_flow_ok(self, active): args = AMQPWriter() args.write_bit(active) self._send_method((20, 21), args)
[ "def", "_x_flow_ok", "(", "self", ",", "active", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_bit", "(", "active", ")", "self", ".", "_send_method", "(", "(", "20", ",", "21", ")", ",", "args", ")" ]
Confirm a flow method Confirms to the peer that a flow command was received and processed. PARAMETERS: active: boolean current flow setting Confirms the setting of the processed flow method: True means the peer will start sending or continue to send content frames; False means it will not.
[ "Confirm", "a", "flow", "method" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L364-L382
246,329
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._x_open
def _x_open(self): """Open a channel for use This method opens a virtual connection (a channel). RULE: This method MUST NOT be called when the channel is already open. PARAMETERS: out_of_band: shortstr (DEPRECATED) out-of-band settings Configures out-of-band transfers on this channel. The syntax and meaning of this field will be formally defined at a later date. """ if self.is_open: return args = AMQPWriter() args.write_shortstr('') # out_of_band: deprecated self._send_method((20, 10), args) return self.wait(allowed_methods=[ (20, 11), # Channel.open_ok ])
python
def _x_open(self): if self.is_open: return args = AMQPWriter() args.write_shortstr('') # out_of_band: deprecated self._send_method((20, 10), args) return self.wait(allowed_methods=[ (20, 11), # Channel.open_ok ])
[ "def", "_x_open", "(", "self", ")", ":", "if", "self", ".", "is_open", ":", "return", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_shortstr", "(", "''", ")", "# out_of_band: deprecated", "self", ".", "_send_method", "(", "(", "20", ",", "10",...
Open a channel for use This method opens a virtual connection (a channel). RULE: This method MUST NOT be called when the channel is already open. PARAMETERS: out_of_band: shortstr (DEPRECATED) out-of-band settings Configures out-of-band transfers on this channel. The syntax and meaning of this field will be formally defined at a later date.
[ "Open", "a", "channel", "for", "use" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L402-L430
246,330
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.exchange_declare
def exchange_declare(self, exchange, type, passive=False, durable=False, auto_delete=True, nowait=False, arguments=None): """Declare exchange, create if needed This method creates an exchange if it does not already exist, and if the exchange exists, verifies that it is of the correct and expected class. RULE: The server SHOULD support a minimum of 16 exchanges per virtual host and ideally, impose no limit except as defined by available resources. PARAMETERS: exchange: shortstr RULE: Exchange names starting with "amq." are reserved for predeclared and standardised exchanges. If the client attempts to create an exchange starting with "amq.", the server MUST raise a channel exception with reply code 403 (access refused). type: shortstr exchange type Each exchange belongs to one of a set of exchange types implemented by the server. The exchange types define the functionality of the exchange - i.e. how messages are routed through it. It is not valid or meaningful to attempt to change the type of an existing exchange. RULE: If the exchange already exists with a different type, the server MUST raise a connection exception with a reply code 507 (not allowed). RULE: If the server does not support the requested exchange type it MUST raise a connection exception with a reply code 503 (command invalid). passive: boolean do not create exchange If set, the server will not create the exchange. The client can use this to check whether an exchange exists without modifying the server state. RULE: If set, and the exchange does not already exist, the server MUST raise a channel exception with reply code 404 (not found). durable: boolean request a durable exchange If set when creating a new exchange, the exchange will be marked as durable. Durable exchanges remain active when a server restarts. Non-durable exchanges (transient exchanges) are purged if/when a server restarts. RULE: The server MUST support both durable and transient exchanges. RULE: The server MUST ignore the durable field if the exchange already exists. auto_delete: boolean auto-delete when unused If set, the exchange is deleted when all queues have finished using it. RULE: The server SHOULD allow for a reasonable delay between the point when it determines that an exchange is not being used (or no longer used), and the point when it deletes the exchange. At the least it must allow a client to create an exchange and then bind a queue to it, with a small but non-zero delay between these two actions. RULE: The server MUST ignore the auto-delete field if the exchange already exists. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. arguments: table arguments for declaration A set of arguments for the declaration. The syntax and semantics of these arguments depends on the server implementation. This field is ignored if passive is True. """ arguments = {} if arguments is None else arguments args = AMQPWriter() args.write_short(0) args.write_shortstr(exchange) args.write_shortstr(type) args.write_bit(passive) args.write_bit(durable) args.write_bit(auto_delete) args.write_bit(False) # internal: deprecated args.write_bit(nowait) args.write_table(arguments) self._send_method((40, 10), args) if auto_delete: warn(VDeprecationWarning(EXCHANGE_AUTODELETE_DEPRECATED)) if not nowait: return self.wait(allowed_methods=[ (40, 11), # Channel.exchange_declare_ok ])
python
def exchange_declare(self, exchange, type, passive=False, durable=False, auto_delete=True, nowait=False, arguments=None): arguments = {} if arguments is None else arguments args = AMQPWriter() args.write_short(0) args.write_shortstr(exchange) args.write_shortstr(type) args.write_bit(passive) args.write_bit(durable) args.write_bit(auto_delete) args.write_bit(False) # internal: deprecated args.write_bit(nowait) args.write_table(arguments) self._send_method((40, 10), args) if auto_delete: warn(VDeprecationWarning(EXCHANGE_AUTODELETE_DEPRECATED)) if not nowait: return self.wait(allowed_methods=[ (40, 11), # Channel.exchange_declare_ok ])
[ "def", "exchange_declare", "(", "self", ",", "exchange", ",", "type", ",", "passive", "=", "False", ",", "durable", "=", "False", ",", "auto_delete", "=", "True", ",", "nowait", "=", "False", ",", "arguments", "=", "None", ")", ":", "arguments", "=", "...
Declare exchange, create if needed This method creates an exchange if it does not already exist, and if the exchange exists, verifies that it is of the correct and expected class. RULE: The server SHOULD support a minimum of 16 exchanges per virtual host and ideally, impose no limit except as defined by available resources. PARAMETERS: exchange: shortstr RULE: Exchange names starting with "amq." are reserved for predeclared and standardised exchanges. If the client attempts to create an exchange starting with "amq.", the server MUST raise a channel exception with reply code 403 (access refused). type: shortstr exchange type Each exchange belongs to one of a set of exchange types implemented by the server. The exchange types define the functionality of the exchange - i.e. how messages are routed through it. It is not valid or meaningful to attempt to change the type of an existing exchange. RULE: If the exchange already exists with a different type, the server MUST raise a connection exception with a reply code 507 (not allowed). RULE: If the server does not support the requested exchange type it MUST raise a connection exception with a reply code 503 (command invalid). passive: boolean do not create exchange If set, the server will not create the exchange. The client can use this to check whether an exchange exists without modifying the server state. RULE: If set, and the exchange does not already exist, the server MUST raise a channel exception with reply code 404 (not found). durable: boolean request a durable exchange If set when creating a new exchange, the exchange will be marked as durable. Durable exchanges remain active when a server restarts. Non-durable exchanges (transient exchanges) are purged if/when a server restarts. RULE: The server MUST support both durable and transient exchanges. RULE: The server MUST ignore the durable field if the exchange already exists. auto_delete: boolean auto-delete when unused If set, the exchange is deleted when all queues have finished using it. RULE: The server SHOULD allow for a reasonable delay between the point when it determines that an exchange is not being used (or no longer used), and the point when it deletes the exchange. At the least it must allow a client to create an exchange and then bind a queue to it, with a small but non-zero delay between these two actions. RULE: The server MUST ignore the auto-delete field if the exchange already exists. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. arguments: table arguments for declaration A set of arguments for the declaration. The syntax and semantics of these arguments depends on the server implementation. This field is ignored if passive is True.
[ "Declare", "exchange", "create", "if", "needed" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L481-L623
246,331
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.exchange_bind
def exchange_bind(self, destination, source='', routing_key='', nowait=False, arguments=None): """This method binds an exchange to an exchange. RULE: A server MUST allow and ignore duplicate bindings - that is, two or more bind methods for a specific exchanges, with identical arguments - without treating these as an error. RULE: A server MUST allow cycles of exchange bindings to be created including allowing an exchange to be bound to itself. RULE: A server MUST not deliver the same message more than once to a destination exchange, even if the topology of exchanges and bindings results in multiple (even infinite) routes to that exchange. PARAMETERS: reserved-1: short destination: shortstr Specifies the name of the destination exchange to bind. RULE: A client MUST NOT be allowed to bind a non- existent destination exchange. RULE: The server MUST accept a blank exchange name to mean the default exchange. source: shortstr Specifies the name of the source exchange to bind. RULE: A client MUST NOT be allowed to bind a non- existent source exchange. RULE: The server MUST accept a blank exchange name to mean the default exchange. routing-key: shortstr Specifies the routing key for the binding. The routing key is used for routing messages depending on the exchange configuration. Not all exchanges use a routing key - refer to the specific exchange documentation. no-wait: bit arguments: table A set of arguments for the binding. The syntax and semantics of these arguments depends on the exchange class. """ arguments = {} if arguments is None else arguments args = AMQPWriter() args.write_short(0) args.write_shortstr(destination) args.write_shortstr(source) args.write_shortstr(routing_key) args.write_bit(nowait) args.write_table(arguments) self._send_method((40, 30), args) if not nowait: return self.wait(allowed_methods=[ (40, 31), # Channel.exchange_bind_ok ])
python
def exchange_bind(self, destination, source='', routing_key='', nowait=False, arguments=None): arguments = {} if arguments is None else arguments args = AMQPWriter() args.write_short(0) args.write_shortstr(destination) args.write_shortstr(source) args.write_shortstr(routing_key) args.write_bit(nowait) args.write_table(arguments) self._send_method((40, 30), args) if not nowait: return self.wait(allowed_methods=[ (40, 31), # Channel.exchange_bind_ok ])
[ "def", "exchange_bind", "(", "self", ",", "destination", ",", "source", "=", "''", ",", "routing_key", "=", "''", ",", "nowait", "=", "False", ",", "arguments", "=", "None", ")", ":", "arguments", "=", "{", "}", "if", "arguments", "is", "None", "else",...
This method binds an exchange to an exchange. RULE: A server MUST allow and ignore duplicate bindings - that is, two or more bind methods for a specific exchanges, with identical arguments - without treating these as an error. RULE: A server MUST allow cycles of exchange bindings to be created including allowing an exchange to be bound to itself. RULE: A server MUST not deliver the same message more than once to a destination exchange, even if the topology of exchanges and bindings results in multiple (even infinite) routes to that exchange. PARAMETERS: reserved-1: short destination: shortstr Specifies the name of the destination exchange to bind. RULE: A client MUST NOT be allowed to bind a non- existent destination exchange. RULE: The server MUST accept a blank exchange name to mean the default exchange. source: shortstr Specifies the name of the source exchange to bind. RULE: A client MUST NOT be allowed to bind a non- existent source exchange. RULE: The server MUST accept a blank exchange name to mean the default exchange. routing-key: shortstr Specifies the routing key for the binding. The routing key is used for routing messages depending on the exchange configuration. Not all exchanges use a routing key - refer to the specific exchange documentation. no-wait: bit arguments: table A set of arguments for the binding. The syntax and semantics of these arguments depends on the exchange class.
[ "This", "method", "binds", "an", "exchange", "to", "an", "exchange", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L697-L783
246,332
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.queue_declare
def queue_declare(self, queue='', passive=False, durable=False, exclusive=False, auto_delete=True, nowait=False, arguments=None): """Declare queue, create if needed This method creates or checks a queue. When creating a new queue the client can specify various properties that control the durability of the queue and its contents, and the level of sharing for the queue. RULE: The server MUST create a default binding for a newly- created queue to the default exchange, which is an exchange of type 'direct'. RULE: The server SHOULD support a minimum of 256 queues per virtual host and ideally, impose no limit except as defined by available resources. PARAMETERS: queue: shortstr RULE: The queue name MAY be empty, in which case the server MUST create a new queue with a unique generated name and return this to the client in the Declare-Ok method. RULE: Queue names starting with "amq." are reserved for predeclared and standardised server queues. If the queue name starts with "amq." and the passive option is False, the server MUST raise a connection exception with reply code 403 (access refused). passive: boolean do not create queue If set, the server will not create the queue. The client can use this to check whether a queue exists without modifying the server state. RULE: If set, and the queue does not already exist, the server MUST respond with a reply code 404 (not found) and raise a channel exception. durable: boolean request a durable queue If set when creating a new queue, the queue will be marked as durable. Durable queues remain active when a server restarts. Non-durable queues (transient queues) are purged if/when a server restarts. Note that durable queues do not necessarily hold persistent messages, although it does not make sense to send persistent messages to a transient queue. RULE: The server MUST recreate the durable queue after a restart. RULE: The server MUST support both durable and transient queues. RULE: The server MUST ignore the durable field if the queue already exists. exclusive: boolean request an exclusive queue Exclusive queues may only be consumed from by the current connection. Setting the 'exclusive' flag always implies 'auto-delete'. RULE: The server MUST support both exclusive (private) and non-exclusive (shared) queues. RULE: The server MUST raise a channel exception if 'exclusive' is specified and the queue already exists and is owned by a different connection. auto_delete: boolean auto-delete queue when unused If set, the queue is deleted when all consumers have finished using it. Last consumer can be cancelled either explicitly or because its channel is closed. If there was no consumer ever on the queue, it won't be deleted. RULE: The server SHOULD allow for a reasonable delay between the point when it determines that a queue is not being used (or no longer used), and the point when it deletes the queue. At the least it must allow a client to create a queue and then create a consumer to read from it, with a small but non-zero delay between these two actions. The server should equally allow for clients that may be disconnected prematurely, and wish to re- consume from the same queue without losing messages. We would recommend a configurable timeout, with a suitable default value being one minute. RULE: The server MUST ignore the auto-delete field if the queue already exists. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. arguments: table arguments for declaration A set of arguments for the declaration. The syntax and semantics of these arguments depends on the server implementation. This field is ignored if passive is True. Returns a tuple containing 3 items: the name of the queue (essential for automatically-named queues) message count consumer count """ arguments = {} if arguments is None else arguments args = AMQPWriter() args.write_short(0) args.write_shortstr(queue) args.write_bit(passive) args.write_bit(durable) args.write_bit(exclusive) args.write_bit(auto_delete) args.write_bit(nowait) args.write_table(arguments) self._send_method((50, 10), args) if not nowait: return self.wait(allowed_methods=[ (50, 11), # Channel.queue_declare_ok ])
python
def queue_declare(self, queue='', passive=False, durable=False, exclusive=False, auto_delete=True, nowait=False, arguments=None): arguments = {} if arguments is None else arguments args = AMQPWriter() args.write_short(0) args.write_shortstr(queue) args.write_bit(passive) args.write_bit(durable) args.write_bit(exclusive) args.write_bit(auto_delete) args.write_bit(nowait) args.write_table(arguments) self._send_method((50, 10), args) if not nowait: return self.wait(allowed_methods=[ (50, 11), # Channel.queue_declare_ok ])
[ "def", "queue_declare", "(", "self", ",", "queue", "=", "''", ",", "passive", "=", "False", ",", "durable", "=", "False", ",", "exclusive", "=", "False", ",", "auto_delete", "=", "True", ",", "nowait", "=", "False", ",", "arguments", "=", "None", ")", ...
Declare queue, create if needed This method creates or checks a queue. When creating a new queue the client can specify various properties that control the durability of the queue and its contents, and the level of sharing for the queue. RULE: The server MUST create a default binding for a newly- created queue to the default exchange, which is an exchange of type 'direct'. RULE: The server SHOULD support a minimum of 256 queues per virtual host and ideally, impose no limit except as defined by available resources. PARAMETERS: queue: shortstr RULE: The queue name MAY be empty, in which case the server MUST create a new queue with a unique generated name and return this to the client in the Declare-Ok method. RULE: Queue names starting with "amq." are reserved for predeclared and standardised server queues. If the queue name starts with "amq." and the passive option is False, the server MUST raise a connection exception with reply code 403 (access refused). passive: boolean do not create queue If set, the server will not create the queue. The client can use this to check whether a queue exists without modifying the server state. RULE: If set, and the queue does not already exist, the server MUST respond with a reply code 404 (not found) and raise a channel exception. durable: boolean request a durable queue If set when creating a new queue, the queue will be marked as durable. Durable queues remain active when a server restarts. Non-durable queues (transient queues) are purged if/when a server restarts. Note that durable queues do not necessarily hold persistent messages, although it does not make sense to send persistent messages to a transient queue. RULE: The server MUST recreate the durable queue after a restart. RULE: The server MUST support both durable and transient queues. RULE: The server MUST ignore the durable field if the queue already exists. exclusive: boolean request an exclusive queue Exclusive queues may only be consumed from by the current connection. Setting the 'exclusive' flag always implies 'auto-delete'. RULE: The server MUST support both exclusive (private) and non-exclusive (shared) queues. RULE: The server MUST raise a channel exception if 'exclusive' is specified and the queue already exists and is owned by a different connection. auto_delete: boolean auto-delete queue when unused If set, the queue is deleted when all consumers have finished using it. Last consumer can be cancelled either explicitly or because its channel is closed. If there was no consumer ever on the queue, it won't be deleted. RULE: The server SHOULD allow for a reasonable delay between the point when it determines that a queue is not being used (or no longer used), and the point when it deletes the queue. At the least it must allow a client to create a queue and then create a consumer to read from it, with a small but non-zero delay between these two actions. The server should equally allow for clients that may be disconnected prematurely, and wish to re- consume from the same queue without losing messages. We would recommend a configurable timeout, with a suitable default value being one minute. RULE: The server MUST ignore the auto-delete field if the queue already exists. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. arguments: table arguments for declaration A set of arguments for the declaration. The syntax and semantics of these arguments depends on the server implementation. This field is ignored if passive is True. Returns a tuple containing 3 items: the name of the queue (essential for automatically-named queues) message count consumer count
[ "Declare", "queue", "create", "if", "needed" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1090-L1260
246,333
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._queue_declare_ok
def _queue_declare_ok(self, args): """Confirms a queue definition This method confirms a Declare method and confirms the name of the queue, essential for automatically-named queues. PARAMETERS: queue: shortstr Reports the name of the queue. If the server generated a queue name, this field contains that name. message_count: long number of messages in queue Reports the number of messages in the queue, which will be zero for newly-created queues. consumer_count: long number of consumers Reports the number of active consumers for the queue. Note that consumers can suspend activity (Channel.Flow) in which case they do not appear in this count. """ return queue_declare_ok_t( args.read_shortstr(), args.read_long(), args.read_long(), )
python
def _queue_declare_ok(self, args): return queue_declare_ok_t( args.read_shortstr(), args.read_long(), args.read_long(), )
[ "def", "_queue_declare_ok", "(", "self", ",", "args", ")", ":", "return", "queue_declare_ok_t", "(", "args", ".", "read_shortstr", "(", ")", ",", "args", ".", "read_long", "(", ")", ",", "args", ".", "read_long", "(", ")", ",", ")" ]
Confirms a queue definition This method confirms a Declare method and confirms the name of the queue, essential for automatically-named queues. PARAMETERS: queue: shortstr Reports the name of the queue. If the server generated a queue name, this field contains that name. message_count: long number of messages in queue Reports the number of messages in the queue, which will be zero for newly-created queues. consumer_count: long number of consumers Reports the number of active consumers for the queue. Note that consumers can suspend activity (Channel.Flow) in which case they do not appear in this count.
[ "Confirms", "a", "queue", "definition" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1262-L1295
246,334
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.queue_delete
def queue_delete(self, queue='', if_unused=False, if_empty=False, nowait=False): """Delete a queue This method deletes a queue. When a queue is deleted any pending messages are sent to a dead-letter queue if this is defined in the server configuration, and all consumers on the queue are cancelled. RULE: The server SHOULD use a dead-letter queue to hold messages that were pending on a deleted queue, and MAY provide facilities for a system administrator to move these messages back to an active queue. PARAMETERS: queue: shortstr Specifies the name of the queue to delete. If the queue name is empty, refers to the current queue for the channel, which is the last declared queue. RULE: If the client did not previously declare a queue, and the queue name in this method is empty, the server MUST raise a connection exception with reply code 530 (not allowed). RULE: The queue must exist. Attempting to delete a non- existing queue causes a channel exception. if_unused: boolean delete only if unused If set, the server will only delete the queue if it has no consumers. If the queue has consumers the server does does not delete it but raises a channel exception instead. RULE: The server MUST respect the if-unused flag when deleting a queue. if_empty: boolean delete only if empty If set, the server will only delete the queue if it has no messages. If the queue is not empty the server raises a channel exception. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. """ args = AMQPWriter() args.write_short(0) args.write_shortstr(queue) args.write_bit(if_unused) args.write_bit(if_empty) args.write_bit(nowait) self._send_method((50, 40), args) if not nowait: return self.wait(allowed_methods=[ (50, 41), # Channel.queue_delete_ok ])
python
def queue_delete(self, queue='', if_unused=False, if_empty=False, nowait=False): args = AMQPWriter() args.write_short(0) args.write_shortstr(queue) args.write_bit(if_unused) args.write_bit(if_empty) args.write_bit(nowait) self._send_method((50, 40), args) if not nowait: return self.wait(allowed_methods=[ (50, 41), # Channel.queue_delete_ok ])
[ "def", "queue_delete", "(", "self", ",", "queue", "=", "''", ",", "if_unused", "=", "False", ",", "if_empty", "=", "False", ",", "nowait", "=", "False", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_short", "(", "0", ")", "args",...
Delete a queue This method deletes a queue. When a queue is deleted any pending messages are sent to a dead-letter queue if this is defined in the server configuration, and all consumers on the queue are cancelled. RULE: The server SHOULD use a dead-letter queue to hold messages that were pending on a deleted queue, and MAY provide facilities for a system administrator to move these messages back to an active queue. PARAMETERS: queue: shortstr Specifies the name of the queue to delete. If the queue name is empty, refers to the current queue for the channel, which is the last declared queue. RULE: If the client did not previously declare a queue, and the queue name in this method is empty, the server MUST raise a connection exception with reply code 530 (not allowed). RULE: The queue must exist. Attempting to delete a non- existing queue causes a channel exception. if_unused: boolean delete only if unused If set, the server will only delete the queue if it has no consumers. If the queue has consumers the server does does not delete it but raises a channel exception instead. RULE: The server MUST respect the if-unused flag when deleting a queue. if_empty: boolean delete only if empty If set, the server will only delete the queue if it has no messages. If the queue is not empty the server raises a channel exception. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception.
[ "Delete", "a", "queue" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1297-L1375
246,335
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.queue_purge
def queue_purge(self, queue='', nowait=False): """Purge a queue This method removes all messages from a queue. It does not cancel consumers. Purged messages are deleted without any formal "undo" mechanism. RULE: A call to purge MUST result in an empty queue. RULE: On transacted channels the server MUST not purge messages that have already been sent to a client but not yet acknowledged. RULE: The server MAY implement a purge queue or log that allows system administrators to recover accidentally-purged messages. The server SHOULD NOT keep purged messages in the same storage spaces as the live messages since the volumes of purged messages may get very large. PARAMETERS: queue: shortstr Specifies the name of the queue to purge. If the queue name is empty, refers to the current queue for the channel, which is the last declared queue. RULE: If the client did not previously declare a queue, and the queue name in this method is empty, the server MUST raise a connection exception with reply code 530 (not allowed). RULE: The queue must exist. Attempting to purge a non- existing queue causes a channel exception. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. if nowait is False, returns a message_count """ args = AMQPWriter() args.write_short(0) args.write_shortstr(queue) args.write_bit(nowait) self._send_method((50, 30), args) if not nowait: return self.wait(allowed_methods=[ (50, 31), # Channel.queue_purge_ok ])
python
def queue_purge(self, queue='', nowait=False): args = AMQPWriter() args.write_short(0) args.write_shortstr(queue) args.write_bit(nowait) self._send_method((50, 30), args) if not nowait: return self.wait(allowed_methods=[ (50, 31), # Channel.queue_purge_ok ])
[ "def", "queue_purge", "(", "self", ",", "queue", "=", "''", ",", "nowait", "=", "False", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_short", "(", "0", ")", "args", ".", "write_shortstr", "(", "queue", ")", "args", ".", "write_b...
Purge a queue This method removes all messages from a queue. It does not cancel consumers. Purged messages are deleted without any formal "undo" mechanism. RULE: A call to purge MUST result in an empty queue. RULE: On transacted channels the server MUST not purge messages that have already been sent to a client but not yet acknowledged. RULE: The server MAY implement a purge queue or log that allows system administrators to recover accidentally-purged messages. The server SHOULD NOT keep purged messages in the same storage spaces as the live messages since the volumes of purged messages may get very large. PARAMETERS: queue: shortstr Specifies the name of the queue to purge. If the queue name is empty, refers to the current queue for the channel, which is the last declared queue. RULE: If the client did not previously declare a queue, and the queue name in this method is empty, the server MUST raise a connection exception with reply code 530 (not allowed). RULE: The queue must exist. Attempting to purge a non- existing queue causes a channel exception. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. if nowait is False, returns a message_count
[ "Purge", "a", "queue" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1392-L1457
246,336
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.basic_ack
def basic_ack(self, delivery_tag, multiple=False): """Acknowledge one or more messages This method acknowledges one or more messages delivered via the Deliver or Get-Ok methods. The client can ask to confirm a single message or a set of messages up to and including a specific message. PARAMETERS: delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". multiple: boolean acknowledge multiple messages If set to True, the delivery tag is treated as "up to and including", so that the client can acknowledge multiple messages with a single method. If set to False, the delivery tag refers to a single message. If the multiple field is True, and the delivery tag is zero, tells the server to acknowledge all outstanding mesages. RULE: The server MUST validate that a non-zero delivery- tag refers to an delivered message, and raise a channel exception if this is not the case. """ args = AMQPWriter() args.write_longlong(delivery_tag) args.write_bit(multiple) self._send_method((60, 80), args)
python
def basic_ack(self, delivery_tag, multiple=False): args = AMQPWriter() args.write_longlong(delivery_tag) args.write_bit(multiple) self._send_method((60, 80), args)
[ "def", "basic_ack", "(", "self", ",", "delivery_tag", ",", "multiple", "=", "False", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_longlong", "(", "delivery_tag", ")", "args", ".", "write_bit", "(", "multiple", ")", "self", ".", "_se...
Acknowledge one or more messages This method acknowledges one or more messages delivered via the Deliver or Get-Ok methods. The client can ask to confirm a single message or a set of messages up to and including a specific message. PARAMETERS: delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". multiple: boolean acknowledge multiple messages If set to True, the delivery tag is treated as "up to and including", so that the client can acknowledge multiple messages with a single method. If set to False, the delivery tag refers to a single message. If the multiple field is True, and the delivery tag is zero, tells the server to acknowledge all outstanding mesages. RULE: The server MUST validate that a non-zero delivery- tag refers to an delivered message, and raise a channel exception if this is not the case.
[ "Acknowledge", "one", "or", "more", "messages" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1534-L1584
246,337
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.basic_cancel
def basic_cancel(self, consumer_tag, nowait=False): """End a queue consumer This method cancels a consumer. This does not affect already delivered messages, but it does mean the server will not send any more messages for that consumer. The client may receive an abitrary number of messages in between sending the cancel method and receiving the cancel-ok reply. RULE: If the queue no longer exists when the client sends a cancel command, or the consumer has been cancelled for other reasons, this command has no effect. PARAMETERS: consumer_tag: shortstr consumer tag Identifier for the consumer, valid within the current connection. RULE: The consumer tag is valid only within the channel from which the consumer was created. I.e. a client MUST NOT create a consumer in one channel and then use it in another. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. """ if self.connection is not None: self.no_ack_consumers.discard(consumer_tag) args = AMQPWriter() args.write_shortstr(consumer_tag) args.write_bit(nowait) self._send_method((60, 30), args) return self.wait(allowed_methods=[ (60, 31), # Channel.basic_cancel_ok ])
python
def basic_cancel(self, consumer_tag, nowait=False): if self.connection is not None: self.no_ack_consumers.discard(consumer_tag) args = AMQPWriter() args.write_shortstr(consumer_tag) args.write_bit(nowait) self._send_method((60, 30), args) return self.wait(allowed_methods=[ (60, 31), # Channel.basic_cancel_ok ])
[ "def", "basic_cancel", "(", "self", ",", "consumer_tag", ",", "nowait", "=", "False", ")", ":", "if", "self", ".", "connection", "is", "not", "None", ":", "self", ".", "no_ack_consumers", ".", "discard", "(", "consumer_tag", ")", "args", "=", "AMQPWriter",...
End a queue consumer This method cancels a consumer. This does not affect already delivered messages, but it does mean the server will not send any more messages for that consumer. The client may receive an abitrary number of messages in between sending the cancel method and receiving the cancel-ok reply. RULE: If the queue no longer exists when the client sends a cancel command, or the consumer has been cancelled for other reasons, this command has no effect. PARAMETERS: consumer_tag: shortstr consumer tag Identifier for the consumer, valid within the current connection. RULE: The consumer tag is valid only within the channel from which the consumer was created. I.e. a client MUST NOT create a consumer in one channel and then use it in another. nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception.
[ "End", "a", "queue", "consumer" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1586-L1634
246,338
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._basic_cancel_notify
def _basic_cancel_notify(self, args): """Consumer cancelled by server. Most likely the queue was deleted. """ consumer_tag = args.read_shortstr() callback = self._on_cancel(consumer_tag) if callback: callback(consumer_tag) else: raise ConsumerCancelled(consumer_tag, (60, 30))
python
def _basic_cancel_notify(self, args): consumer_tag = args.read_shortstr() callback = self._on_cancel(consumer_tag) if callback: callback(consumer_tag) else: raise ConsumerCancelled(consumer_tag, (60, 30))
[ "def", "_basic_cancel_notify", "(", "self", ",", "args", ")", ":", "consumer_tag", "=", "args", ".", "read_shortstr", "(", ")", "callback", "=", "self", ".", "_on_cancel", "(", "consumer_tag", ")", "if", "callback", ":", "callback", "(", "consumer_tag", ")",...
Consumer cancelled by server. Most likely the queue was deleted.
[ "Consumer", "cancelled", "by", "server", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1636-L1647
246,339
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.basic_consume
def basic_consume(self, queue='', consumer_tag='', no_local=False, no_ack=False, exclusive=False, nowait=False, callback=None, arguments=None, on_cancel=None): """Start a queue consumer This method asks the server to start a "consumer", which is a transient request for messages from a specific queue. Consumers last as long as the channel they were created on, or until the client cancels them. RULE: The server SHOULD support at least 16 consumers per queue, unless the queue was declared as private, and ideally, impose no limit except as defined by available resources. PARAMETERS: queue: shortstr Specifies the name of the queue to consume from. If the queue name is null, refers to the current queue for the channel, which is the last declared queue. RULE: If the client did not previously declare a queue, and the queue name in this method is empty, the server MUST raise a connection exception with reply code 530 (not allowed). consumer_tag: shortstr Specifies the identifier for the consumer. The consumer tag is local to a connection, so two clients can use the same consumer tags. If this field is empty the server will generate a unique tag. RULE: The tag MUST NOT refer to an existing consumer. If the client attempts to create two consumers with the same non-empty tag the server MUST raise a connection exception with reply code 530 (not allowed). no_local: boolean do not deliver own messages If the no-local field is set the server will not send messages to the client that published them. no_ack: boolean no acknowledgement needed If this field is set the server does not expect acknowledgments for messages. That is, when a message is delivered to the client the server automatically and silently acknowledges it on behalf of the client. This functionality increases performance but at the cost of reliability. Messages can get lost if a client dies before it can deliver them to the application. exclusive: boolean request exclusive access Request exclusive consumer access, meaning only this consumer can access the queue. RULE: If the server cannot grant exclusive access to the queue when asked, - because there are other consumers active - it MUST raise a channel exception with return code 403 (access refused). nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. callback: Python callable function/method called with each delivered message For each message delivered by the broker, the callable will be called with a Message object as the single argument. If no callable is specified, messages are quietly discarded, no_ack should probably be set to True in that case. """ args = AMQPWriter() args.write_short(0) args.write_shortstr(queue) args.write_shortstr(consumer_tag) args.write_bit(no_local) args.write_bit(no_ack) args.write_bit(exclusive) args.write_bit(nowait) args.write_table(arguments or {}) self._send_method((60, 20), args) if not nowait: consumer_tag = self.wait(allowed_methods=[ (60, 21), # Channel.basic_consume_ok ]) self.callbacks[consumer_tag] = callback if on_cancel: self.cancel_callbacks[consumer_tag] = on_cancel if no_ack: self.no_ack_consumers.add(consumer_tag) return consumer_tag
python
def basic_consume(self, queue='', consumer_tag='', no_local=False, no_ack=False, exclusive=False, nowait=False, callback=None, arguments=None, on_cancel=None): args = AMQPWriter() args.write_short(0) args.write_shortstr(queue) args.write_shortstr(consumer_tag) args.write_bit(no_local) args.write_bit(no_ack) args.write_bit(exclusive) args.write_bit(nowait) args.write_table(arguments or {}) self._send_method((60, 20), args) if not nowait: consumer_tag = self.wait(allowed_methods=[ (60, 21), # Channel.basic_consume_ok ]) self.callbacks[consumer_tag] = callback if on_cancel: self.cancel_callbacks[consumer_tag] = on_cancel if no_ack: self.no_ack_consumers.add(consumer_tag) return consumer_tag
[ "def", "basic_consume", "(", "self", ",", "queue", "=", "''", ",", "consumer_tag", "=", "''", ",", "no_local", "=", "False", ",", "no_ack", "=", "False", ",", "exclusive", "=", "False", ",", "nowait", "=", "False", ",", "callback", "=", "None", ",", ...
Start a queue consumer This method asks the server to start a "consumer", which is a transient request for messages from a specific queue. Consumers last as long as the channel they were created on, or until the client cancels them. RULE: The server SHOULD support at least 16 consumers per queue, unless the queue was declared as private, and ideally, impose no limit except as defined by available resources. PARAMETERS: queue: shortstr Specifies the name of the queue to consume from. If the queue name is null, refers to the current queue for the channel, which is the last declared queue. RULE: If the client did not previously declare a queue, and the queue name in this method is empty, the server MUST raise a connection exception with reply code 530 (not allowed). consumer_tag: shortstr Specifies the identifier for the consumer. The consumer tag is local to a connection, so two clients can use the same consumer tags. If this field is empty the server will generate a unique tag. RULE: The tag MUST NOT refer to an existing consumer. If the client attempts to create two consumers with the same non-empty tag the server MUST raise a connection exception with reply code 530 (not allowed). no_local: boolean do not deliver own messages If the no-local field is set the server will not send messages to the client that published them. no_ack: boolean no acknowledgement needed If this field is set the server does not expect acknowledgments for messages. That is, when a message is delivered to the client the server automatically and silently acknowledges it on behalf of the client. This functionality increases performance but at the cost of reliability. Messages can get lost if a client dies before it can deliver them to the application. exclusive: boolean request exclusive access Request exclusive consumer access, meaning only this consumer can access the queue. RULE: If the server cannot grant exclusive access to the queue when asked, - because there are other consumers active - it MUST raise a channel exception with return code 403 (access refused). nowait: boolean do not send a reply method If set, the server will not respond to the method. The client should not wait for a reply method. If the server could not complete the method it will raise a channel or connection exception. callback: Python callable function/method called with each delivered message For each message delivered by the broker, the callable will be called with a Message object as the single argument. If no callable is specified, messages are quietly discarded, no_ack should probably be set to True in that case.
[ "Start", "a", "queue", "consumer" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1677-L1798
246,340
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._basic_deliver
def _basic_deliver(self, args, msg): """Notify the client of a consumer message This method delivers a message to the client, via a consumer. In the asynchronous message delivery model, the client starts a consumer using the Consume method, then the server responds with Deliver methods as and when messages arrive for that consumer. RULE: The server SHOULD track the number of times a message has been delivered to clients and when a message is redelivered a certain number of times - e.g. 5 times - without being acknowledged, the server SHOULD consider the message to be unprocessable (possibly causing client applications to abort), and move the message to a dead letter queue. PARAMETERS: consumer_tag: shortstr consumer tag Identifier for the consumer, valid within the current connection. RULE: The consumer tag is valid only within the channel from which the consumer was created. I.e. a client MUST NOT create a consumer in one channel and then use it in another. delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". redelivered: boolean message is being redelivered This indicates that the message has been previously delivered to this or another client. exchange: shortstr Specifies the name of the exchange that the message was originally published to. routing_key: shortstr Message routing key Specifies the routing key name specified when the message was published. """ consumer_tag = args.read_shortstr() delivery_tag = args.read_longlong() redelivered = args.read_bit() exchange = args.read_shortstr() routing_key = args.read_shortstr() msg.channel = self msg.delivery_info = { 'consumer_tag': consumer_tag, 'delivery_tag': delivery_tag, 'redelivered': redelivered, 'exchange': exchange, 'routing_key': routing_key, } try: fun = self.callbacks[consumer_tag] except KeyError: pass else: fun(msg)
python
def _basic_deliver(self, args, msg): consumer_tag = args.read_shortstr() delivery_tag = args.read_longlong() redelivered = args.read_bit() exchange = args.read_shortstr() routing_key = args.read_shortstr() msg.channel = self msg.delivery_info = { 'consumer_tag': consumer_tag, 'delivery_tag': delivery_tag, 'redelivered': redelivered, 'exchange': exchange, 'routing_key': routing_key, } try: fun = self.callbacks[consumer_tag] except KeyError: pass else: fun(msg)
[ "def", "_basic_deliver", "(", "self", ",", "args", ",", "msg", ")", ":", "consumer_tag", "=", "args", ".", "read_shortstr", "(", ")", "delivery_tag", "=", "args", ".", "read_longlong", "(", ")", "redelivered", "=", "args", ".", "read_bit", "(", ")", "exc...
Notify the client of a consumer message This method delivers a message to the client, via a consumer. In the asynchronous message delivery model, the client starts a consumer using the Consume method, then the server responds with Deliver methods as and when messages arrive for that consumer. RULE: The server SHOULD track the number of times a message has been delivered to clients and when a message is redelivered a certain number of times - e.g. 5 times - without being acknowledged, the server SHOULD consider the message to be unprocessable (possibly causing client applications to abort), and move the message to a dead letter queue. PARAMETERS: consumer_tag: shortstr consumer tag Identifier for the consumer, valid within the current connection. RULE: The consumer tag is valid only within the channel from which the consumer was created. I.e. a client MUST NOT create a consumer in one channel and then use it in another. delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". redelivered: boolean message is being redelivered This indicates that the message has been previously delivered to this or another client. exchange: shortstr Specifies the name of the exchange that the message was originally published to. routing_key: shortstr Message routing key Specifies the routing key name specified when the message was published.
[ "Notify", "the", "client", "of", "a", "consumer", "message" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1816-L1909
246,341
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._basic_get_ok
def _basic_get_ok(self, args, msg): """Provide client with a message This method delivers a message to the client following a get method. A message delivered by 'get-ok' must be acknowledged unless the no-ack option was set in the get method. PARAMETERS: delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". redelivered: boolean message is being redelivered This indicates that the message has been previously delivered to this or another client. exchange: shortstr Specifies the name of the exchange that the message was originally published to. If empty, the message was published to the default exchange. routing_key: shortstr Message routing key Specifies the routing key name specified when the message was published. message_count: long number of messages pending This field reports the number of messages pending on the queue, excluding the message being delivered. Note that this figure is indicative, not reliable, and can change arbitrarily as messages are added to the queue and removed by other clients. """ delivery_tag = args.read_longlong() redelivered = args.read_bit() exchange = args.read_shortstr() routing_key = args.read_shortstr() message_count = args.read_long() msg.channel = self msg.delivery_info = { 'delivery_tag': delivery_tag, 'redelivered': redelivered, 'exchange': exchange, 'routing_key': routing_key, 'message_count': message_count } return msg
python
def _basic_get_ok(self, args, msg): delivery_tag = args.read_longlong() redelivered = args.read_bit() exchange = args.read_shortstr() routing_key = args.read_shortstr() message_count = args.read_long() msg.channel = self msg.delivery_info = { 'delivery_tag': delivery_tag, 'redelivered': redelivered, 'exchange': exchange, 'routing_key': routing_key, 'message_count': message_count } return msg
[ "def", "_basic_get_ok", "(", "self", ",", "args", ",", "msg", ")", ":", "delivery_tag", "=", "args", ".", "read_longlong", "(", ")", "redelivered", "=", "args", ".", "read_bit", "(", ")", "exchange", "=", "args", ".", "read_shortstr", "(", ")", "routing_...
Provide client with a message This method delivers a message to the client following a get method. A message delivered by 'get-ok' must be acknowledged unless the no-ack option was set in the get method. PARAMETERS: delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". redelivered: boolean message is being redelivered This indicates that the message has been previously delivered to this or another client. exchange: shortstr Specifies the name of the exchange that the message was originally published to. If empty, the message was published to the default exchange. routing_key: shortstr Message routing key Specifies the routing key name specified when the message was published. message_count: long number of messages pending This field reports the number of messages pending on the queue, excluding the message being delivered. Note that this figure is indicative, not reliable, and can change arbitrarily as messages are added to the queue and removed by other clients.
[ "Provide", "client", "with", "a", "message" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L1975-L2047
246,342
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._basic_publish
def _basic_publish(self, msg, exchange='', routing_key='', mandatory=False, immediate=False): """Publish a message This method publishes a message to a specific exchange. The message will be routed to queues as defined by the exchange configuration and distributed to any active consumers when the transaction, if any, is committed. PARAMETERS: exchange: shortstr Specifies the name of the exchange to publish to. The exchange name can be empty, meaning the default exchange. If the exchange name is specified, and that exchange does not exist, the server will raise a channel exception. RULE: The server MUST accept a blank exchange name to mean the default exchange. RULE: The exchange MAY refuse basic content in which case it MUST raise a channel exception with reply code 540 (not implemented). routing_key: shortstr Message routing key Specifies the routing key for the message. The routing key is used for routing messages depending on the exchange configuration. mandatory: boolean indicate mandatory routing This flag tells the server how to react if the message cannot be routed to a queue. If this flag is True, the server will return an unroutable message with a Return method. If this flag is False, the server silently drops the message. RULE: The server SHOULD implement the mandatory flag. immediate: boolean request immediate delivery This flag tells the server how to react if the message cannot be routed to a queue consumer immediately. If this flag is set, the server will return an undeliverable message with a Return method. If this flag is zero, the server will queue the message, but with no guarantee that it will ever be consumed. RULE: The server SHOULD implement the immediate flag. """ args = AMQPWriter() args.write_short(0) args.write_shortstr(exchange) args.write_shortstr(routing_key) args.write_bit(mandatory) args.write_bit(immediate) self._send_method((60, 40), args, msg)
python
def _basic_publish(self, msg, exchange='', routing_key='', mandatory=False, immediate=False): args = AMQPWriter() args.write_short(0) args.write_shortstr(exchange) args.write_shortstr(routing_key) args.write_bit(mandatory) args.write_bit(immediate) self._send_method((60, 40), args, msg)
[ "def", "_basic_publish", "(", "self", ",", "msg", ",", "exchange", "=", "''", ",", "routing_key", "=", "''", ",", "mandatory", "=", "False", ",", "immediate", "=", "False", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_short", "(",...
Publish a message This method publishes a message to a specific exchange. The message will be routed to queues as defined by the exchange configuration and distributed to any active consumers when the transaction, if any, is committed. PARAMETERS: exchange: shortstr Specifies the name of the exchange to publish to. The exchange name can be empty, meaning the default exchange. If the exchange name is specified, and that exchange does not exist, the server will raise a channel exception. RULE: The server MUST accept a blank exchange name to mean the default exchange. RULE: The exchange MAY refuse basic content in which case it MUST raise a channel exception with reply code 540 (not implemented). routing_key: shortstr Message routing key Specifies the routing key for the message. The routing key is used for routing messages depending on the exchange configuration. mandatory: boolean indicate mandatory routing This flag tells the server how to react if the message cannot be routed to a queue. If this flag is True, the server will return an unroutable message with a Return method. If this flag is False, the server silently drops the message. RULE: The server SHOULD implement the mandatory flag. immediate: boolean request immediate delivery This flag tells the server how to react if the message cannot be routed to a queue consumer immediately. If this flag is set, the server will return an undeliverable message with a Return method. If this flag is zero, the server will queue the message, but with no guarantee that it will ever be consumed. RULE: The server SHOULD implement the immediate flag.
[ "Publish", "a", "message" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L2049-L2123
246,343
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.basic_qos
def basic_qos(self, prefetch_size, prefetch_count, a_global): """Specify quality of service This method requests a specific quality of service. The QoS can be specified for the current channel or for all channels on the connection. The particular properties and semantics of a qos method always depend on the content class semantics. Though the qos method could in principle apply to both peers, it is currently meaningful only for the server. PARAMETERS: prefetch_size: long prefetch window in octets The client can request that messages be sent in advance so that when the client finishes processing a message, the following message is already held locally, rather than needing to be sent down the channel. Prefetching gives a performance improvement. This field specifies the prefetch window size in octets. The server will send a message in advance if it is equal to or smaller in size than the available prefetch size (and also falls into other prefetch limits). May be set to zero, meaning "no specific limit", although other prefetch limits may still apply. The prefetch-size is ignored if the no-ack option is set. RULE: The server MUST ignore this setting when the client is not processing any messages - i.e. the prefetch size does not limit the transfer of single messages to a client, only the sending in advance of more messages while the client still has one or more unacknowledged messages. prefetch_count: short prefetch window in messages Specifies a prefetch window in terms of whole messages. This field may be used in combination with the prefetch-size field; a message will only be sent in advance if both prefetch windows (and those at the channel and connection level) allow it. The prefetch- count is ignored if the no-ack option is set. RULE: The server MAY send less data in advance than allowed by the client's specified prefetch windows but it MUST NOT send more. a_global: boolean apply to entire connection By default the QoS settings apply to the current channel only. If this field is set, they are applied to the entire connection. """ args = AMQPWriter() args.write_long(prefetch_size) args.write_short(prefetch_count) args.write_bit(a_global) self._send_method((60, 10), args) return self.wait(allowed_methods=[ (60, 11), # Channel.basic_qos_ok ])
python
def basic_qos(self, prefetch_size, prefetch_count, a_global): args = AMQPWriter() args.write_long(prefetch_size) args.write_short(prefetch_count) args.write_bit(a_global) self._send_method((60, 10), args) return self.wait(allowed_methods=[ (60, 11), # Channel.basic_qos_ok ])
[ "def", "basic_qos", "(", "self", ",", "prefetch_size", ",", "prefetch_count", ",", "a_global", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_long", "(", "prefetch_size", ")", "args", ".", "write_short", "(", "prefetch_count", ")", "args"...
Specify quality of service This method requests a specific quality of service. The QoS can be specified for the current channel or for all channels on the connection. The particular properties and semantics of a qos method always depend on the content class semantics. Though the qos method could in principle apply to both peers, it is currently meaningful only for the server. PARAMETERS: prefetch_size: long prefetch window in octets The client can request that messages be sent in advance so that when the client finishes processing a message, the following message is already held locally, rather than needing to be sent down the channel. Prefetching gives a performance improvement. This field specifies the prefetch window size in octets. The server will send a message in advance if it is equal to or smaller in size than the available prefetch size (and also falls into other prefetch limits). May be set to zero, meaning "no specific limit", although other prefetch limits may still apply. The prefetch-size is ignored if the no-ack option is set. RULE: The server MUST ignore this setting when the client is not processing any messages - i.e. the prefetch size does not limit the transfer of single messages to a client, only the sending in advance of more messages while the client still has one or more unacknowledged messages. prefetch_count: short prefetch window in messages Specifies a prefetch window in terms of whole messages. This field may be used in combination with the prefetch-size field; a message will only be sent in advance if both prefetch windows (and those at the channel and connection level) allow it. The prefetch- count is ignored if the no-ack option is set. RULE: The server MAY send less data in advance than allowed by the client's specified prefetch windows but it MUST NOT send more. a_global: boolean apply to entire connection By default the QoS settings apply to the current channel only. If this field is set, they are applied to the entire connection.
[ "Specify", "quality", "of", "service" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L2135-L2206
246,344
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.basic_recover
def basic_recover(self, requeue=False): """Redeliver unacknowledged messages This method asks the broker to redeliver all unacknowledged messages on a specified channel. Zero or more messages may be redelivered. This method is only allowed on non-transacted channels. RULE: The server MUST set the redelivered flag on all messages that are resent. RULE: The server MUST raise a channel exception if this is called on a transacted channel. PARAMETERS: requeue: boolean requeue the message If this field is False, the message will be redelivered to the original recipient. If this field is True, the server will attempt to requeue the message, potentially then delivering it to an alternative subscriber. """ args = AMQPWriter() args.write_bit(requeue) self._send_method((60, 110), args)
python
def basic_recover(self, requeue=False): args = AMQPWriter() args.write_bit(requeue) self._send_method((60, 110), args)
[ "def", "basic_recover", "(", "self", ",", "requeue", "=", "False", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_bit", "(", "requeue", ")", "self", ".", "_send_method", "(", "(", "60", ",", "110", ")", ",", "args", ")" ]
Redeliver unacknowledged messages This method asks the broker to redeliver all unacknowledged messages on a specified channel. Zero or more messages may be redelivered. This method is only allowed on non-transacted channels. RULE: The server MUST set the redelivered flag on all messages that are resent. RULE: The server MUST raise a channel exception if this is called on a transacted channel. PARAMETERS: requeue: boolean requeue the message If this field is False, the message will be redelivered to the original recipient. If this field is True, the server will attempt to requeue the message, potentially then delivering it to an alternative subscriber.
[ "Redeliver", "unacknowledged", "messages" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L2218-L2250
246,345
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel.basic_reject
def basic_reject(self, delivery_tag, requeue): """Reject an incoming message This method allows a client to reject a message. It can be used to interrupt and cancel large incoming messages, or return untreatable messages to their original queue. RULE: The server SHOULD be capable of accepting and process the Reject method while sending message content with a Deliver or Get-Ok method. I.e. the server should read and process incoming methods while sending output frames. To cancel a partially-send content, the server sends a content body frame of size 1 (i.e. with no data except the frame-end octet). RULE: The server SHOULD interpret this method as meaning that the client is unable to process the message at this time. RULE: A client MUST NOT use this method as a means of selecting messages to process. A rejected message MAY be discarded or dead-lettered, not necessarily passed to another client. PARAMETERS: delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". requeue: boolean requeue the message If this field is False, the message will be discarded. If this field is True, the server will attempt to requeue the message. RULE: The server MUST NOT deliver the message to the same client within the context of the current channel. The recommended strategy is to attempt to deliver the message to an alternative consumer, and if that is not possible, to move the message to a dead-letter queue. The server MAY use more sophisticated tracking to hold the message on the queue and redeliver it to the same client at a later stage. """ args = AMQPWriter() args.write_longlong(delivery_tag) args.write_bit(requeue) self._send_method((60, 90), args)
python
def basic_reject(self, delivery_tag, requeue): args = AMQPWriter() args.write_longlong(delivery_tag) args.write_bit(requeue) self._send_method((60, 90), args)
[ "def", "basic_reject", "(", "self", ",", "delivery_tag", ",", "requeue", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_longlong", "(", "delivery_tag", ")", "args", ".", "write_bit", "(", "requeue", ")", "self", ".", "_send_method", "("...
Reject an incoming message This method allows a client to reject a message. It can be used to interrupt and cancel large incoming messages, or return untreatable messages to their original queue. RULE: The server SHOULD be capable of accepting and process the Reject method while sending message content with a Deliver or Get-Ok method. I.e. the server should read and process incoming methods while sending output frames. To cancel a partially-send content, the server sends a content body frame of size 1 (i.e. with no data except the frame-end octet). RULE: The server SHOULD interpret this method as meaning that the client is unable to process the message at this time. RULE: A client MUST NOT use this method as a means of selecting messages to process. A rejected message MAY be discarded or dead-lettered, not necessarily passed to another client. PARAMETERS: delivery_tag: longlong server-assigned delivery tag The server-assigned and channel-specific delivery tag RULE: The delivery tag is valid only within the channel from which the message was received. I.e. a client MUST NOT receive a message on one channel and then acknowledge it on another. RULE: The server MUST NOT use a zero value for delivery tags. Zero is reserved for client use, meaning "all messages so far received". requeue: boolean requeue the message If this field is False, the message will be discarded. If this field is True, the server will attempt to requeue the message. RULE: The server MUST NOT deliver the message to the same client within the context of the current channel. The recommended strategy is to attempt to deliver the message to an alternative consumer, and if that is not possible, to move the message to a dead-letter queue. The server MAY use more sophisticated tracking to hold the message on the queue and redeliver it to the same client at a later stage.
[ "Reject", "an", "incoming", "message" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L2261-L2334
246,346
nerdvegas/rez
src/rez/vendor/amqp/channel.py
Channel._basic_return
def _basic_return(self, args, msg): """Return a failed message This method returns an undeliverable message that was published with the "immediate" flag set, or an unroutable message published with the "mandatory" flag set. The reply code and text provide information about the reason that the message was undeliverable. PARAMETERS: reply_code: short The reply code. The AMQ reply codes are defined in AMQ RFC 011. reply_text: shortstr The localised reply text. This text can be logged as an aid to resolving issues. exchange: shortstr Specifies the name of the exchange that the message was originally published to. routing_key: shortstr Message routing key Specifies the routing key name specified when the message was published. """ self.returned_messages.put(basic_return_t( args.read_short(), args.read_shortstr(), args.read_shortstr(), args.read_shortstr(), msg, ))
python
def _basic_return(self, args, msg): self.returned_messages.put(basic_return_t( args.read_short(), args.read_shortstr(), args.read_shortstr(), args.read_shortstr(), msg, ))
[ "def", "_basic_return", "(", "self", ",", "args", ",", "msg", ")", ":", "self", ".", "returned_messages", ".", "put", "(", "basic_return_t", "(", "args", ".", "read_short", "(", ")", ",", "args", ".", "read_shortstr", "(", ")", ",", "args", ".", "read_...
Return a failed message This method returns an undeliverable message that was published with the "immediate" flag set, or an unroutable message published with the "mandatory" flag set. The reply code and text provide information about the reason that the message was undeliverable. PARAMETERS: reply_code: short The reply code. The AMQ reply codes are defined in AMQ RFC 011. reply_text: shortstr The localised reply text. This text can be logged as an aid to resolving issues. exchange: shortstr Specifies the name of the exchange that the message was originally published to. routing_key: shortstr Message routing key Specifies the routing key name specified when the message was published.
[ "Return", "a", "failed", "message" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/channel.py#L2336-L2375
246,347
nerdvegas/rez
src/rez/build_process_.py
create_build_process
def create_build_process(process_type, working_dir, build_system, package=None, vcs=None, ensure_latest=True, skip_repo_errors=False, ignore_existing_tag=False, verbose=False, quiet=False): """Create a `BuildProcess` instance.""" from rez.plugin_managers import plugin_manager process_types = get_build_process_types() if process_type not in process_types: raise BuildProcessError("Unknown build process: %r" % process_type) cls = plugin_manager.get_plugin_class('build_process', process_type) return cls(working_dir, # ignored (deprecated) build_system, package=package, # ignored (deprecated) vcs=vcs, ensure_latest=ensure_latest, skip_repo_errors=skip_repo_errors, ignore_existing_tag=ignore_existing_tag, verbose=verbose, quiet=quiet)
python
def create_build_process(process_type, working_dir, build_system, package=None, vcs=None, ensure_latest=True, skip_repo_errors=False, ignore_existing_tag=False, verbose=False, quiet=False): from rez.plugin_managers import plugin_manager process_types = get_build_process_types() if process_type not in process_types: raise BuildProcessError("Unknown build process: %r" % process_type) cls = plugin_manager.get_plugin_class('build_process', process_type) return cls(working_dir, # ignored (deprecated) build_system, package=package, # ignored (deprecated) vcs=vcs, ensure_latest=ensure_latest, skip_repo_errors=skip_repo_errors, ignore_existing_tag=ignore_existing_tag, verbose=verbose, quiet=quiet)
[ "def", "create_build_process", "(", "process_type", ",", "working_dir", ",", "build_system", ",", "package", "=", "None", ",", "vcs", "=", "None", ",", "ensure_latest", "=", "True", ",", "skip_repo_errors", "=", "False", ",", "ignore_existing_tag", "=", "False",...
Create a `BuildProcess` instance.
[ "Create", "a", "BuildProcess", "instance", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_process_.py#L26-L45
246,348
nerdvegas/rez
src/rez/build_process_.py
BuildProcessHelper.visit_variants
def visit_variants(self, func, variants=None, **kwargs): """Iterate over variants and call a function on each.""" if variants: present_variants = range(self.package.num_variants) invalid_variants = set(variants) - set(present_variants) if invalid_variants: raise BuildError( "The package does not contain the variants: %s" % ", ".join(str(x) for x in sorted(invalid_variants))) # iterate over variants results = [] num_visited = 0 for variant in self.package.iter_variants(): if variants and variant.index not in variants: self._print_header( "Skipping variant %s (%s)..." % (variant.index, self._n_of_m(variant))) continue # visit the variant result = func(variant, **kwargs) results.append(result) num_visited += 1 return num_visited, results
python
def visit_variants(self, func, variants=None, **kwargs): if variants: present_variants = range(self.package.num_variants) invalid_variants = set(variants) - set(present_variants) if invalid_variants: raise BuildError( "The package does not contain the variants: %s" % ", ".join(str(x) for x in sorted(invalid_variants))) # iterate over variants results = [] num_visited = 0 for variant in self.package.iter_variants(): if variants and variant.index not in variants: self._print_header( "Skipping variant %s (%s)..." % (variant.index, self._n_of_m(variant))) continue # visit the variant result = func(variant, **kwargs) results.append(result) num_visited += 1 return num_visited, results
[ "def", "visit_variants", "(", "self", ",", "func", ",", "variants", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "variants", ":", "present_variants", "=", "range", "(", "self", ".", "package", ".", "num_variants", ")", "invalid_variants", "=", "...
Iterate over variants and call a function on each.
[ "Iterate", "over", "variants", "and", "call", "a", "function", "on", "each", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_process_.py#L175-L201
246,349
nerdvegas/rez
src/rez/build_process_.py
BuildProcessHelper.create_build_context
def create_build_context(self, variant, build_type, build_path): """Create a context to build the variant within.""" request = variant.get_requires(build_requires=True, private_build_requires=True) req_strs = map(str, request) quoted_req_strs = map(quote, req_strs) self._print("Resolving build environment: %s", ' '.join(quoted_req_strs)) if build_type == BuildType.local: packages_path = self.package.config.packages_path else: packages_path = self.package.config.nonlocal_packages_path if self.package.config.is_overridden("package_filter"): from rez.package_filter import PackageFilterList data = self.package.config.package_filter package_filter = PackageFilterList.from_pod(data) else: package_filter = None context = ResolvedContext(request, package_paths=packages_path, package_filter=package_filter, building=True) if self.verbose: context.print_info() # save context before possible fail, so user can debug rxt_filepath = os.path.join(build_path, "build.rxt") context.save(rxt_filepath) if context.status != ResolverStatus.solved: raise BuildContextResolveError(context) return context, rxt_filepath
python
def create_build_context(self, variant, build_type, build_path): request = variant.get_requires(build_requires=True, private_build_requires=True) req_strs = map(str, request) quoted_req_strs = map(quote, req_strs) self._print("Resolving build environment: %s", ' '.join(quoted_req_strs)) if build_type == BuildType.local: packages_path = self.package.config.packages_path else: packages_path = self.package.config.nonlocal_packages_path if self.package.config.is_overridden("package_filter"): from rez.package_filter import PackageFilterList data = self.package.config.package_filter package_filter = PackageFilterList.from_pod(data) else: package_filter = None context = ResolvedContext(request, package_paths=packages_path, package_filter=package_filter, building=True) if self.verbose: context.print_info() # save context before possible fail, so user can debug rxt_filepath = os.path.join(build_path, "build.rxt") context.save(rxt_filepath) if context.status != ResolverStatus.solved: raise BuildContextResolveError(context) return context, rxt_filepath
[ "def", "create_build_context", "(", "self", ",", "variant", ",", "build_type", ",", "build_path", ")", ":", "request", "=", "variant", ".", "get_requires", "(", "build_requires", "=", "True", ",", "private_build_requires", "=", "True", ")", "req_strs", "=", "m...
Create a context to build the variant within.
[ "Create", "a", "context", "to", "build", "the", "variant", "within", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_process_.py#L218-L253
246,350
nerdvegas/rez
src/rez/build_process_.py
BuildProcessHelper.get_release_data
def get_release_data(self): """Get release data for this release. Returns: dict. """ previous_package = self.get_previous_release() if previous_package: previous_version = previous_package.version previous_revision = previous_package.revision else: previous_version = None previous_revision = None if self.vcs is None: return dict(vcs="None", previous_version=previous_version) revision = None with self.repo_operation(): revision = self.vcs.get_current_revision() changelog = self.get_changelog() # truncate changelog - very large changelogs can cause package load # times to be very high, we don't want that maxlen = config.max_package_changelog_chars if maxlen and changelog and len(changelog) > maxlen + 3: changelog = changelog[:maxlen] + "..." return dict(vcs=self.vcs.name(), revision=revision, changelog=changelog, previous_version=previous_version, previous_revision=previous_revision)
python
def get_release_data(self): previous_package = self.get_previous_release() if previous_package: previous_version = previous_package.version previous_revision = previous_package.revision else: previous_version = None previous_revision = None if self.vcs is None: return dict(vcs="None", previous_version=previous_version) revision = None with self.repo_operation(): revision = self.vcs.get_current_revision() changelog = self.get_changelog() # truncate changelog - very large changelogs can cause package load # times to be very high, we don't want that maxlen = config.max_package_changelog_chars if maxlen and changelog and len(changelog) > maxlen + 3: changelog = changelog[:maxlen] + "..." return dict(vcs=self.vcs.name(), revision=revision, changelog=changelog, previous_version=previous_version, previous_revision=previous_revision)
[ "def", "get_release_data", "(", "self", ")", ":", "previous_package", "=", "self", ".", "get_previous_release", "(", ")", "if", "previous_package", ":", "previous_version", "=", "previous_package", ".", "version", "previous_revision", "=", "previous_package", ".", "...
Get release data for this release. Returns: dict.
[ "Get", "release", "data", "for", "this", "release", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_process_.py#L368-L402
246,351
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/minmax.py
minimal_spanning_tree
def minimal_spanning_tree(graph, root=None): """ Minimal spanning tree. @attention: Minimal spanning tree is meaningful only for weighted graphs. @type graph: graph @param graph: Graph. @type root: node @param root: Optional root node (will explore only root's connected component) @rtype: dictionary @return: Generated spanning tree. """ visited = [] # List for marking visited and non-visited nodes spanning_tree = {} # MInimal Spanning tree # Initialization if (root is not None): visited.append(root) nroot = root spanning_tree[root] = None else: nroot = 1 # Algorithm loop while (nroot is not None): ledge = _lightest_edge(graph, visited) if (ledge == None): if (root is not None): break nroot = _first_unvisited(graph, visited) if (nroot is not None): spanning_tree[nroot] = None visited.append(nroot) else: spanning_tree[ledge[1]] = ledge[0] visited.append(ledge[1]) return spanning_tree
python
def minimal_spanning_tree(graph, root=None): visited = [] # List for marking visited and non-visited nodes spanning_tree = {} # MInimal Spanning tree # Initialization if (root is not None): visited.append(root) nroot = root spanning_tree[root] = None else: nroot = 1 # Algorithm loop while (nroot is not None): ledge = _lightest_edge(graph, visited) if (ledge == None): if (root is not None): break nroot = _first_unvisited(graph, visited) if (nroot is not None): spanning_tree[nroot] = None visited.append(nroot) else: spanning_tree[ledge[1]] = ledge[0] visited.append(ledge[1]) return spanning_tree
[ "def", "minimal_spanning_tree", "(", "graph", ",", "root", "=", "None", ")", ":", "visited", "=", "[", "]", "# List for marking visited and non-visited nodes", "spanning_tree", "=", "{", "}", "# MInimal Spanning tree", "# Initialization", "if", "(", "root", "is", "n...
Minimal spanning tree. @attention: Minimal spanning tree is meaningful only for weighted graphs. @type graph: graph @param graph: Graph. @type root: node @param root: Optional root node (will explore only root's connected component) @rtype: dictionary @return: Generated spanning tree.
[ "Minimal", "spanning", "tree", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/minmax.py#L46-L86
246,352
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/minmax.py
cut_value
def cut_value(graph, flow, cut): """ Calculate the value of a cut. @type graph: digraph @param graph: Graph @type flow: dictionary @param flow: Dictionary containing a flow for each edge. @type cut: dictionary @param cut: Dictionary mapping each node to a subset index. The function only considers the flow between nodes with 0 and 1. @rtype: float @return: The value of the flow between the subsets 0 and 1 """ #max flow/min cut value calculation S = [] T = [] for node in cut.keys(): if cut[node] == 0: S.append(node) elif cut[node] == 1: T.append(node) value = 0 for node in S: for neigh in graph.neighbors(node): if neigh in T: value = value + flow[(node,neigh)] for inc in graph.incidents(node): if inc in T: value = value - flow[(inc,node)] return value
python
def cut_value(graph, flow, cut): #max flow/min cut value calculation S = [] T = [] for node in cut.keys(): if cut[node] == 0: S.append(node) elif cut[node] == 1: T.append(node) value = 0 for node in S: for neigh in graph.neighbors(node): if neigh in T: value = value + flow[(node,neigh)] for inc in graph.incidents(node): if inc in T: value = value - flow[(inc,node)] return value
[ "def", "cut_value", "(", "graph", ",", "flow", ",", "cut", ")", ":", "#max flow/min cut value calculation", "S", "=", "[", "]", "T", "=", "[", "]", "for", "node", "in", "cut", ".", "keys", "(", ")", ":", "if", "cut", "[", "node", "]", "==", "0", ...
Calculate the value of a cut. @type graph: digraph @param graph: Graph @type flow: dictionary @param flow: Dictionary containing a flow for each edge. @type cut: dictionary @param cut: Dictionary mapping each node to a subset index. The function only considers the flow between nodes with 0 and 1. @rtype: float @return: The value of the flow between the subsets 0 and 1
[ "Calculate", "the", "value", "of", "a", "cut", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/minmax.py#L412-L445
246,353
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/minmax.py
cut_tree
def cut_tree(igraph, caps = None): """ Construct a Gomory-Hu cut tree by applying the algorithm of Gusfield. @type igraph: graph @param igraph: Graph @type caps: dictionary @param caps: Dictionary specifying a maximum capacity for each edge. If not given, the weight of the edge will be used as its capacity. Otherwise, for each edge (a,b), caps[(a,b)] should be given. @rtype: dictionary @return: Gomory-Hu cut tree as a dictionary, where each edge is associated with its weight """ #maximum flow needs a digraph, we get a graph #I think this conversion relies on implementation details outside the api and may break in the future graph = digraph() graph.add_graph(igraph) #handle optional argument if not caps: caps = {} for edge in graph.edges(): caps[edge] = igraph.edge_weight(edge) #temporary flow variable f = {} #we use a numbering of the nodes for easier handling n = {} N = 0 for node in graph.nodes(): n[N] = node N = N + 1 #predecessor function p = {}.fromkeys(range(N),0) p[0] = None for s in range(1,N): t = p[s] S = [] #max flow calculation (flow,cut) = maximum_flow(graph,n[s],n[t],caps) for i in range(N): if cut[n[i]] == 0: S.append(i) value = cut_value(graph,flow,cut) f[s] = value for i in range(N): if i == s: continue if i in S and p[i] == t: p[i] = s if p[t] in S: p[s] = p[t] p[t] = s f[s] = f[t] f[t] = value #cut tree is a dictionary, where each edge is associated with its weight b = {} for i in range(1,N): b[(n[i],n[p[i]])] = f[i] return b
python
def cut_tree(igraph, caps = None): #maximum flow needs a digraph, we get a graph #I think this conversion relies on implementation details outside the api and may break in the future graph = digraph() graph.add_graph(igraph) #handle optional argument if not caps: caps = {} for edge in graph.edges(): caps[edge] = igraph.edge_weight(edge) #temporary flow variable f = {} #we use a numbering of the nodes for easier handling n = {} N = 0 for node in graph.nodes(): n[N] = node N = N + 1 #predecessor function p = {}.fromkeys(range(N),0) p[0] = None for s in range(1,N): t = p[s] S = [] #max flow calculation (flow,cut) = maximum_flow(graph,n[s],n[t],caps) for i in range(N): if cut[n[i]] == 0: S.append(i) value = cut_value(graph,flow,cut) f[s] = value for i in range(N): if i == s: continue if i in S and p[i] == t: p[i] = s if p[t] in S: p[s] = p[t] p[t] = s f[s] = f[t] f[t] = value #cut tree is a dictionary, where each edge is associated with its weight b = {} for i in range(1,N): b[(n[i],n[p[i]])] = f[i] return b
[ "def", "cut_tree", "(", "igraph", ",", "caps", "=", "None", ")", ":", "#maximum flow needs a digraph, we get a graph", "#I think this conversion relies on implementation details outside the api and may break in the future", "graph", "=", "digraph", "(", ")", "graph", ".", "add_...
Construct a Gomory-Hu cut tree by applying the algorithm of Gusfield. @type igraph: graph @param igraph: Graph @type caps: dictionary @param caps: Dictionary specifying a maximum capacity for each edge. If not given, the weight of the edge will be used as its capacity. Otherwise, for each edge (a,b), caps[(a,b)] should be given. @rtype: dictionary @return: Gomory-Hu cut tree as a dictionary, where each edge is associated with its weight
[ "Construct", "a", "Gomory", "-", "Hu", "cut", "tree", "by", "applying", "the", "algorithm", "of", "Gusfield", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/minmax.py#L447-L515
246,354
nerdvegas/rez
src/rez/vendor/distlib/locators.py
Locator.locate
def locate(self, requirement, prereleases=False): """ Find the most recent distribution which matches the given requirement. :param requirement: A requirement of the form 'foo (1.0)' or perhaps 'foo (>= 1.0, < 2.0, != 1.3)' :param prereleases: If ``True``, allow pre-release versions to be located. Otherwise, pre-release versions are not returned. :return: A :class:`Distribution` instance, or ``None`` if no such distribution could be located. """ result = None r = parse_requirement(requirement) if r is None: raise DistlibException('Not a valid requirement: %r' % requirement) scheme = get_scheme(self.scheme) self.matcher = matcher = scheme.matcher(r.requirement) logger.debug('matcher: %s (%s)', matcher, type(matcher).__name__) versions = self.get_project(r.name) if len(versions) > 2: # urls and digests keys are present # sometimes, versions are invalid slist = [] vcls = matcher.version_class for k in versions: if k in ('urls', 'digests'): continue try: if not matcher.match(k): logger.debug('%s did not match %r', matcher, k) else: if prereleases or not vcls(k).is_prerelease: slist.append(k) else: logger.debug('skipping pre-release ' 'version %s of %s', k, matcher.name) except Exception: # pragma: no cover logger.warning('error matching %s with %r', matcher, k) pass # slist.append(k) if len(slist) > 1: slist = sorted(slist, key=scheme.key) if slist: logger.debug('sorted list: %s', slist) version = slist[-1] result = versions[version] if result: if r.extras: result.extras = r.extras result.download_urls = versions.get('urls', {}).get(version, set()) d = {} sd = versions.get('digests', {}) for url in result.download_urls: if url in sd: d[url] = sd[url] result.digests = d self.matcher = None return result
python
def locate(self, requirement, prereleases=False): result = None r = parse_requirement(requirement) if r is None: raise DistlibException('Not a valid requirement: %r' % requirement) scheme = get_scheme(self.scheme) self.matcher = matcher = scheme.matcher(r.requirement) logger.debug('matcher: %s (%s)', matcher, type(matcher).__name__) versions = self.get_project(r.name) if len(versions) > 2: # urls and digests keys are present # sometimes, versions are invalid slist = [] vcls = matcher.version_class for k in versions: if k in ('urls', 'digests'): continue try: if not matcher.match(k): logger.debug('%s did not match %r', matcher, k) else: if prereleases or not vcls(k).is_prerelease: slist.append(k) else: logger.debug('skipping pre-release ' 'version %s of %s', k, matcher.name) except Exception: # pragma: no cover logger.warning('error matching %s with %r', matcher, k) pass # slist.append(k) if len(slist) > 1: slist = sorted(slist, key=scheme.key) if slist: logger.debug('sorted list: %s', slist) version = slist[-1] result = versions[version] if result: if r.extras: result.extras = r.extras result.download_urls = versions.get('urls', {}).get(version, set()) d = {} sd = versions.get('digests', {}) for url in result.download_urls: if url in sd: d[url] = sd[url] result.digests = d self.matcher = None return result
[ "def", "locate", "(", "self", ",", "requirement", ",", "prereleases", "=", "False", ")", ":", "result", "=", "None", "r", "=", "parse_requirement", "(", "requirement", ")", "if", "r", "is", "None", ":", "raise", "DistlibException", "(", "'Not a valid require...
Find the most recent distribution which matches the given requirement. :param requirement: A requirement of the form 'foo (1.0)' or perhaps 'foo (>= 1.0, < 2.0, != 1.3)' :param prereleases: If ``True``, allow pre-release versions to be located. Otherwise, pre-release versions are not returned. :return: A :class:`Distribution` instance, or ``None`` if no such distribution could be located.
[ "Find", "the", "most", "recent", "distribution", "which", "matches", "the", "given", "requirement", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/distlib/locators.py#L313-L370
246,355
nerdvegas/rez
src/rez/package_bind.py
get_bind_modules
def get_bind_modules(verbose=False): """Get available bind modules. Returns: dict: Map of (name, filepath) listing all bind modules. """ builtin_path = os.path.join(module_root_path, "bind") searchpaths = config.bind_module_path + [builtin_path] bindnames = {} for path in searchpaths: if verbose: print "searching %s..." % path if not os.path.isdir(path): continue for filename in os.listdir(path): fpath = os.path.join(path, filename) fname, ext = os.path.splitext(filename) if os.path.isfile(fpath) and ext == ".py" \ and not fname.startswith('_'): bindnames[fname] = fpath return bindnames
python
def get_bind_modules(verbose=False): builtin_path = os.path.join(module_root_path, "bind") searchpaths = config.bind_module_path + [builtin_path] bindnames = {} for path in searchpaths: if verbose: print "searching %s..." % path if not os.path.isdir(path): continue for filename in os.listdir(path): fpath = os.path.join(path, filename) fname, ext = os.path.splitext(filename) if os.path.isfile(fpath) and ext == ".py" \ and not fname.startswith('_'): bindnames[fname] = fpath return bindnames
[ "def", "get_bind_modules", "(", "verbose", "=", "False", ")", ":", "builtin_path", "=", "os", ".", "path", ".", "join", "(", "module_root_path", ",", "\"bind\"", ")", "searchpaths", "=", "config", ".", "bind_module_path", "+", "[", "builtin_path", "]", "bind...
Get available bind modules. Returns: dict: Map of (name, filepath) listing all bind modules.
[ "Get", "available", "bind", "modules", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_bind.py#L13-L36
246,356
nerdvegas/rez
src/rez/package_bind.py
find_bind_module
def find_bind_module(name, verbose=False): """Find the bind module matching the given name. Args: name (str): Name of package to find bind module for. verbose (bool): If True, print extra output. Returns: str: Filepath to bind module .py file, or None if not found. """ bindnames = get_bind_modules(verbose=verbose) bindfile = bindnames.get(name) if bindfile: return bindfile if not verbose: return None # suggest close matches fuzzy_matches = get_close_pkgs(name, bindnames.keys()) if fuzzy_matches: rows = [(x[0], bindnames[x[0]]) for x in fuzzy_matches] print "'%s' not found. Close matches:" % name print '\n'.join(columnise(rows)) else: print "No matches." return None
python
def find_bind_module(name, verbose=False): bindnames = get_bind_modules(verbose=verbose) bindfile = bindnames.get(name) if bindfile: return bindfile if not verbose: return None # suggest close matches fuzzy_matches = get_close_pkgs(name, bindnames.keys()) if fuzzy_matches: rows = [(x[0], bindnames[x[0]]) for x in fuzzy_matches] print "'%s' not found. Close matches:" % name print '\n'.join(columnise(rows)) else: print "No matches." return None
[ "def", "find_bind_module", "(", "name", ",", "verbose", "=", "False", ")", ":", "bindnames", "=", "get_bind_modules", "(", "verbose", "=", "verbose", ")", "bindfile", "=", "bindnames", ".", "get", "(", "name", ")", "if", "bindfile", ":", "return", "bindfil...
Find the bind module matching the given name. Args: name (str): Name of package to find bind module for. verbose (bool): If True, print extra output. Returns: str: Filepath to bind module .py file, or None if not found.
[ "Find", "the", "bind", "module", "matching", "the", "given", "name", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_bind.py#L39-L68
246,357
nerdvegas/rez
src/rez/package_bind.py
bind_package
def bind_package(name, path=None, version_range=None, no_deps=False, bind_args=None, quiet=False): """Bind software available on the current system, as a rez package. Note: `bind_args` is provided when software is bound via the 'rez-bind' command line tool. Bind modules can define their own command line options, and they will be present in `bind_args` if applicable. Args: name (str): Package name. path (str): Package path to install into; local packages path if None. version_range (`VersionRange`): If provided, only bind the software if it falls within this version range. no_deps (bool): If True, don't bind dependencies. bind_args (list of str): Command line options. quiet (bool): If True, suppress superfluous output. Returns: List of `Variant`: The variant(s) that were installed as a result of binding this package. """ pending = set([name]) installed_variants = [] installed_package_names = set() primary = True # bind package and possibly dependencies while pending: pending_ = pending pending = set() exc_type = None for name_ in pending_: # turn error on binding of dependencies into a warning - we don't # want to skip binding some dependencies because others failed try: variants_ = _bind_package(name_, path=path, version_range=version_range, bind_args=bind_args, quiet=quiet) except exc_type as e: print_error("Could not bind '%s': %s: %s" % (name_, e.__class__.__name__, str(e))) continue installed_variants.extend(variants_) for variant in variants_: installed_package_names.add(variant.name) # add dependencies if not no_deps: for variant in variants_: for requirement in variant.requires: if not requirement.conflict: pending.add(requirement.name) # non-primary packages are treated a little differently primary = False version_range = None bind_args = None exc_type = RezBindError if installed_variants and not quiet: print "The following packages were installed:" print _print_package_list(installed_variants) return installed_variants
python
def bind_package(name, path=None, version_range=None, no_deps=False, bind_args=None, quiet=False): pending = set([name]) installed_variants = [] installed_package_names = set() primary = True # bind package and possibly dependencies while pending: pending_ = pending pending = set() exc_type = None for name_ in pending_: # turn error on binding of dependencies into a warning - we don't # want to skip binding some dependencies because others failed try: variants_ = _bind_package(name_, path=path, version_range=version_range, bind_args=bind_args, quiet=quiet) except exc_type as e: print_error("Could not bind '%s': %s: %s" % (name_, e.__class__.__name__, str(e))) continue installed_variants.extend(variants_) for variant in variants_: installed_package_names.add(variant.name) # add dependencies if not no_deps: for variant in variants_: for requirement in variant.requires: if not requirement.conflict: pending.add(requirement.name) # non-primary packages are treated a little differently primary = False version_range = None bind_args = None exc_type = RezBindError if installed_variants and not quiet: print "The following packages were installed:" print _print_package_list(installed_variants) return installed_variants
[ "def", "bind_package", "(", "name", ",", "path", "=", "None", ",", "version_range", "=", "None", ",", "no_deps", "=", "False", ",", "bind_args", "=", "None", ",", "quiet", "=", "False", ")", ":", "pending", "=", "set", "(", "[", "name", "]", ")", "...
Bind software available on the current system, as a rez package. Note: `bind_args` is provided when software is bound via the 'rez-bind' command line tool. Bind modules can define their own command line options, and they will be present in `bind_args` if applicable. Args: name (str): Package name. path (str): Package path to install into; local packages path if None. version_range (`VersionRange`): If provided, only bind the software if it falls within this version range. no_deps (bool): If True, don't bind dependencies. bind_args (list of str): Command line options. quiet (bool): If True, suppress superfluous output. Returns: List of `Variant`: The variant(s) that were installed as a result of binding this package.
[ "Bind", "software", "available", "on", "the", "current", "system", "as", "a", "rez", "package", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_bind.py#L71-L141
246,358
nerdvegas/rez
src/rez/release_hook.py
create_release_hook
def create_release_hook(name, source_path): """Return a new release hook of the given type.""" from rez.plugin_managers import plugin_manager return plugin_manager.create_instance('release_hook', name, source_path=source_path)
python
def create_release_hook(name, source_path): from rez.plugin_managers import plugin_manager return plugin_manager.create_instance('release_hook', name, source_path=source_path)
[ "def", "create_release_hook", "(", "name", ",", "source_path", ")", ":", "from", "rez", ".", "plugin_managers", "import", "plugin_manager", "return", "plugin_manager", ".", "create_instance", "(", "'release_hook'", ",", "name", ",", "source_path", "=", "source_path"...
Return a new release hook of the given type.
[ "Return", "a", "new", "release", "hook", "of", "the", "given", "type", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/release_hook.py#L12-L17
246,359
nerdvegas/rez
src/rez/release_hook.py
ReleaseHook.pre_build
def pre_build(self, user, install_path, variants=None, release_message=None, changelog=None, previous_version=None, previous_revision=None, **kwargs): """Pre-build hook. Args: user: Name of person who did the release. install_path: Directory the package was installed into. variants: List of variant indices we are attempting to build, or None release_message: User-supplied release message. changelog: List of strings describing changes since last release. previous_version: Version object - previously-release package, or None if no previous release. previous_revision: Revision of previously-released package (type depends on repo - see ReleaseVCS.get_current_revision(). kwargs: Reserved. Note: This method should raise a `ReleaseHookCancellingError` if the release process should be cancelled. """ pass
python
def pre_build(self, user, install_path, variants=None, release_message=None, changelog=None, previous_version=None, previous_revision=None, **kwargs): pass
[ "def", "pre_build", "(", "self", ",", "user", ",", "install_path", ",", "variants", "=", "None", ",", "release_message", "=", "None", ",", "changelog", "=", "None", ",", "previous_version", "=", "None", ",", "previous_revision", "=", "None", ",", "*", "*",...
Pre-build hook. Args: user: Name of person who did the release. install_path: Directory the package was installed into. variants: List of variant indices we are attempting to build, or None release_message: User-supplied release message. changelog: List of strings describing changes since last release. previous_version: Version object - previously-release package, or None if no previous release. previous_revision: Revision of previously-released package (type depends on repo - see ReleaseVCS.get_current_revision(). kwargs: Reserved. Note: This method should raise a `ReleaseHookCancellingError` if the release process should be cancelled.
[ "Pre", "-", "build", "hook", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/release_hook.py#L56-L78
246,360
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/traversal.py
traversal
def traversal(graph, node, order): """ Graph traversal iterator. @type graph: graph, digraph @param graph: Graph. @type node: node @param node: Node. @type order: string @param order: traversal ordering. Possible values are: 2. 'pre' - Preordering (default) 1. 'post' - Postordering @rtype: iterator @return: Traversal iterator. """ visited = {} if (order == 'pre'): pre = 1 post = 0 elif (order == 'post'): pre = 0 post = 1 for each in _dfs(graph, visited, node, pre, post): yield each
python
def traversal(graph, node, order): visited = {} if (order == 'pre'): pre = 1 post = 0 elif (order == 'post'): pre = 0 post = 1 for each in _dfs(graph, visited, node, pre, post): yield each
[ "def", "traversal", "(", "graph", ",", "node", ",", "order", ")", ":", "visited", "=", "{", "}", "if", "(", "order", "==", "'pre'", ")", ":", "pre", "=", "1", "post", "=", "0", "elif", "(", "order", "==", "'post'", ")", ":", "pre", "=", "0", ...
Graph traversal iterator. @type graph: graph, digraph @param graph: Graph. @type node: node @param node: Node. @type order: string @param order: traversal ordering. Possible values are: 2. 'pre' - Preordering (default) 1. 'post' - Postordering @rtype: iterator @return: Traversal iterator.
[ "Graph", "traversal", "iterator", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/traversal.py#L34-L61
246,361
nerdvegas/rez
src/rez/backport/zipfile.py
is_zipfile
def is_zipfile(filename): """Quickly see if file is a ZIP file by checking the magic number.""" try: fpin = open(filename, "rb") endrec = _EndRecData(fpin) fpin.close() if endrec: return True # file has correct magic number except IOError: pass return False
python
def is_zipfile(filename): try: fpin = open(filename, "rb") endrec = _EndRecData(fpin) fpin.close() if endrec: return True # file has correct magic number except IOError: pass return False
[ "def", "is_zipfile", "(", "filename", ")", ":", "try", ":", "fpin", "=", "open", "(", "filename", ",", "\"rb\"", ")", "endrec", "=", "_EndRecData", "(", "fpin", ")", "fpin", ".", "close", "(", ")", "if", "endrec", ":", "return", "True", "# file has cor...
Quickly see if file is a ZIP file by checking the magic number.
[ "Quickly", "see", "if", "file", "is", "a", "ZIP", "file", "by", "checking", "the", "magic", "number", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L133-L143
246,362
nerdvegas/rez
src/rez/backport/zipfile.py
_EndRecData
def _EndRecData(fpin): """Return data from the "End of Central Directory" record, or None. The data is a list of the nine items in the ZIP "End of central dir" record followed by a tenth item, the file seek offset of this record.""" # Determine file size fpin.seek(0, 2) filesize = fpin.tell() # Check to see if this is ZIP file with no archive comment (the # "end of central directory" structure should be the last item in the # file if this is the case). try: fpin.seek(-sizeEndCentDir, 2) except IOError: return None data = fpin.read() if data[0:4] == stringEndArchive and data[-2:] == "\000\000": # the signature is correct and there's no comment, unpack structure endrec = struct.unpack(structEndArchive, data) endrec=list(endrec) # Append a blank comment and record start offset endrec.append("") endrec.append(filesize - sizeEndCentDir) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, -sizeEndCentDir, endrec) # Either this is not a ZIP file, or it is a ZIP file with an archive # comment. Search the end of the file for the "end of central directory" # record signature. The comment is the last item in the ZIP file and may be # up to 64K long. It is assumed that the "end of central directory" magic # number does not appear in the comment. maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0) fpin.seek(maxCommentStart, 0) data = fpin.read() start = data.rfind(stringEndArchive) if start >= 0: # found the magic number; attempt to unpack and interpret recData = data[start:start+sizeEndCentDir] endrec = list(struct.unpack(structEndArchive, recData)) comment = data[start+sizeEndCentDir:] # check that comment length is correct if endrec[_ECD_COMMENT_SIZE] == len(comment): # Append the archive comment and start offset endrec.append(comment) endrec.append(maxCommentStart + start) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, maxCommentStart + start - filesize, endrec) # Unable to find a valid end of central directory structure return
python
def _EndRecData(fpin): # Determine file size fpin.seek(0, 2) filesize = fpin.tell() # Check to see if this is ZIP file with no archive comment (the # "end of central directory" structure should be the last item in the # file if this is the case). try: fpin.seek(-sizeEndCentDir, 2) except IOError: return None data = fpin.read() if data[0:4] == stringEndArchive and data[-2:] == "\000\000": # the signature is correct and there's no comment, unpack structure endrec = struct.unpack(structEndArchive, data) endrec=list(endrec) # Append a blank comment and record start offset endrec.append("") endrec.append(filesize - sizeEndCentDir) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, -sizeEndCentDir, endrec) # Either this is not a ZIP file, or it is a ZIP file with an archive # comment. Search the end of the file for the "end of central directory" # record signature. The comment is the last item in the ZIP file and may be # up to 64K long. It is assumed that the "end of central directory" magic # number does not appear in the comment. maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0) fpin.seek(maxCommentStart, 0) data = fpin.read() start = data.rfind(stringEndArchive) if start >= 0: # found the magic number; attempt to unpack and interpret recData = data[start:start+sizeEndCentDir] endrec = list(struct.unpack(structEndArchive, recData)) comment = data[start+sizeEndCentDir:] # check that comment length is correct if endrec[_ECD_COMMENT_SIZE] == len(comment): # Append the archive comment and start offset endrec.append(comment) endrec.append(maxCommentStart + start) # Try to read the "Zip64 end of central directory" structure return _EndRecData64(fpin, maxCommentStart + start - filesize, endrec) # Unable to find a valid end of central directory structure return
[ "def", "_EndRecData", "(", "fpin", ")", ":", "# Determine file size", "fpin", ".", "seek", "(", "0", ",", "2", ")", "filesize", "=", "fpin", ".", "tell", "(", ")", "# Check to see if this is ZIP file with no archive comment (the", "# \"end of central directory\" structu...
Return data from the "End of Central Directory" record, or None. The data is a list of the nine items in the ZIP "End of central dir" record followed by a tenth item, the file seek offset of this record.
[ "Return", "data", "from", "the", "End", "of", "Central", "Directory", "record", "or", "None", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L178-L233
246,363
nerdvegas/rez
src/rez/backport/zipfile.py
_ZipDecrypter._GenerateCRCTable
def _GenerateCRCTable(): """Generate a CRC-32 table. ZIP encryption uses the CRC32 one-byte primitive for scrambling some internal keys. We noticed that a direct implementation is faster than relying on binascii.crc32(). """ poly = 0xedb88320 table = [0] * 256 for i in range(256): crc = i for j in range(8): if crc & 1: crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly else: crc = ((crc >> 1) & 0x7FFFFFFF) table[i] = crc return table
python
def _GenerateCRCTable(): poly = 0xedb88320 table = [0] * 256 for i in range(256): crc = i for j in range(8): if crc & 1: crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly else: crc = ((crc >> 1) & 0x7FFFFFFF) table[i] = crc return table
[ "def", "_GenerateCRCTable", "(", ")", ":", "poly", "=", "0xedb88320", "table", "=", "[", "0", "]", "*", "256", "for", "i", "in", "range", "(", "256", ")", ":", "crc", "=", "i", "for", "j", "in", "range", "(", "8", ")", ":", "if", "crc", "&", ...
Generate a CRC-32 table. ZIP encryption uses the CRC32 one-byte primitive for scrambling some internal keys. We noticed that a direct implementation is faster than relying on binascii.crc32().
[ "Generate", "a", "CRC", "-", "32", "table", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L398-L415
246,364
nerdvegas/rez
src/rez/backport/zipfile.py
_ZipDecrypter._crc32
def _crc32(self, ch, crc): """Compute the CRC32 primitive on one byte.""" return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff]
python
def _crc32(self, ch, crc): return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff]
[ "def", "_crc32", "(", "self", ",", "ch", ",", "crc", ")", ":", "return", "(", "(", "crc", ">>", "8", ")", "&", "0xffffff", ")", "^", "self", ".", "crctable", "[", "(", "crc", "^", "ord", "(", "ch", ")", ")", "&", "0xff", "]" ]
Compute the CRC32 primitive on one byte.
[ "Compute", "the", "CRC32", "primitive", "on", "one", "byte", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L418-L420
246,365
nerdvegas/rez
src/rez/backport/zipfile.py
ZipExtFile.readline
def readline(self, size = -1): """Read a line with approx. size. If size is negative, read a whole line. """ if size < 0: size = sys.maxint elif size == 0: return '' # check for a newline already in buffer nl, nllen = self._checkfornewline() if nl >= 0: # the next line was already in the buffer nl = min(nl, size) else: # no line break in buffer - try to read more size -= len(self.linebuffer) while nl < 0 and size > 0: buf = self.read(min(size, 100)) if not buf: break self.linebuffer += buf size -= len(buf) # check for a newline in buffer nl, nllen = self._checkfornewline() # we either ran out of bytes in the file, or # met the specified size limit without finding a newline, # so return current buffer if nl < 0: s = self.linebuffer self.linebuffer = '' return s buf = self.linebuffer[:nl] self.lastdiscard = self.linebuffer[nl:nl + nllen] self.linebuffer = self.linebuffer[nl + nllen:] # line is always returned with \n as newline char (except possibly # for a final incomplete line in the file, which is handled above). return buf + "\n"
python
def readline(self, size = -1): if size < 0: size = sys.maxint elif size == 0: return '' # check for a newline already in buffer nl, nllen = self._checkfornewline() if nl >= 0: # the next line was already in the buffer nl = min(nl, size) else: # no line break in buffer - try to read more size -= len(self.linebuffer) while nl < 0 and size > 0: buf = self.read(min(size, 100)) if not buf: break self.linebuffer += buf size -= len(buf) # check for a newline in buffer nl, nllen = self._checkfornewline() # we either ran out of bytes in the file, or # met the specified size limit without finding a newline, # so return current buffer if nl < 0: s = self.linebuffer self.linebuffer = '' return s buf = self.linebuffer[:nl] self.lastdiscard = self.linebuffer[nl:nl + nllen] self.linebuffer = self.linebuffer[nl + nllen:] # line is always returned with \n as newline char (except possibly # for a final incomplete line in the file, which is handled above). return buf + "\n"
[ "def", "readline", "(", "self", ",", "size", "=", "-", "1", ")", ":", "if", "size", "<", "0", ":", "size", "=", "sys", ".", "maxint", "elif", "size", "==", "0", ":", "return", "''", "# check for a newline already in buffer", "nl", ",", "nllen", "=", ...
Read a line with approx. size. If size is negative, read a whole line.
[ "Read", "a", "line", "with", "approx", ".", "size", ".", "If", "size", "is", "negative", "read", "a", "whole", "line", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L511-L553
246,366
nerdvegas/rez
src/rez/backport/zipfile.py
ZipFile._GetContents
def _GetContents(self): """Read the directory, making sure we close the file if the format is bad.""" try: self._RealGetContents() except BadZipfile: if not self._filePassed: self.fp.close() self.fp = None raise
python
def _GetContents(self): try: self._RealGetContents() except BadZipfile: if not self._filePassed: self.fp.close() self.fp = None raise
[ "def", "_GetContents", "(", "self", ")", ":", "try", ":", "self", ".", "_RealGetContents", "(", ")", "except", "BadZipfile", ":", "if", "not", "self", ".", "_filePassed", ":", "self", ".", "fp", ".", "close", "(", ")", "self", ".", "fp", "=", "None",...
Read the directory, making sure we close the file if the format is bad.
[ "Read", "the", "directory", "making", "sure", "we", "close", "the", "file", "if", "the", "format", "is", "bad", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L714-L723
246,367
nerdvegas/rez
src/rez/backport/zipfile.py
ZipFile.namelist
def namelist(self): """Return a list of file names in the archive.""" l = [] for data in self.filelist: l.append(data.filename) return l
python
def namelist(self): l = [] for data in self.filelist: l.append(data.filename) return l
[ "def", "namelist", "(", "self", ")", ":", "l", "=", "[", "]", "for", "data", "in", "self", ".", "filelist", ":", "l", ".", "append", "(", "data", ".", "filename", ")", "return", "l" ]
Return a list of file names in the archive.
[ "Return", "a", "list", "of", "file", "names", "in", "the", "archive", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L789-L794
246,368
nerdvegas/rez
src/rez/backport/zipfile.py
ZipFile.printdir
def printdir(self): """Print a table of contents for the zip file.""" print "%-46s %19s %12s" % ("File Name", "Modified ", "Size") for zinfo in self.filelist: date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6] print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size)
python
def printdir(self): print "%-46s %19s %12s" % ("File Name", "Modified ", "Size") for zinfo in self.filelist: date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6] print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size)
[ "def", "printdir", "(", "self", ")", ":", "print", "\"%-46s %19s %12s\"", "%", "(", "\"File Name\"", ",", "\"Modified \"", ",", "\"Size\"", ")", "for", "zinfo", "in", "self", ".", "filelist", ":", "date", "=", "\"%d-%02d-%02d %02d:%02d:%02d\"", "%", "zinfo", ...
Print a table of contents for the zip file.
[ "Print", "a", "table", "of", "contents", "for", "the", "zip", "file", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L801-L806
246,369
nerdvegas/rez
src/rez/backport/zipfile.py
ZipFile.getinfo
def getinfo(self, name): """Return the instance of ZipInfo given 'name'.""" info = self.NameToInfo.get(name) if info is None: raise KeyError( 'There is no item named %r in the archive' % name) return info
python
def getinfo(self, name): info = self.NameToInfo.get(name) if info is None: raise KeyError( 'There is no item named %r in the archive' % name) return info
[ "def", "getinfo", "(", "self", ",", "name", ")", ":", "info", "=", "self", ".", "NameToInfo", ".", "get", "(", "name", ")", "if", "info", "is", "None", ":", "raise", "KeyError", "(", "'There is no item named %r in the archive'", "%", "name", ")", "return",...
Return the instance of ZipInfo given 'name'.
[ "Return", "the", "instance", "of", "ZipInfo", "given", "name", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L821-L828
246,370
nerdvegas/rez
src/rez/backport/zipfile.py
ZipFile.extract
def extract(self, member, path=None, pwd=None): """Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. `member' may be a filename or a ZipInfo object. You can specify a different directory using `path'. """ if not isinstance(member, ZipInfo): member = self.getinfo(member) if path is None: path = os.getcwd() return self._extract_member(member, path, pwd)
python
def extract(self, member, path=None, pwd=None): if not isinstance(member, ZipInfo): member = self.getinfo(member) if path is None: path = os.getcwd() return self._extract_member(member, path, pwd)
[ "def", "extract", "(", "self", ",", "member", ",", "path", "=", "None", ",", "pwd", "=", "None", ")", ":", "if", "not", "isinstance", "(", "member", ",", "ZipInfo", ")", ":", "member", "=", "self", ".", "getinfo", "(", "member", ")", "if", "path", ...
Extract a member from the archive to the current working directory, using its full name. Its file information is extracted as accurately as possible. `member' may be a filename or a ZipInfo object. You can specify a different directory using `path'.
[ "Extract", "a", "member", "from", "the", "archive", "to", "the", "current", "working", "directory", "using", "its", "full", "name", ".", "Its", "file", "information", "is", "extracted", "as", "accurately", "as", "possible", ".", "member", "may", "be", "a", ...
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L916-L928
246,371
nerdvegas/rez
src/rez/backport/zipfile.py
PyZipFile.writepy
def writepy(self, pathname, basename = ""): """Add all files from "pathname" to the ZIP archive. If pathname is a package directory, search the directory and all package subdirectories recursively for all *.py and enter the modules into the archive. If pathname is a plain directory, listdir *.py and enter all modules. Else, pathname must be a Python *.py file and the module will be put into the archive. Added modules are always module.pyo or module.pyc. This method will compile the module.py into module.pyc if necessary. """ dir, name = os.path.split(pathname) if os.path.isdir(pathname): initname = os.path.join(pathname, "__init__.py") if os.path.isfile(initname): # This is a package directory, add it if basename: basename = "%s/%s" % (basename, name) else: basename = name if self.debug: print "Adding package in", pathname, "as", basename fname, arcname = self._get_codename(initname[0:-3], basename) if self.debug: print "Adding", arcname self.write(fname, arcname) dirlist = os.listdir(pathname) dirlist.remove("__init__.py") # Add all *.py files and package subdirectories for filename in dirlist: path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) if os.path.isdir(path): if os.path.isfile(os.path.join(path, "__init__.py")): # This is a package directory, add it self.writepy(path, basename) # Recursive call elif ext == ".py": fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: print "Adding", arcname self.write(fname, arcname) else: # This is NOT a package directory, add its files at top level if self.debug: print "Adding files from directory", pathname for filename in os.listdir(pathname): path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) if ext == ".py": fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: print "Adding", arcname self.write(fname, arcname) else: if pathname[-3:] != ".py": raise RuntimeError, \ 'Files added with writepy() must end with ".py"' fname, arcname = self._get_codename(pathname[0:-3], basename) if self.debug: print "Adding file", arcname self.write(fname, arcname)
python
def writepy(self, pathname, basename = ""): dir, name = os.path.split(pathname) if os.path.isdir(pathname): initname = os.path.join(pathname, "__init__.py") if os.path.isfile(initname): # This is a package directory, add it if basename: basename = "%s/%s" % (basename, name) else: basename = name if self.debug: print "Adding package in", pathname, "as", basename fname, arcname = self._get_codename(initname[0:-3], basename) if self.debug: print "Adding", arcname self.write(fname, arcname) dirlist = os.listdir(pathname) dirlist.remove("__init__.py") # Add all *.py files and package subdirectories for filename in dirlist: path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) if os.path.isdir(path): if os.path.isfile(os.path.join(path, "__init__.py")): # This is a package directory, add it self.writepy(path, basename) # Recursive call elif ext == ".py": fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: print "Adding", arcname self.write(fname, arcname) else: # This is NOT a package directory, add its files at top level if self.debug: print "Adding files from directory", pathname for filename in os.listdir(pathname): path = os.path.join(pathname, filename) root, ext = os.path.splitext(filename) if ext == ".py": fname, arcname = self._get_codename(path[0:-3], basename) if self.debug: print "Adding", arcname self.write(fname, arcname) else: if pathname[-3:] != ".py": raise RuntimeError, \ 'Files added with writepy() must end with ".py"' fname, arcname = self._get_codename(pathname[0:-3], basename) if self.debug: print "Adding file", arcname self.write(fname, arcname)
[ "def", "writepy", "(", "self", ",", "pathname", ",", "basename", "=", "\"\"", ")", ":", "dir", ",", "name", "=", "os", ".", "path", ".", "split", "(", "pathname", ")", "if", "os", ".", "path", ".", "isdir", "(", "pathname", ")", ":", "initname", ...
Add all files from "pathname" to the ZIP archive. If pathname is a package directory, search the directory and all package subdirectories recursively for all *.py and enter the modules into the archive. If pathname is a plain directory, listdir *.py and enter all modules. Else, pathname must be a Python *.py file and the module will be put into the archive. Added modules are always module.pyo or module.pyc. This method will compile the module.py into module.pyc if necessary.
[ "Add", "all", "files", "from", "pathname", "to", "the", "ZIP", "archive", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L1241-L1304
246,372
nerdvegas/rez
src/rez/vendor/atomicwrites/__init__.py
AtomicWriter.get_fileobject
def get_fileobject(self, dir=None, **kwargs): '''Return the temporary file to use.''' if dir is None: dir = os.path.normpath(os.path.dirname(self._path)) descriptor, name = tempfile.mkstemp(dir=dir) # io.open() will take either the descriptor or the name, but we need # the name later for commit()/replace_atomic() and couldn't find a way # to get the filename from the descriptor. os.close(descriptor) kwargs['mode'] = self._mode kwargs['file'] = name return io.open(**kwargs)
python
def get_fileobject(self, dir=None, **kwargs): '''Return the temporary file to use.''' if dir is None: dir = os.path.normpath(os.path.dirname(self._path)) descriptor, name = tempfile.mkstemp(dir=dir) # io.open() will take either the descriptor or the name, but we need # the name later for commit()/replace_atomic() and couldn't find a way # to get the filename from the descriptor. os.close(descriptor) kwargs['mode'] = self._mode kwargs['file'] = name return io.open(**kwargs)
[ "def", "get_fileobject", "(", "self", ",", "dir", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "dir", "is", "None", ":", "dir", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "dirname", "(", "self", ".", "_path", ...
Return the temporary file to use.
[ "Return", "the", "temporary", "file", "to", "use", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/atomicwrites/__init__.py#L163-L174
246,373
nerdvegas/rez
src/rez/vendor/atomicwrites/__init__.py
AtomicWriter.commit
def commit(self, f): '''Move the temporary file to the target location.''' if self._overwrite: replace_atomic(f.name, self._path) else: move_atomic(f.name, self._path)
python
def commit(self, f): '''Move the temporary file to the target location.''' if self._overwrite: replace_atomic(f.name, self._path) else: move_atomic(f.name, self._path)
[ "def", "commit", "(", "self", ",", "f", ")", ":", "if", "self", ".", "_overwrite", ":", "replace_atomic", "(", "f", ".", "name", ",", "self", ".", "_path", ")", "else", ":", "move_atomic", "(", "f", ".", "name", ",", "self", ".", "_path", ")" ]
Move the temporary file to the target location.
[ "Move", "the", "temporary", "file", "to", "the", "target", "location", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/atomicwrites/__init__.py#L182-L187
246,374
nerdvegas/rez
src/rez/vendor/lockfile/pidlockfile.py
read_pid_from_pidfile
def read_pid_from_pidfile(pidfile_path): """ Read the PID recorded in the named PID file. Read and return the numeric PID recorded as text in the named PID file. If the PID file cannot be read, or if the content is not a valid PID, return ``None``. """ pid = None try: pidfile = open(pidfile_path, 'r') except IOError: pass else: # According to the FHS 2.3 section on PID files in /var/run: # # The file must consist of the process identifier in # ASCII-encoded decimal, followed by a newline character. # # Programs that read PID files should be somewhat flexible # in what they accept; i.e., they should ignore extra # whitespace, leading zeroes, absence of the trailing # newline, or additional lines in the PID file. line = pidfile.readline().strip() try: pid = int(line) except ValueError: pass pidfile.close() return pid
python
def read_pid_from_pidfile(pidfile_path): pid = None try: pidfile = open(pidfile_path, 'r') except IOError: pass else: # According to the FHS 2.3 section on PID files in /var/run: # # The file must consist of the process identifier in # ASCII-encoded decimal, followed by a newline character. # # Programs that read PID files should be somewhat flexible # in what they accept; i.e., they should ignore extra # whitespace, leading zeroes, absence of the trailing # newline, or additional lines in the PID file. line = pidfile.readline().strip() try: pid = int(line) except ValueError: pass pidfile.close() return pid
[ "def", "read_pid_from_pidfile", "(", "pidfile_path", ")", ":", "pid", "=", "None", "try", ":", "pidfile", "=", "open", "(", "pidfile_path", ",", "'r'", ")", "except", "IOError", ":", "pass", "else", ":", "# According to the FHS 2.3 section on PID files in /var/run:"...
Read the PID recorded in the named PID file. Read and return the numeric PID recorded as text in the named PID file. If the PID file cannot be read, or if the content is not a valid PID, return ``None``.
[ "Read", "the", "PID", "recorded", "in", "the", "named", "PID", "file", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/lockfile/pidlockfile.py#L120-L151
246,375
nerdvegas/rez
src/rezgui/widgets/ConfiguredSplitter.py
ConfiguredSplitter.apply_saved_layout
def apply_saved_layout(self): """Call this after adding your child widgets.""" num_widgets = self.config.get(self.config_key + "/num_widgets", int) if num_widgets: sizes = [] for i in range(num_widgets): key = "%s/size_%d" % (self.config_key, i) size = self.config.get(key, int) sizes.append(size) self.setSizes(sizes) return True return False
python
def apply_saved_layout(self): num_widgets = self.config.get(self.config_key + "/num_widgets", int) if num_widgets: sizes = [] for i in range(num_widgets): key = "%s/size_%d" % (self.config_key, i) size = self.config.get(key, int) sizes.append(size) self.setSizes(sizes) return True return False
[ "def", "apply_saved_layout", "(", "self", ")", ":", "num_widgets", "=", "self", ".", "config", ".", "get", "(", "self", ".", "config_key", "+", "\"/num_widgets\"", ",", "int", ")", "if", "num_widgets", ":", "sizes", "=", "[", "]", "for", "i", "in", "ra...
Call this after adding your child widgets.
[ "Call", "this", "after", "adding", "your", "child", "widgets", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/widgets/ConfiguredSplitter.py#L14-L25
246,376
nerdvegas/rez
src/rez/utils/data_utils.py
remove_nones
def remove_nones(**kwargs): """Return diict copy with nones removed. """ return dict((k, v) for k, v in kwargs.iteritems() if v is not None)
python
def remove_nones(**kwargs): return dict((k, v) for k, v in kwargs.iteritems() if v is not None)
[ "def", "remove_nones", "(", "*", "*", "kwargs", ")", ":", "return", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "kwargs", ".", "iteritems", "(", ")", "if", "v", "is", "not", "None", ")" ]
Return diict copy with nones removed.
[ "Return", "diict", "copy", "with", "nones", "removed", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/data_utils.py#L33-L36
246,377
nerdvegas/rez
src/rez/utils/data_utils.py
deep_update
def deep_update(dict1, dict2): """Perform a deep merge of `dict2` into `dict1`. Note that `dict2` and any nested dicts are unchanged. Supports `ModifyList` instances. """ def flatten(v): if isinstance(v, ModifyList): return v.apply([]) elif isinstance(v, dict): return dict((k, flatten(v_)) for k, v_ in v.iteritems()) else: return v def merge(v1, v2): if isinstance(v1, dict) and isinstance(v2, dict): deep_update(v1, v2) return v1 elif isinstance(v2, ModifyList): v1 = flatten(v1) return v2.apply(v1) else: return flatten(v2) for k1, v1 in dict1.iteritems(): if k1 not in dict2: dict1[k1] = flatten(v1) for k2, v2 in dict2.iteritems(): v1 = dict1.get(k2) if v1 is KeyError: dict1[k2] = flatten(v2) else: dict1[k2] = merge(v1, v2)
python
def deep_update(dict1, dict2): def flatten(v): if isinstance(v, ModifyList): return v.apply([]) elif isinstance(v, dict): return dict((k, flatten(v_)) for k, v_ in v.iteritems()) else: return v def merge(v1, v2): if isinstance(v1, dict) and isinstance(v2, dict): deep_update(v1, v2) return v1 elif isinstance(v2, ModifyList): v1 = flatten(v1) return v2.apply(v1) else: return flatten(v2) for k1, v1 in dict1.iteritems(): if k1 not in dict2: dict1[k1] = flatten(v1) for k2, v2 in dict2.iteritems(): v1 = dict1.get(k2) if v1 is KeyError: dict1[k2] = flatten(v2) else: dict1[k2] = merge(v1, v2)
[ "def", "deep_update", "(", "dict1", ",", "dict2", ")", ":", "def", "flatten", "(", "v", ")", ":", "if", "isinstance", "(", "v", ",", "ModifyList", ")", ":", "return", "v", ".", "apply", "(", "[", "]", ")", "elif", "isinstance", "(", "v", ",", "di...
Perform a deep merge of `dict2` into `dict1`. Note that `dict2` and any nested dicts are unchanged. Supports `ModifyList` instances.
[ "Perform", "a", "deep", "merge", "of", "dict2", "into", "dict1", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/data_utils.py#L39-L74
246,378
nerdvegas/rez
src/rez/utils/data_utils.py
deep_del
def deep_del(data, fn): """Create dict copy with removed items. Recursively remove items where fn(value) is True. Returns: dict: New dict with matching items removed. """ result = {} for k, v in data.iteritems(): if not fn(v): if isinstance(v, dict): result[k] = deep_del(v, fn) else: result[k] = v return result
python
def deep_del(data, fn): result = {} for k, v in data.iteritems(): if not fn(v): if isinstance(v, dict): result[k] = deep_del(v, fn) else: result[k] = v return result
[ "def", "deep_del", "(", "data", ",", "fn", ")", ":", "result", "=", "{", "}", "for", "k", ",", "v", "in", "data", ".", "iteritems", "(", ")", ":", "if", "not", "fn", "(", "v", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "...
Create dict copy with removed items. Recursively remove items where fn(value) is True. Returns: dict: New dict with matching items removed.
[ "Create", "dict", "copy", "with", "removed", "items", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/data_utils.py#L77-L94
246,379
nerdvegas/rez
src/rez/utils/data_utils.py
get_dict_diff_str
def get_dict_diff_str(d1, d2, title): """Returns same as `get_dict_diff`, but as a readable string. """ added, removed, changed = get_dict_diff(d1, d2) lines = [title] if added: lines.append("Added attributes: %s" % ['.'.join(x) for x in added]) if removed: lines.append("Removed attributes: %s" % ['.'.join(x) for x in removed]) if changed: lines.append("Changed attributes: %s" % ['.'.join(x) for x in changed]) return '\n'.join(lines)
python
def get_dict_diff_str(d1, d2, title): added, removed, changed = get_dict_diff(d1, d2) lines = [title] if added: lines.append("Added attributes: %s" % ['.'.join(x) for x in added]) if removed: lines.append("Removed attributes: %s" % ['.'.join(x) for x in removed]) if changed: lines.append("Changed attributes: %s" % ['.'.join(x) for x in changed]) return '\n'.join(lines)
[ "def", "get_dict_diff_str", "(", "d1", ",", "d2", ",", "title", ")", ":", "added", ",", "removed", ",", "changed", "=", "get_dict_diff", "(", "d1", ",", "d2", ")", "lines", "=", "[", "title", "]", "if", "added", ":", "lines", ".", "append", "(", "\...
Returns same as `get_dict_diff`, but as a readable string.
[ "Returns", "same", "as", "get_dict_diff", "but", "as", "a", "readable", "string", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/data_utils.py#L138-L154
246,380
nerdvegas/rez
src/rez/utils/data_utils.py
convert_dicts
def convert_dicts(d, to_class=AttrDictWrapper, from_class=dict): """Recursively convert dict and UserDict types. Note that `d` is unchanged. Args: to_class (type): Dict-like type to convert values to, usually UserDict subclass, or dict. from_class (type): Dict-like type to convert values from. If a tuple, multiple types are converted. Returns: Converted data as `to_class` instance. """ d_ = to_class() for key, value in d.iteritems(): if isinstance(value, from_class): d_[key] = convert_dicts(value, to_class=to_class, from_class=from_class) else: d_[key] = value return d_
python
def convert_dicts(d, to_class=AttrDictWrapper, from_class=dict): d_ = to_class() for key, value in d.iteritems(): if isinstance(value, from_class): d_[key] = convert_dicts(value, to_class=to_class, from_class=from_class) else: d_[key] = value return d_
[ "def", "convert_dicts", "(", "d", ",", "to_class", "=", "AttrDictWrapper", ",", "from_class", "=", "dict", ")", ":", "d_", "=", "to_class", "(", ")", "for", "key", ",", "value", "in", "d", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "va...
Recursively convert dict and UserDict types. Note that `d` is unchanged. Args: to_class (type): Dict-like type to convert values to, usually UserDict subclass, or dict. from_class (type): Dict-like type to convert values from. If a tuple, multiple types are converted. Returns: Converted data as `to_class` instance.
[ "Recursively", "convert", "dict", "and", "UserDict", "types", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/data_utils.py#L319-L340
246,381
nerdvegas/rez
src/rez/package_repository.py
PackageRepositoryGlobalStats.package_loading
def package_loading(self): """Use this around code in your package repository that is loading a package, for example from file or cache. """ t1 = time.time() yield None t2 = time.time() self.package_load_time += t2 - t1
python
def package_loading(self): t1 = time.time() yield None t2 = time.time() self.package_load_time += t2 - t1
[ "def", "package_loading", "(", "self", ")", ":", "t1", "=", "time", ".", "time", "(", ")", "yield", "None", "t2", "=", "time", ".", "time", "(", ")", "self", ".", "package_load_time", "+=", "t2", "-", "t1" ]
Use this around code in your package repository that is loading a package, for example from file or cache.
[ "Use", "this", "around", "code", "in", "your", "package", "repository", "that", "is", "loading", "a", "package", "for", "example", "from", "file", "or", "cache", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_repository.py#L42-L50
246,382
nerdvegas/rez
src/rez/package_repository.py
PackageRepository.is_empty
def is_empty(self): """Determine if the repository contains any packages. Returns: True if there are no packages, False if there are at least one. """ for family in self.iter_package_families(): for pkg in self.iter_packages(family): return False return True
python
def is_empty(self): for family in self.iter_package_families(): for pkg in self.iter_packages(family): return False return True
[ "def", "is_empty", "(", "self", ")", ":", "for", "family", "in", "self", ".", "iter_package_families", "(", ")", ":", "for", "pkg", "in", "self", ".", "iter_packages", "(", "family", ")", ":", "return", "False", "return", "True" ]
Determine if the repository contains any packages. Returns: True if there are no packages, False if there are at least one.
[ "Determine", "if", "the", "repository", "contains", "any", "packages", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_repository.py#L119-L129
246,383
nerdvegas/rez
src/rez/package_repository.py
PackageRepository.make_resource_handle
def make_resource_handle(self, resource_key, **variables): """Create a `ResourceHandle` Nearly all `ResourceHandle` creation should go through here, because it gives the various resource classes a chance to normalize / standardize the resource handles, to improve caching / comparison / etc. """ if variables.get("repository_type", self.name()) != self.name(): raise ResourceError("repository_type mismatch - requested %r, " "repository_type is %r" % (variables["repository_type"], self.name())) variables["repository_type"] = self.name() if variables.get("location", self.location) != self.location: raise ResourceError("location mismatch - requested %r, repository " "location is %r" % (variables["location"], self.location)) variables["location"] = self.location resource_cls = self.pool.get_resource_class(resource_key) variables = resource_cls.normalize_variables(variables) return ResourceHandle(resource_key, variables)
python
def make_resource_handle(self, resource_key, **variables): if variables.get("repository_type", self.name()) != self.name(): raise ResourceError("repository_type mismatch - requested %r, " "repository_type is %r" % (variables["repository_type"], self.name())) variables["repository_type"] = self.name() if variables.get("location", self.location) != self.location: raise ResourceError("location mismatch - requested %r, repository " "location is %r" % (variables["location"], self.location)) variables["location"] = self.location resource_cls = self.pool.get_resource_class(resource_key) variables = resource_cls.normalize_variables(variables) return ResourceHandle(resource_key, variables)
[ "def", "make_resource_handle", "(", "self", ",", "resource_key", ",", "*", "*", "variables", ")", ":", "if", "variables", ".", "get", "(", "\"repository_type\"", ",", "self", ".", "name", "(", ")", ")", "!=", "self", ".", "name", "(", ")", ":", "raise"...
Create a `ResourceHandle` Nearly all `ResourceHandle` creation should go through here, because it gives the various resource classes a chance to normalize / standardize the resource handles, to improve caching / comparison / etc.
[ "Create", "a", "ResourceHandle" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_repository.py#L256-L278
246,384
nerdvegas/rez
src/rez/package_repository.py
PackageRepositoryManager.get_repository
def get_repository(self, path): """Get a package repository. Args: path (str): Entry from the 'packages_path' config setting. This may simply be a path (which is managed by the 'filesystem' package repository plugin), or a string in the form "type@location", where 'type' identifies the repository plugin type to use. Returns: `PackageRepository` instance. """ # normalise parts = path.split('@', 1) if len(parts) == 1: parts = ("filesystem", parts[0]) repo_type, location = parts if repo_type == "filesystem": # choice of abspath here vs realpath is deliberate. Realpath gives # canonical path, which can be a problem if two studios are sharing # packages, and have mirrored package paths, but some are actually # different paths, symlinked to look the same. It happened! location = os.path.abspath(location) normalised_path = "%s@%s" % (repo_type, location) return self._get_repository(normalised_path)
python
def get_repository(self, path): # normalise parts = path.split('@', 1) if len(parts) == 1: parts = ("filesystem", parts[0]) repo_type, location = parts if repo_type == "filesystem": # choice of abspath here vs realpath is deliberate. Realpath gives # canonical path, which can be a problem if two studios are sharing # packages, and have mirrored package paths, but some are actually # different paths, symlinked to look the same. It happened! location = os.path.abspath(location) normalised_path = "%s@%s" % (repo_type, location) return self._get_repository(normalised_path)
[ "def", "get_repository", "(", "self", ",", "path", ")", ":", "# normalise", "parts", "=", "path", ".", "split", "(", "'@'", ",", "1", ")", "if", "len", "(", "parts", ")", "==", "1", ":", "parts", "=", "(", "\"filesystem\"", ",", "parts", "[", "0", ...
Get a package repository. Args: path (str): Entry from the 'packages_path' config setting. This may simply be a path (which is managed by the 'filesystem' package repository plugin), or a string in the form "type@location", where 'type' identifies the repository plugin type to use. Returns: `PackageRepository` instance.
[ "Get", "a", "package", "repository", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_repository.py#L368-L394
246,385
nerdvegas/rez
src/rez/package_repository.py
PackageRepositoryManager.are_same
def are_same(self, path_1, path_2): """Test that `path_1` and `path_2` refer to the same repository. This is more reliable than testing that the strings match, since slightly different strings might refer to the same repository (consider small differences in a filesystem path for example, eg '//svr/foo', '/svr/foo'). Returns: True if the paths refer to the same repository, False otherwise. """ if path_1 == path_2: return True repo_1 = self.get_repository(path_1) repo_2 = self.get_repository(path_2) return (repo_1.uid == repo_2.uid)
python
def are_same(self, path_1, path_2): if path_1 == path_2: return True repo_1 = self.get_repository(path_1) repo_2 = self.get_repository(path_2) return (repo_1.uid == repo_2.uid)
[ "def", "are_same", "(", "self", ",", "path_1", ",", "path_2", ")", ":", "if", "path_1", "==", "path_2", ":", "return", "True", "repo_1", "=", "self", ".", "get_repository", "(", "path_1", ")", "repo_2", "=", "self", ".", "get_repository", "(", "path_2", ...
Test that `path_1` and `path_2` refer to the same repository. This is more reliable than testing that the strings match, since slightly different strings might refer to the same repository (consider small differences in a filesystem path for example, eg '//svr/foo', '/svr/foo'). Returns: True if the paths refer to the same repository, False otherwise.
[ "Test", "that", "path_1", "and", "path_2", "refer", "to", "the", "same", "repository", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_repository.py#L396-L411
246,386
nerdvegas/rez
src/rez/vendor/amqp/transport.py
create_transport
def create_transport(host, connect_timeout, ssl=False): """Given a few parameters from the Connection constructor, select and create a subclass of _AbstractTransport.""" if ssl: return SSLTransport(host, connect_timeout, ssl) else: return TCPTransport(host, connect_timeout)
python
def create_transport(host, connect_timeout, ssl=False): if ssl: return SSLTransport(host, connect_timeout, ssl) else: return TCPTransport(host, connect_timeout)
[ "def", "create_transport", "(", "host", ",", "connect_timeout", ",", "ssl", "=", "False", ")", ":", "if", "ssl", ":", "return", "SSLTransport", "(", "host", ",", "connect_timeout", ",", "ssl", ")", "else", ":", "return", "TCPTransport", "(", "host", ",", ...
Given a few parameters from the Connection constructor, select and create a subclass of _AbstractTransport.
[ "Given", "a", "few", "parameters", "from", "the", "Connection", "constructor", "select", "and", "create", "a", "subclass", "of", "_AbstractTransport", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/transport.py#L293-L299
246,387
nerdvegas/rez
src/rez/plugin_managers.py
RezPluginType.get_plugin_class
def get_plugin_class(self, plugin_name): """Returns the class registered under the given plugin name.""" try: return self.plugin_classes[plugin_name] except KeyError: raise RezPluginError("Unrecognised %s plugin: '%s'" % (self.pretty_type_name, plugin_name))
python
def get_plugin_class(self, plugin_name): try: return self.plugin_classes[plugin_name] except KeyError: raise RezPluginError("Unrecognised %s plugin: '%s'" % (self.pretty_type_name, plugin_name))
[ "def", "get_plugin_class", "(", "self", ",", "plugin_name", ")", ":", "try", ":", "return", "self", ".", "plugin_classes", "[", "plugin_name", "]", "except", "KeyError", ":", "raise", "RezPluginError", "(", "\"Unrecognised %s plugin: '%s'\"", "%", "(", "self", "...
Returns the class registered under the given plugin name.
[ "Returns", "the", "class", "registered", "under", "the", "given", "plugin", "name", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L157-L163
246,388
nerdvegas/rez
src/rez/plugin_managers.py
RezPluginType.get_plugin_module
def get_plugin_module(self, plugin_name): """Returns the module containing the plugin of the given name.""" try: return self.plugin_modules[plugin_name] except KeyError: raise RezPluginError("Unrecognised %s plugin: '%s'" % (self.pretty_type_name, plugin_name))
python
def get_plugin_module(self, plugin_name): try: return self.plugin_modules[plugin_name] except KeyError: raise RezPluginError("Unrecognised %s plugin: '%s'" % (self.pretty_type_name, plugin_name))
[ "def", "get_plugin_module", "(", "self", ",", "plugin_name", ")", ":", "try", ":", "return", "self", ".", "plugin_modules", "[", "plugin_name", "]", "except", "KeyError", ":", "raise", "RezPluginError", "(", "\"Unrecognised %s plugin: '%s'\"", "%", "(", "self", ...
Returns the module containing the plugin of the given name.
[ "Returns", "the", "module", "containing", "the", "plugin", "of", "the", "given", "name", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L165-L171
246,389
nerdvegas/rez
src/rez/plugin_managers.py
RezPluginType.config_schema
def config_schema(self): """Returns the merged configuration data schema for this plugin type.""" from rez.config import _plugin_config_dict d = _plugin_config_dict.get(self.type_name, {}) for name, plugin_class in self.plugin_classes.iteritems(): if hasattr(plugin_class, "schema_dict") \ and plugin_class.schema_dict: d_ = {name: plugin_class.schema_dict} deep_update(d, d_) return dict_to_schema(d, required=True, modifier=expand_system_vars)
python
def config_schema(self): from rez.config import _plugin_config_dict d = _plugin_config_dict.get(self.type_name, {}) for name, plugin_class in self.plugin_classes.iteritems(): if hasattr(plugin_class, "schema_dict") \ and plugin_class.schema_dict: d_ = {name: plugin_class.schema_dict} deep_update(d, d_) return dict_to_schema(d, required=True, modifier=expand_system_vars)
[ "def", "config_schema", "(", "self", ")", ":", "from", "rez", ".", "config", "import", "_plugin_config_dict", "d", "=", "_plugin_config_dict", ".", "get", "(", "self", ".", "type_name", ",", "{", "}", ")", "for", "name", ",", "plugin_class", "in", "self", ...
Returns the merged configuration data schema for this plugin type.
[ "Returns", "the", "merged", "configuration", "data", "schema", "for", "this", "plugin", "type", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L174-L185
246,390
nerdvegas/rez
src/rez/plugin_managers.py
RezPluginManager.get_plugin_class
def get_plugin_class(self, plugin_type, plugin_name): """Return the class registered under the given plugin name.""" plugin = self._get_plugin_type(plugin_type) return plugin.get_plugin_class(plugin_name)
python
def get_plugin_class(self, plugin_type, plugin_name): plugin = self._get_plugin_type(plugin_type) return plugin.get_plugin_class(plugin_name)
[ "def", "get_plugin_class", "(", "self", ",", "plugin_type", ",", "plugin_name", ")", ":", "plugin", "=", "self", ".", "_get_plugin_type", "(", "plugin_type", ")", "return", "plugin", ".", "get_plugin_class", "(", "plugin_name", ")" ]
Return the class registered under the given plugin name.
[ "Return", "the", "class", "registered", "under", "the", "given", "plugin", "name", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L278-L281
246,391
nerdvegas/rez
src/rez/plugin_managers.py
RezPluginManager.get_plugin_module
def get_plugin_module(self, plugin_type, plugin_name): """Return the module defining the class registered under the given plugin name.""" plugin = self._get_plugin_type(plugin_type) return plugin.get_plugin_module(plugin_name)
python
def get_plugin_module(self, plugin_type, plugin_name): plugin = self._get_plugin_type(plugin_type) return plugin.get_plugin_module(plugin_name)
[ "def", "get_plugin_module", "(", "self", ",", "plugin_type", ",", "plugin_name", ")", ":", "plugin", "=", "self", ".", "_get_plugin_type", "(", "plugin_type", ")", "return", "plugin", ".", "get_plugin_module", "(", "plugin_name", ")" ]
Return the module defining the class registered under the given plugin name.
[ "Return", "the", "module", "defining", "the", "class", "registered", "under", "the", "given", "plugin", "name", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L283-L287
246,392
nerdvegas/rez
src/rez/plugin_managers.py
RezPluginManager.create_instance
def create_instance(self, plugin_type, plugin_name, **instance_kwargs): """Create and return an instance of the given plugin.""" plugin_type = self._get_plugin_type(plugin_type) return plugin_type.create_instance(plugin_name, **instance_kwargs)
python
def create_instance(self, plugin_type, plugin_name, **instance_kwargs): plugin_type = self._get_plugin_type(plugin_type) return plugin_type.create_instance(plugin_name, **instance_kwargs)
[ "def", "create_instance", "(", "self", ",", "plugin_type", ",", "plugin_name", ",", "*", "*", "instance_kwargs", ")", ":", "plugin_type", "=", "self", ".", "_get_plugin_type", "(", "plugin_type", ")", "return", "plugin_type", ".", "create_instance", "(", "plugin...
Create and return an instance of the given plugin.
[ "Create", "and", "return", "an", "instance", "of", "the", "given", "plugin", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L308-L311
246,393
nerdvegas/rez
src/rez/plugin_managers.py
RezPluginManager.get_summary_string
def get_summary_string(self): """Get a formatted string summarising the plugins that were loaded.""" rows = [["PLUGIN TYPE", "NAME", "DESCRIPTION", "STATUS"], ["-----------", "----", "-----------", "------"]] for plugin_type in sorted(self.get_plugin_types()): type_name = plugin_type.replace('_', ' ') for name in sorted(self.get_plugins(plugin_type)): module = self.get_plugin_module(plugin_type, name) desc = (getattr(module, "__doc__", None) or '').strip() rows.append((type_name, name, desc, "loaded")) for (name, reason) in sorted(self.get_failed_plugins(plugin_type)): msg = "FAILED: %s" % reason rows.append((type_name, name, '', msg)) return '\n'.join(columnise(rows))
python
def get_summary_string(self): rows = [["PLUGIN TYPE", "NAME", "DESCRIPTION", "STATUS"], ["-----------", "----", "-----------", "------"]] for plugin_type in sorted(self.get_plugin_types()): type_name = plugin_type.replace('_', ' ') for name in sorted(self.get_plugins(plugin_type)): module = self.get_plugin_module(plugin_type, name) desc = (getattr(module, "__doc__", None) or '').strip() rows.append((type_name, name, desc, "loaded")) for (name, reason) in sorted(self.get_failed_plugins(plugin_type)): msg = "FAILED: %s" % reason rows.append((type_name, name, '', msg)) return '\n'.join(columnise(rows))
[ "def", "get_summary_string", "(", "self", ")", ":", "rows", "=", "[", "[", "\"PLUGIN TYPE\"", ",", "\"NAME\"", ",", "\"DESCRIPTION\"", ",", "\"STATUS\"", "]", ",", "[", "\"-----------\"", ",", "\"----\"", ",", "\"-----------\"", ",", "\"------\"", "]", "]", ...
Get a formatted string summarising the plugins that were loaded.
[ "Get", "a", "formatted", "string", "summarising", "the", "plugins", "that", "were", "loaded", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L313-L326
246,394
nerdvegas/rez
src/rez/vendor/distlib/markers.py
Evaluator.get_fragment
def get_fragment(self, offset): """ Get the part of the source which is causing a problem. """ fragment_len = 10 s = '%r' % (self.source[offset:offset + fragment_len]) if offset + fragment_len < len(self.source): s += '...' return s
python
def get_fragment(self, offset): fragment_len = 10 s = '%r' % (self.source[offset:offset + fragment_len]) if offset + fragment_len < len(self.source): s += '...' return s
[ "def", "get_fragment", "(", "self", ",", "offset", ")", ":", "fragment_len", "=", "10", "s", "=", "'%r'", "%", "(", "self", ".", "source", "[", "offset", ":", "offset", "+", "fragment_len", "]", ")", "if", "offset", "+", "fragment_len", "<", "len", "...
Get the part of the source which is causing a problem.
[ "Get", "the", "part", "of", "the", "source", "which", "is", "causing", "a", "problem", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/distlib/markers.py#L60-L68
246,395
nerdvegas/rez
src/rez/vendor/distlib/markers.py
Evaluator.evaluate
def evaluate(self, node, filename=None): """ Evaluate a source string or node, using ``filename`` when displaying errors. """ if isinstance(node, string_types): self.source = node kwargs = {'mode': 'eval'} if filename: kwargs['filename'] = filename try: node = ast.parse(node, **kwargs) except SyntaxError as e: s = self.get_fragment(e.offset) raise SyntaxError('syntax error %s' % s) node_type = node.__class__.__name__.lower() handler = self.get_handler(node_type) if handler is None: if self.source is None: s = '(source not available)' else: s = self.get_fragment(node.col_offset) raise SyntaxError("don't know how to evaluate %r %s" % ( node_type, s)) return handler(node)
python
def evaluate(self, node, filename=None): if isinstance(node, string_types): self.source = node kwargs = {'mode': 'eval'} if filename: kwargs['filename'] = filename try: node = ast.parse(node, **kwargs) except SyntaxError as e: s = self.get_fragment(e.offset) raise SyntaxError('syntax error %s' % s) node_type = node.__class__.__name__.lower() handler = self.get_handler(node_type) if handler is None: if self.source is None: s = '(source not available)' else: s = self.get_fragment(node.col_offset) raise SyntaxError("don't know how to evaluate %r %s" % ( node_type, s)) return handler(node)
[ "def", "evaluate", "(", "self", ",", "node", ",", "filename", "=", "None", ")", ":", "if", "isinstance", "(", "node", ",", "string_types", ")", ":", "self", ".", "source", "=", "node", "kwargs", "=", "{", "'mode'", ":", "'eval'", "}", "if", "filename...
Evaluate a source string or node, using ``filename`` when displaying errors.
[ "Evaluate", "a", "source", "string", "or", "node", "using", "filename", "when", "displaying", "errors", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/distlib/markers.py#L76-L100
246,396
nerdvegas/rez
src/rez/vendor/sortedcontainers/sortedlist.py
recursive_repr
def recursive_repr(func): """Decorator to prevent infinite repr recursion.""" repr_running = set() @wraps(func) def wrapper(self): "Return ellipsis on recursive re-entry to function." key = id(self), get_ident() if key in repr_running: return '...' repr_running.add(key) try: return func(self) finally: repr_running.discard(key) return wrapper
python
def recursive_repr(func): repr_running = set() @wraps(func) def wrapper(self): "Return ellipsis on recursive re-entry to function." key = id(self), get_ident() if key in repr_running: return '...' repr_running.add(key) try: return func(self) finally: repr_running.discard(key) return wrapper
[ "def", "recursive_repr", "(", "func", ")", ":", "repr_running", "=", "set", "(", ")", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "self", ")", ":", "\"Return ellipsis on recursive re-entry to function.\"", "key", "=", "id", "(", "self", ")", ",", ...
Decorator to prevent infinite repr recursion.
[ "Decorator", "to", "prevent", "infinite", "repr", "recursion", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedlist.py#L33-L52
246,397
nerdvegas/rez
src/rez/vendor/sortedcontainers/sortedlist.py
SortedList._reset
def _reset(self, load): """ Reset sorted list load. The *load* specifies the load-factor of the list. The default load factor of '1000' works well for lists from tens to tens of millions of elements. Good practice is to use a value that is the cube root of the list size. With billions of elements, the best load factor depends on your usage. It's best to leave the load factor at the default until you start benchmarking. """ values = reduce(iadd, self._lists, []) self._clear() self._load = load self._half = load >> 1 self._dual = load << 1 self._update(values)
python
def _reset(self, load): values = reduce(iadd, self._lists, []) self._clear() self._load = load self._half = load >> 1 self._dual = load << 1 self._update(values)
[ "def", "_reset", "(", "self", ",", "load", ")", ":", "values", "=", "reduce", "(", "iadd", ",", "self", ".", "_lists", ",", "[", "]", ")", "self", ".", "_clear", "(", ")", "self", ".", "_load", "=", "load", "self", ".", "_half", "=", "load", ">...
Reset sorted list load. The *load* specifies the load-factor of the list. The default load factor of '1000' works well for lists from tens to tens of millions of elements. Good practice is to use a value that is the cube root of the list size. With billions of elements, the best load factor depends on your usage. It's best to leave the load factor at the default until you start benchmarking.
[ "Reset", "sorted", "list", "load", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedlist.py#L105-L121
246,398
nerdvegas/rez
src/rez/vendor/sortedcontainers/sortedlist.py
SortedList._build_index
def _build_index(self): """Build an index for indexing the sorted list. Indexes are represented as binary trees in a dense array notation similar to a binary heap. For example, given a _lists representation storing integers: [0]: 1 2 3 [1]: 4 5 [2]: 6 7 8 9 [3]: 10 11 12 13 14 The first transformation maps the sub-lists by their length. The first row of the index is the length of the sub-lists. [0]: 3 2 4 5 Each row after that is the sum of consecutive pairs of the previous row: [1]: 5 9 [2]: 14 Finally, the index is built by concatenating these lists together: _index = 14 5 9 3 2 4 5 An offset storing the start of the first row is also stored: _offset = 3 When built, the index can be used for efficient indexing into the list. See the comment and notes on self._pos for details. """ row0 = list(map(len, self._lists)) if len(row0) == 1: self._index[:] = row0 self._offset = 0 return head = iter(row0) tail = iter(head) row1 = list(starmap(add, zip(head, tail))) if len(row0) & 1: row1.append(row0[-1]) if len(row1) == 1: self._index[:] = row1 + row0 self._offset = 1 return size = 2 ** (int(log_e(len(row1) - 1, 2)) + 1) row1.extend(repeat(0, size - len(row1))) tree = [row0, row1] while len(tree[-1]) > 1: head = iter(tree[-1]) tail = iter(head) row = list(starmap(add, zip(head, tail))) tree.append(row) reduce(iadd, reversed(tree), self._index) self._offset = size * 2 - 1
python
def _build_index(self): row0 = list(map(len, self._lists)) if len(row0) == 1: self._index[:] = row0 self._offset = 0 return head = iter(row0) tail = iter(head) row1 = list(starmap(add, zip(head, tail))) if len(row0) & 1: row1.append(row0[-1]) if len(row1) == 1: self._index[:] = row1 + row0 self._offset = 1 return size = 2 ** (int(log_e(len(row1) - 1, 2)) + 1) row1.extend(repeat(0, size - len(row1))) tree = [row0, row1] while len(tree[-1]) > 1: head = iter(tree[-1]) tail = iter(head) row = list(starmap(add, zip(head, tail))) tree.append(row) reduce(iadd, reversed(tree), self._index) self._offset = size * 2 - 1
[ "def", "_build_index", "(", "self", ")", ":", "row0", "=", "list", "(", "map", "(", "len", ",", "self", ".", "_lists", ")", ")", "if", "len", "(", "row0", ")", "==", "1", ":", "self", ".", "_index", "[", ":", "]", "=", "row0", "self", ".", "_...
Build an index for indexing the sorted list. Indexes are represented as binary trees in a dense array notation similar to a binary heap. For example, given a _lists representation storing integers: [0]: 1 2 3 [1]: 4 5 [2]: 6 7 8 9 [3]: 10 11 12 13 14 The first transformation maps the sub-lists by their length. The first row of the index is the length of the sub-lists. [0]: 3 2 4 5 Each row after that is the sum of consecutive pairs of the previous row: [1]: 5 9 [2]: 14 Finally, the index is built by concatenating these lists together: _index = 14 5 9 3 2 4 5 An offset storing the start of the first row is also stored: _offset = 3 When built, the index can be used for efficient indexing into the list. See the comment and notes on self._pos for details.
[ "Build", "an", "index", "for", "indexing", "the", "sorted", "list", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedlist.py#L494-L558
246,399
nerdvegas/rez
src/rez/vendor/sortedcontainers/sortedlist.py
SortedListWithKey.irange_key
def irange_key(self, min_key=None, max_key=None, inclusive=(True, True), reverse=False): """ Create an iterator of values between `min_key` and `max_key`. `inclusive` is a pair of booleans that indicates whether the min_key and max_key ought to be included in the range, respectively. The default is (True, True) such that the range is inclusive of both `min_key` and `max_key`. Both `min_key` and `max_key` default to `None` which is automatically inclusive of the start and end of the list, respectively. When `reverse` is `True` the values are yielded from the iterator in reverse order; `reverse` defaults to `False`. """ _maxes = self._maxes if not _maxes: return iter(()) _keys = self._keys # Calculate the minimum (pos, idx) pair. By default this location # will be inclusive in our calculation. if min_key is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_keys[min_pos], min_key) else: min_pos = bisect_right(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_keys[min_pos], min_key) # Calculate the maximum (pos, idx) pair. By default this location # will be exclusive in our calculation. if max_key is None: max_pos = len(_maxes) - 1 max_idx = len(_keys[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_right(_keys[max_pos], max_key) else: max_pos = bisect_left(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_left(_keys[max_pos], max_key) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
python
def irange_key(self, min_key=None, max_key=None, inclusive=(True, True), reverse=False): _maxes = self._maxes if not _maxes: return iter(()) _keys = self._keys # Calculate the minimum (pos, idx) pair. By default this location # will be inclusive in our calculation. if min_key is None: min_pos = 0 min_idx = 0 else: if inclusive[0]: min_pos = bisect_left(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_left(_keys[min_pos], min_key) else: min_pos = bisect_right(_maxes, min_key) if min_pos == len(_maxes): return iter(()) min_idx = bisect_right(_keys[min_pos], min_key) # Calculate the maximum (pos, idx) pair. By default this location # will be exclusive in our calculation. if max_key is None: max_pos = len(_maxes) - 1 max_idx = len(_keys[max_pos]) else: if inclusive[1]: max_pos = bisect_right(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_right(_keys[max_pos], max_key) else: max_pos = bisect_left(_maxes, max_key) if max_pos == len(_maxes): max_pos -= 1 max_idx = len(_keys[max_pos]) else: max_idx = bisect_left(_keys[max_pos], max_key) return self._islice(min_pos, min_idx, max_pos, max_idx, reverse)
[ "def", "irange_key", "(", "self", ",", "min_key", "=", "None", ",", "max_key", "=", "None", ",", "inclusive", "=", "(", "True", ",", "True", ")", ",", "reverse", "=", "False", ")", ":", "_maxes", "=", "self", ".", "_maxes", "if", "not", "_maxes", "...
Create an iterator of values between `min_key` and `max_key`. `inclusive` is a pair of booleans that indicates whether the min_key and max_key ought to be included in the range, respectively. The default is (True, True) such that the range is inclusive of both `min_key` and `max_key`. Both `min_key` and `max_key` default to `None` which is automatically inclusive of the start and end of the list, respectively. When `reverse` is `True` the values are yielded from the iterator in reverse order; `reverse` defaults to `False`.
[ "Create", "an", "iterator", "of", "values", "between", "min_key", "and", "max_key", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedlist.py#L1966-L2035