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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
232,400
nerdvegas/rez
src/rezgui/util.py
create_pane
def create_pane(widgets, horizontal, parent_widget=None, compact=False, compact_spacing=2): """Create a widget containing an aligned set of widgets. Args: widgets (list of `QWidget`). horizontal (bool). align (str): One of: - 'left', 'right' (horizontal); - 'top', 'bottom' (vertical) parent_widget (`QWidget`): Owner widget, QWidget is created if this is not provided. Returns: `QWidget` """ pane = parent_widget or QtGui.QWidget() type_ = QtGui.QHBoxLayout if horizontal else QtGui.QVBoxLayout layout = type_() if compact: layout.setSpacing(compact_spacing) layout.setContentsMargins(compact_spacing, compact_spacing, compact_spacing, compact_spacing) for widget in widgets: stretch = 0 if isinstance(widget, tuple): widget, stretch = widget if isinstance(widget, int): layout.addSpacing(widget) elif widget: layout.addWidget(widget, stretch) else: layout.addStretch() pane.setLayout(layout) return pane
python
def create_pane(widgets, horizontal, parent_widget=None, compact=False, compact_spacing=2): """Create a widget containing an aligned set of widgets. Args: widgets (list of `QWidget`). horizontal (bool). align (str): One of: - 'left', 'right' (horizontal); - 'top', 'bottom' (vertical) parent_widget (`QWidget`): Owner widget, QWidget is created if this is not provided. Returns: `QWidget` """ pane = parent_widget or QtGui.QWidget() type_ = QtGui.QHBoxLayout if horizontal else QtGui.QVBoxLayout layout = type_() if compact: layout.setSpacing(compact_spacing) layout.setContentsMargins(compact_spacing, compact_spacing, compact_spacing, compact_spacing) for widget in widgets: stretch = 0 if isinstance(widget, tuple): widget, stretch = widget if isinstance(widget, int): layout.addSpacing(widget) elif widget: layout.addWidget(widget, stretch) else: layout.addStretch() pane.setLayout(layout) return pane
[ "def", "create_pane", "(", "widgets", ",", "horizontal", ",", "parent_widget", "=", "None", ",", "compact", "=", "False", ",", "compact_spacing", "=", "2", ")", ":", "pane", "=", "parent_widget", "or", "QtGui", ".", "QWidget", "(", ")", "type_", "=", "QtGui", ".", "QHBoxLayout", "if", "horizontal", "else", "QtGui", ".", "QVBoxLayout", "layout", "=", "type_", "(", ")", "if", "compact", ":", "layout", ".", "setSpacing", "(", "compact_spacing", ")", "layout", ".", "setContentsMargins", "(", "compact_spacing", ",", "compact_spacing", ",", "compact_spacing", ",", "compact_spacing", ")", "for", "widget", "in", "widgets", ":", "stretch", "=", "0", "if", "isinstance", "(", "widget", ",", "tuple", ")", ":", "widget", ",", "stretch", "=", "widget", "if", "isinstance", "(", "widget", ",", "int", ")", ":", "layout", ".", "addSpacing", "(", "widget", ")", "elif", "widget", ":", "layout", ".", "addWidget", "(", "widget", ",", "stretch", ")", "else", ":", "layout", ".", "addStretch", "(", ")", "pane", ".", "setLayout", "(", "layout", ")", "return", "pane" ]
Create a widget containing an aligned set of widgets. Args: widgets (list of `QWidget`). horizontal (bool). align (str): One of: - 'left', 'right' (horizontal); - 'top', 'bottom' (vertical) parent_widget (`QWidget`): Owner widget, QWidget is created if this is not provided. Returns: `QWidget`
[ "Create", "a", "widget", "containing", "an", "aligned", "set", "of", "widgets", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/util.py#L7-L44
232,401
nerdvegas/rez
src/rezgui/util.py
get_icon
def get_icon(name, as_qicon=False): """Returns a `QPixmap` containing the given image, or a QIcon if `as_qicon` is True""" filename = name + ".png" icon = icons.get(filename) if not icon: path = os.path.dirname(__file__) path = os.path.join(path, "icons") filepath = os.path.join(path, filename) if not os.path.exists(filepath): filepath = os.path.join(path, "pink.png") icon = QtGui.QPixmap(filepath) icons[filename] = icon return QtGui.QIcon(icon) if as_qicon else icon
python
def get_icon(name, as_qicon=False): """Returns a `QPixmap` containing the given image, or a QIcon if `as_qicon` is True""" filename = name + ".png" icon = icons.get(filename) if not icon: path = os.path.dirname(__file__) path = os.path.join(path, "icons") filepath = os.path.join(path, filename) if not os.path.exists(filepath): filepath = os.path.join(path, "pink.png") icon = QtGui.QPixmap(filepath) icons[filename] = icon return QtGui.QIcon(icon) if as_qicon else icon
[ "def", "get_icon", "(", "name", ",", "as_qicon", "=", "False", ")", ":", "filename", "=", "name", "+", "\".png\"", "icon", "=", "icons", ".", "get", "(", "filename", ")", "if", "not", "icon", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"icons\"", ")", "filepath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "filepath", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "\"pink.png\"", ")", "icon", "=", "QtGui", ".", "QPixmap", "(", "filepath", ")", "icons", "[", "filename", "]", "=", "icon", "return", "QtGui", ".", "QIcon", "(", "icon", ")", "if", "as_qicon", "else", "icon" ]
Returns a `QPixmap` containing the given image, or a QIcon if `as_qicon` is True
[ "Returns", "a", "QPixmap", "containing", "the", "given", "image", "or", "a", "QIcon", "if", "as_qicon", "is", "True" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/util.py#L50-L65
232,402
nerdvegas/rez
src/rezgui/util.py
interp_color
def interp_color(a, b, f): """Interpolate between two colors. Returns: `QColor` object. """ a_ = (a.redF(), a.greenF(), a.blueF()) b_ = (b.redF(), b.greenF(), b.blueF()) a_ = [x * (1 - f) for x in a_] b_ = [x * f for x in b_] c = [x + y for x, y in zip(a_, b_)] return QtGui.QColor.fromRgbF(*c)
python
def interp_color(a, b, f): """Interpolate between two colors. Returns: `QColor` object. """ a_ = (a.redF(), a.greenF(), a.blueF()) b_ = (b.redF(), b.greenF(), b.blueF()) a_ = [x * (1 - f) for x in a_] b_ = [x * f for x in b_] c = [x + y for x, y in zip(a_, b_)] return QtGui.QColor.fromRgbF(*c)
[ "def", "interp_color", "(", "a", ",", "b", ",", "f", ")", ":", "a_", "=", "(", "a", ".", "redF", "(", ")", ",", "a", ".", "greenF", "(", ")", ",", "a", ".", "blueF", "(", ")", ")", "b_", "=", "(", "b", ".", "redF", "(", ")", ",", "b", ".", "greenF", "(", ")", ",", "b", ".", "blueF", "(", ")", ")", "a_", "=", "[", "x", "*", "(", "1", "-", "f", ")", "for", "x", "in", "a_", "]", "b_", "=", "[", "x", "*", "f", "for", "x", "in", "b_", "]", "c", "=", "[", "x", "+", "y", "for", "x", ",", "y", "in", "zip", "(", "a_", ",", "b_", ")", "]", "return", "QtGui", ".", "QColor", ".", "fromRgbF", "(", "*", "c", ")" ]
Interpolate between two colors. Returns: `QColor` object.
[ "Interpolate", "between", "two", "colors", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/util.py#L105-L116
232,403
nerdvegas/rez
src/rezgui/util.py
create_toolbutton
def create_toolbutton(entries, parent=None): """Create a toolbutton. Args: entries: List of (label, slot) tuples. Returns: `QtGui.QToolBar`. """ btn = QtGui.QToolButton(parent) menu = QtGui.QMenu() actions = [] for label, slot in entries: action = add_menu_action(menu, label, slot) actions.append(action) btn.setPopupMode(QtGui.QToolButton.MenuButtonPopup) btn.setDefaultAction(actions[0]) btn.setMenu(menu) return btn, actions
python
def create_toolbutton(entries, parent=None): """Create a toolbutton. Args: entries: List of (label, slot) tuples. Returns: `QtGui.QToolBar`. """ btn = QtGui.QToolButton(parent) menu = QtGui.QMenu() actions = [] for label, slot in entries: action = add_menu_action(menu, label, slot) actions.append(action) btn.setPopupMode(QtGui.QToolButton.MenuButtonPopup) btn.setDefaultAction(actions[0]) btn.setMenu(menu) return btn, actions
[ "def", "create_toolbutton", "(", "entries", ",", "parent", "=", "None", ")", ":", "btn", "=", "QtGui", ".", "QToolButton", "(", "parent", ")", "menu", "=", "QtGui", ".", "QMenu", "(", ")", "actions", "=", "[", "]", "for", "label", ",", "slot", "in", "entries", ":", "action", "=", "add_menu_action", "(", "menu", ",", "label", ",", "slot", ")", "actions", ".", "append", "(", "action", ")", "btn", ".", "setPopupMode", "(", "QtGui", ".", "QToolButton", ".", "MenuButtonPopup", ")", "btn", ".", "setDefaultAction", "(", "actions", "[", "0", "]", ")", "btn", ".", "setMenu", "(", "menu", ")", "return", "btn", ",", "actions" ]
Create a toolbutton. Args: entries: List of (label, slot) tuples. Returns: `QtGui.QToolBar`.
[ "Create", "a", "toolbutton", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/util.py#L119-L139
232,404
nerdvegas/rez
src/build_utils/distlib/locators.py
SimpleScrapingLocator.get_page
def get_page(self, url): """ Get the HTML for an URL, possibly from an in-memory cache. XXX TODO Note: this cache is never actually cleared. It's assumed that the data won't get stale over the lifetime of a locator instance (not necessarily true for the default_locator). """ # http://peak.telecommunity.com/DevCenter/EasyInstall#package-index-api scheme, netloc, path, _, _, _ = urlparse(url) if scheme == 'file' and os.path.isdir(url2pathname(path)): url = urljoin(ensure_slash(url), 'index.html') if url in self._page_cache: result = self._page_cache[url] logger.debug('Returning %s from cache: %s', url, result) else: host = netloc.split(':', 1)[0] result = None if host in self._bad_hosts: logger.debug('Skipping %s due to bad host %s', url, host) else: req = Request(url, headers={'Accept-encoding': 'identity'}) try: logger.debug('Fetching %s', url) resp = self.opener.open(req, timeout=self.timeout) logger.debug('Fetched %s', url) headers = resp.info() content_type = headers.get('Content-Type', '') if HTML_CONTENT_TYPE.match(content_type): final_url = resp.geturl() data = resp.read() encoding = headers.get('Content-Encoding') if encoding: decoder = self.decoders[encoding] # fail if not found data = decoder(data) encoding = 'utf-8' m = CHARSET.search(content_type) if m: encoding = m.group(1) try: data = data.decode(encoding) except UnicodeError: data = data.decode('latin-1') # fallback result = Page(data, final_url) self._page_cache[final_url] = result except HTTPError as e: if e.code != 404: logger.exception('Fetch failed: %s: %s', url, e) except URLError as e: logger.exception('Fetch failed: %s: %s', url, e) with self._lock: self._bad_hosts.add(host) except Exception as e: logger.exception('Fetch failed: %s: %s', url, e) finally: self._page_cache[url] = result # even if None (failure) return result
python
def get_page(self, url): """ Get the HTML for an URL, possibly from an in-memory cache. XXX TODO Note: this cache is never actually cleared. It's assumed that the data won't get stale over the lifetime of a locator instance (not necessarily true for the default_locator). """ # http://peak.telecommunity.com/DevCenter/EasyInstall#package-index-api scheme, netloc, path, _, _, _ = urlparse(url) if scheme == 'file' and os.path.isdir(url2pathname(path)): url = urljoin(ensure_slash(url), 'index.html') if url in self._page_cache: result = self._page_cache[url] logger.debug('Returning %s from cache: %s', url, result) else: host = netloc.split(':', 1)[0] result = None if host in self._bad_hosts: logger.debug('Skipping %s due to bad host %s', url, host) else: req = Request(url, headers={'Accept-encoding': 'identity'}) try: logger.debug('Fetching %s', url) resp = self.opener.open(req, timeout=self.timeout) logger.debug('Fetched %s', url) headers = resp.info() content_type = headers.get('Content-Type', '') if HTML_CONTENT_TYPE.match(content_type): final_url = resp.geturl() data = resp.read() encoding = headers.get('Content-Encoding') if encoding: decoder = self.decoders[encoding] # fail if not found data = decoder(data) encoding = 'utf-8' m = CHARSET.search(content_type) if m: encoding = m.group(1) try: data = data.decode(encoding) except UnicodeError: data = data.decode('latin-1') # fallback result = Page(data, final_url) self._page_cache[final_url] = result except HTTPError as e: if e.code != 404: logger.exception('Fetch failed: %s: %s', url, e) except URLError as e: logger.exception('Fetch failed: %s: %s', url, e) with self._lock: self._bad_hosts.add(host) except Exception as e: logger.exception('Fetch failed: %s: %s', url, e) finally: self._page_cache[url] = result # even if None (failure) return result
[ "def", "get_page", "(", "self", ",", "url", ")", ":", "# http://peak.telecommunity.com/DevCenter/EasyInstall#package-index-api", "scheme", ",", "netloc", ",", "path", ",", "_", ",", "_", ",", "_", "=", "urlparse", "(", "url", ")", "if", "scheme", "==", "'file'", "and", "os", ".", "path", ".", "isdir", "(", "url2pathname", "(", "path", ")", ")", ":", "url", "=", "urljoin", "(", "ensure_slash", "(", "url", ")", ",", "'index.html'", ")", "if", "url", "in", "self", ".", "_page_cache", ":", "result", "=", "self", ".", "_page_cache", "[", "url", "]", "logger", ".", "debug", "(", "'Returning %s from cache: %s'", ",", "url", ",", "result", ")", "else", ":", "host", "=", "netloc", ".", "split", "(", "':'", ",", "1", ")", "[", "0", "]", "result", "=", "None", "if", "host", "in", "self", ".", "_bad_hosts", ":", "logger", ".", "debug", "(", "'Skipping %s due to bad host %s'", ",", "url", ",", "host", ")", "else", ":", "req", "=", "Request", "(", "url", ",", "headers", "=", "{", "'Accept-encoding'", ":", "'identity'", "}", ")", "try", ":", "logger", ".", "debug", "(", "'Fetching %s'", ",", "url", ")", "resp", "=", "self", ".", "opener", ".", "open", "(", "req", ",", "timeout", "=", "self", ".", "timeout", ")", "logger", ".", "debug", "(", "'Fetched %s'", ",", "url", ")", "headers", "=", "resp", ".", "info", "(", ")", "content_type", "=", "headers", ".", "get", "(", "'Content-Type'", ",", "''", ")", "if", "HTML_CONTENT_TYPE", ".", "match", "(", "content_type", ")", ":", "final_url", "=", "resp", ".", "geturl", "(", ")", "data", "=", "resp", ".", "read", "(", ")", "encoding", "=", "headers", ".", "get", "(", "'Content-Encoding'", ")", "if", "encoding", ":", "decoder", "=", "self", ".", "decoders", "[", "encoding", "]", "# fail if not found", "data", "=", "decoder", "(", "data", ")", "encoding", "=", "'utf-8'", "m", "=", "CHARSET", ".", "search", "(", "content_type", ")", "if", "m", ":", "encoding", "=", "m", ".", "group", "(", "1", ")", "try", ":", "data", "=", "data", ".", "decode", "(", "encoding", ")", "except", "UnicodeError", ":", "data", "=", "data", ".", "decode", "(", "'latin-1'", ")", "# fallback", "result", "=", "Page", "(", "data", ",", "final_url", ")", "self", ".", "_page_cache", "[", "final_url", "]", "=", "result", "except", "HTTPError", "as", "e", ":", "if", "e", ".", "code", "!=", "404", ":", "logger", ".", "exception", "(", "'Fetch failed: %s: %s'", ",", "url", ",", "e", ")", "except", "URLError", "as", "e", ":", "logger", ".", "exception", "(", "'Fetch failed: %s: %s'", ",", "url", ",", "e", ")", "with", "self", ".", "_lock", ":", "self", ".", "_bad_hosts", ".", "add", "(", "host", ")", "except", "Exception", "as", "e", ":", "logger", ".", "exception", "(", "'Fetch failed: %s: %s'", ",", "url", ",", "e", ")", "finally", ":", "self", ".", "_page_cache", "[", "url", "]", "=", "result", "# even if None (failure)", "return", "result" ]
Get the HTML for an URL, possibly from an in-memory cache. XXX TODO Note: this cache is never actually cleared. It's assumed that the data won't get stale over the lifetime of a locator instance (not necessarily true for the default_locator).
[ "Get", "the", "HTML", "for", "an", "URL", "possibly", "from", "an", "in", "-", "memory", "cache", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/build_utils/distlib/locators.py#L673-L730
232,405
nerdvegas/rez
src/rez/package_search.py
get_reverse_dependency_tree
def get_reverse_dependency_tree(package_name, depth=None, paths=None, build_requires=False, private_build_requires=False): """Find packages that depend on the given package. This is a reverse dependency lookup. A tree is constructed, showing what packages depend on the given package, with an optional depth limit. A resolve does not occur. Only the latest version of each package is used, and requirements from all variants of that package are used. Args: package_name (str): Name of the package depended on. depth (int): Tree depth limit, unlimited if None. paths (list of str): paths to search for packages, defaults to `config.packages_path`. build_requires (bool): If True, includes packages' build_requires. private_build_requires (bool): If True, include `package_name`'s private_build_requires. Returns: A 2-tuple: - (list of list of str): Lists of package names, where each list is a single depth in the tree. The first list is always [`package_name`]. - `pygraph.digraph` object, where nodes are package names, and `package_name` is always the leaf node. """ pkgs_list = [[package_name]] g = digraph() g.add_node(package_name) # build reverse lookup it = iter_package_families(paths) package_names = set(x.name for x in it) if package_name not in package_names: raise PackageFamilyNotFoundError("No such package family %r" % package_name) if depth == 0: return pkgs_list, g bar = ProgressBar("Searching", len(package_names)) lookup = defaultdict(set) for i, package_name_ in enumerate(package_names): it = iter_packages(name=package_name_, paths=paths) packages = list(it) if not packages: continue pkg = max(packages, key=lambda x: x.version) requires = [] for variant in pkg.iter_variants(): pbr = (private_build_requires and pkg.name == package_name) requires += variant.get_requires( build_requires=build_requires, private_build_requires=pbr ) for req in requires: if not req.conflict: lookup[req.name].add(package_name_) bar.next() bar.finish() # perform traversal n = 0 consumed = set([package_name]) working_set = set([package_name]) node_color = "#F6F6F6" node_fontsize = 10 node_attrs = [("fillcolor", node_color), ("style", "filled"), ("fontsize", node_fontsize)] while working_set and (depth is None or n < depth): working_set_ = set() for child in working_set: parents = lookup[child] - consumed working_set_.update(parents) consumed.update(parents) for parent in parents: g.add_node(parent, attrs=node_attrs) g.add_edge((parent, child)) if working_set_: pkgs_list.append(sorted(list(working_set_))) working_set = working_set_ n += 1 return pkgs_list, g
python
def get_reverse_dependency_tree(package_name, depth=None, paths=None, build_requires=False, private_build_requires=False): """Find packages that depend on the given package. This is a reverse dependency lookup. A tree is constructed, showing what packages depend on the given package, with an optional depth limit. A resolve does not occur. Only the latest version of each package is used, and requirements from all variants of that package are used. Args: package_name (str): Name of the package depended on. depth (int): Tree depth limit, unlimited if None. paths (list of str): paths to search for packages, defaults to `config.packages_path`. build_requires (bool): If True, includes packages' build_requires. private_build_requires (bool): If True, include `package_name`'s private_build_requires. Returns: A 2-tuple: - (list of list of str): Lists of package names, where each list is a single depth in the tree. The first list is always [`package_name`]. - `pygraph.digraph` object, where nodes are package names, and `package_name` is always the leaf node. """ pkgs_list = [[package_name]] g = digraph() g.add_node(package_name) # build reverse lookup it = iter_package_families(paths) package_names = set(x.name for x in it) if package_name not in package_names: raise PackageFamilyNotFoundError("No such package family %r" % package_name) if depth == 0: return pkgs_list, g bar = ProgressBar("Searching", len(package_names)) lookup = defaultdict(set) for i, package_name_ in enumerate(package_names): it = iter_packages(name=package_name_, paths=paths) packages = list(it) if not packages: continue pkg = max(packages, key=lambda x: x.version) requires = [] for variant in pkg.iter_variants(): pbr = (private_build_requires and pkg.name == package_name) requires += variant.get_requires( build_requires=build_requires, private_build_requires=pbr ) for req in requires: if not req.conflict: lookup[req.name].add(package_name_) bar.next() bar.finish() # perform traversal n = 0 consumed = set([package_name]) working_set = set([package_name]) node_color = "#F6F6F6" node_fontsize = 10 node_attrs = [("fillcolor", node_color), ("style", "filled"), ("fontsize", node_fontsize)] while working_set and (depth is None or n < depth): working_set_ = set() for child in working_set: parents = lookup[child] - consumed working_set_.update(parents) consumed.update(parents) for parent in parents: g.add_node(parent, attrs=node_attrs) g.add_edge((parent, child)) if working_set_: pkgs_list.append(sorted(list(working_set_))) working_set = working_set_ n += 1 return pkgs_list, g
[ "def", "get_reverse_dependency_tree", "(", "package_name", ",", "depth", "=", "None", ",", "paths", "=", "None", ",", "build_requires", "=", "False", ",", "private_build_requires", "=", "False", ")", ":", "pkgs_list", "=", "[", "[", "package_name", "]", "]", "g", "=", "digraph", "(", ")", "g", ".", "add_node", "(", "package_name", ")", "# build reverse lookup", "it", "=", "iter_package_families", "(", "paths", ")", "package_names", "=", "set", "(", "x", ".", "name", "for", "x", "in", "it", ")", "if", "package_name", "not", "in", "package_names", ":", "raise", "PackageFamilyNotFoundError", "(", "\"No such package family %r\"", "%", "package_name", ")", "if", "depth", "==", "0", ":", "return", "pkgs_list", ",", "g", "bar", "=", "ProgressBar", "(", "\"Searching\"", ",", "len", "(", "package_names", ")", ")", "lookup", "=", "defaultdict", "(", "set", ")", "for", "i", ",", "package_name_", "in", "enumerate", "(", "package_names", ")", ":", "it", "=", "iter_packages", "(", "name", "=", "package_name_", ",", "paths", "=", "paths", ")", "packages", "=", "list", "(", "it", ")", "if", "not", "packages", ":", "continue", "pkg", "=", "max", "(", "packages", ",", "key", "=", "lambda", "x", ":", "x", ".", "version", ")", "requires", "=", "[", "]", "for", "variant", "in", "pkg", ".", "iter_variants", "(", ")", ":", "pbr", "=", "(", "private_build_requires", "and", "pkg", ".", "name", "==", "package_name", ")", "requires", "+=", "variant", ".", "get_requires", "(", "build_requires", "=", "build_requires", ",", "private_build_requires", "=", "pbr", ")", "for", "req", "in", "requires", ":", "if", "not", "req", ".", "conflict", ":", "lookup", "[", "req", ".", "name", "]", ".", "add", "(", "package_name_", ")", "bar", ".", "next", "(", ")", "bar", ".", "finish", "(", ")", "# perform traversal", "n", "=", "0", "consumed", "=", "set", "(", "[", "package_name", "]", ")", "working_set", "=", "set", "(", "[", "package_name", "]", ")", "node_color", "=", "\"#F6F6F6\"", "node_fontsize", "=", "10", "node_attrs", "=", "[", "(", "\"fillcolor\"", ",", "node_color", ")", ",", "(", "\"style\"", ",", "\"filled\"", ")", ",", "(", "\"fontsize\"", ",", "node_fontsize", ")", "]", "while", "working_set", "and", "(", "depth", "is", "None", "or", "n", "<", "depth", ")", ":", "working_set_", "=", "set", "(", ")", "for", "child", "in", "working_set", ":", "parents", "=", "lookup", "[", "child", "]", "-", "consumed", "working_set_", ".", "update", "(", "parents", ")", "consumed", ".", "update", "(", "parents", ")", "for", "parent", "in", "parents", ":", "g", ".", "add_node", "(", "parent", ",", "attrs", "=", "node_attrs", ")", "g", ".", "add_edge", "(", "(", "parent", ",", "child", ")", ")", "if", "working_set_", ":", "pkgs_list", ".", "append", "(", "sorted", "(", "list", "(", "working_set_", ")", ")", ")", "working_set", "=", "working_set_", "n", "+=", "1", "return", "pkgs_list", ",", "g" ]
Find packages that depend on the given package. This is a reverse dependency lookup. A tree is constructed, showing what packages depend on the given package, with an optional depth limit. A resolve does not occur. Only the latest version of each package is used, and requirements from all variants of that package are used. Args: package_name (str): Name of the package depended on. depth (int): Tree depth limit, unlimited if None. paths (list of str): paths to search for packages, defaults to `config.packages_path`. build_requires (bool): If True, includes packages' build_requires. private_build_requires (bool): If True, include `package_name`'s private_build_requires. Returns: A 2-tuple: - (list of list of str): Lists of package names, where each list is a single depth in the tree. The first list is always [`package_name`]. - `pygraph.digraph` object, where nodes are package names, and `package_name` is always the leaf node.
[ "Find", "packages", "that", "depend", "on", "the", "given", "package", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_search.py#L25-L121
232,406
nerdvegas/rez
src/rez/package_search.py
get_plugins
def get_plugins(package_name, paths=None): """Find packages that are plugins of the given package. Args: package_name (str): Name of the package. paths (list of str): Paths to search for packages, defaults to `config.packages_path`. Returns: list of str: The packages that are plugins of the given package. """ pkg = get_latest_package(package_name, paths=paths, error=True) if not pkg.has_plugins: return [] it = iter_package_families(paths) package_names = set(x.name for x in it) bar = ProgressBar("Searching", len(package_names)) plugin_pkgs = [] for package_name_ in package_names: bar.next() if package_name_ == package_name: continue # not a plugin of itself plugin_pkg = get_latest_package(package_name_, paths=paths) if not plugin_pkg.plugin_for: continue for plugin_for in plugin_pkg.plugin_for: if plugin_for == pkg.name: plugin_pkgs.append(package_name_) bar.finish() return plugin_pkgs
python
def get_plugins(package_name, paths=None): """Find packages that are plugins of the given package. Args: package_name (str): Name of the package. paths (list of str): Paths to search for packages, defaults to `config.packages_path`. Returns: list of str: The packages that are plugins of the given package. """ pkg = get_latest_package(package_name, paths=paths, error=True) if not pkg.has_plugins: return [] it = iter_package_families(paths) package_names = set(x.name for x in it) bar = ProgressBar("Searching", len(package_names)) plugin_pkgs = [] for package_name_ in package_names: bar.next() if package_name_ == package_name: continue # not a plugin of itself plugin_pkg = get_latest_package(package_name_, paths=paths) if not plugin_pkg.plugin_for: continue for plugin_for in plugin_pkg.plugin_for: if plugin_for == pkg.name: plugin_pkgs.append(package_name_) bar.finish() return plugin_pkgs
[ "def", "get_plugins", "(", "package_name", ",", "paths", "=", "None", ")", ":", "pkg", "=", "get_latest_package", "(", "package_name", ",", "paths", "=", "paths", ",", "error", "=", "True", ")", "if", "not", "pkg", ".", "has_plugins", ":", "return", "[", "]", "it", "=", "iter_package_families", "(", "paths", ")", "package_names", "=", "set", "(", "x", ".", "name", "for", "x", "in", "it", ")", "bar", "=", "ProgressBar", "(", "\"Searching\"", ",", "len", "(", "package_names", ")", ")", "plugin_pkgs", "=", "[", "]", "for", "package_name_", "in", "package_names", ":", "bar", ".", "next", "(", ")", "if", "package_name_", "==", "package_name", ":", "continue", "# not a plugin of itself", "plugin_pkg", "=", "get_latest_package", "(", "package_name_", ",", "paths", "=", "paths", ")", "if", "not", "plugin_pkg", ".", "plugin_for", ":", "continue", "for", "plugin_for", "in", "plugin_pkg", ".", "plugin_for", ":", "if", "plugin_for", "==", "pkg", ".", "name", ":", "plugin_pkgs", ".", "append", "(", "package_name_", ")", "bar", ".", "finish", "(", ")", "return", "plugin_pkgs" ]
Find packages that are plugins of the given package. Args: package_name (str): Name of the package. paths (list of str): Paths to search for packages, defaults to `config.packages_path`. Returns: list of str: The packages that are plugins of the given package.
[ "Find", "packages", "that", "are", "plugins", "of", "the", "given", "package", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_search.py#L124-L157
232,407
nerdvegas/rez
src/rez/package_search.py
ResourceSearcher.search
def search(self, resources_request=None): """Search for resources. Args: resources_request (str): Resource to search, glob-style patterns are supported. If None, returns all matching resource types. Returns: 2-tuple: - str: resource type (family, package, variant); - List of `ResourceSearchResult`: Matching resources. Will be in alphabetical order if families, and version ascending for packages or variants. """ # Find matching package families name_pattern, version_range = self._parse_request(resources_request) family_names = set( x.name for x in iter_package_families(paths=self.package_paths) if fnmatch.fnmatch(x.name, name_pattern) ) family_names = sorted(family_names) # determine what type of resource we're searching for if self.resource_type: resource_type = self.resource_type elif version_range or len(family_names) == 1: resource_type = "package" else: resource_type = "family" if not family_names: return resource_type, [] # return list of family names (validation is n/a in this case) if resource_type == "family": results = [ResourceSearchResult(x, "family") for x in family_names] return "family", results results = [] # iterate over packages/variants for name in family_names: it = iter_packages(name, version_range, paths=self.package_paths) packages = sorted(it, key=lambda x: x.version) if self.latest and packages: packages = [packages[-1]] for package in packages: # validate and check time (accessing timestamp may cause # validation fail) try: if package.timestamp: if self.after_time and package.timestamp < self.after_time: continue if self.before_time and package.timestamp >= self.before_time: continue if self.validate: package.validate_data() except ResourceContentError as e: if resource_type == "package": result = ResourceSearchResult(package, "package", str(e)) results.append(result) continue if resource_type == "package": result = ResourceSearchResult(package, "package") results.append(result) continue # iterate variants try: for variant in package.iter_variants(): if self.validate: try: variant.validate_data() except ResourceContentError as e: result = ResourceSearchResult( variant, "variant", str(e)) results.append(result) continue result = ResourceSearchResult(variant, "variant") results.append(result) except ResourceContentError: # this may happen if 'variants' in package is malformed continue return resource_type, results
python
def search(self, resources_request=None): """Search for resources. Args: resources_request (str): Resource to search, glob-style patterns are supported. If None, returns all matching resource types. Returns: 2-tuple: - str: resource type (family, package, variant); - List of `ResourceSearchResult`: Matching resources. Will be in alphabetical order if families, and version ascending for packages or variants. """ # Find matching package families name_pattern, version_range = self._parse_request(resources_request) family_names = set( x.name for x in iter_package_families(paths=self.package_paths) if fnmatch.fnmatch(x.name, name_pattern) ) family_names = sorted(family_names) # determine what type of resource we're searching for if self.resource_type: resource_type = self.resource_type elif version_range or len(family_names) == 1: resource_type = "package" else: resource_type = "family" if not family_names: return resource_type, [] # return list of family names (validation is n/a in this case) if resource_type == "family": results = [ResourceSearchResult(x, "family") for x in family_names] return "family", results results = [] # iterate over packages/variants for name in family_names: it = iter_packages(name, version_range, paths=self.package_paths) packages = sorted(it, key=lambda x: x.version) if self.latest and packages: packages = [packages[-1]] for package in packages: # validate and check time (accessing timestamp may cause # validation fail) try: if package.timestamp: if self.after_time and package.timestamp < self.after_time: continue if self.before_time and package.timestamp >= self.before_time: continue if self.validate: package.validate_data() except ResourceContentError as e: if resource_type == "package": result = ResourceSearchResult(package, "package", str(e)) results.append(result) continue if resource_type == "package": result = ResourceSearchResult(package, "package") results.append(result) continue # iterate variants try: for variant in package.iter_variants(): if self.validate: try: variant.validate_data() except ResourceContentError as e: result = ResourceSearchResult( variant, "variant", str(e)) results.append(result) continue result = ResourceSearchResult(variant, "variant") results.append(result) except ResourceContentError: # this may happen if 'variants' in package is malformed continue return resource_type, results
[ "def", "search", "(", "self", ",", "resources_request", "=", "None", ")", ":", "# Find matching package families", "name_pattern", ",", "version_range", "=", "self", ".", "_parse_request", "(", "resources_request", ")", "family_names", "=", "set", "(", "x", ".", "name", "for", "x", "in", "iter_package_families", "(", "paths", "=", "self", ".", "package_paths", ")", "if", "fnmatch", ".", "fnmatch", "(", "x", ".", "name", ",", "name_pattern", ")", ")", "family_names", "=", "sorted", "(", "family_names", ")", "# determine what type of resource we're searching for", "if", "self", ".", "resource_type", ":", "resource_type", "=", "self", ".", "resource_type", "elif", "version_range", "or", "len", "(", "family_names", ")", "==", "1", ":", "resource_type", "=", "\"package\"", "else", ":", "resource_type", "=", "\"family\"", "if", "not", "family_names", ":", "return", "resource_type", ",", "[", "]", "# return list of family names (validation is n/a in this case)", "if", "resource_type", "==", "\"family\"", ":", "results", "=", "[", "ResourceSearchResult", "(", "x", ",", "\"family\"", ")", "for", "x", "in", "family_names", "]", "return", "\"family\"", ",", "results", "results", "=", "[", "]", "# iterate over packages/variants", "for", "name", "in", "family_names", ":", "it", "=", "iter_packages", "(", "name", ",", "version_range", ",", "paths", "=", "self", ".", "package_paths", ")", "packages", "=", "sorted", "(", "it", ",", "key", "=", "lambda", "x", ":", "x", ".", "version", ")", "if", "self", ".", "latest", "and", "packages", ":", "packages", "=", "[", "packages", "[", "-", "1", "]", "]", "for", "package", "in", "packages", ":", "# validate and check time (accessing timestamp may cause", "# validation fail)", "try", ":", "if", "package", ".", "timestamp", ":", "if", "self", ".", "after_time", "and", "package", ".", "timestamp", "<", "self", ".", "after_time", ":", "continue", "if", "self", ".", "before_time", "and", "package", ".", "timestamp", ">=", "self", ".", "before_time", ":", "continue", "if", "self", ".", "validate", ":", "package", ".", "validate_data", "(", ")", "except", "ResourceContentError", "as", "e", ":", "if", "resource_type", "==", "\"package\"", ":", "result", "=", "ResourceSearchResult", "(", "package", ",", "\"package\"", ",", "str", "(", "e", ")", ")", "results", ".", "append", "(", "result", ")", "continue", "if", "resource_type", "==", "\"package\"", ":", "result", "=", "ResourceSearchResult", "(", "package", ",", "\"package\"", ")", "results", ".", "append", "(", "result", ")", "continue", "# iterate variants", "try", ":", "for", "variant", "in", "package", ".", "iter_variants", "(", ")", ":", "if", "self", ".", "validate", ":", "try", ":", "variant", ".", "validate_data", "(", ")", "except", "ResourceContentError", "as", "e", ":", "result", "=", "ResourceSearchResult", "(", "variant", ",", "\"variant\"", ",", "str", "(", "e", ")", ")", "results", ".", "append", "(", "result", ")", "continue", "result", "=", "ResourceSearchResult", "(", "variant", ",", "\"variant\"", ")", "results", ".", "append", "(", "result", ")", "except", "ResourceContentError", ":", "# this may happen if 'variants' in package is malformed", "continue", "return", "resource_type", ",", "results" ]
Search for resources. Args: resources_request (str): Resource to search, glob-style patterns are supported. If None, returns all matching resource types. Returns: 2-tuple: - str: resource type (family, package, variant); - List of `ResourceSearchResult`: Matching resources. Will be in alphabetical order if families, and version ascending for packages or variants.
[ "Search", "for", "resources", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_search.py#L210-L305
232,408
nerdvegas/rez
src/rez/package_search.py
ResourceSearchResultFormatter.print_search_results
def print_search_results(self, search_results, buf=sys.stdout): """Print formatted search results. Args: search_results (list of `ResourceSearchResult`): Search to format. """ formatted_lines = self.format_search_results(search_results) pr = Printer(buf) for txt, style in formatted_lines: pr(txt, style)
python
def print_search_results(self, search_results, buf=sys.stdout): """Print formatted search results. Args: search_results (list of `ResourceSearchResult`): Search to format. """ formatted_lines = self.format_search_results(search_results) pr = Printer(buf) for txt, style in formatted_lines: pr(txt, style)
[ "def", "print_search_results", "(", "self", ",", "search_results", ",", "buf", "=", "sys", ".", "stdout", ")", ":", "formatted_lines", "=", "self", ".", "format_search_results", "(", "search_results", ")", "pr", "=", "Printer", "(", "buf", ")", "for", "txt", ",", "style", "in", "formatted_lines", ":", "pr", "(", "txt", ",", "style", ")" ]
Print formatted search results. Args: search_results (list of `ResourceSearchResult`): Search to format.
[ "Print", "formatted", "search", "results", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_search.py#L347-L357
232,409
nerdvegas/rez
src/rez/package_search.py
ResourceSearchResultFormatter.format_search_results
def format_search_results(self, search_results): """Format search results. Args: search_results (list of `ResourceSearchResult`): Search to format. Returns: List of 2-tuple: Text and color to print in. """ formatted_lines = [] for search_result in search_results: lines = self._format_search_result(search_result) formatted_lines.extend(lines) return formatted_lines
python
def format_search_results(self, search_results): """Format search results. Args: search_results (list of `ResourceSearchResult`): Search to format. Returns: List of 2-tuple: Text and color to print in. """ formatted_lines = [] for search_result in search_results: lines = self._format_search_result(search_result) formatted_lines.extend(lines) return formatted_lines
[ "def", "format_search_results", "(", "self", ",", "search_results", ")", ":", "formatted_lines", "=", "[", "]", "for", "search_result", "in", "search_results", ":", "lines", "=", "self", ".", "_format_search_result", "(", "search_result", ")", "formatted_lines", ".", "extend", "(", "lines", ")", "return", "formatted_lines" ]
Format search results. Args: search_results (list of `ResourceSearchResult`): Search to format. Returns: List of 2-tuple: Text and color to print in.
[ "Format", "search", "results", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_search.py#L359-L374
232,410
nerdvegas/rez
src/rez/vendor/pygraph/readwrite/dot.py
read
def read(string): """ Read a graph from a string in Dot language and return it. Nodes and edges specified in the input will be added to the current graph. @type string: string @param string: Input string in Dot format specifying a graph. @rtype: graph @return: Graph """ dotG = pydot.graph_from_dot_data(string) if (dotG.get_type() == "graph"): G = graph() elif (dotG.get_type() == "digraph"): G = digraph() elif (dotG.get_type() == "hypergraph"): return read_hypergraph(string) else: raise InvalidGraphType # Read nodes... # Note: If the nodes aren't explicitly listed, they need to be for each_node in dotG.get_nodes(): G.add_node(each_node.get_name()) for each_attr_key, each_attr_val in each_node.get_attributes().items(): G.add_node_attribute(each_node.get_name(), (each_attr_key, each_attr_val)) # Read edges... for each_edge in dotG.get_edges(): # Check if the nodes have been added if not G.has_node(each_edge.get_source()): G.add_node(each_edge.get_source()) if not G.has_node(each_edge.get_destination()): G.add_node(each_edge.get_destination()) # See if there's a weight if 'weight' in each_edge.get_attributes().keys(): _wt = each_edge.get_attributes()['weight'] else: _wt = 1 # See if there is a label if 'label' in each_edge.get_attributes().keys(): _label = each_edge.get_attributes()['label'] else: _label = '' G.add_edge((each_edge.get_source(), each_edge.get_destination()), wt = _wt, label = _label) for each_attr_key, each_attr_val in each_edge.get_attributes().items(): if not each_attr_key in ['weight', 'label']: G.add_edge_attribute((each_edge.get_source(), each_edge.get_destination()), \ (each_attr_key, each_attr_val)) return G
python
def read(string): """ Read a graph from a string in Dot language and return it. Nodes and edges specified in the input will be added to the current graph. @type string: string @param string: Input string in Dot format specifying a graph. @rtype: graph @return: Graph """ dotG = pydot.graph_from_dot_data(string) if (dotG.get_type() == "graph"): G = graph() elif (dotG.get_type() == "digraph"): G = digraph() elif (dotG.get_type() == "hypergraph"): return read_hypergraph(string) else: raise InvalidGraphType # Read nodes... # Note: If the nodes aren't explicitly listed, they need to be for each_node in dotG.get_nodes(): G.add_node(each_node.get_name()) for each_attr_key, each_attr_val in each_node.get_attributes().items(): G.add_node_attribute(each_node.get_name(), (each_attr_key, each_attr_val)) # Read edges... for each_edge in dotG.get_edges(): # Check if the nodes have been added if not G.has_node(each_edge.get_source()): G.add_node(each_edge.get_source()) if not G.has_node(each_edge.get_destination()): G.add_node(each_edge.get_destination()) # See if there's a weight if 'weight' in each_edge.get_attributes().keys(): _wt = each_edge.get_attributes()['weight'] else: _wt = 1 # See if there is a label if 'label' in each_edge.get_attributes().keys(): _label = each_edge.get_attributes()['label'] else: _label = '' G.add_edge((each_edge.get_source(), each_edge.get_destination()), wt = _wt, label = _label) for each_attr_key, each_attr_val in each_edge.get_attributes().items(): if not each_attr_key in ['weight', 'label']: G.add_edge_attribute((each_edge.get_source(), each_edge.get_destination()), \ (each_attr_key, each_attr_val)) return G
[ "def", "read", "(", "string", ")", ":", "dotG", "=", "pydot", ".", "graph_from_dot_data", "(", "string", ")", "if", "(", "dotG", ".", "get_type", "(", ")", "==", "\"graph\"", ")", ":", "G", "=", "graph", "(", ")", "elif", "(", "dotG", ".", "get_type", "(", ")", "==", "\"digraph\"", ")", ":", "G", "=", "digraph", "(", ")", "elif", "(", "dotG", ".", "get_type", "(", ")", "==", "\"hypergraph\"", ")", ":", "return", "read_hypergraph", "(", "string", ")", "else", ":", "raise", "InvalidGraphType", "# Read nodes...", "# Note: If the nodes aren't explicitly listed, they need to be", "for", "each_node", "in", "dotG", ".", "get_nodes", "(", ")", ":", "G", ".", "add_node", "(", "each_node", ".", "get_name", "(", ")", ")", "for", "each_attr_key", ",", "each_attr_val", "in", "each_node", ".", "get_attributes", "(", ")", ".", "items", "(", ")", ":", "G", ".", "add_node_attribute", "(", "each_node", ".", "get_name", "(", ")", ",", "(", "each_attr_key", ",", "each_attr_val", ")", ")", "# Read edges...", "for", "each_edge", "in", "dotG", ".", "get_edges", "(", ")", ":", "# Check if the nodes have been added", "if", "not", "G", ".", "has_node", "(", "each_edge", ".", "get_source", "(", ")", ")", ":", "G", ".", "add_node", "(", "each_edge", ".", "get_source", "(", ")", ")", "if", "not", "G", ".", "has_node", "(", "each_edge", ".", "get_destination", "(", ")", ")", ":", "G", ".", "add_node", "(", "each_edge", ".", "get_destination", "(", ")", ")", "# See if there's a weight", "if", "'weight'", "in", "each_edge", ".", "get_attributes", "(", ")", ".", "keys", "(", ")", ":", "_wt", "=", "each_edge", ".", "get_attributes", "(", ")", "[", "'weight'", "]", "else", ":", "_wt", "=", "1", "# See if there is a label", "if", "'label'", "in", "each_edge", ".", "get_attributes", "(", ")", ".", "keys", "(", ")", ":", "_label", "=", "each_edge", ".", "get_attributes", "(", ")", "[", "'label'", "]", "else", ":", "_label", "=", "''", "G", ".", "add_edge", "(", "(", "each_edge", ".", "get_source", "(", ")", ",", "each_edge", ".", "get_destination", "(", ")", ")", ",", "wt", "=", "_wt", ",", "label", "=", "_label", ")", "for", "each_attr_key", ",", "each_attr_val", "in", "each_edge", ".", "get_attributes", "(", ")", ".", "items", "(", ")", ":", "if", "not", "each_attr_key", "in", "[", "'weight'", ",", "'label'", "]", ":", "G", ".", "add_edge_attribute", "(", "(", "each_edge", ".", "get_source", "(", ")", ",", "each_edge", ".", "get_destination", "(", ")", ")", ",", "(", "each_attr_key", ",", "each_attr_val", ")", ")", "return", "G" ]
Read a graph from a string in Dot language and return it. Nodes and edges specified in the input will be added to the current graph. @type string: string @param string: Input string in Dot format specifying a graph. @rtype: graph @return: Graph
[ "Read", "a", "graph", "from", "a", "string", "in", "Dot", "language", "and", "return", "it", ".", "Nodes", "and", "edges", "specified", "in", "the", "input", "will", "be", "added", "to", "the", "current", "graph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/readwrite/dot.py#L47-L104
232,411
nerdvegas/rez
src/rez/vendor/pygraph/readwrite/dot.py
read_hypergraph
def read_hypergraph(string): """ Read a hypergraph from a string in dot format. Nodes and edges specified in the input will be added to the current hypergraph. @type string: string @param string: Input string in dot format specifying a graph. @rtype: hypergraph @return: Hypergraph """ hgr = hypergraph() dotG = pydot.graph_from_dot_data(string) # Read the hypernode nodes... # Note 1: We need to assume that all of the nodes are listed since we need to know if they # are a hyperedge or a normal node # Note 2: We should read in all of the nodes before putting in the links for each_node in dotG.get_nodes(): if 'hypernode' == each_node.get('hyper_node_type'): hgr.add_node(each_node.get_name()) elif 'hyperedge' == each_node.get('hyper_node_type'): hgr.add_hyperedge(each_node.get_name()) # Now read in the links to connect the hyperedges for each_link in dotG.get_edges(): if hgr.has_node(each_link.get_source()): link_hypernode = each_link.get_source() link_hyperedge = each_link.get_destination() elif hgr.has_node(each_link.get_destination()): link_hypernode = each_link.get_destination() link_hyperedge = each_link.get_source() hgr.link(link_hypernode, link_hyperedge) return hgr
python
def read_hypergraph(string): """ Read a hypergraph from a string in dot format. Nodes and edges specified in the input will be added to the current hypergraph. @type string: string @param string: Input string in dot format specifying a graph. @rtype: hypergraph @return: Hypergraph """ hgr = hypergraph() dotG = pydot.graph_from_dot_data(string) # Read the hypernode nodes... # Note 1: We need to assume that all of the nodes are listed since we need to know if they # are a hyperedge or a normal node # Note 2: We should read in all of the nodes before putting in the links for each_node in dotG.get_nodes(): if 'hypernode' == each_node.get('hyper_node_type'): hgr.add_node(each_node.get_name()) elif 'hyperedge' == each_node.get('hyper_node_type'): hgr.add_hyperedge(each_node.get_name()) # Now read in the links to connect the hyperedges for each_link in dotG.get_edges(): if hgr.has_node(each_link.get_source()): link_hypernode = each_link.get_source() link_hyperedge = each_link.get_destination() elif hgr.has_node(each_link.get_destination()): link_hypernode = each_link.get_destination() link_hyperedge = each_link.get_source() hgr.link(link_hypernode, link_hyperedge) return hgr
[ "def", "read_hypergraph", "(", "string", ")", ":", "hgr", "=", "hypergraph", "(", ")", "dotG", "=", "pydot", ".", "graph_from_dot_data", "(", "string", ")", "# Read the hypernode nodes...", "# Note 1: We need to assume that all of the nodes are listed since we need to know if they", "# are a hyperedge or a normal node", "# Note 2: We should read in all of the nodes before putting in the links", "for", "each_node", "in", "dotG", ".", "get_nodes", "(", ")", ":", "if", "'hypernode'", "==", "each_node", ".", "get", "(", "'hyper_node_type'", ")", ":", "hgr", ".", "add_node", "(", "each_node", ".", "get_name", "(", ")", ")", "elif", "'hyperedge'", "==", "each_node", ".", "get", "(", "'hyper_node_type'", ")", ":", "hgr", ".", "add_hyperedge", "(", "each_node", ".", "get_name", "(", ")", ")", "# Now read in the links to connect the hyperedges", "for", "each_link", "in", "dotG", ".", "get_edges", "(", ")", ":", "if", "hgr", ".", "has_node", "(", "each_link", ".", "get_source", "(", ")", ")", ":", "link_hypernode", "=", "each_link", ".", "get_source", "(", ")", "link_hyperedge", "=", "each_link", ".", "get_destination", "(", ")", "elif", "hgr", ".", "has_node", "(", "each_link", ".", "get_destination", "(", ")", ")", ":", "link_hypernode", "=", "each_link", ".", "get_destination", "(", ")", "link_hyperedge", "=", "each_link", ".", "get_source", "(", ")", "hgr", ".", "link", "(", "link_hypernode", ",", "link_hyperedge", ")", "return", "hgr" ]
Read a hypergraph from a string in dot format. Nodes and edges specified in the input will be added to the current hypergraph. @type string: string @param string: Input string in dot format specifying a graph. @rtype: hypergraph @return: Hypergraph
[ "Read", "a", "hypergraph", "from", "a", "string", "in", "dot", "format", ".", "Nodes", "and", "edges", "specified", "in", "the", "input", "will", "be", "added", "to", "the", "current", "hypergraph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/readwrite/dot.py#L179-L213
232,412
nerdvegas/rez
src/rez/vendor/pydot/pydot.py
graph_from_dot_file
def graph_from_dot_file(path): """Load graph as defined by a DOT file. The file is assumed to be in DOT format. It will be loaded, parsed and a Dot class will be returned, representing the graph. """ fd = file(path, 'rb') data = fd.read() fd.close() return graph_from_dot_data(data)
python
def graph_from_dot_file(path): """Load graph as defined by a DOT file. The file is assumed to be in DOT format. It will be loaded, parsed and a Dot class will be returned, representing the graph. """ fd = file(path, 'rb') data = fd.read() fd.close() return graph_from_dot_data(data)
[ "def", "graph_from_dot_file", "(", "path", ")", ":", "fd", "=", "file", "(", "path", ",", "'rb'", ")", "data", "=", "fd", ".", "read", "(", ")", "fd", ".", "close", "(", ")", "return", "graph_from_dot_data", "(", "data", ")" ]
Load graph as defined by a DOT file. The file is assumed to be in DOT format. It will be loaded, parsed and a Dot class will be returned, representing the graph.
[ "Load", "graph", "as", "defined", "by", "a", "DOT", "file", ".", "The", "file", "is", "assumed", "to", "be", "in", "DOT", "format", ".", "It", "will", "be", "loaded", "parsed", "and", "a", "Dot", "class", "will", "be", "returned", "representing", "the", "graph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pydot/pydot.py#L220-L232
232,413
nerdvegas/rez
src/rez/vendor/pydot/pydot.py
__find_executables
def __find_executables(path): """Used by find_graphviz path - single directory as a string If any of the executables are found, it will return a dictionary containing the program names as keys and their paths as values. Otherwise returns None """ success = False progs = {'dot': '', 'twopi': '', 'neato': '', 'circo': '', 'fdp': '', 'sfdp': ''} was_quoted = False path = path.strip() if path.startswith('"') and path.endswith('"'): path = path[1:-1] was_quoted = True if os.path.isdir(path) : for prg in progs.iterkeys(): if progs[prg]: continue if os.path.exists( os.path.join(path, prg) ): if was_quoted: progs[prg] = '"' + os.path.join(path, prg) + '"' else: progs[prg] = os.path.join(path, prg) success = True elif os.path.exists( os.path.join(path, prg + '.exe') ): if was_quoted: progs[prg] = '"' + os.path.join(path, prg + '.exe') + '"' else: progs[prg] = os.path.join(path, prg + '.exe') success = True if success: return progs else: return None
python
def __find_executables(path): """Used by find_graphviz path - single directory as a string If any of the executables are found, it will return a dictionary containing the program names as keys and their paths as values. Otherwise returns None """ success = False progs = {'dot': '', 'twopi': '', 'neato': '', 'circo': '', 'fdp': '', 'sfdp': ''} was_quoted = False path = path.strip() if path.startswith('"') and path.endswith('"'): path = path[1:-1] was_quoted = True if os.path.isdir(path) : for prg in progs.iterkeys(): if progs[prg]: continue if os.path.exists( os.path.join(path, prg) ): if was_quoted: progs[prg] = '"' + os.path.join(path, prg) + '"' else: progs[prg] = os.path.join(path, prg) success = True elif os.path.exists( os.path.join(path, prg + '.exe') ): if was_quoted: progs[prg] = '"' + os.path.join(path, prg + '.exe') + '"' else: progs[prg] = os.path.join(path, prg + '.exe') success = True if success: return progs else: return None
[ "def", "__find_executables", "(", "path", ")", ":", "success", "=", "False", "progs", "=", "{", "'dot'", ":", "''", ",", "'twopi'", ":", "''", ",", "'neato'", ":", "''", ",", "'circo'", ":", "''", ",", "'fdp'", ":", "''", ",", "'sfdp'", ":", "''", "}", "was_quoted", "=", "False", "path", "=", "path", ".", "strip", "(", ")", "if", "path", ".", "startswith", "(", "'\"'", ")", "and", "path", ".", "endswith", "(", "'\"'", ")", ":", "path", "=", "path", "[", "1", ":", "-", "1", "]", "was_quoted", "=", "True", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "for", "prg", "in", "progs", ".", "iterkeys", "(", ")", ":", "if", "progs", "[", "prg", "]", ":", "continue", "if", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "path", ",", "prg", ")", ")", ":", "if", "was_quoted", ":", "progs", "[", "prg", "]", "=", "'\"'", "+", "os", ".", "path", ".", "join", "(", "path", ",", "prg", ")", "+", "'\"'", "else", ":", "progs", "[", "prg", "]", "=", "os", ".", "path", ".", "join", "(", "path", ",", "prg", ")", "success", "=", "True", "elif", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "path", ",", "prg", "+", "'.exe'", ")", ")", ":", "if", "was_quoted", ":", "progs", "[", "prg", "]", "=", "'\"'", "+", "os", ".", "path", ".", "join", "(", "path", ",", "prg", "+", "'.exe'", ")", "+", "'\"'", "else", ":", "progs", "[", "prg", "]", "=", "os", ".", "path", ".", "join", "(", "path", ",", "prg", "+", "'.exe'", ")", "success", "=", "True", "if", "success", ":", "return", "progs", "else", ":", "return", "None" ]
Used by find_graphviz path - single directory as a string If any of the executables are found, it will return a dictionary containing the program names as keys and their paths as values. Otherwise returns None
[ "Used", "by", "find_graphviz", "path", "-", "single", "directory", "as", "a", "string", "If", "any", "of", "the", "executables", "are", "found", "it", "will", "return", "a", "dictionary", "containing", "the", "program", "names", "as", "keys", "and", "their", "paths", "as", "values", ".", "Otherwise", "returns", "None" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pydot/pydot.py#L347-L398
232,414
nerdvegas/rez
src/rez/vendor/pydot/pydot.py
Edge.to_string
def to_string(self): """Returns a string representation of the edge in dot language. """ src = self.parse_node_ref( self.get_source() ) dst = self.parse_node_ref( self.get_destination() ) if isinstance(src, frozendict): edge = [ Subgraph(obj_dict=src).to_string() ] elif isinstance(src, (int, long)): edge = [ str(src) ] else: edge = [ src ] if (self.get_parent_graph() and self.get_parent_graph().get_top_graph_type() and self.get_parent_graph().get_top_graph_type() == 'digraph' ): edge.append( '->' ) else: edge.append( '--' ) if isinstance(dst, frozendict): edge.append( Subgraph(obj_dict=dst).to_string() ) elif isinstance(dst, (int, long)): edge.append( str(dst) ) else: edge.append( dst ) edge_attr = list() for attr, value in self.obj_dict['attributes'].iteritems(): if value is not None: edge_attr.append( '%s=%s' % (attr, quote_if_necessary(value) ) ) else: edge_attr.append( attr ) edge_attr = ', '.join(edge_attr) if edge_attr: edge.append( ' [' + edge_attr + ']' ) return ' '.join(edge) + ';'
python
def to_string(self): """Returns a string representation of the edge in dot language. """ src = self.parse_node_ref( self.get_source() ) dst = self.parse_node_ref( self.get_destination() ) if isinstance(src, frozendict): edge = [ Subgraph(obj_dict=src).to_string() ] elif isinstance(src, (int, long)): edge = [ str(src) ] else: edge = [ src ] if (self.get_parent_graph() and self.get_parent_graph().get_top_graph_type() and self.get_parent_graph().get_top_graph_type() == 'digraph' ): edge.append( '->' ) else: edge.append( '--' ) if isinstance(dst, frozendict): edge.append( Subgraph(obj_dict=dst).to_string() ) elif isinstance(dst, (int, long)): edge.append( str(dst) ) else: edge.append( dst ) edge_attr = list() for attr, value in self.obj_dict['attributes'].iteritems(): if value is not None: edge_attr.append( '%s=%s' % (attr, quote_if_necessary(value) ) ) else: edge_attr.append( attr ) edge_attr = ', '.join(edge_attr) if edge_attr: edge.append( ' [' + edge_attr + ']' ) return ' '.join(edge) + ';'
[ "def", "to_string", "(", "self", ")", ":", "src", "=", "self", ".", "parse_node_ref", "(", "self", ".", "get_source", "(", ")", ")", "dst", "=", "self", ".", "parse_node_ref", "(", "self", ".", "get_destination", "(", ")", ")", "if", "isinstance", "(", "src", ",", "frozendict", ")", ":", "edge", "=", "[", "Subgraph", "(", "obj_dict", "=", "src", ")", ".", "to_string", "(", ")", "]", "elif", "isinstance", "(", "src", ",", "(", "int", ",", "long", ")", ")", ":", "edge", "=", "[", "str", "(", "src", ")", "]", "else", ":", "edge", "=", "[", "src", "]", "if", "(", "self", ".", "get_parent_graph", "(", ")", "and", "self", ".", "get_parent_graph", "(", ")", ".", "get_top_graph_type", "(", ")", "and", "self", ".", "get_parent_graph", "(", ")", ".", "get_top_graph_type", "(", ")", "==", "'digraph'", ")", ":", "edge", ".", "append", "(", "'->'", ")", "else", ":", "edge", ".", "append", "(", "'--'", ")", "if", "isinstance", "(", "dst", ",", "frozendict", ")", ":", "edge", ".", "append", "(", "Subgraph", "(", "obj_dict", "=", "dst", ")", ".", "to_string", "(", ")", ")", "elif", "isinstance", "(", "dst", ",", "(", "int", ",", "long", ")", ")", ":", "edge", ".", "append", "(", "str", "(", "dst", ")", ")", "else", ":", "edge", ".", "append", "(", "dst", ")", "edge_attr", "=", "list", "(", ")", "for", "attr", ",", "value", "in", "self", ".", "obj_dict", "[", "'attributes'", "]", ".", "iteritems", "(", ")", ":", "if", "value", "is", "not", "None", ":", "edge_attr", ".", "append", "(", "'%s=%s'", "%", "(", "attr", ",", "quote_if_necessary", "(", "value", ")", ")", ")", "else", ":", "edge_attr", ".", "append", "(", "attr", ")", "edge_attr", "=", "', '", ".", "join", "(", "edge_attr", ")", "if", "edge_attr", ":", "edge", ".", "append", "(", "' ['", "+", "edge_attr", "+", "']'", ")", "return", "' '", ".", "join", "(", "edge", ")", "+", "';'" ]
Returns a string representation of the edge in dot language.
[ "Returns", "a", "string", "representation", "of", "the", "edge", "in", "dot", "language", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pydot/pydot.py#L974-L1019
232,415
nerdvegas/rez
src/rez/vendor/pydot/pydot.py
Graph.get_node
def get_node(self, name): """Retrieve a node from the graph. Given a node's name the corresponding Node instance will be returned. If one or more nodes exist with that name a list of Node instances is returned. An empty list is returned otherwise. """ match = list() if self.obj_dict['nodes'].has_key(name): match.extend( [ Node( obj_dict = obj_dict ) for obj_dict in self.obj_dict['nodes'][name] ]) return match
python
def get_node(self, name): """Retrieve a node from the graph. Given a node's name the corresponding Node instance will be returned. If one or more nodes exist with that name a list of Node instances is returned. An empty list is returned otherwise. """ match = list() if self.obj_dict['nodes'].has_key(name): match.extend( [ Node( obj_dict = obj_dict ) for obj_dict in self.obj_dict['nodes'][name] ]) return match
[ "def", "get_node", "(", "self", ",", "name", ")", ":", "match", "=", "list", "(", ")", "if", "self", ".", "obj_dict", "[", "'nodes'", "]", ".", "has_key", "(", "name", ")", ":", "match", ".", "extend", "(", "[", "Node", "(", "obj_dict", "=", "obj_dict", ")", "for", "obj_dict", "in", "self", ".", "obj_dict", "[", "'nodes'", "]", "[", "name", "]", "]", ")", "return", "match" ]
Retrieve a node from the graph. Given a node's name the corresponding Node instance will be returned. If one or more nodes exist with that name a list of Node instances is returned. An empty list is returned otherwise.
[ "Retrieve", "a", "node", "from", "the", "graph", ".", "Given", "a", "node", "s", "name", "the", "corresponding", "Node", "instance", "will", "be", "returned", ".", "If", "one", "or", "more", "nodes", "exist", "with", "that", "name", "a", "list", "of", "Node", "instances", "is", "returned", ".", "An", "empty", "list", "is", "returned", "otherwise", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pydot/pydot.py#L1323-L1340
232,416
nerdvegas/rez
src/rez/vendor/pydot/pydot.py
Graph.add_edge
def add_edge(self, graph_edge): """Adds an edge object to the graph. It takes a edge object as its only argument and returns None. """ if not isinstance(graph_edge, Edge): raise TypeError('add_edge() received a non edge class object: ' + str(graph_edge)) edge_points = ( graph_edge.get_source(), graph_edge.get_destination() ) if self.obj_dict['edges'].has_key(edge_points): edge_list = self.obj_dict['edges'][edge_points] edge_list.append(graph_edge.obj_dict) else: self.obj_dict['edges'][edge_points] = [ graph_edge.obj_dict ] graph_edge.set_sequence( self.get_next_sequence_number() ) graph_edge.set_parent_graph( self.get_parent_graph() )
python
def add_edge(self, graph_edge): """Adds an edge object to the graph. It takes a edge object as its only argument and returns None. """ if not isinstance(graph_edge, Edge): raise TypeError('add_edge() received a non edge class object: ' + str(graph_edge)) edge_points = ( graph_edge.get_source(), graph_edge.get_destination() ) if self.obj_dict['edges'].has_key(edge_points): edge_list = self.obj_dict['edges'][edge_points] edge_list.append(graph_edge.obj_dict) else: self.obj_dict['edges'][edge_points] = [ graph_edge.obj_dict ] graph_edge.set_sequence( self.get_next_sequence_number() ) graph_edge.set_parent_graph( self.get_parent_graph() )
[ "def", "add_edge", "(", "self", ",", "graph_edge", ")", ":", "if", "not", "isinstance", "(", "graph_edge", ",", "Edge", ")", ":", "raise", "TypeError", "(", "'add_edge() received a non edge class object: '", "+", "str", "(", "graph_edge", ")", ")", "edge_points", "=", "(", "graph_edge", ".", "get_source", "(", ")", ",", "graph_edge", ".", "get_destination", "(", ")", ")", "if", "self", ".", "obj_dict", "[", "'edges'", "]", ".", "has_key", "(", "edge_points", ")", ":", "edge_list", "=", "self", ".", "obj_dict", "[", "'edges'", "]", "[", "edge_points", "]", "edge_list", ".", "append", "(", "graph_edge", ".", "obj_dict", ")", "else", ":", "self", ".", "obj_dict", "[", "'edges'", "]", "[", "edge_points", "]", "=", "[", "graph_edge", ".", "obj_dict", "]", "graph_edge", ".", "set_sequence", "(", "self", ".", "get_next_sequence_number", "(", ")", ")", "graph_edge", ".", "set_parent_graph", "(", "self", ".", "get_parent_graph", "(", ")", ")" ]
Adds an edge object to the graph. It takes a edge object as its only argument and returns None.
[ "Adds", "an", "edge", "object", "to", "the", "graph", ".", "It", "takes", "a", "edge", "object", "as", "its", "only", "argument", "and", "returns", "None", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pydot/pydot.py#L1365-L1389
232,417
nerdvegas/rez
src/rez/vendor/pydot/pydot.py
Graph.add_subgraph
def add_subgraph(self, sgraph): """Adds an subgraph object to the graph. It takes a subgraph object as its only argument and returns None. """ if not isinstance(sgraph, Subgraph) and not isinstance(sgraph, Cluster): raise TypeError('add_subgraph() received a non subgraph class object:' + str(sgraph)) if self.obj_dict['subgraphs'].has_key(sgraph.get_name()): sgraph_list = self.obj_dict['subgraphs'][ sgraph.get_name() ] sgraph_list.append( sgraph.obj_dict ) else: self.obj_dict['subgraphs'][ sgraph.get_name() ] = [ sgraph.obj_dict ] sgraph.set_sequence( self.get_next_sequence_number() ) sgraph.set_parent_graph( self.get_parent_graph() )
python
def add_subgraph(self, sgraph): """Adds an subgraph object to the graph. It takes a subgraph object as its only argument and returns None. """ if not isinstance(sgraph, Subgraph) and not isinstance(sgraph, Cluster): raise TypeError('add_subgraph() received a non subgraph class object:' + str(sgraph)) if self.obj_dict['subgraphs'].has_key(sgraph.get_name()): sgraph_list = self.obj_dict['subgraphs'][ sgraph.get_name() ] sgraph_list.append( sgraph.obj_dict ) else: self.obj_dict['subgraphs'][ sgraph.get_name() ] = [ sgraph.obj_dict ] sgraph.set_sequence( self.get_next_sequence_number() ) sgraph.set_parent_graph( self.get_parent_graph() )
[ "def", "add_subgraph", "(", "self", ",", "sgraph", ")", ":", "if", "not", "isinstance", "(", "sgraph", ",", "Subgraph", ")", "and", "not", "isinstance", "(", "sgraph", ",", "Cluster", ")", ":", "raise", "TypeError", "(", "'add_subgraph() received a non subgraph class object:'", "+", "str", "(", "sgraph", ")", ")", "if", "self", ".", "obj_dict", "[", "'subgraphs'", "]", ".", "has_key", "(", "sgraph", ".", "get_name", "(", ")", ")", ":", "sgraph_list", "=", "self", ".", "obj_dict", "[", "'subgraphs'", "]", "[", "sgraph", ".", "get_name", "(", ")", "]", "sgraph_list", ".", "append", "(", "sgraph", ".", "obj_dict", ")", "else", ":", "self", ".", "obj_dict", "[", "'subgraphs'", "]", "[", "sgraph", ".", "get_name", "(", ")", "]", "=", "[", "sgraph", ".", "obj_dict", "]", "sgraph", ".", "set_sequence", "(", "self", ".", "get_next_sequence_number", "(", ")", ")", "sgraph", ".", "set_parent_graph", "(", "self", ".", "get_parent_graph", "(", ")", ")" ]
Adds an subgraph object to the graph. It takes a subgraph object as its only argument and returns None.
[ "Adds", "an", "subgraph", "object", "to", "the", "graph", ".", "It", "takes", "a", "subgraph", "object", "as", "its", "only", "argument", "and", "returns", "None", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pydot/pydot.py#L1488-L1508
232,418
nerdvegas/rez
src/rez/vendor/pydot/pydot.py
Graph.to_string
def to_string(self): """Returns a string representation of the graph in dot language. It will return the graph and all its subelements in string from. """ graph = list() if self.obj_dict.get('strict', None) is not None: if self==self.get_parent_graph() and self.obj_dict['strict']: graph.append('strict ') if self.obj_dict['name'] == '': if 'show_keyword' in self.obj_dict and self.obj_dict['show_keyword']: graph.append( 'subgraph {\n' ) else: graph.append( '{\n' ) else: graph.append( '%s %s {\n' % (self.obj_dict['type'], self.obj_dict['name']) ) for attr in self.obj_dict['attributes'].iterkeys(): if self.obj_dict['attributes'].get(attr, None) is not None: val = self.obj_dict['attributes'].get(attr) if val is not None: graph.append( '%s=%s' % (attr, quote_if_necessary(val)) ) else: graph.append( attr ) graph.append( ';\n' ) edges_done = set() edge_obj_dicts = list() for e in self.obj_dict['edges'].itervalues(): edge_obj_dicts.extend(e) if edge_obj_dicts: edge_src_set, edge_dst_set = zip( *[obj['points'] for obj in edge_obj_dicts] ) edge_src_set, edge_dst_set = set(edge_src_set), set(edge_dst_set) else: edge_src_set, edge_dst_set = set(), set() node_obj_dicts = list() for e in self.obj_dict['nodes'].itervalues(): node_obj_dicts.extend(e) sgraph_obj_dicts = list() for sg in self.obj_dict['subgraphs'].itervalues(): sgraph_obj_dicts.extend(sg) obj_list = [ (obj['sequence'], obj) for obj in (edge_obj_dicts + node_obj_dicts + sgraph_obj_dicts) ] obj_list.sort() for idx, obj in obj_list: if obj['type'] == 'node': node = Node(obj_dict=obj) if self.obj_dict.get('suppress_disconnected', False): if (node.get_name() not in edge_src_set and node.get_name() not in edge_dst_set): continue graph.append( node.to_string()+'\n' ) elif obj['type'] == 'edge': edge = Edge(obj_dict=obj) if self.obj_dict.get('simplify', False) and edge in edges_done: continue graph.append( edge.to_string() + '\n' ) edges_done.add(edge) else: sgraph = Subgraph(obj_dict=obj) graph.append( sgraph.to_string()+'\n' ) graph.append( '}\n' ) return ''.join(graph)
python
def to_string(self): """Returns a string representation of the graph in dot language. It will return the graph and all its subelements in string from. """ graph = list() if self.obj_dict.get('strict', None) is not None: if self==self.get_parent_graph() and self.obj_dict['strict']: graph.append('strict ') if self.obj_dict['name'] == '': if 'show_keyword' in self.obj_dict and self.obj_dict['show_keyword']: graph.append( 'subgraph {\n' ) else: graph.append( '{\n' ) else: graph.append( '%s %s {\n' % (self.obj_dict['type'], self.obj_dict['name']) ) for attr in self.obj_dict['attributes'].iterkeys(): if self.obj_dict['attributes'].get(attr, None) is not None: val = self.obj_dict['attributes'].get(attr) if val is not None: graph.append( '%s=%s' % (attr, quote_if_necessary(val)) ) else: graph.append( attr ) graph.append( ';\n' ) edges_done = set() edge_obj_dicts = list() for e in self.obj_dict['edges'].itervalues(): edge_obj_dicts.extend(e) if edge_obj_dicts: edge_src_set, edge_dst_set = zip( *[obj['points'] for obj in edge_obj_dicts] ) edge_src_set, edge_dst_set = set(edge_src_set), set(edge_dst_set) else: edge_src_set, edge_dst_set = set(), set() node_obj_dicts = list() for e in self.obj_dict['nodes'].itervalues(): node_obj_dicts.extend(e) sgraph_obj_dicts = list() for sg in self.obj_dict['subgraphs'].itervalues(): sgraph_obj_dicts.extend(sg) obj_list = [ (obj['sequence'], obj) for obj in (edge_obj_dicts + node_obj_dicts + sgraph_obj_dicts) ] obj_list.sort() for idx, obj in obj_list: if obj['type'] == 'node': node = Node(obj_dict=obj) if self.obj_dict.get('suppress_disconnected', False): if (node.get_name() not in edge_src_set and node.get_name() not in edge_dst_set): continue graph.append( node.to_string()+'\n' ) elif obj['type'] == 'edge': edge = Edge(obj_dict=obj) if self.obj_dict.get('simplify', False) and edge in edges_done: continue graph.append( edge.to_string() + '\n' ) edges_done.add(edge) else: sgraph = Subgraph(obj_dict=obj) graph.append( sgraph.to_string()+'\n' ) graph.append( '}\n' ) return ''.join(graph)
[ "def", "to_string", "(", "self", ")", ":", "graph", "=", "list", "(", ")", "if", "self", ".", "obj_dict", ".", "get", "(", "'strict'", ",", "None", ")", "is", "not", "None", ":", "if", "self", "==", "self", ".", "get_parent_graph", "(", ")", "and", "self", ".", "obj_dict", "[", "'strict'", "]", ":", "graph", ".", "append", "(", "'strict '", ")", "if", "self", ".", "obj_dict", "[", "'name'", "]", "==", "''", ":", "if", "'show_keyword'", "in", "self", ".", "obj_dict", "and", "self", ".", "obj_dict", "[", "'show_keyword'", "]", ":", "graph", ".", "append", "(", "'subgraph {\\n'", ")", "else", ":", "graph", ".", "append", "(", "'{\\n'", ")", "else", ":", "graph", ".", "append", "(", "'%s %s {\\n'", "%", "(", "self", ".", "obj_dict", "[", "'type'", "]", ",", "self", ".", "obj_dict", "[", "'name'", "]", ")", ")", "for", "attr", "in", "self", ".", "obj_dict", "[", "'attributes'", "]", ".", "iterkeys", "(", ")", ":", "if", "self", ".", "obj_dict", "[", "'attributes'", "]", ".", "get", "(", "attr", ",", "None", ")", "is", "not", "None", ":", "val", "=", "self", ".", "obj_dict", "[", "'attributes'", "]", ".", "get", "(", "attr", ")", "if", "val", "is", "not", "None", ":", "graph", ".", "append", "(", "'%s=%s'", "%", "(", "attr", ",", "quote_if_necessary", "(", "val", ")", ")", ")", "else", ":", "graph", ".", "append", "(", "attr", ")", "graph", ".", "append", "(", "';\\n'", ")", "edges_done", "=", "set", "(", ")", "edge_obj_dicts", "=", "list", "(", ")", "for", "e", "in", "self", ".", "obj_dict", "[", "'edges'", "]", ".", "itervalues", "(", ")", ":", "edge_obj_dicts", ".", "extend", "(", "e", ")", "if", "edge_obj_dicts", ":", "edge_src_set", ",", "edge_dst_set", "=", "zip", "(", "*", "[", "obj", "[", "'points'", "]", "for", "obj", "in", "edge_obj_dicts", "]", ")", "edge_src_set", ",", "edge_dst_set", "=", "set", "(", "edge_src_set", ")", ",", "set", "(", "edge_dst_set", ")", "else", ":", "edge_src_set", ",", "edge_dst_set", "=", "set", "(", ")", ",", "set", "(", ")", "node_obj_dicts", "=", "list", "(", ")", "for", "e", "in", "self", ".", "obj_dict", "[", "'nodes'", "]", ".", "itervalues", "(", ")", ":", "node_obj_dicts", ".", "extend", "(", "e", ")", "sgraph_obj_dicts", "=", "list", "(", ")", "for", "sg", "in", "self", ".", "obj_dict", "[", "'subgraphs'", "]", ".", "itervalues", "(", ")", ":", "sgraph_obj_dicts", ".", "extend", "(", "sg", ")", "obj_list", "=", "[", "(", "obj", "[", "'sequence'", "]", ",", "obj", ")", "for", "obj", "in", "(", "edge_obj_dicts", "+", "node_obj_dicts", "+", "sgraph_obj_dicts", ")", "]", "obj_list", ".", "sort", "(", ")", "for", "idx", ",", "obj", "in", "obj_list", ":", "if", "obj", "[", "'type'", "]", "==", "'node'", ":", "node", "=", "Node", "(", "obj_dict", "=", "obj", ")", "if", "self", ".", "obj_dict", ".", "get", "(", "'suppress_disconnected'", ",", "False", ")", ":", "if", "(", "node", ".", "get_name", "(", ")", "not", "in", "edge_src_set", "and", "node", ".", "get_name", "(", ")", "not", "in", "edge_dst_set", ")", ":", "continue", "graph", ".", "append", "(", "node", ".", "to_string", "(", ")", "+", "'\\n'", ")", "elif", "obj", "[", "'type'", "]", "==", "'edge'", ":", "edge", "=", "Edge", "(", "obj_dict", "=", "obj", ")", "if", "self", ".", "obj_dict", ".", "get", "(", "'simplify'", ",", "False", ")", "and", "edge", "in", "edges_done", ":", "continue", "graph", ".", "append", "(", "edge", ".", "to_string", "(", ")", "+", "'\\n'", ")", "edges_done", ".", "add", "(", "edge", ")", "else", ":", "sgraph", "=", "Subgraph", "(", "obj_dict", "=", "obj", ")", "graph", ".", "append", "(", "sgraph", ".", "to_string", "(", ")", "+", "'\\n'", ")", "graph", ".", "append", "(", "'}\\n'", ")", "return", "''", ".", "join", "(", "graph", ")" ]
Returns a string representation of the graph in dot language. It will return the graph and all its subelements in string from.
[ "Returns", "a", "string", "representation", "of", "the", "graph", "in", "dot", "language", ".", "It", "will", "return", "the", "graph", "and", "all", "its", "subelements", "in", "string", "from", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pydot/pydot.py#L1576-L1670
232,419
nerdvegas/rez
src/rez/vendor/pydot/pydot.py
Dot.create
def create(self, prog=None, format='ps'): """Creates and returns a Postscript representation of the graph. create will write the graph to a temporary dot file and process it with the program given by 'prog' (which defaults to 'twopi'), reading the Postscript output and returning it as a string is the operation is successful. On failure None is returned. There's also the preferred possibility of using: create_'format'(prog='program') which are automatically defined for all the supported formats. [create_ps(), create_gif(), create_dia(), ...] If 'prog' is a list instead of a string the fist item is expected to be the program name, followed by any optional command-line arguments for it: [ 'twopi', '-Tdot', '-s10' ] """ if prog is None: prog = self.prog if isinstance(prog, (list, tuple)): prog, args = prog[0], prog[1:] else: args = [] if self.progs is None: self.progs = find_graphviz() if self.progs is None: raise InvocationException( 'GraphViz\'s executables not found' ) if not self.progs.has_key(prog): raise InvocationException( 'GraphViz\'s executable "%s" not found' % prog ) if not os.path.exists( self.progs[prog] ) or not os.path.isfile( self.progs[prog] ): raise InvocationException( 'GraphViz\'s executable "%s" is not a file or doesn\'t exist' % self.progs[prog] ) tmp_fd, tmp_name = tempfile.mkstemp() os.close(tmp_fd) self.write(tmp_name) tmp_dir = os.path.dirname(tmp_name ) # For each of the image files... # for img in self.shape_files: # Get its data # f = file(img, 'rb') f_data = f.read() f.close() # And copy it under a file with the same name in the temporary directory # f = file( os.path.join( tmp_dir, os.path.basename(img) ), 'wb' ) f.write(f_data) f.close() cmdline = [self.progs[prog], '-T'+format, tmp_name] + args p = subprocess.Popen( cmdline, cwd=tmp_dir, stderr=subprocess.PIPE, stdout=subprocess.PIPE) stderr = p.stderr stdout = p.stdout stdout_output = list() while True: data = stdout.read() if not data: break stdout_output.append(data) stdout.close() stdout_output = ''.join(stdout_output) if not stderr.closed: stderr_output = list() while True: data = stderr.read() if not data: break stderr_output.append(data) stderr.close() if stderr_output: stderr_output = ''.join(stderr_output) #pid, status = os.waitpid(p.pid, 0) status = p.wait() if status != 0 : raise InvocationException( 'Program terminated with status: %d. stderr follows: %s' % ( status, stderr_output) ) elif stderr_output: print stderr_output # For each of the image files... # for img in self.shape_files: # remove it # os.unlink( os.path.join( tmp_dir, os.path.basename(img) ) ) os.unlink(tmp_name) return stdout_output
python
def create(self, prog=None, format='ps'): """Creates and returns a Postscript representation of the graph. create will write the graph to a temporary dot file and process it with the program given by 'prog' (which defaults to 'twopi'), reading the Postscript output and returning it as a string is the operation is successful. On failure None is returned. There's also the preferred possibility of using: create_'format'(prog='program') which are automatically defined for all the supported formats. [create_ps(), create_gif(), create_dia(), ...] If 'prog' is a list instead of a string the fist item is expected to be the program name, followed by any optional command-line arguments for it: [ 'twopi', '-Tdot', '-s10' ] """ if prog is None: prog = self.prog if isinstance(prog, (list, tuple)): prog, args = prog[0], prog[1:] else: args = [] if self.progs is None: self.progs = find_graphviz() if self.progs is None: raise InvocationException( 'GraphViz\'s executables not found' ) if not self.progs.has_key(prog): raise InvocationException( 'GraphViz\'s executable "%s" not found' % prog ) if not os.path.exists( self.progs[prog] ) or not os.path.isfile( self.progs[prog] ): raise InvocationException( 'GraphViz\'s executable "%s" is not a file or doesn\'t exist' % self.progs[prog] ) tmp_fd, tmp_name = tempfile.mkstemp() os.close(tmp_fd) self.write(tmp_name) tmp_dir = os.path.dirname(tmp_name ) # For each of the image files... # for img in self.shape_files: # Get its data # f = file(img, 'rb') f_data = f.read() f.close() # And copy it under a file with the same name in the temporary directory # f = file( os.path.join( tmp_dir, os.path.basename(img) ), 'wb' ) f.write(f_data) f.close() cmdline = [self.progs[prog], '-T'+format, tmp_name] + args p = subprocess.Popen( cmdline, cwd=tmp_dir, stderr=subprocess.PIPE, stdout=subprocess.PIPE) stderr = p.stderr stdout = p.stdout stdout_output = list() while True: data = stdout.read() if not data: break stdout_output.append(data) stdout.close() stdout_output = ''.join(stdout_output) if not stderr.closed: stderr_output = list() while True: data = stderr.read() if not data: break stderr_output.append(data) stderr.close() if stderr_output: stderr_output = ''.join(stderr_output) #pid, status = os.waitpid(p.pid, 0) status = p.wait() if status != 0 : raise InvocationException( 'Program terminated with status: %d. stderr follows: %s' % ( status, stderr_output) ) elif stderr_output: print stderr_output # For each of the image files... # for img in self.shape_files: # remove it # os.unlink( os.path.join( tmp_dir, os.path.basename(img) ) ) os.unlink(tmp_name) return stdout_output
[ "def", "create", "(", "self", ",", "prog", "=", "None", ",", "format", "=", "'ps'", ")", ":", "if", "prog", "is", "None", ":", "prog", "=", "self", ".", "prog", "if", "isinstance", "(", "prog", ",", "(", "list", ",", "tuple", ")", ")", ":", "prog", ",", "args", "=", "prog", "[", "0", "]", ",", "prog", "[", "1", ":", "]", "else", ":", "args", "=", "[", "]", "if", "self", ".", "progs", "is", "None", ":", "self", ".", "progs", "=", "find_graphviz", "(", ")", "if", "self", ".", "progs", "is", "None", ":", "raise", "InvocationException", "(", "'GraphViz\\'s executables not found'", ")", "if", "not", "self", ".", "progs", ".", "has_key", "(", "prog", ")", ":", "raise", "InvocationException", "(", "'GraphViz\\'s executable \"%s\" not found'", "%", "prog", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "progs", "[", "prog", "]", ")", "or", "not", "os", ".", "path", ".", "isfile", "(", "self", ".", "progs", "[", "prog", "]", ")", ":", "raise", "InvocationException", "(", "'GraphViz\\'s executable \"%s\" is not a file or doesn\\'t exist'", "%", "self", ".", "progs", "[", "prog", "]", ")", "tmp_fd", ",", "tmp_name", "=", "tempfile", ".", "mkstemp", "(", ")", "os", ".", "close", "(", "tmp_fd", ")", "self", ".", "write", "(", "tmp_name", ")", "tmp_dir", "=", "os", ".", "path", ".", "dirname", "(", "tmp_name", ")", "# For each of the image files...", "#", "for", "img", "in", "self", ".", "shape_files", ":", "# Get its data", "#", "f", "=", "file", "(", "img", ",", "'rb'", ")", "f_data", "=", "f", ".", "read", "(", ")", "f", ".", "close", "(", ")", "# And copy it under a file with the same name in the temporary directory", "#", "f", "=", "file", "(", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "os", ".", "path", ".", "basename", "(", "img", ")", ")", ",", "'wb'", ")", "f", ".", "write", "(", "f_data", ")", "f", ".", "close", "(", ")", "cmdline", "=", "[", "self", ".", "progs", "[", "prog", "]", ",", "'-T'", "+", "format", ",", "tmp_name", "]", "+", "args", "p", "=", "subprocess", ".", "Popen", "(", "cmdline", ",", "cwd", "=", "tmp_dir", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "stderr", "=", "p", ".", "stderr", "stdout", "=", "p", ".", "stdout", "stdout_output", "=", "list", "(", ")", "while", "True", ":", "data", "=", "stdout", ".", "read", "(", ")", "if", "not", "data", ":", "break", "stdout_output", ".", "append", "(", "data", ")", "stdout", ".", "close", "(", ")", "stdout_output", "=", "''", ".", "join", "(", "stdout_output", ")", "if", "not", "stderr", ".", "closed", ":", "stderr_output", "=", "list", "(", ")", "while", "True", ":", "data", "=", "stderr", ".", "read", "(", ")", "if", "not", "data", ":", "break", "stderr_output", ".", "append", "(", "data", ")", "stderr", ".", "close", "(", ")", "if", "stderr_output", ":", "stderr_output", "=", "''", ".", "join", "(", "stderr_output", ")", "#pid, status = os.waitpid(p.pid, 0)", "status", "=", "p", ".", "wait", "(", ")", "if", "status", "!=", "0", ":", "raise", "InvocationException", "(", "'Program terminated with status: %d. stderr follows: %s'", "%", "(", "status", ",", "stderr_output", ")", ")", "elif", "stderr_output", ":", "print", "stderr_output", "# For each of the image files...", "#", "for", "img", "in", "self", ".", "shape_files", ":", "# remove it", "#", "os", ".", "unlink", "(", "os", ".", "path", ".", "join", "(", "tmp_dir", ",", "os", ".", "path", ".", "basename", "(", "img", ")", ")", ")", "os", ".", "unlink", "(", "tmp_name", ")", "return", "stdout_output" ]
Creates and returns a Postscript representation of the graph. create will write the graph to a temporary dot file and process it with the program given by 'prog' (which defaults to 'twopi'), reading the Postscript output and returning it as a string is the operation is successful. On failure None is returned. There's also the preferred possibility of using: create_'format'(prog='program') which are automatically defined for all the supported formats. [create_ps(), create_gif(), create_dia(), ...] If 'prog' is a list instead of a string the fist item is expected to be the program name, followed by any optional command-line arguments for it: [ 'twopi', '-Tdot', '-s10' ]
[ "Creates", "and", "returns", "a", "Postscript", "representation", "of", "the", "graph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pydot/pydot.py#L1915-L2034
232,420
nerdvegas/rez
src/rez/utils/yaml.py
dump_yaml
def dump_yaml(data, Dumper=_Dumper, default_flow_style=False): """Returns data as yaml-formatted string.""" content = yaml.dump(data, default_flow_style=default_flow_style, Dumper=Dumper) return content.strip()
python
def dump_yaml(data, Dumper=_Dumper, default_flow_style=False): """Returns data as yaml-formatted string.""" content = yaml.dump(data, default_flow_style=default_flow_style, Dumper=Dumper) return content.strip()
[ "def", "dump_yaml", "(", "data", ",", "Dumper", "=", "_Dumper", ",", "default_flow_style", "=", "False", ")", ":", "content", "=", "yaml", ".", "dump", "(", "data", ",", "default_flow_style", "=", "default_flow_style", ",", "Dumper", "=", "Dumper", ")", "return", "content", ".", "strip", "(", ")" ]
Returns data as yaml-formatted string.
[ "Returns", "data", "as", "yaml", "-", "formatted", "string", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/yaml.py#L64-L69
232,421
nerdvegas/rez
src/rez/utils/yaml.py
load_yaml
def load_yaml(filepath): """Convenience function for loading yaml-encoded data from disk.""" with open(filepath) as f: txt = f.read() return yaml.load(txt)
python
def load_yaml(filepath): """Convenience function for loading yaml-encoded data from disk.""" with open(filepath) as f: txt = f.read() return yaml.load(txt)
[ "def", "load_yaml", "(", "filepath", ")", ":", "with", "open", "(", "filepath", ")", "as", "f", ":", "txt", "=", "f", ".", "read", "(", ")", "return", "yaml", ".", "load", "(", "txt", ")" ]
Convenience function for loading yaml-encoded data from disk.
[ "Convenience", "function", "for", "loading", "yaml", "-", "encoded", "data", "from", "disk", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/yaml.py#L72-L76
232,422
nerdvegas/rez
src/rez/utils/memcached.py
memcached_client
def memcached_client(servers=config.memcached_uri, debug=config.debug_memcache): """Get a shared memcached instance. This function shares the same memcached instance across nested invocations. This is done so that memcached connections can be kept to a minimum, but at the same time unnecessary extra reconnections are avoided. Typically an initial scope (using 'with' construct) is made around parts of code that hit the cache server many times - such as a resolve, or executing a context. On exit of the topmost scope, the memcached client is disconnected. Returns: `Client`: Memcached instance. """ key = None try: client, key = scoped_instance_manager.acquire(servers, debug=debug) yield client finally: if key: scoped_instance_manager.release(key)
python
def memcached_client(servers=config.memcached_uri, debug=config.debug_memcache): """Get a shared memcached instance. This function shares the same memcached instance across nested invocations. This is done so that memcached connections can be kept to a minimum, but at the same time unnecessary extra reconnections are avoided. Typically an initial scope (using 'with' construct) is made around parts of code that hit the cache server many times - such as a resolve, or executing a context. On exit of the topmost scope, the memcached client is disconnected. Returns: `Client`: Memcached instance. """ key = None try: client, key = scoped_instance_manager.acquire(servers, debug=debug) yield client finally: if key: scoped_instance_manager.release(key)
[ "def", "memcached_client", "(", "servers", "=", "config", ".", "memcached_uri", ",", "debug", "=", "config", ".", "debug_memcache", ")", ":", "key", "=", "None", "try", ":", "client", ",", "key", "=", "scoped_instance_manager", ".", "acquire", "(", "servers", ",", "debug", "=", "debug", ")", "yield", "client", "finally", ":", "if", "key", ":", "scoped_instance_manager", ".", "release", "(", "key", ")" ]
Get a shared memcached instance. This function shares the same memcached instance across nested invocations. This is done so that memcached connections can be kept to a minimum, but at the same time unnecessary extra reconnections are avoided. Typically an initial scope (using 'with' construct) is made around parts of code that hit the cache server many times - such as a resolve, or executing a context. On exit of the topmost scope, the memcached client is disconnected. Returns: `Client`: Memcached instance.
[ "Get", "a", "shared", "memcached", "instance", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/memcached.py#L207-L226
232,423
nerdvegas/rez
src/rez/utils/memcached.py
pool_memcached_connections
def pool_memcached_connections(func): """Function decorator to pool memcached connections. Use this to wrap functions that might make multiple calls to memcached. This will cause a single memcached client to be shared for all connections. """ if isgeneratorfunction(func): def wrapper(*nargs, **kwargs): with memcached_client(): for result in func(*nargs, **kwargs): yield result else: def wrapper(*nargs, **kwargs): with memcached_client(): return func(*nargs, **kwargs) return update_wrapper(wrapper, func)
python
def pool_memcached_connections(func): """Function decorator to pool memcached connections. Use this to wrap functions that might make multiple calls to memcached. This will cause a single memcached client to be shared for all connections. """ if isgeneratorfunction(func): def wrapper(*nargs, **kwargs): with memcached_client(): for result in func(*nargs, **kwargs): yield result else: def wrapper(*nargs, **kwargs): with memcached_client(): return func(*nargs, **kwargs) return update_wrapper(wrapper, func)
[ "def", "pool_memcached_connections", "(", "func", ")", ":", "if", "isgeneratorfunction", "(", "func", ")", ":", "def", "wrapper", "(", "*", "nargs", ",", "*", "*", "kwargs", ")", ":", "with", "memcached_client", "(", ")", ":", "for", "result", "in", "func", "(", "*", "nargs", ",", "*", "*", "kwargs", ")", ":", "yield", "result", "else", ":", "def", "wrapper", "(", "*", "nargs", ",", "*", "*", "kwargs", ")", ":", "with", "memcached_client", "(", ")", ":", "return", "func", "(", "*", "nargs", ",", "*", "*", "kwargs", ")", "return", "update_wrapper", "(", "wrapper", ",", "func", ")" ]
Function decorator to pool memcached connections. Use this to wrap functions that might make multiple calls to memcached. This will cause a single memcached client to be shared for all connections.
[ "Function", "decorator", "to", "pool", "memcached", "connections", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/memcached.py#L229-L245
232,424
nerdvegas/rez
src/rez/utils/memcached.py
memcached
def memcached(servers, key=None, from_cache=None, to_cache=None, time=0, min_compress_len=0, debug=False): """memcached memoization function decorator. The wrapped function is expected to return a value that is stored to a memcached server, first translated by `to_cache` if provided. In the event of a cache hit, the data is translated by `from_cache` if provided, before being returned. If you do not want a result to be cached, wrap the return value of your function in a `DoNotCache` object. Example: @memcached('127.0.0.1:11211') def _listdir(path): return os.path.listdir(path) Note: If using the default key function, ensure that repr() is implemented on all your arguments and that they are hashable. Note: `from_cache` and `to_cache` both accept the value as first parameter, then the target function's arguments follow. Args: servers (str or list of str): memcached server uri(s), eg '127.0.0.1:11211'. This arg can be None also, in which case memcaching is disabled. key (callable, optional): Function that, given the target function's args, returns the string key to use in memcached. from_cache (callable, optional): If provided, and a cache hit occurs, the cached value will be translated by this function before being returned. to_cache (callable, optional): If provided, and a cache miss occurs, the function's return value will be translated by this function before being cached. time (int): Tells memcached the time which this value should expire, either as a delta number of seconds, or an absolute unix time-since-the-epoch value. See the memcached protocol docs section "Storage Commands" for more info on <exptime>. We default to 0 == cache forever. min_compress_len (int): The threshold length to kick in auto-compression of the value using the zlib.compress() routine. If the value being cached is a string, then the length of the string is measured, else if the value is an object, then the length of the pickle result is measured. If the resulting attempt at compression yeilds a larger string than the input, then it is discarded. For backwards compatability, this parameter defaults to 0, indicating don't ever try to compress. debug (bool): If True, memcache keys are kept human readable, so you can read them if running a foreground memcached proc with 'memcached -vv'. However this increases chances of key clashes so should not be left turned on. """ def default_key(func, *nargs, **kwargs): parts = [func.__module__] argnames = getargspec(func).args if argnames: if argnames[0] == "cls": cls_ = nargs[0] parts.append(cls_.__name__) nargs = nargs[1:] elif argnames[0] == "self": cls_ = nargs[0].__class__ parts.append(cls_.__name__) nargs = nargs[1:] parts.append(func.__name__) value = ('.'.join(parts), nargs, tuple(sorted(kwargs.items()))) # make sure key is hashable. We don't strictly need it to be, but this # is a way of hopefully avoiding object types that are not ordered (these # would give an unreliable key). If you need to key on unhashable args, # you should provide your own `key` functor. _ = hash(value) return repr(value) def identity(value, *nargs, **kwargs): return value from_cache = from_cache or identity to_cache = to_cache or identity def decorator(func): if servers: def wrapper(*nargs, **kwargs): with memcached_client(servers, debug=debug) as client: if key: cache_key = key(*nargs, **kwargs) else: cache_key = default_key(func, *nargs, **kwargs) # get result = client.get(cache_key) if result is not client.miss: return from_cache(result, *nargs, **kwargs) # cache miss - run target function result = func(*nargs, **kwargs) if isinstance(result, DoNotCache): return result.result # store cache_result = to_cache(result, *nargs, **kwargs) client.set(key=cache_key, val=cache_result, time=time, min_compress_len=min_compress_len) return result else: def wrapper(*nargs, **kwargs): result = func(*nargs, **kwargs) if isinstance(result, DoNotCache): return result.result return result def forget(): """Forget entries in the cache. Note that this does not delete entries from a memcached server - that would be slow and error-prone. Calling this function only ensures that entries set by the current process will no longer be seen during this process. """ with memcached_client(servers, debug=debug) as client: client.flush() wrapper.forget = forget wrapper.__wrapped__ = func return update_wrapper(wrapper, func) return decorator
python
def memcached(servers, key=None, from_cache=None, to_cache=None, time=0, min_compress_len=0, debug=False): """memcached memoization function decorator. The wrapped function is expected to return a value that is stored to a memcached server, first translated by `to_cache` if provided. In the event of a cache hit, the data is translated by `from_cache` if provided, before being returned. If you do not want a result to be cached, wrap the return value of your function in a `DoNotCache` object. Example: @memcached('127.0.0.1:11211') def _listdir(path): return os.path.listdir(path) Note: If using the default key function, ensure that repr() is implemented on all your arguments and that they are hashable. Note: `from_cache` and `to_cache` both accept the value as first parameter, then the target function's arguments follow. Args: servers (str or list of str): memcached server uri(s), eg '127.0.0.1:11211'. This arg can be None also, in which case memcaching is disabled. key (callable, optional): Function that, given the target function's args, returns the string key to use in memcached. from_cache (callable, optional): If provided, and a cache hit occurs, the cached value will be translated by this function before being returned. to_cache (callable, optional): If provided, and a cache miss occurs, the function's return value will be translated by this function before being cached. time (int): Tells memcached the time which this value should expire, either as a delta number of seconds, or an absolute unix time-since-the-epoch value. See the memcached protocol docs section "Storage Commands" for more info on <exptime>. We default to 0 == cache forever. min_compress_len (int): The threshold length to kick in auto-compression of the value using the zlib.compress() routine. If the value being cached is a string, then the length of the string is measured, else if the value is an object, then the length of the pickle result is measured. If the resulting attempt at compression yeilds a larger string than the input, then it is discarded. For backwards compatability, this parameter defaults to 0, indicating don't ever try to compress. debug (bool): If True, memcache keys are kept human readable, so you can read them if running a foreground memcached proc with 'memcached -vv'. However this increases chances of key clashes so should not be left turned on. """ def default_key(func, *nargs, **kwargs): parts = [func.__module__] argnames = getargspec(func).args if argnames: if argnames[0] == "cls": cls_ = nargs[0] parts.append(cls_.__name__) nargs = nargs[1:] elif argnames[0] == "self": cls_ = nargs[0].__class__ parts.append(cls_.__name__) nargs = nargs[1:] parts.append(func.__name__) value = ('.'.join(parts), nargs, tuple(sorted(kwargs.items()))) # make sure key is hashable. We don't strictly need it to be, but this # is a way of hopefully avoiding object types that are not ordered (these # would give an unreliable key). If you need to key on unhashable args, # you should provide your own `key` functor. _ = hash(value) return repr(value) def identity(value, *nargs, **kwargs): return value from_cache = from_cache or identity to_cache = to_cache or identity def decorator(func): if servers: def wrapper(*nargs, **kwargs): with memcached_client(servers, debug=debug) as client: if key: cache_key = key(*nargs, **kwargs) else: cache_key = default_key(func, *nargs, **kwargs) # get result = client.get(cache_key) if result is not client.miss: return from_cache(result, *nargs, **kwargs) # cache miss - run target function result = func(*nargs, **kwargs) if isinstance(result, DoNotCache): return result.result # store cache_result = to_cache(result, *nargs, **kwargs) client.set(key=cache_key, val=cache_result, time=time, min_compress_len=min_compress_len) return result else: def wrapper(*nargs, **kwargs): result = func(*nargs, **kwargs) if isinstance(result, DoNotCache): return result.result return result def forget(): """Forget entries in the cache. Note that this does not delete entries from a memcached server - that would be slow and error-prone. Calling this function only ensures that entries set by the current process will no longer be seen during this process. """ with memcached_client(servers, debug=debug) as client: client.flush() wrapper.forget = forget wrapper.__wrapped__ = func return update_wrapper(wrapper, func) return decorator
[ "def", "memcached", "(", "servers", ",", "key", "=", "None", ",", "from_cache", "=", "None", ",", "to_cache", "=", "None", ",", "time", "=", "0", ",", "min_compress_len", "=", "0", ",", "debug", "=", "False", ")", ":", "def", "default_key", "(", "func", ",", "*", "nargs", ",", "*", "*", "kwargs", ")", ":", "parts", "=", "[", "func", ".", "__module__", "]", "argnames", "=", "getargspec", "(", "func", ")", ".", "args", "if", "argnames", ":", "if", "argnames", "[", "0", "]", "==", "\"cls\"", ":", "cls_", "=", "nargs", "[", "0", "]", "parts", ".", "append", "(", "cls_", ".", "__name__", ")", "nargs", "=", "nargs", "[", "1", ":", "]", "elif", "argnames", "[", "0", "]", "==", "\"self\"", ":", "cls_", "=", "nargs", "[", "0", "]", ".", "__class__", "parts", ".", "append", "(", "cls_", ".", "__name__", ")", "nargs", "=", "nargs", "[", "1", ":", "]", "parts", ".", "append", "(", "func", ".", "__name__", ")", "value", "=", "(", "'.'", ".", "join", "(", "parts", ")", ",", "nargs", ",", "tuple", "(", "sorted", "(", "kwargs", ".", "items", "(", ")", ")", ")", ")", "# make sure key is hashable. We don't strictly need it to be, but this", "# is a way of hopefully avoiding object types that are not ordered (these", "# would give an unreliable key). If you need to key on unhashable args,", "# you should provide your own `key` functor.", "_", "=", "hash", "(", "value", ")", "return", "repr", "(", "value", ")", "def", "identity", "(", "value", ",", "*", "nargs", ",", "*", "*", "kwargs", ")", ":", "return", "value", "from_cache", "=", "from_cache", "or", "identity", "to_cache", "=", "to_cache", "or", "identity", "def", "decorator", "(", "func", ")", ":", "if", "servers", ":", "def", "wrapper", "(", "*", "nargs", ",", "*", "*", "kwargs", ")", ":", "with", "memcached_client", "(", "servers", ",", "debug", "=", "debug", ")", "as", "client", ":", "if", "key", ":", "cache_key", "=", "key", "(", "*", "nargs", ",", "*", "*", "kwargs", ")", "else", ":", "cache_key", "=", "default_key", "(", "func", ",", "*", "nargs", ",", "*", "*", "kwargs", ")", "# get", "result", "=", "client", ".", "get", "(", "cache_key", ")", "if", "result", "is", "not", "client", ".", "miss", ":", "return", "from_cache", "(", "result", ",", "*", "nargs", ",", "*", "*", "kwargs", ")", "# cache miss - run target function", "result", "=", "func", "(", "*", "nargs", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "result", ",", "DoNotCache", ")", ":", "return", "result", ".", "result", "# store", "cache_result", "=", "to_cache", "(", "result", ",", "*", "nargs", ",", "*", "*", "kwargs", ")", "client", ".", "set", "(", "key", "=", "cache_key", ",", "val", "=", "cache_result", ",", "time", "=", "time", ",", "min_compress_len", "=", "min_compress_len", ")", "return", "result", "else", ":", "def", "wrapper", "(", "*", "nargs", ",", "*", "*", "kwargs", ")", ":", "result", "=", "func", "(", "*", "nargs", ",", "*", "*", "kwargs", ")", "if", "isinstance", "(", "result", ",", "DoNotCache", ")", ":", "return", "result", ".", "result", "return", "result", "def", "forget", "(", ")", ":", "\"\"\"Forget entries in the cache.\n\n Note that this does not delete entries from a memcached server - that\n would be slow and error-prone. Calling this function only ensures\n that entries set by the current process will no longer be seen during\n this process.\n \"\"\"", "with", "memcached_client", "(", "servers", ",", "debug", "=", "debug", ")", "as", "client", ":", "client", ".", "flush", "(", ")", "wrapper", ".", "forget", "=", "forget", "wrapper", ".", "__wrapped__", "=", "func", "return", "update_wrapper", "(", "wrapper", ",", "func", ")", "return", "decorator" ]
memcached memoization function decorator. The wrapped function is expected to return a value that is stored to a memcached server, first translated by `to_cache` if provided. In the event of a cache hit, the data is translated by `from_cache` if provided, before being returned. If you do not want a result to be cached, wrap the return value of your function in a `DoNotCache` object. Example: @memcached('127.0.0.1:11211') def _listdir(path): return os.path.listdir(path) Note: If using the default key function, ensure that repr() is implemented on all your arguments and that they are hashable. Note: `from_cache` and `to_cache` both accept the value as first parameter, then the target function's arguments follow. Args: servers (str or list of str): memcached server uri(s), eg '127.0.0.1:11211'. This arg can be None also, in which case memcaching is disabled. key (callable, optional): Function that, given the target function's args, returns the string key to use in memcached. from_cache (callable, optional): If provided, and a cache hit occurs, the cached value will be translated by this function before being returned. to_cache (callable, optional): If provided, and a cache miss occurs, the function's return value will be translated by this function before being cached. time (int): Tells memcached the time which this value should expire, either as a delta number of seconds, or an absolute unix time-since-the-epoch value. See the memcached protocol docs section "Storage Commands" for more info on <exptime>. We default to 0 == cache forever. min_compress_len (int): The threshold length to kick in auto-compression of the value using the zlib.compress() routine. If the value being cached is a string, then the length of the string is measured, else if the value is an object, then the length of the pickle result is measured. If the resulting attempt at compression yeilds a larger string than the input, then it is discarded. For backwards compatability, this parameter defaults to 0, indicating don't ever try to compress. debug (bool): If True, memcache keys are kept human readable, so you can read them if running a foreground memcached proc with 'memcached -vv'. However this increases chances of key clashes so should not be left turned on.
[ "memcached", "memoization", "function", "decorator", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/memcached.py#L248-L375
232,425
nerdvegas/rez
src/rez/utils/memcached.py
Client.client
def client(self): """Get the native memcache client. Returns: `memcache.Client` instance. """ if self._client is None: self._client = Client_(self.servers) return self._client
python
def client(self): """Get the native memcache client. Returns: `memcache.Client` instance. """ if self._client is None: self._client = Client_(self.servers) return self._client
[ "def", "client", "(", "self", ")", ":", "if", "self", ".", "_client", "is", "None", ":", "self", ".", "_client", "=", "Client_", "(", "self", ".", "servers", ")", "return", "self", ".", "_client" ]
Get the native memcache client. Returns: `memcache.Client` instance.
[ "Get", "the", "native", "memcache", "client", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/memcached.py#L48-L56
232,426
nerdvegas/rez
src/rez/utils/memcached.py
Client.flush
def flush(self, hard=False): """Drop existing entries from the cache. Args: hard (bool): If True, all current entries are flushed from the server(s), which affects all users. If False, only the local process is affected. """ if not self.servers: return if hard: self.client.flush_all() self.reset_stats() else: from uuid import uuid4 tag = uuid4().hex if self.debug: tag = "flushed" + tag self.current = tag
python
def flush(self, hard=False): """Drop existing entries from the cache. Args: hard (bool): If True, all current entries are flushed from the server(s), which affects all users. If False, only the local process is affected. """ if not self.servers: return if hard: self.client.flush_all() self.reset_stats() else: from uuid import uuid4 tag = uuid4().hex if self.debug: tag = "flushed" + tag self.current = tag
[ "def", "flush", "(", "self", ",", "hard", "=", "False", ")", ":", "if", "not", "self", ".", "servers", ":", "return", "if", "hard", ":", "self", ".", "client", ".", "flush_all", "(", ")", "self", ".", "reset_stats", "(", ")", "else", ":", "from", "uuid", "import", "uuid4", "tag", "=", "uuid4", "(", ")", ".", "hex", "if", "self", ".", "debug", ":", "tag", "=", "\"flushed\"", "+", "tag", "self", ".", "current", "=", "tag" ]
Drop existing entries from the cache. Args: hard (bool): If True, all current entries are flushed from the server(s), which affects all users. If False, only the local process is affected.
[ "Drop", "existing", "entries", "from", "the", "cache", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/memcached.py#L119-L137
232,427
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/searching.py
depth_first_search
def depth_first_search(graph, root=None, filter=null()): """ Depth-first search. @type graph: graph, digraph @param graph: Graph. @type root: node @param root: Optional root node (will explore only root's connected component) @rtype: tuple @return: A tupple containing a dictionary and two lists: 1. Generated spanning tree 2. Graph's preordering 3. Graph's postordering """ recursionlimit = getrecursionlimit() setrecursionlimit(max(len(graph.nodes())*2,recursionlimit)) def dfs(node): """ Depth-first search subfunction. """ visited[node] = 1 pre.append(node) # Explore recursively the connected component for each in graph[node]: if (each not in visited and filter(each, node)): spanning_tree[each] = node dfs(each) post.append(node) visited = {} # List for marking visited and non-visited nodes spanning_tree = {} # Spanning tree pre = [] # Graph's preordering post = [] # Graph's postordering filter.configure(graph, spanning_tree) # DFS from one node only if (root is not None): if filter(root, None): spanning_tree[root] = None dfs(root) setrecursionlimit(recursionlimit) return spanning_tree, pre, post # Algorithm loop for each in graph: # Select a non-visited node if (each not in visited and filter(each, None)): spanning_tree[each] = None # Explore node's connected component dfs(each) setrecursionlimit(recursionlimit) return (spanning_tree, pre, post)
python
def depth_first_search(graph, root=None, filter=null()): """ Depth-first search. @type graph: graph, digraph @param graph: Graph. @type root: node @param root: Optional root node (will explore only root's connected component) @rtype: tuple @return: A tupple containing a dictionary and two lists: 1. Generated spanning tree 2. Graph's preordering 3. Graph's postordering """ recursionlimit = getrecursionlimit() setrecursionlimit(max(len(graph.nodes())*2,recursionlimit)) def dfs(node): """ Depth-first search subfunction. """ visited[node] = 1 pre.append(node) # Explore recursively the connected component for each in graph[node]: if (each not in visited and filter(each, node)): spanning_tree[each] = node dfs(each) post.append(node) visited = {} # List for marking visited and non-visited nodes spanning_tree = {} # Spanning tree pre = [] # Graph's preordering post = [] # Graph's postordering filter.configure(graph, spanning_tree) # DFS from one node only if (root is not None): if filter(root, None): spanning_tree[root] = None dfs(root) setrecursionlimit(recursionlimit) return spanning_tree, pre, post # Algorithm loop for each in graph: # Select a non-visited node if (each not in visited and filter(each, None)): spanning_tree[each] = None # Explore node's connected component dfs(each) setrecursionlimit(recursionlimit) return (spanning_tree, pre, post)
[ "def", "depth_first_search", "(", "graph", ",", "root", "=", "None", ",", "filter", "=", "null", "(", ")", ")", ":", "recursionlimit", "=", "getrecursionlimit", "(", ")", "setrecursionlimit", "(", "max", "(", "len", "(", "graph", ".", "nodes", "(", ")", ")", "*", "2", ",", "recursionlimit", ")", ")", "def", "dfs", "(", "node", ")", ":", "\"\"\"\n Depth-first search subfunction.\n \"\"\"", "visited", "[", "node", "]", "=", "1", "pre", ".", "append", "(", "node", ")", "# Explore recursively the connected component", "for", "each", "in", "graph", "[", "node", "]", ":", "if", "(", "each", "not", "in", "visited", "and", "filter", "(", "each", ",", "node", ")", ")", ":", "spanning_tree", "[", "each", "]", "=", "node", "dfs", "(", "each", ")", "post", ".", "append", "(", "node", ")", "visited", "=", "{", "}", "# List for marking visited and non-visited nodes", "spanning_tree", "=", "{", "}", "# Spanning tree", "pre", "=", "[", "]", "# Graph's preordering", "post", "=", "[", "]", "# Graph's postordering", "filter", ".", "configure", "(", "graph", ",", "spanning_tree", ")", "# DFS from one node only", "if", "(", "root", "is", "not", "None", ")", ":", "if", "filter", "(", "root", ",", "None", ")", ":", "spanning_tree", "[", "root", "]", "=", "None", "dfs", "(", "root", ")", "setrecursionlimit", "(", "recursionlimit", ")", "return", "spanning_tree", ",", "pre", ",", "post", "# Algorithm loop", "for", "each", "in", "graph", ":", "# Select a non-visited node", "if", "(", "each", "not", "in", "visited", "and", "filter", "(", "each", ",", "None", ")", ")", ":", "spanning_tree", "[", "each", "]", "=", "None", "# Explore node's connected component", "dfs", "(", "each", ")", "setrecursionlimit", "(", "recursionlimit", ")", "return", "(", "spanning_tree", ",", "pre", ",", "post", ")" ]
Depth-first search. @type graph: graph, digraph @param graph: Graph. @type root: node @param root: Optional root node (will explore only root's connected component) @rtype: tuple @return: A tupple containing a dictionary and two lists: 1. Generated spanning tree 2. Graph's preordering 3. Graph's postordering
[ "Depth", "-", "first", "search", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/searching.py#L39-L96
232,428
nerdvegas/rez
src/rez/vendor/pygraph/algorithms/searching.py
breadth_first_search
def breadth_first_search(graph, root=None, filter=null()): """ Breadth-first search. @type graph: graph, digraph @param graph: Graph. @type root: node @param root: Optional root node (will explore only root's connected component) @rtype: tuple @return: A tuple containing a dictionary and a list. 1. Generated spanning tree 2. Graph's level-based ordering """ def bfs(): """ Breadth-first search subfunction. """ while (queue != []): node = queue.pop(0) for other in graph[node]: if (other not in spanning_tree and filter(other, node)): queue.append(other) ordering.append(other) spanning_tree[other] = node queue = [] # Visiting queue spanning_tree = {} # Spanning tree ordering = [] filter.configure(graph, spanning_tree) # BFS from one node only if (root is not None): if filter(root, None): queue.append(root) ordering.append(root) spanning_tree[root] = None bfs() return spanning_tree, ordering # Algorithm for each in graph: if (each not in spanning_tree): if filter(each, None): queue.append(each) ordering.append(each) spanning_tree[each] = None bfs() return spanning_tree, ordering
python
def breadth_first_search(graph, root=None, filter=null()): """ Breadth-first search. @type graph: graph, digraph @param graph: Graph. @type root: node @param root: Optional root node (will explore only root's connected component) @rtype: tuple @return: A tuple containing a dictionary and a list. 1. Generated spanning tree 2. Graph's level-based ordering """ def bfs(): """ Breadth-first search subfunction. """ while (queue != []): node = queue.pop(0) for other in graph[node]: if (other not in spanning_tree and filter(other, node)): queue.append(other) ordering.append(other) spanning_tree[other] = node queue = [] # Visiting queue spanning_tree = {} # Spanning tree ordering = [] filter.configure(graph, spanning_tree) # BFS from one node only if (root is not None): if filter(root, None): queue.append(root) ordering.append(root) spanning_tree[root] = None bfs() return spanning_tree, ordering # Algorithm for each in graph: if (each not in spanning_tree): if filter(each, None): queue.append(each) ordering.append(each) spanning_tree[each] = None bfs() return spanning_tree, ordering
[ "def", "breadth_first_search", "(", "graph", ",", "root", "=", "None", ",", "filter", "=", "null", "(", ")", ")", ":", "def", "bfs", "(", ")", ":", "\"\"\"\n Breadth-first search subfunction.\n \"\"\"", "while", "(", "queue", "!=", "[", "]", ")", ":", "node", "=", "queue", ".", "pop", "(", "0", ")", "for", "other", "in", "graph", "[", "node", "]", ":", "if", "(", "other", "not", "in", "spanning_tree", "and", "filter", "(", "other", ",", "node", ")", ")", ":", "queue", ".", "append", "(", "other", ")", "ordering", ".", "append", "(", "other", ")", "spanning_tree", "[", "other", "]", "=", "node", "queue", "=", "[", "]", "# Visiting queue", "spanning_tree", "=", "{", "}", "# Spanning tree", "ordering", "=", "[", "]", "filter", ".", "configure", "(", "graph", ",", "spanning_tree", ")", "# BFS from one node only", "if", "(", "root", "is", "not", "None", ")", ":", "if", "filter", "(", "root", ",", "None", ")", ":", "queue", ".", "append", "(", "root", ")", "ordering", ".", "append", "(", "root", ")", "spanning_tree", "[", "root", "]", "=", "None", "bfs", "(", ")", "return", "spanning_tree", ",", "ordering", "# Algorithm", "for", "each", "in", "graph", ":", "if", "(", "each", "not", "in", "spanning_tree", ")", ":", "if", "filter", "(", "each", ",", "None", ")", ":", "queue", ".", "append", "(", "each", ")", "ordering", ".", "append", "(", "each", ")", "spanning_tree", "[", "each", "]", "=", "None", "bfs", "(", ")", "return", "spanning_tree", ",", "ordering" ]
Breadth-first search. @type graph: graph, digraph @param graph: Graph. @type root: node @param root: Optional root node (will explore only root's connected component) @rtype: tuple @return: A tuple containing a dictionary and a list. 1. Generated spanning tree 2. Graph's level-based ordering
[ "Breadth", "-", "first", "search", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/searching.py#L101-L153
232,429
nerdvegas/rez
src/rez/package_resources_.py
PackageResource.normalize_variables
def normalize_variables(cls, variables): """Make sure version is treated consistently """ # if the version is False, empty string, etc, throw it out if variables.get('version', True) in ('', False, '_NO_VERSION', None): del variables['version'] return super(PackageResource, cls).normalize_variables(variables)
python
def normalize_variables(cls, variables): """Make sure version is treated consistently """ # if the version is False, empty string, etc, throw it out if variables.get('version', True) in ('', False, '_NO_VERSION', None): del variables['version'] return super(PackageResource, cls).normalize_variables(variables)
[ "def", "normalize_variables", "(", "cls", ",", "variables", ")", ":", "# if the version is False, empty string, etc, throw it out", "if", "variables", ".", "get", "(", "'version'", ",", "True", ")", "in", "(", "''", ",", "False", ",", "'_NO_VERSION'", ",", "None", ")", ":", "del", "variables", "[", "'version'", "]", "return", "super", "(", "PackageResource", ",", "cls", ")", ".", "normalize_variables", "(", "variables", ")" ]
Make sure version is treated consistently
[ "Make", "sure", "version", "is", "treated", "consistently" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_resources_.py#L300-L306
232,430
nerdvegas/rez
src/rez/vendor/argcomplete/my_shlex.py
shlex.push_source
def push_source(self, newstream, newfile=None): "Push an input source onto the lexer's input source stack." if isinstance(newstream, basestring): newstream = StringIO(newstream) self.filestack.appendleft((self.infile, self.instream, self.lineno)) self.infile = newfile self.instream = newstream self.lineno = 1
python
def push_source(self, newstream, newfile=None): "Push an input source onto the lexer's input source stack." if isinstance(newstream, basestring): newstream = StringIO(newstream) self.filestack.appendleft((self.infile, self.instream, self.lineno)) self.infile = newfile self.instream = newstream self.lineno = 1
[ "def", "push_source", "(", "self", ",", "newstream", ",", "newfile", "=", "None", ")", ":", "if", "isinstance", "(", "newstream", ",", "basestring", ")", ":", "newstream", "=", "StringIO", "(", "newstream", ")", "self", ".", "filestack", ".", "appendleft", "(", "(", "self", ".", "infile", ",", "self", ".", "instream", ",", "self", ".", "lineno", ")", ")", "self", ".", "infile", "=", "newfile", "self", ".", "instream", "=", "newstream", "self", ".", "lineno", "=", "1" ]
Push an input source onto the lexer's input source stack.
[ "Push", "an", "input", "source", "onto", "the", "lexer", "s", "input", "source", "stack", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/argcomplete/my_shlex.py#L100-L107
232,431
nerdvegas/rez
src/rez/vendor/argcomplete/my_shlex.py
shlex.error_leader
def error_leader(self, infile=None, lineno=None): "Emit a C-compiler-like, Emacs-friendly error-message leader." if infile is None: infile = self.infile if lineno is None: lineno = self.lineno return "\"%s\", line %d: " % (infile, lineno)
python
def error_leader(self, infile=None, lineno=None): "Emit a C-compiler-like, Emacs-friendly error-message leader." if infile is None: infile = self.infile if lineno is None: lineno = self.lineno return "\"%s\", line %d: " % (infile, lineno)
[ "def", "error_leader", "(", "self", ",", "infile", "=", "None", ",", "lineno", "=", "None", ")", ":", "if", "infile", "is", "None", ":", "infile", "=", "self", ".", "infile", "if", "lineno", "is", "None", ":", "lineno", "=", "self", ".", "lineno", "return", "\"\\\"%s\\\", line %d: \"", "%", "(", "infile", ",", "lineno", ")" ]
Emit a C-compiler-like, Emacs-friendly error-message leader.
[ "Emit", "a", "C", "-", "compiler", "-", "like", "Emacs", "-", "friendly", "error", "-", "message", "leader", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/argcomplete/my_shlex.py#L278-L284
232,432
nerdvegas/rez
src/rez/system.py
System.rez_bin_path
def rez_bin_path(self): """Get path containing rez binaries, or None if no binaries are available, or Rez is not a production install. """ binpath = None if sys.argv and sys.argv[0]: executable = sys.argv[0] path = which("rezolve", env={"PATH":os.path.dirname(executable), "PATHEXT":os.environ.get("PATHEXT", "")}) binpath = os.path.dirname(path) if path else None # TODO: improve this, could still pick up non-production 'rezolve' if not binpath: path = which("rezolve") if path: binpath = os.path.dirname(path) if binpath: validation_file = os.path.join(binpath, ".rez_production_install") if os.path.exists(validation_file): return os.path.realpath(binpath) return None
python
def rez_bin_path(self): """Get path containing rez binaries, or None if no binaries are available, or Rez is not a production install. """ binpath = None if sys.argv and sys.argv[0]: executable = sys.argv[0] path = which("rezolve", env={"PATH":os.path.dirname(executable), "PATHEXT":os.environ.get("PATHEXT", "")}) binpath = os.path.dirname(path) if path else None # TODO: improve this, could still pick up non-production 'rezolve' if not binpath: path = which("rezolve") if path: binpath = os.path.dirname(path) if binpath: validation_file = os.path.join(binpath, ".rez_production_install") if os.path.exists(validation_file): return os.path.realpath(binpath) return None
[ "def", "rez_bin_path", "(", "self", ")", ":", "binpath", "=", "None", "if", "sys", ".", "argv", "and", "sys", ".", "argv", "[", "0", "]", ":", "executable", "=", "sys", ".", "argv", "[", "0", "]", "path", "=", "which", "(", "\"rezolve\"", ",", "env", "=", "{", "\"PATH\"", ":", "os", ".", "path", ".", "dirname", "(", "executable", ")", ",", "\"PATHEXT\"", ":", "os", ".", "environ", ".", "get", "(", "\"PATHEXT\"", ",", "\"\"", ")", "}", ")", "binpath", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "path", "else", "None", "# TODO: improve this, could still pick up non-production 'rezolve'", "if", "not", "binpath", ":", "path", "=", "which", "(", "\"rezolve\"", ")", "if", "path", ":", "binpath", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "binpath", ":", "validation_file", "=", "os", ".", "path", ".", "join", "(", "binpath", ",", "\".rez_production_install\"", ")", "if", "os", ".", "path", ".", "exists", "(", "validation_file", ")", ":", "return", "os", ".", "path", ".", "realpath", "(", "binpath", ")", "return", "None" ]
Get path containing rez binaries, or None if no binaries are available, or Rez is not a production install.
[ "Get", "path", "containing", "rez", "binaries", "or", "None", "if", "no", "binaries", "are", "available", "or", "Rez", "is", "not", "a", "production", "install", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/system.py#L191-L214
232,433
nerdvegas/rez
src/rez/system.py
System.get_summary_string
def get_summary_string(self): """Get a string summarising the state of Rez as a whole. Returns: String. """ from rez.plugin_managers import plugin_manager txt = "Rez %s" % __version__ txt += "\n\n%s" % plugin_manager.get_summary_string() return txt
python
def get_summary_string(self): """Get a string summarising the state of Rez as a whole. Returns: String. """ from rez.plugin_managers import plugin_manager txt = "Rez %s" % __version__ txt += "\n\n%s" % plugin_manager.get_summary_string() return txt
[ "def", "get_summary_string", "(", "self", ")", ":", "from", "rez", ".", "plugin_managers", "import", "plugin_manager", "txt", "=", "\"Rez %s\"", "%", "__version__", "txt", "+=", "\"\\n\\n%s\"", "%", "plugin_manager", ".", "get_summary_string", "(", ")", "return", "txt" ]
Get a string summarising the state of Rez as a whole. Returns: String.
[ "Get", "a", "string", "summarising", "the", "state", "of", "Rez", "as", "a", "whole", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/system.py#L221-L231
232,434
nerdvegas/rez
src/rez/system.py
System.clear_caches
def clear_caches(self, hard=False): """Clear all caches in Rez. Rez caches package contents and iteration during a python session. Thus newly released packages, and changes to existing packages, may not be picked up. You need to clear the cache for these changes to become visible. Args: hard (bool): Perform a 'hard' cache clear. This just means that the memcached cache is also cleared. Generally this is not needed - this option is for debugging purposes. """ from rez.package_repository import package_repository_manager from rez.utils.memcached import memcached_client package_repository_manager.clear_caches() if hard: with memcached_client() as client: client.flush()
python
def clear_caches(self, hard=False): """Clear all caches in Rez. Rez caches package contents and iteration during a python session. Thus newly released packages, and changes to existing packages, may not be picked up. You need to clear the cache for these changes to become visible. Args: hard (bool): Perform a 'hard' cache clear. This just means that the memcached cache is also cleared. Generally this is not needed - this option is for debugging purposes. """ from rez.package_repository import package_repository_manager from rez.utils.memcached import memcached_client package_repository_manager.clear_caches() if hard: with memcached_client() as client: client.flush()
[ "def", "clear_caches", "(", "self", ",", "hard", "=", "False", ")", ":", "from", "rez", ".", "package_repository", "import", "package_repository_manager", "from", "rez", ".", "utils", ".", "memcached", "import", "memcached_client", "package_repository_manager", ".", "clear_caches", "(", ")", "if", "hard", ":", "with", "memcached_client", "(", ")", "as", "client", ":", "client", ".", "flush", "(", ")" ]
Clear all caches in Rez. Rez caches package contents and iteration during a python session. Thus newly released packages, and changes to existing packages, may not be picked up. You need to clear the cache for these changes to become visible. Args: hard (bool): Perform a 'hard' cache clear. This just means that the memcached cache is also cleared. Generally this is not needed - this option is for debugging purposes.
[ "Clear", "all", "caches", "in", "Rez", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/system.py#L233-L252
232,435
nerdvegas/rez
src/rez/resolver.py
Resolver.solve
def solve(self): """Perform the solve. """ with log_duration(self._print, "memcache get (resolve) took %s"): solver_dict = self._get_cached_solve() if solver_dict: self.from_cache = True self._set_result(solver_dict) else: self.from_cache = False solver = self._solve() solver_dict = self._solver_to_dict(solver) self._set_result(solver_dict) with log_duration(self._print, "memcache set (resolve) took %s"): self._set_cached_solve(solver_dict)
python
def solve(self): """Perform the solve. """ with log_duration(self._print, "memcache get (resolve) took %s"): solver_dict = self._get_cached_solve() if solver_dict: self.from_cache = True self._set_result(solver_dict) else: self.from_cache = False solver = self._solve() solver_dict = self._solver_to_dict(solver) self._set_result(solver_dict) with log_duration(self._print, "memcache set (resolve) took %s"): self._set_cached_solve(solver_dict)
[ "def", "solve", "(", "self", ")", ":", "with", "log_duration", "(", "self", ".", "_print", ",", "\"memcache get (resolve) took %s\"", ")", ":", "solver_dict", "=", "self", ".", "_get_cached_solve", "(", ")", "if", "solver_dict", ":", "self", ".", "from_cache", "=", "True", "self", ".", "_set_result", "(", "solver_dict", ")", "else", ":", "self", ".", "from_cache", "=", "False", "solver", "=", "self", ".", "_solve", "(", ")", "solver_dict", "=", "self", ".", "_solver_to_dict", "(", "solver", ")", "self", ".", "_set_result", "(", "solver_dict", ")", "with", "log_duration", "(", "self", ".", "_print", ",", "\"memcache set (resolve) took %s\"", ")", ":", "self", ".", "_set_cached_solve", "(", "solver_dict", ")" ]
Perform the solve.
[ "Perform", "the", "solve", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolver.py#L107-L123
232,436
nerdvegas/rez
src/rez/resolver.py
Resolver._set_cached_solve
def _set_cached_solve(self, solver_dict): """Store a solve to memcached. If there is NOT a resolve timestamp: - store the solve to a non-timestamped entry. If there IS a resolve timestamp (let us call this T): - if NO newer package in the solve has been released since T, - then store the solve to a non-timestamped entry; - else: - store the solve to a timestamped entry. """ if self.status_ != ResolverStatus.solved: return # don't cache failed solves if not (self.caching and self.memcached_servers): return # most recent release times get stored with solve result in the cache releases_since_solve = False release_times_dict = {} variant_states_dict = {} for variant in self.resolved_packages_: time_ = get_last_release_time(variant.name, self.package_paths) # don't cache if a release time isn't known if time_ == 0: self._print("Did not send memcache key: a repository could " "not provide a most recent release time for %r", variant.name) return if self.timestamp and self.timestamp < time_: releases_since_solve = True release_times_dict[variant.name] = time_ repo = variant.resource._repository variant_states_dict[variant.name] = \ repo.get_variant_state_handle(variant.resource) timestamped = (self.timestamp and releases_since_solve) key = self._memcache_key(timestamped=timestamped) data = (solver_dict, release_times_dict, variant_states_dict) with self._memcached_client() as client: client.set(key, data) self._print("Sent memcache key: %r", key)
python
def _set_cached_solve(self, solver_dict): """Store a solve to memcached. If there is NOT a resolve timestamp: - store the solve to a non-timestamped entry. If there IS a resolve timestamp (let us call this T): - if NO newer package in the solve has been released since T, - then store the solve to a non-timestamped entry; - else: - store the solve to a timestamped entry. """ if self.status_ != ResolverStatus.solved: return # don't cache failed solves if not (self.caching and self.memcached_servers): return # most recent release times get stored with solve result in the cache releases_since_solve = False release_times_dict = {} variant_states_dict = {} for variant in self.resolved_packages_: time_ = get_last_release_time(variant.name, self.package_paths) # don't cache if a release time isn't known if time_ == 0: self._print("Did not send memcache key: a repository could " "not provide a most recent release time for %r", variant.name) return if self.timestamp and self.timestamp < time_: releases_since_solve = True release_times_dict[variant.name] = time_ repo = variant.resource._repository variant_states_dict[variant.name] = \ repo.get_variant_state_handle(variant.resource) timestamped = (self.timestamp and releases_since_solve) key = self._memcache_key(timestamped=timestamped) data = (solver_dict, release_times_dict, variant_states_dict) with self._memcached_client() as client: client.set(key, data) self._print("Sent memcache key: %r", key)
[ "def", "_set_cached_solve", "(", "self", ",", "solver_dict", ")", ":", "if", "self", ".", "status_", "!=", "ResolverStatus", ".", "solved", ":", "return", "# don't cache failed solves", "if", "not", "(", "self", ".", "caching", "and", "self", ".", "memcached_servers", ")", ":", "return", "# most recent release times get stored with solve result in the cache", "releases_since_solve", "=", "False", "release_times_dict", "=", "{", "}", "variant_states_dict", "=", "{", "}", "for", "variant", "in", "self", ".", "resolved_packages_", ":", "time_", "=", "get_last_release_time", "(", "variant", ".", "name", ",", "self", ".", "package_paths", ")", "# don't cache if a release time isn't known", "if", "time_", "==", "0", ":", "self", ".", "_print", "(", "\"Did not send memcache key: a repository could \"", "\"not provide a most recent release time for %r\"", ",", "variant", ".", "name", ")", "return", "if", "self", ".", "timestamp", "and", "self", ".", "timestamp", "<", "time_", ":", "releases_since_solve", "=", "True", "release_times_dict", "[", "variant", ".", "name", "]", "=", "time_", "repo", "=", "variant", ".", "resource", ".", "_repository", "variant_states_dict", "[", "variant", ".", "name", "]", "=", "repo", ".", "get_variant_state_handle", "(", "variant", ".", "resource", ")", "timestamped", "=", "(", "self", ".", "timestamp", "and", "releases_since_solve", ")", "key", "=", "self", ".", "_memcache_key", "(", "timestamped", "=", "timestamped", ")", "data", "=", "(", "solver_dict", ",", "release_times_dict", ",", "variant_states_dict", ")", "with", "self", ".", "_memcached_client", "(", ")", "as", "client", ":", "client", ".", "set", "(", "key", ",", "data", ")", "self", ".", "_print", "(", "\"Sent memcache key: %r\"", ",", "key", ")" ]
Store a solve to memcached. If there is NOT a resolve timestamp: - store the solve to a non-timestamped entry. If there IS a resolve timestamp (let us call this T): - if NO newer package in the solve has been released since T, - then store the solve to a non-timestamped entry; - else: - store the solve to a timestamped entry.
[ "Store", "a", "solve", "to", "memcached", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolver.py#L310-L356
232,437
nerdvegas/rez
src/rez/resolver.py
Resolver._memcache_key
def _memcache_key(self, timestamped=False): """Makes a key suitable as a memcache entry.""" request = tuple(map(str, self.package_requests)) repo_ids = [] for path in self.package_paths: repo = package_repository_manager.get_repository(path) repo_ids.append(repo.uid) t = ["resolve", request, tuple(repo_ids), self.package_filter_hash, self.package_orderers_hash, self.building, config.prune_failed_graph] if timestamped and self.timestamp: t.append(self.timestamp) return str(tuple(t))
python
def _memcache_key(self, timestamped=False): """Makes a key suitable as a memcache entry.""" request = tuple(map(str, self.package_requests)) repo_ids = [] for path in self.package_paths: repo = package_repository_manager.get_repository(path) repo_ids.append(repo.uid) t = ["resolve", request, tuple(repo_ids), self.package_filter_hash, self.package_orderers_hash, self.building, config.prune_failed_graph] if timestamped and self.timestamp: t.append(self.timestamp) return str(tuple(t))
[ "def", "_memcache_key", "(", "self", ",", "timestamped", "=", "False", ")", ":", "request", "=", "tuple", "(", "map", "(", "str", ",", "self", ".", "package_requests", ")", ")", "repo_ids", "=", "[", "]", "for", "path", "in", "self", ".", "package_paths", ":", "repo", "=", "package_repository_manager", ".", "get_repository", "(", "path", ")", "repo_ids", ".", "append", "(", "repo", ".", "uid", ")", "t", "=", "[", "\"resolve\"", ",", "request", ",", "tuple", "(", "repo_ids", ")", ",", "self", ".", "package_filter_hash", ",", "self", ".", "package_orderers_hash", ",", "self", ".", "building", ",", "config", ".", "prune_failed_graph", "]", "if", "timestamped", "and", "self", ".", "timestamp", ":", "t", ".", "append", "(", "self", ".", "timestamp", ")", "return", "str", "(", "tuple", "(", "t", ")", ")" ]
Makes a key suitable as a memcache entry.
[ "Makes", "a", "key", "suitable", "as", "a", "memcache", "entry", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolver.py#L358-L377
232,438
nerdvegas/rez
src/rez/shells.py
create_shell
def create_shell(shell=None, **kwargs): """Returns a Shell of the given type, or the current shell type if shell is None.""" if not shell: shell = config.default_shell if not shell: from rez.system import system shell = system.shell from rez.plugin_managers import plugin_manager return plugin_manager.create_instance('shell', shell, **kwargs)
python
def create_shell(shell=None, **kwargs): """Returns a Shell of the given type, or the current shell type if shell is None.""" if not shell: shell = config.default_shell if not shell: from rez.system import system shell = system.shell from rez.plugin_managers import plugin_manager return plugin_manager.create_instance('shell', shell, **kwargs)
[ "def", "create_shell", "(", "shell", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "shell", ":", "shell", "=", "config", ".", "default_shell", "if", "not", "shell", ":", "from", "rez", ".", "system", "import", "system", "shell", "=", "system", ".", "shell", "from", "rez", ".", "plugin_managers", "import", "plugin_manager", "return", "plugin_manager", ".", "create_instance", "(", "'shell'", ",", "shell", ",", "*", "*", "kwargs", ")" ]
Returns a Shell of the given type, or the current shell type if shell is None.
[ "Returns", "a", "Shell", "of", "the", "given", "type", "or", "the", "current", "shell", "type", "if", "shell", "is", "None", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/shells.py#L25-L35
232,439
nerdvegas/rez
src/rez/shells.py
Shell.startup_capabilities
def startup_capabilities(cls, rcfile=False, norc=False, stdin=False, command=False): """ Given a set of options related to shell startup, return the actual options that will be applied. @returns 4-tuple representing applied value of each option. """ raise NotImplementedError
python
def startup_capabilities(cls, rcfile=False, norc=False, stdin=False, command=False): """ Given a set of options related to shell startup, return the actual options that will be applied. @returns 4-tuple representing applied value of each option. """ raise NotImplementedError
[ "def", "startup_capabilities", "(", "cls", ",", "rcfile", "=", "False", ",", "norc", "=", "False", ",", "stdin", "=", "False", ",", "command", "=", "False", ")", ":", "raise", "NotImplementedError" ]
Given a set of options related to shell startup, return the actual options that will be applied. @returns 4-tuple representing applied value of each option.
[ "Given", "a", "set", "of", "options", "related", "to", "shell", "startup", "return", "the", "actual", "options", "that", "will", "be", "applied", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/shells.py#L54-L61
232,440
nerdvegas/rez
src/rez/vendor/distlib/index.py
PackageIndex.upload_file
def upload_file(self, metadata, filename, signer=None, sign_password=None, filetype='sdist', pyversion='source', keystore=None): """ Upload a release file to the index. :param metadata: A :class:`Metadata` instance defining at least a name and version number for the file to be uploaded. :param filename: The pathname of the file to be uploaded. :param signer: The identifier of the signer of the file. :param sign_password: The passphrase for the signer's private key used for signing. :param filetype: The type of the file being uploaded. This is the distutils command which produced that file, e.g. ``sdist`` or ``bdist_wheel``. :param pyversion: The version of Python which the release relates to. For code compatible with any Python, this would be ``source``, otherwise it would be e.g. ``3.2``. :param keystore: The path to a directory which contains the keys used in signing. If not specified, the instance's ``gpg_home`` attribute is used instead. :return: The HTTP response received from PyPI upon submission of the request. """ self.check_credentials() if not os.path.exists(filename): raise DistlibException('not found: %s' % filename) metadata.validate() d = metadata.todict() sig_file = None if signer: if not self.gpg: logger.warning('no signing program available - not signed') else: sig_file = self.sign_file(filename, signer, sign_password, keystore) with open(filename, 'rb') as f: file_data = f.read() md5_digest = hashlib.md5(file_data).hexdigest() sha256_digest = hashlib.sha256(file_data).hexdigest() d.update({ ':action': 'file_upload', 'protcol_version': '1', 'filetype': filetype, 'pyversion': pyversion, 'md5_digest': md5_digest, 'sha256_digest': sha256_digest, }) files = [('content', os.path.basename(filename), file_data)] if sig_file: with open(sig_file, 'rb') as f: sig_data = f.read() files.append(('gpg_signature', os.path.basename(sig_file), sig_data)) shutil.rmtree(os.path.dirname(sig_file)) request = self.encode_request(d.items(), files) return self.send_request(request)
python
def upload_file(self, metadata, filename, signer=None, sign_password=None, filetype='sdist', pyversion='source', keystore=None): """ Upload a release file to the index. :param metadata: A :class:`Metadata` instance defining at least a name and version number for the file to be uploaded. :param filename: The pathname of the file to be uploaded. :param signer: The identifier of the signer of the file. :param sign_password: The passphrase for the signer's private key used for signing. :param filetype: The type of the file being uploaded. This is the distutils command which produced that file, e.g. ``sdist`` or ``bdist_wheel``. :param pyversion: The version of Python which the release relates to. For code compatible with any Python, this would be ``source``, otherwise it would be e.g. ``3.2``. :param keystore: The path to a directory which contains the keys used in signing. If not specified, the instance's ``gpg_home`` attribute is used instead. :return: The HTTP response received from PyPI upon submission of the request. """ self.check_credentials() if not os.path.exists(filename): raise DistlibException('not found: %s' % filename) metadata.validate() d = metadata.todict() sig_file = None if signer: if not self.gpg: logger.warning('no signing program available - not signed') else: sig_file = self.sign_file(filename, signer, sign_password, keystore) with open(filename, 'rb') as f: file_data = f.read() md5_digest = hashlib.md5(file_data).hexdigest() sha256_digest = hashlib.sha256(file_data).hexdigest() d.update({ ':action': 'file_upload', 'protcol_version': '1', 'filetype': filetype, 'pyversion': pyversion, 'md5_digest': md5_digest, 'sha256_digest': sha256_digest, }) files = [('content', os.path.basename(filename), file_data)] if sig_file: with open(sig_file, 'rb') as f: sig_data = f.read() files.append(('gpg_signature', os.path.basename(sig_file), sig_data)) shutil.rmtree(os.path.dirname(sig_file)) request = self.encode_request(d.items(), files) return self.send_request(request)
[ "def", "upload_file", "(", "self", ",", "metadata", ",", "filename", ",", "signer", "=", "None", ",", "sign_password", "=", "None", ",", "filetype", "=", "'sdist'", ",", "pyversion", "=", "'source'", ",", "keystore", "=", "None", ")", ":", "self", ".", "check_credentials", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "raise", "DistlibException", "(", "'not found: %s'", "%", "filename", ")", "metadata", ".", "validate", "(", ")", "d", "=", "metadata", ".", "todict", "(", ")", "sig_file", "=", "None", "if", "signer", ":", "if", "not", "self", ".", "gpg", ":", "logger", ".", "warning", "(", "'no signing program available - not signed'", ")", "else", ":", "sig_file", "=", "self", ".", "sign_file", "(", "filename", ",", "signer", ",", "sign_password", ",", "keystore", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "file_data", "=", "f", ".", "read", "(", ")", "md5_digest", "=", "hashlib", ".", "md5", "(", "file_data", ")", ".", "hexdigest", "(", ")", "sha256_digest", "=", "hashlib", ".", "sha256", "(", "file_data", ")", ".", "hexdigest", "(", ")", "d", ".", "update", "(", "{", "':action'", ":", "'file_upload'", ",", "'protcol_version'", ":", "'1'", ",", "'filetype'", ":", "filetype", ",", "'pyversion'", ":", "pyversion", ",", "'md5_digest'", ":", "md5_digest", ",", "'sha256_digest'", ":", "sha256_digest", ",", "}", ")", "files", "=", "[", "(", "'content'", ",", "os", ".", "path", ".", "basename", "(", "filename", ")", ",", "file_data", ")", "]", "if", "sig_file", ":", "with", "open", "(", "sig_file", ",", "'rb'", ")", "as", "f", ":", "sig_data", "=", "f", ".", "read", "(", ")", "files", ".", "append", "(", "(", "'gpg_signature'", ",", "os", ".", "path", ".", "basename", "(", "sig_file", ")", ",", "sig_data", ")", ")", "shutil", ".", "rmtree", "(", "os", ".", "path", ".", "dirname", "(", "sig_file", ")", ")", "request", "=", "self", ".", "encode_request", "(", "d", ".", "items", "(", ")", ",", "files", ")", "return", "self", ".", "send_request", "(", "request", ")" ]
Upload a release file to the index. :param metadata: A :class:`Metadata` instance defining at least a name and version number for the file to be uploaded. :param filename: The pathname of the file to be uploaded. :param signer: The identifier of the signer of the file. :param sign_password: The passphrase for the signer's private key used for signing. :param filetype: The type of the file being uploaded. This is the distutils command which produced that file, e.g. ``sdist`` or ``bdist_wheel``. :param pyversion: The version of Python which the release relates to. For code compatible with any Python, this would be ``source``, otherwise it would be e.g. ``3.2``. :param keystore: The path to a directory which contains the keys used in signing. If not specified, the instance's ``gpg_home`` attribute is used instead. :return: The HTTP response received from PyPI upon submission of the request.
[ "Upload", "a", "release", "file", "to", "the", "index", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/distlib/index.py#L238-L293
232,441
nerdvegas/rez
src/rez/solver.py
_get_dependency_order
def _get_dependency_order(g, node_list): """Return list of nodes as close as possible to the ordering in node_list, but with child nodes earlier in the list than parents.""" access_ = accessibility(g) deps = dict((k, set(v) - set([k])) for k, v in access_.iteritems()) nodes = node_list + list(set(g.nodes()) - set(node_list)) ordered_nodes = [] while nodes: n_ = nodes[0] n_deps = deps.get(n_) if (n_ in ordered_nodes) or (n_deps is None): nodes = nodes[1:] continue moved = False for i, n in enumerate(nodes[1:]): if n in n_deps: nodes = [nodes[i + 1]] + nodes[:i + 1] + nodes[i + 2:] moved = True break if not moved: ordered_nodes.append(n_) nodes = nodes[1:] return ordered_nodes
python
def _get_dependency_order(g, node_list): """Return list of nodes as close as possible to the ordering in node_list, but with child nodes earlier in the list than parents.""" access_ = accessibility(g) deps = dict((k, set(v) - set([k])) for k, v in access_.iteritems()) nodes = node_list + list(set(g.nodes()) - set(node_list)) ordered_nodes = [] while nodes: n_ = nodes[0] n_deps = deps.get(n_) if (n_ in ordered_nodes) or (n_deps is None): nodes = nodes[1:] continue moved = False for i, n in enumerate(nodes[1:]): if n in n_deps: nodes = [nodes[i + 1]] + nodes[:i + 1] + nodes[i + 2:] moved = True break if not moved: ordered_nodes.append(n_) nodes = nodes[1:] return ordered_nodes
[ "def", "_get_dependency_order", "(", "g", ",", "node_list", ")", ":", "access_", "=", "accessibility", "(", "g", ")", "deps", "=", "dict", "(", "(", "k", ",", "set", "(", "v", ")", "-", "set", "(", "[", "k", "]", ")", ")", "for", "k", ",", "v", "in", "access_", ".", "iteritems", "(", ")", ")", "nodes", "=", "node_list", "+", "list", "(", "set", "(", "g", ".", "nodes", "(", ")", ")", "-", "set", "(", "node_list", ")", ")", "ordered_nodes", "=", "[", "]", "while", "nodes", ":", "n_", "=", "nodes", "[", "0", "]", "n_deps", "=", "deps", ".", "get", "(", "n_", ")", "if", "(", "n_", "in", "ordered_nodes", ")", "or", "(", "n_deps", "is", "None", ")", ":", "nodes", "=", "nodes", "[", "1", ":", "]", "continue", "moved", "=", "False", "for", "i", ",", "n", "in", "enumerate", "(", "nodes", "[", "1", ":", "]", ")", ":", "if", "n", "in", "n_deps", ":", "nodes", "=", "[", "nodes", "[", "i", "+", "1", "]", "]", "+", "nodes", "[", ":", "i", "+", "1", "]", "+", "nodes", "[", "i", "+", "2", ":", "]", "moved", "=", "True", "break", "if", "not", "moved", ":", "ordered_nodes", ".", "append", "(", "n_", ")", "nodes", "=", "nodes", "[", "1", ":", "]", "return", "ordered_nodes" ]
Return list of nodes as close as possible to the ordering in node_list, but with child nodes earlier in the list than parents.
[ "Return", "list", "of", "nodes", "as", "close", "as", "possible", "to", "the", "ordering", "in", "node_list", "but", "with", "child", "nodes", "earlier", "in", "the", "list", "than", "parents", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L1110-L1136
232,442
nerdvegas/rez
src/rez/solver.py
_short_req_str
def _short_req_str(package_request): """print shortened version of '==X|==Y|==Z' ranged requests.""" if not package_request.conflict: versions = package_request.range.to_versions() if versions and len(versions) == len(package_request.range) \ and len(versions) > 1: return "%s-%s(%d)" % (package_request.name, str(package_request.range.span()), len(versions)) return str(package_request)
python
def _short_req_str(package_request): """print shortened version of '==X|==Y|==Z' ranged requests.""" if not package_request.conflict: versions = package_request.range.to_versions() if versions and len(versions) == len(package_request.range) \ and len(versions) > 1: return "%s-%s(%d)" % (package_request.name, str(package_request.range.span()), len(versions)) return str(package_request)
[ "def", "_short_req_str", "(", "package_request", ")", ":", "if", "not", "package_request", ".", "conflict", ":", "versions", "=", "package_request", ".", "range", ".", "to_versions", "(", ")", "if", "versions", "and", "len", "(", "versions", ")", "==", "len", "(", "package_request", ".", "range", ")", "and", "len", "(", "versions", ")", ">", "1", ":", "return", "\"%s-%s(%d)\"", "%", "(", "package_request", ".", "name", ",", "str", "(", "package_request", ".", "range", ".", "span", "(", ")", ")", ",", "len", "(", "versions", ")", ")", "return", "str", "(", "package_request", ")" ]
print shortened version of '==X|==Y|==Z' ranged requests.
[ "print", "shortened", "version", "of", "==", "X|", "==", "Y|", "==", "Z", "ranged", "requests", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L2275-L2284
232,443
nerdvegas/rez
src/rez/solver.py
PackageVariant.requires_list
def requires_list(self): """ It is important that this property is calculated lazily. Getting the 'requires' attribute may trigger a package load, which may be avoided if this variant is reduced away before that happens. """ requires = self.variant.get_requires(build_requires=self.building) reqlist = RequirementList(requires) if reqlist.conflict: raise ResolveError( "The package %s has an internal requirements conflict: %s" % (str(self), str(reqlist))) return reqlist
python
def requires_list(self): """ It is important that this property is calculated lazily. Getting the 'requires' attribute may trigger a package load, which may be avoided if this variant is reduced away before that happens. """ requires = self.variant.get_requires(build_requires=self.building) reqlist = RequirementList(requires) if reqlist.conflict: raise ResolveError( "The package %s has an internal requirements conflict: %s" % (str(self), str(reqlist))) return reqlist
[ "def", "requires_list", "(", "self", ")", ":", "requires", "=", "self", ".", "variant", ".", "get_requires", "(", "build_requires", "=", "self", ".", "building", ")", "reqlist", "=", "RequirementList", "(", "requires", ")", "if", "reqlist", ".", "conflict", ":", "raise", "ResolveError", "(", "\"The package %s has an internal requirements conflict: %s\"", "%", "(", "str", "(", "self", ")", ",", "str", "(", "reqlist", ")", ")", ")", "return", "reqlist" ]
It is important that this property is calculated lazily. Getting the 'requires' attribute may trigger a package load, which may be avoided if this variant is reduced away before that happens.
[ "It", "is", "important", "that", "this", "property", "is", "calculated", "lazily", ".", "Getting", "the", "requires", "attribute", "may", "trigger", "a", "package", "load", "which", "may", "be", "avoided", "if", "this", "variant", "is", "reduced", "away", "before", "that", "happens", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L299-L313
232,444
nerdvegas/rez
src/rez/solver.py
_PackageEntry.sort
def sort(self): """Sort variants from most correct to consume, to least. Sort rules: version_priority: - sort by highest versions of packages shared with request; - THEN least number of additional packages added to solve; - THEN highest versions of additional packages; - THEN alphabetical on name of additional packages; - THEN variant index. intersection_priority: - sort by highest number of packages shared with request; - THEN sort according to version_priority Note: In theory 'variant.index' should never factor into the sort unless two variants are identical (which shouldn't happen) - this is just here as a safety measure so that sorting is guaranteed repeatable regardless. """ if self.sorted: return def key(variant): requested_key = [] names = set() for i, request in enumerate(self.solver.request_list): if not request.conflict: req = variant.requires_list.get(request.name) if req is not None: requested_key.append((-i, req.range)) names.add(req.name) additional_key = [] for request in variant.requires_list: if not request.conflict and request.name not in names: additional_key.append((request.range, request.name)) if (VariantSelectMode[config.variant_select_mode] == VariantSelectMode.version_priority): k = (requested_key, -len(additional_key), additional_key, variant.index) else: # VariantSelectMode.intersection_priority k = (len(requested_key), requested_key, -len(additional_key), additional_key, variant.index) return k self.variants.sort(key=key, reverse=True) self.sorted = True
python
def sort(self): """Sort variants from most correct to consume, to least. Sort rules: version_priority: - sort by highest versions of packages shared with request; - THEN least number of additional packages added to solve; - THEN highest versions of additional packages; - THEN alphabetical on name of additional packages; - THEN variant index. intersection_priority: - sort by highest number of packages shared with request; - THEN sort according to version_priority Note: In theory 'variant.index' should never factor into the sort unless two variants are identical (which shouldn't happen) - this is just here as a safety measure so that sorting is guaranteed repeatable regardless. """ if self.sorted: return def key(variant): requested_key = [] names = set() for i, request in enumerate(self.solver.request_list): if not request.conflict: req = variant.requires_list.get(request.name) if req is not None: requested_key.append((-i, req.range)) names.add(req.name) additional_key = [] for request in variant.requires_list: if not request.conflict and request.name not in names: additional_key.append((request.range, request.name)) if (VariantSelectMode[config.variant_select_mode] == VariantSelectMode.version_priority): k = (requested_key, -len(additional_key), additional_key, variant.index) else: # VariantSelectMode.intersection_priority k = (len(requested_key), requested_key, -len(additional_key), additional_key, variant.index) return k self.variants.sort(key=key, reverse=True) self.sorted = True
[ "def", "sort", "(", "self", ")", ":", "if", "self", ".", "sorted", ":", "return", "def", "key", "(", "variant", ")", ":", "requested_key", "=", "[", "]", "names", "=", "set", "(", ")", "for", "i", ",", "request", "in", "enumerate", "(", "self", ".", "solver", ".", "request_list", ")", ":", "if", "not", "request", ".", "conflict", ":", "req", "=", "variant", ".", "requires_list", ".", "get", "(", "request", ".", "name", ")", "if", "req", "is", "not", "None", ":", "requested_key", ".", "append", "(", "(", "-", "i", ",", "req", ".", "range", ")", ")", "names", ".", "add", "(", "req", ".", "name", ")", "additional_key", "=", "[", "]", "for", "request", "in", "variant", ".", "requires_list", ":", "if", "not", "request", ".", "conflict", "and", "request", ".", "name", "not", "in", "names", ":", "additional_key", ".", "append", "(", "(", "request", ".", "range", ",", "request", ".", "name", ")", ")", "if", "(", "VariantSelectMode", "[", "config", ".", "variant_select_mode", "]", "==", "VariantSelectMode", ".", "version_priority", ")", ":", "k", "=", "(", "requested_key", ",", "-", "len", "(", "additional_key", ")", ",", "additional_key", ",", "variant", ".", "index", ")", "else", ":", "# VariantSelectMode.intersection_priority", "k", "=", "(", "len", "(", "requested_key", ")", ",", "requested_key", ",", "-", "len", "(", "additional_key", ")", ",", "additional_key", ",", "variant", ".", "index", ")", "return", "k", "self", ".", "variants", ".", "sort", "(", "key", "=", "key", ",", "reverse", "=", "True", ")", "self", ".", "sorted", "=", "True" ]
Sort variants from most correct to consume, to least. Sort rules: version_priority: - sort by highest versions of packages shared with request; - THEN least number of additional packages added to solve; - THEN highest versions of additional packages; - THEN alphabetical on name of additional packages; - THEN variant index. intersection_priority: - sort by highest number of packages shared with request; - THEN sort according to version_priority Note: In theory 'variant.index' should never factor into the sort unless two variants are identical (which shouldn't happen) - this is just here as a safety measure so that sorting is guaranteed repeatable regardless.
[ "Sort", "variants", "from", "most", "correct", "to", "consume", "to", "least", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L370-L427
232,445
nerdvegas/rez
src/rez/solver.py
_PackageVariantList.get_intersection
def get_intersection(self, range_): """Get a list of variants that intersect with the given range. Args: range_ (`VersionRange`): Package version range. Returns: List of `_PackageEntry` objects. """ result = [] for entry in self.entries: package, value = entry if value is None: continue # package was blocked by package filters if package.version not in range_: continue if isinstance(value, list): variants = value entry_ = _PackageEntry(package, variants, self.solver) result.append(entry_) continue # apply package filter if self.solver.package_filter: rule = self.solver.package_filter.excludes(package) if rule: if config.debug_package_exclusions: print_debug("Package '%s' was excluded by rule '%s'" % (package.qualified_name, str(rule))) entry[1] = None continue # expand package entry into list of variants if self.solver.package_load_callback: self.solver.package_load_callback(package) variants_ = [] for var in package.iter_variants(): variant = PackageVariant(var, self.solver.building) variants_.append(variant) entry[1] = variants_ entry_ = _PackageEntry(package, variants_, self.solver) result.append(entry_) return result or None
python
def get_intersection(self, range_): """Get a list of variants that intersect with the given range. Args: range_ (`VersionRange`): Package version range. Returns: List of `_PackageEntry` objects. """ result = [] for entry in self.entries: package, value = entry if value is None: continue # package was blocked by package filters if package.version not in range_: continue if isinstance(value, list): variants = value entry_ = _PackageEntry(package, variants, self.solver) result.append(entry_) continue # apply package filter if self.solver.package_filter: rule = self.solver.package_filter.excludes(package) if rule: if config.debug_package_exclusions: print_debug("Package '%s' was excluded by rule '%s'" % (package.qualified_name, str(rule))) entry[1] = None continue # expand package entry into list of variants if self.solver.package_load_callback: self.solver.package_load_callback(package) variants_ = [] for var in package.iter_variants(): variant = PackageVariant(var, self.solver.building) variants_.append(variant) entry[1] = variants_ entry_ = _PackageEntry(package, variants_, self.solver) result.append(entry_) return result or None
[ "def", "get_intersection", "(", "self", ",", "range_", ")", ":", "result", "=", "[", "]", "for", "entry", "in", "self", ".", "entries", ":", "package", ",", "value", "=", "entry", "if", "value", "is", "None", ":", "continue", "# package was blocked by package filters", "if", "package", ".", "version", "not", "in", "range_", ":", "continue", "if", "isinstance", "(", "value", ",", "list", ")", ":", "variants", "=", "value", "entry_", "=", "_PackageEntry", "(", "package", ",", "variants", ",", "self", ".", "solver", ")", "result", ".", "append", "(", "entry_", ")", "continue", "# apply package filter", "if", "self", ".", "solver", ".", "package_filter", ":", "rule", "=", "self", ".", "solver", ".", "package_filter", ".", "excludes", "(", "package", ")", "if", "rule", ":", "if", "config", ".", "debug_package_exclusions", ":", "print_debug", "(", "\"Package '%s' was excluded by rule '%s'\"", "%", "(", "package", ".", "qualified_name", ",", "str", "(", "rule", ")", ")", ")", "entry", "[", "1", "]", "=", "None", "continue", "# expand package entry into list of variants", "if", "self", ".", "solver", ".", "package_load_callback", ":", "self", ".", "solver", ".", "package_load_callback", "(", "package", ")", "variants_", "=", "[", "]", "for", "var", "in", "package", ".", "iter_variants", "(", ")", ":", "variant", "=", "PackageVariant", "(", "var", ",", "self", ".", "solver", ".", "building", ")", "variants_", ".", "append", "(", "variant", ")", "entry", "[", "1", "]", "=", "variants_", "entry_", "=", "_PackageEntry", "(", "package", ",", "variants_", ",", "self", ".", "solver", ")", "result", ".", "append", "(", "entry_", ")", "return", "result", "or", "None" ]
Get a list of variants that intersect with the given range. Args: range_ (`VersionRange`): Package version range. Returns: List of `_PackageEntry` objects.
[ "Get", "a", "list", "of", "variants", "that", "intersect", "with", "the", "given", "range", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L453-L502
232,446
nerdvegas/rez
src/rez/solver.py
_PackageVariantSlice.intersect
def intersect(self, range_): self.solver.intersection_broad_tests_count += 1 """Remove variants whose version fall outside of the given range.""" if range_.is_any(): return self if self.solver.optimised: if range_ in self.been_intersected_with: return self if self.pr: self.pr.passive("intersecting %s wrt range '%s'...", self, range_) self.solver.intersection_tests_count += 1 with self.solver.timed(self.solver.intersection_time): # this is faster than iter_intersecting :( entries = [x for x in self.entries if x.version in range_] if not entries: return None elif len(entries) < len(self.entries): copy_ = self._copy(entries) copy_.been_intersected_with.add(range_) return copy_ else: self.been_intersected_with.add(range_) return self
python
def intersect(self, range_): self.solver.intersection_broad_tests_count += 1 """Remove variants whose version fall outside of the given range.""" if range_.is_any(): return self if self.solver.optimised: if range_ in self.been_intersected_with: return self if self.pr: self.pr.passive("intersecting %s wrt range '%s'...", self, range_) self.solver.intersection_tests_count += 1 with self.solver.timed(self.solver.intersection_time): # this is faster than iter_intersecting :( entries = [x for x in self.entries if x.version in range_] if not entries: return None elif len(entries) < len(self.entries): copy_ = self._copy(entries) copy_.been_intersected_with.add(range_) return copy_ else: self.been_intersected_with.add(range_) return self
[ "def", "intersect", "(", "self", ",", "range_", ")", ":", "self", ".", "solver", ".", "intersection_broad_tests_count", "+=", "1", "if", "range_", ".", "is_any", "(", ")", ":", "return", "self", "if", "self", ".", "solver", ".", "optimised", ":", "if", "range_", "in", "self", ".", "been_intersected_with", ":", "return", "self", "if", "self", ".", "pr", ":", "self", ".", "pr", ".", "passive", "(", "\"intersecting %s wrt range '%s'...\"", ",", "self", ",", "range_", ")", "self", ".", "solver", ".", "intersection_tests_count", "+=", "1", "with", "self", ".", "solver", ".", "timed", "(", "self", ".", "solver", ".", "intersection_time", ")", ":", "# this is faster than iter_intersecting :(", "entries", "=", "[", "x", "for", "x", "in", "self", ".", "entries", "if", "x", ".", "version", "in", "range_", "]", "if", "not", "entries", ":", "return", "None", "elif", "len", "(", "entries", ")", "<", "len", "(", "self", ".", "entries", ")", ":", "copy_", "=", "self", ".", "_copy", "(", "entries", ")", "copy_", ".", "been_intersected_with", ".", "add", "(", "range_", ")", "return", "copy_", "else", ":", "self", ".", "been_intersected_with", ".", "add", "(", "range_", ")", "return", "self" ]
Remove variants whose version fall outside of the given range.
[ "Remove", "variants", "whose", "version", "fall", "outside", "of", "the", "given", "range", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L594-L622
232,447
nerdvegas/rez
src/rez/solver.py
_PackageVariantSlice.reduce_by
def reduce_by(self, package_request): """Remove variants whos dependencies conflict with the given package request. Returns: (VariantSlice, [Reduction]) tuple, where slice may be None if all variants were reduced. """ if self.pr: reqstr = _short_req_str(package_request) self.pr.passive("reducing %s wrt %s...", self, reqstr) if self.solver.optimised: if package_request in self.been_reduced_by: return (self, []) if (package_request.range is None) or \ (package_request.name not in self.fam_requires): return (self, []) with self.solver.timed(self.solver.reduction_time): return self._reduce_by(package_request)
python
def reduce_by(self, package_request): """Remove variants whos dependencies conflict with the given package request. Returns: (VariantSlice, [Reduction]) tuple, where slice may be None if all variants were reduced. """ if self.pr: reqstr = _short_req_str(package_request) self.pr.passive("reducing %s wrt %s...", self, reqstr) if self.solver.optimised: if package_request in self.been_reduced_by: return (self, []) if (package_request.range is None) or \ (package_request.name not in self.fam_requires): return (self, []) with self.solver.timed(self.solver.reduction_time): return self._reduce_by(package_request)
[ "def", "reduce_by", "(", "self", ",", "package_request", ")", ":", "if", "self", ".", "pr", ":", "reqstr", "=", "_short_req_str", "(", "package_request", ")", "self", ".", "pr", ".", "passive", "(", "\"reducing %s wrt %s...\"", ",", "self", ",", "reqstr", ")", "if", "self", ".", "solver", ".", "optimised", ":", "if", "package_request", "in", "self", ".", "been_reduced_by", ":", "return", "(", "self", ",", "[", "]", ")", "if", "(", "package_request", ".", "range", "is", "None", ")", "or", "(", "package_request", ".", "name", "not", "in", "self", ".", "fam_requires", ")", ":", "return", "(", "self", ",", "[", "]", ")", "with", "self", ".", "solver", ".", "timed", "(", "self", ".", "solver", ".", "reduction_time", ")", ":", "return", "self", ".", "_reduce_by", "(", "package_request", ")" ]
Remove variants whos dependencies conflict with the given package request. Returns: (VariantSlice, [Reduction]) tuple, where slice may be None if all variants were reduced.
[ "Remove", "variants", "whos", "dependencies", "conflict", "with", "the", "given", "package", "request", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L624-L645
232,448
nerdvegas/rez
src/rez/solver.py
_PackageVariantSlice.split
def split(self): """Split the slice. Returns: (`_PackageVariantSlice`, `_PackageVariantSlice`) tuple, where the first is the preferred slice. """ # We sort here in the split in order to sort as late as possible. # Because splits usually happen after intersections/reductions, this # means there can be less entries to sort. # self.sort_versions() def _split(i_entry, n_variants, common_fams=None): # perform a split at a specific point result = self.entries[i_entry].split(n_variants) if result: entry, next_entry = result entries = self.entries[:i_entry] + [entry] next_entries = [next_entry] + self.entries[i_entry + 1:] else: entries = self.entries[:i_entry + 1] next_entries = self.entries[i_entry + 1:] slice_ = self._copy(entries) next_slice = self._copy(next_entries) if self.pr: if common_fams: if len(common_fams) == 1: reason_str = iter(common_fams).next() else: reason_str = ", ".join(common_fams) else: reason_str = "first variant" self.pr("split (reason: %s) %s into %s and %s", reason_str, self, slice_, next_slice) return slice_, next_slice # determine if we need to find first variant without common dependency if len(self) > 2: fams = self.first_variant.request_fams - self.extracted_fams else: fams = None if not fams: # trivial case, split on first variant return _split(0, 1) # find split point - first variant with no dependency shared with previous prev = None for i, entry in enumerate(self.entries): # sort the variants. This is done here in order to do the sort as # late as possible, simply to avoid the cost. entry.sort() for j, variant in enumerate(entry.variants): fams = fams & variant.request_fams if not fams: return _split(*prev) prev = (i, j + 1, fams) # should never get here - it's only possible if there's a common # dependency, but if there's a common dependency, split() should never # have been called. raise RezSystemError( "Unexpected solver error: common family(s) still in slice being " "split: slice: %s, family(s): %s" % (self, str(fams)))
python
def split(self): """Split the slice. Returns: (`_PackageVariantSlice`, `_PackageVariantSlice`) tuple, where the first is the preferred slice. """ # We sort here in the split in order to sort as late as possible. # Because splits usually happen after intersections/reductions, this # means there can be less entries to sort. # self.sort_versions() def _split(i_entry, n_variants, common_fams=None): # perform a split at a specific point result = self.entries[i_entry].split(n_variants) if result: entry, next_entry = result entries = self.entries[:i_entry] + [entry] next_entries = [next_entry] + self.entries[i_entry + 1:] else: entries = self.entries[:i_entry + 1] next_entries = self.entries[i_entry + 1:] slice_ = self._copy(entries) next_slice = self._copy(next_entries) if self.pr: if common_fams: if len(common_fams) == 1: reason_str = iter(common_fams).next() else: reason_str = ", ".join(common_fams) else: reason_str = "first variant" self.pr("split (reason: %s) %s into %s and %s", reason_str, self, slice_, next_slice) return slice_, next_slice # determine if we need to find first variant without common dependency if len(self) > 2: fams = self.first_variant.request_fams - self.extracted_fams else: fams = None if not fams: # trivial case, split on first variant return _split(0, 1) # find split point - first variant with no dependency shared with previous prev = None for i, entry in enumerate(self.entries): # sort the variants. This is done here in order to do the sort as # late as possible, simply to avoid the cost. entry.sort() for j, variant in enumerate(entry.variants): fams = fams & variant.request_fams if not fams: return _split(*prev) prev = (i, j + 1, fams) # should never get here - it's only possible if there's a common # dependency, but if there's a common dependency, split() should never # have been called. raise RezSystemError( "Unexpected solver error: common family(s) still in slice being " "split: slice: %s, family(s): %s" % (self, str(fams)))
[ "def", "split", "(", "self", ")", ":", "# We sort here in the split in order to sort as late as possible.", "# Because splits usually happen after intersections/reductions, this", "# means there can be less entries to sort.", "#", "self", ".", "sort_versions", "(", ")", "def", "_split", "(", "i_entry", ",", "n_variants", ",", "common_fams", "=", "None", ")", ":", "# perform a split at a specific point", "result", "=", "self", ".", "entries", "[", "i_entry", "]", ".", "split", "(", "n_variants", ")", "if", "result", ":", "entry", ",", "next_entry", "=", "result", "entries", "=", "self", ".", "entries", "[", ":", "i_entry", "]", "+", "[", "entry", "]", "next_entries", "=", "[", "next_entry", "]", "+", "self", ".", "entries", "[", "i_entry", "+", "1", ":", "]", "else", ":", "entries", "=", "self", ".", "entries", "[", ":", "i_entry", "+", "1", "]", "next_entries", "=", "self", ".", "entries", "[", "i_entry", "+", "1", ":", "]", "slice_", "=", "self", ".", "_copy", "(", "entries", ")", "next_slice", "=", "self", ".", "_copy", "(", "next_entries", ")", "if", "self", ".", "pr", ":", "if", "common_fams", ":", "if", "len", "(", "common_fams", ")", "==", "1", ":", "reason_str", "=", "iter", "(", "common_fams", ")", ".", "next", "(", ")", "else", ":", "reason_str", "=", "\", \"", ".", "join", "(", "common_fams", ")", "else", ":", "reason_str", "=", "\"first variant\"", "self", ".", "pr", "(", "\"split (reason: %s) %s into %s and %s\"", ",", "reason_str", ",", "self", ",", "slice_", ",", "next_slice", ")", "return", "slice_", ",", "next_slice", "# determine if we need to find first variant without common dependency", "if", "len", "(", "self", ")", ">", "2", ":", "fams", "=", "self", ".", "first_variant", ".", "request_fams", "-", "self", ".", "extracted_fams", "else", ":", "fams", "=", "None", "if", "not", "fams", ":", "# trivial case, split on first variant", "return", "_split", "(", "0", ",", "1", ")", "# find split point - first variant with no dependency shared with previous", "prev", "=", "None", "for", "i", ",", "entry", "in", "enumerate", "(", "self", ".", "entries", ")", ":", "# sort the variants. This is done here in order to do the sort as", "# late as possible, simply to avoid the cost.", "entry", ".", "sort", "(", ")", "for", "j", ",", "variant", "in", "enumerate", "(", "entry", ".", "variants", ")", ":", "fams", "=", "fams", "&", "variant", ".", "request_fams", "if", "not", "fams", ":", "return", "_split", "(", "*", "prev", ")", "prev", "=", "(", "i", ",", "j", "+", "1", ",", "fams", ")", "# should never get here - it's only possible if there's a common", "# dependency, but if there's a common dependency, split() should never", "# have been called.", "raise", "RezSystemError", "(", "\"Unexpected solver error: common family(s) still in slice being \"", "\"split: slice: %s, family(s): %s\"", "%", "(", "self", ",", "str", "(", "fams", ")", ")", ")" ]
Split the slice. Returns: (`_PackageVariantSlice`, `_PackageVariantSlice`) tuple, where the first is the preferred slice.
[ "Split", "the", "slice", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L730-L801
232,449
nerdvegas/rez
src/rez/solver.py
_PackageVariantSlice.sort_versions
def sort_versions(self): """Sort entries by version. The order is typically descending, but package order functions can change this. """ if self.sorted: return for orderer in (self.solver.package_orderers or []): entries = orderer.reorder(self.entries, key=lambda x: x.package) if entries is not None: self.entries = entries self.sorted = True if self.pr: self.pr("sorted: %s packages: %s", self.package_name, repr(orderer)) return # default ordering is version descending self.entries = sorted(self.entries, key=lambda x: x.version, reverse=True) self.sorted = True if self.pr: self.pr("sorted: %s packages: version descending", self.package_name)
python
def sort_versions(self): """Sort entries by version. The order is typically descending, but package order functions can change this. """ if self.sorted: return for orderer in (self.solver.package_orderers or []): entries = orderer.reorder(self.entries, key=lambda x: x.package) if entries is not None: self.entries = entries self.sorted = True if self.pr: self.pr("sorted: %s packages: %s", self.package_name, repr(orderer)) return # default ordering is version descending self.entries = sorted(self.entries, key=lambda x: x.version, reverse=True) self.sorted = True if self.pr: self.pr("sorted: %s packages: version descending", self.package_name)
[ "def", "sort_versions", "(", "self", ")", ":", "if", "self", ".", "sorted", ":", "return", "for", "orderer", "in", "(", "self", ".", "solver", ".", "package_orderers", "or", "[", "]", ")", ":", "entries", "=", "orderer", ".", "reorder", "(", "self", ".", "entries", ",", "key", "=", "lambda", "x", ":", "x", ".", "package", ")", "if", "entries", "is", "not", "None", ":", "self", ".", "entries", "=", "entries", "self", ".", "sorted", "=", "True", "if", "self", ".", "pr", ":", "self", ".", "pr", "(", "\"sorted: %s packages: %s\"", ",", "self", ".", "package_name", ",", "repr", "(", "orderer", ")", ")", "return", "# default ordering is version descending", "self", ".", "entries", "=", "sorted", "(", "self", ".", "entries", ",", "key", "=", "lambda", "x", ":", "x", ".", "version", ",", "reverse", "=", "True", ")", "self", ".", "sorted", "=", "True", "if", "self", ".", "pr", ":", "self", ".", "pr", "(", "\"sorted: %s packages: version descending\"", ",", "self", ".", "package_name", ")" ]
Sort entries by version. The order is typically descending, but package order functions can change this.
[ "Sort", "entries", "by", "version", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L803-L827
232,450
nerdvegas/rez
src/rez/solver.py
PackageVariantCache.get_variant_slice
def get_variant_slice(self, package_name, range_): """Get a list of variants from the cache. Args: package_name (str): Name of package. range_ (`VersionRange`): Package version range. Returns: `_PackageVariantSlice` object. """ variant_list = self.variant_lists.get(package_name) if variant_list is None: variant_list = _PackageVariantList(package_name, self.solver) self.variant_lists[package_name] = variant_list entries = variant_list.get_intersection(range_) if not entries: return None slice_ = _PackageVariantSlice(package_name, entries=entries, solver=self.solver) return slice_
python
def get_variant_slice(self, package_name, range_): """Get a list of variants from the cache. Args: package_name (str): Name of package. range_ (`VersionRange`): Package version range. Returns: `_PackageVariantSlice` object. """ variant_list = self.variant_lists.get(package_name) if variant_list is None: variant_list = _PackageVariantList(package_name, self.solver) self.variant_lists[package_name] = variant_list entries = variant_list.get_intersection(range_) if not entries: return None slice_ = _PackageVariantSlice(package_name, entries=entries, solver=self.solver) return slice_
[ "def", "get_variant_slice", "(", "self", ",", "package_name", ",", "range_", ")", ":", "variant_list", "=", "self", ".", "variant_lists", ".", "get", "(", "package_name", ")", "if", "variant_list", "is", "None", ":", "variant_list", "=", "_PackageVariantList", "(", "package_name", ",", "self", ".", "solver", ")", "self", ".", "variant_lists", "[", "package_name", "]", "=", "variant_list", "entries", "=", "variant_list", ".", "get_intersection", "(", "range_", ")", "if", "not", "entries", ":", "return", "None", "slice_", "=", "_PackageVariantSlice", "(", "package_name", ",", "entries", "=", "entries", ",", "solver", "=", "self", ".", "solver", ")", "return", "slice_" ]
Get a list of variants from the cache. Args: package_name (str): Name of package. range_ (`VersionRange`): Package version range. Returns: `_PackageVariantSlice` object.
[ "Get", "a", "list", "of", "variants", "from", "the", "cache", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L902-L925
232,451
nerdvegas/rez
src/rez/solver.py
_PackageScope.intersect
def intersect(self, range_): """Intersect this scope with a package range. Returns: A new copy of this scope, with variants whos version fall outside of the given range removed. If there were no removals, self is returned. If all variants were removed, None is returned. """ new_slice = None if self.package_request.conflict: if self.package_request.range is None: new_slice = self.solver._get_variant_slice( self.package_name, range_) else: new_range = range_ - self.package_request.range if new_range is not None: new_slice = self.solver._get_variant_slice( self.package_name, new_range) else: new_slice = self.variant_slice.intersect(range_) # intersection reduced the scope to nothing if new_slice is None: if self.pr: self.pr("%s intersected with range '%s' resulted in no packages", self, range_) return None # intersection narrowed the scope if new_slice is not self.variant_slice: scope = self._copy(new_slice) if self.pr: self.pr("%s was intersected to %s by range '%s'", self, scope, range_) return scope # intersection did not change the scope return self
python
def intersect(self, range_): """Intersect this scope with a package range. Returns: A new copy of this scope, with variants whos version fall outside of the given range removed. If there were no removals, self is returned. If all variants were removed, None is returned. """ new_slice = None if self.package_request.conflict: if self.package_request.range is None: new_slice = self.solver._get_variant_slice( self.package_name, range_) else: new_range = range_ - self.package_request.range if new_range is not None: new_slice = self.solver._get_variant_slice( self.package_name, new_range) else: new_slice = self.variant_slice.intersect(range_) # intersection reduced the scope to nothing if new_slice is None: if self.pr: self.pr("%s intersected with range '%s' resulted in no packages", self, range_) return None # intersection narrowed the scope if new_slice is not self.variant_slice: scope = self._copy(new_slice) if self.pr: self.pr("%s was intersected to %s by range '%s'", self, scope, range_) return scope # intersection did not change the scope return self
[ "def", "intersect", "(", "self", ",", "range_", ")", ":", "new_slice", "=", "None", "if", "self", ".", "package_request", ".", "conflict", ":", "if", "self", ".", "package_request", ".", "range", "is", "None", ":", "new_slice", "=", "self", ".", "solver", ".", "_get_variant_slice", "(", "self", ".", "package_name", ",", "range_", ")", "else", ":", "new_range", "=", "range_", "-", "self", ".", "package_request", ".", "range", "if", "new_range", "is", "not", "None", ":", "new_slice", "=", "self", ".", "solver", ".", "_get_variant_slice", "(", "self", ".", "package_name", ",", "new_range", ")", "else", ":", "new_slice", "=", "self", ".", "variant_slice", ".", "intersect", "(", "range_", ")", "# intersection reduced the scope to nothing", "if", "new_slice", "is", "None", ":", "if", "self", ".", "pr", ":", "self", ".", "pr", "(", "\"%s intersected with range '%s' resulted in no packages\"", ",", "self", ",", "range_", ")", "return", "None", "# intersection narrowed the scope", "if", "new_slice", "is", "not", "self", ".", "variant_slice", ":", "scope", "=", "self", ".", "_copy", "(", "new_slice", ")", "if", "self", ".", "pr", ":", "self", ".", "pr", "(", "\"%s was intersected to %s by range '%s'\"", ",", "self", ",", "scope", ",", "range_", ")", "return", "scope", "# intersection did not change the scope", "return", "self" ]
Intersect this scope with a package range. Returns: A new copy of this scope, with variants whos version fall outside of the given range removed. If there were no removals, self is returned. If all variants were removed, None is returned.
[ "Intersect", "this", "scope", "with", "a", "package", "range", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L956-L994
232,452
nerdvegas/rez
src/rez/solver.py
_PackageScope.reduce_by
def reduce_by(self, package_request): """Reduce this scope wrt a package request. Returns: A (_PackageScope, [Reduction]) tuple, where the scope is a new scope copy with reductions applied, or self if there were no reductions, or None if the scope was completely reduced. """ self.solver.reduction_broad_tests_count += 1 if self.package_request.conflict: # conflict scopes don't reduce. Instead, other scopes will be # reduced against a conflict scope. return (self, []) # perform the reduction new_slice, reductions = self.variant_slice.reduce_by(package_request) # there was total reduction if new_slice is None: self.solver.reductions_count += 1 if self.pr: reqstr = _short_req_str(package_request) self.pr("%s was reduced to nothing by %s", self, reqstr) self.pr.br() return (None, reductions) # there was some reduction if new_slice is not self.variant_slice: self.solver.reductions_count += 1 scope = self._copy(new_slice) if self.pr: reqstr = _short_req_str(package_request) self.pr("%s was reduced to %s by %s", self, scope, reqstr) self.pr.br() return (scope, reductions) # there was no reduction return (self, [])
python
def reduce_by(self, package_request): """Reduce this scope wrt a package request. Returns: A (_PackageScope, [Reduction]) tuple, where the scope is a new scope copy with reductions applied, or self if there were no reductions, or None if the scope was completely reduced. """ self.solver.reduction_broad_tests_count += 1 if self.package_request.conflict: # conflict scopes don't reduce. Instead, other scopes will be # reduced against a conflict scope. return (self, []) # perform the reduction new_slice, reductions = self.variant_slice.reduce_by(package_request) # there was total reduction if new_slice is None: self.solver.reductions_count += 1 if self.pr: reqstr = _short_req_str(package_request) self.pr("%s was reduced to nothing by %s", self, reqstr) self.pr.br() return (None, reductions) # there was some reduction if new_slice is not self.variant_slice: self.solver.reductions_count += 1 scope = self._copy(new_slice) if self.pr: reqstr = _short_req_str(package_request) self.pr("%s was reduced to %s by %s", self, scope, reqstr) self.pr.br() return (scope, reductions) # there was no reduction return (self, [])
[ "def", "reduce_by", "(", "self", ",", "package_request", ")", ":", "self", ".", "solver", ".", "reduction_broad_tests_count", "+=", "1", "if", "self", ".", "package_request", ".", "conflict", ":", "# conflict scopes don't reduce. Instead, other scopes will be", "# reduced against a conflict scope.", "return", "(", "self", ",", "[", "]", ")", "# perform the reduction", "new_slice", ",", "reductions", "=", "self", ".", "variant_slice", ".", "reduce_by", "(", "package_request", ")", "# there was total reduction", "if", "new_slice", "is", "None", ":", "self", ".", "solver", ".", "reductions_count", "+=", "1", "if", "self", ".", "pr", ":", "reqstr", "=", "_short_req_str", "(", "package_request", ")", "self", ".", "pr", "(", "\"%s was reduced to nothing by %s\"", ",", "self", ",", "reqstr", ")", "self", ".", "pr", ".", "br", "(", ")", "return", "(", "None", ",", "reductions", ")", "# there was some reduction", "if", "new_slice", "is", "not", "self", ".", "variant_slice", ":", "self", ".", "solver", ".", "reductions_count", "+=", "1", "scope", "=", "self", ".", "_copy", "(", "new_slice", ")", "if", "self", ".", "pr", ":", "reqstr", "=", "_short_req_str", "(", "package_request", ")", "self", ".", "pr", "(", "\"%s was reduced to %s by %s\"", ",", "self", ",", "scope", ",", "reqstr", ")", "self", ".", "pr", ".", "br", "(", ")", "return", "(", "scope", ",", "reductions", ")", "# there was no reduction", "return", "(", "self", ",", "[", "]", ")" ]
Reduce this scope wrt a package request. Returns: A (_PackageScope, [Reduction]) tuple, where the scope is a new scope copy with reductions applied, or self if there were no reductions, or None if the scope was completely reduced.
[ "Reduce", "this", "scope", "wrt", "a", "package", "request", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L996-L1037
232,453
nerdvegas/rez
src/rez/solver.py
_PackageScope.split
def split(self): """Split the scope. Returns: A (_PackageScope, _PackageScope) tuple, where the first scope is guaranteed to have a common dependency. Or None, if splitting is not applicable to this scope. """ if self.package_request.conflict or (len(self.variant_slice) == 1): return None else: r = self.variant_slice.split() if r is None: return None else: slice, next_slice = r scope = self._copy(slice) next_scope = self._copy(next_slice) return (scope, next_scope)
python
def split(self): """Split the scope. Returns: A (_PackageScope, _PackageScope) tuple, where the first scope is guaranteed to have a common dependency. Or None, if splitting is not applicable to this scope. """ if self.package_request.conflict or (len(self.variant_slice) == 1): return None else: r = self.variant_slice.split() if r is None: return None else: slice, next_slice = r scope = self._copy(slice) next_scope = self._copy(next_slice) return (scope, next_scope)
[ "def", "split", "(", "self", ")", ":", "if", "self", ".", "package_request", ".", "conflict", "or", "(", "len", "(", "self", ".", "variant_slice", ")", "==", "1", ")", ":", "return", "None", "else", ":", "r", "=", "self", ".", "variant_slice", ".", "split", "(", ")", "if", "r", "is", "None", ":", "return", "None", "else", ":", "slice", ",", "next_slice", "=", "r", "scope", "=", "self", ".", "_copy", "(", "slice", ")", "next_scope", "=", "self", ".", "_copy", "(", "next_slice", ")", "return", "(", "scope", ",", "next_scope", ")" ]
Split the scope. Returns: A (_PackageScope, _PackageScope) tuple, where the first scope is guaranteed to have a common dependency. Or None, if splitting is not applicable to this scope.
[ "Split", "the", "scope", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L1059-L1077
232,454
nerdvegas/rez
src/rez/solver.py
_ResolvePhase.finalise
def finalise(self): """Remove conflict requests, detect cyclic dependencies, and reorder packages wrt dependency and then request order. Returns: A new copy of the phase with conflict requests removed and packages correctly ordered; or, if cyclic dependencies were detected, a new phase marked as cyclic. """ assert(self._is_solved()) g = self._get_minimal_graph() scopes = dict((x.package_name, x) for x in self.scopes if not x.package_request.conflict) # check for cyclic dependencies fam_cycle = find_cycle(g) if fam_cycle: cycle = [] for fam in fam_cycle: scope = scopes[fam] variant = scope._get_solved_variant() stmt = VersionedObject.construct(fam, variant.version) cycle.append(stmt) phase = copy.copy(self) phase.scopes = scopes.values() phase.failure_reason = Cycle(cycle) phase.status = SolverStatus.cyclic return phase # reorder wrt dependencies, keeping original request order where possible fams = [x.name for x in self.solver.request_list] ordered_fams = _get_dependency_order(g, fams) scopes_ = [] for fam in ordered_fams: scope = scopes[fam] if not scope.package_request.conflict: scopes_.append(scope) phase = copy.copy(self) phase.scopes = scopes_ return phase
python
def finalise(self): """Remove conflict requests, detect cyclic dependencies, and reorder packages wrt dependency and then request order. Returns: A new copy of the phase with conflict requests removed and packages correctly ordered; or, if cyclic dependencies were detected, a new phase marked as cyclic. """ assert(self._is_solved()) g = self._get_minimal_graph() scopes = dict((x.package_name, x) for x in self.scopes if not x.package_request.conflict) # check for cyclic dependencies fam_cycle = find_cycle(g) if fam_cycle: cycle = [] for fam in fam_cycle: scope = scopes[fam] variant = scope._get_solved_variant() stmt = VersionedObject.construct(fam, variant.version) cycle.append(stmt) phase = copy.copy(self) phase.scopes = scopes.values() phase.failure_reason = Cycle(cycle) phase.status = SolverStatus.cyclic return phase # reorder wrt dependencies, keeping original request order where possible fams = [x.name for x in self.solver.request_list] ordered_fams = _get_dependency_order(g, fams) scopes_ = [] for fam in ordered_fams: scope = scopes[fam] if not scope.package_request.conflict: scopes_.append(scope) phase = copy.copy(self) phase.scopes = scopes_ return phase
[ "def", "finalise", "(", "self", ")", ":", "assert", "(", "self", ".", "_is_solved", "(", ")", ")", "g", "=", "self", ".", "_get_minimal_graph", "(", ")", "scopes", "=", "dict", "(", "(", "x", ".", "package_name", ",", "x", ")", "for", "x", "in", "self", ".", "scopes", "if", "not", "x", ".", "package_request", ".", "conflict", ")", "# check for cyclic dependencies", "fam_cycle", "=", "find_cycle", "(", "g", ")", "if", "fam_cycle", ":", "cycle", "=", "[", "]", "for", "fam", "in", "fam_cycle", ":", "scope", "=", "scopes", "[", "fam", "]", "variant", "=", "scope", ".", "_get_solved_variant", "(", ")", "stmt", "=", "VersionedObject", ".", "construct", "(", "fam", ",", "variant", ".", "version", ")", "cycle", ".", "append", "(", "stmt", ")", "phase", "=", "copy", ".", "copy", "(", "self", ")", "phase", ".", "scopes", "=", "scopes", ".", "values", "(", ")", "phase", ".", "failure_reason", "=", "Cycle", "(", "cycle", ")", "phase", ".", "status", "=", "SolverStatus", ".", "cyclic", "return", "phase", "# reorder wrt dependencies, keeping original request order where possible", "fams", "=", "[", "x", ".", "name", "for", "x", "in", "self", ".", "solver", ".", "request_list", "]", "ordered_fams", "=", "_get_dependency_order", "(", "g", ",", "fams", ")", "scopes_", "=", "[", "]", "for", "fam", "in", "ordered_fams", ":", "scope", "=", "scopes", "[", "fam", "]", "if", "not", "scope", ".", "package_request", ".", "conflict", ":", "scopes_", ".", "append", "(", "scope", ")", "phase", "=", "copy", ".", "copy", "(", "self", ")", "phase", ".", "scopes", "=", "scopes_", "return", "phase" ]
Remove conflict requests, detect cyclic dependencies, and reorder packages wrt dependency and then request order. Returns: A new copy of the phase with conflict requests removed and packages correctly ordered; or, if cyclic dependencies were detected, a new phase marked as cyclic.
[ "Remove", "conflict", "requests", "detect", "cyclic", "dependencies", "and", "reorder", "packages", "wrt", "dependency", "and", "then", "request", "order", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L1368-L1410
232,455
nerdvegas/rez
src/rez/solver.py
_ResolvePhase.split
def split(self): """Split the phase. When a phase is exhausted, it gets split into a pair of phases to be further solved. The split happens like so: 1) Select the first unsolved package scope. 2) Find some common dependency in the first N variants of the scope. 3) Split the scope into two: [:N] and [N:]. 4) Create two copies of the phase, containing each half of the split scope. The result of this split is that we have a new phase (the first phase), which contains a package scope with a common dependency. This dependency can now be intersected with the current resolve, thus progressing it. Returns: A 2-tuple of _ResolvePhase objects, where the first phase is the best contender for resolving. """ assert(self.status == SolverStatus.exhausted) scopes = [] next_scopes = [] split_i = None for i, scope in enumerate(self.scopes): if split_i is None: r = scope.split() if r is not None: scope_, next_scope = r scopes.append(scope_) next_scopes.append(next_scope) split_i = i continue scopes.append(scope) next_scopes.append(scope) assert split_i is not None phase = copy.copy(self) phase.scopes = scopes phase.status = SolverStatus.pending phase.changed_scopes_i = set([split_i]) # because a scope was narrowed by a split, other scopes need to be # reduced against it #for i in range(len(phase.scopes)): # if i != split_i: # phase.pending_reducts.add((i, split_i)) next_phase = copy.copy(phase) next_phase.scopes = next_scopes return (phase, next_phase)
python
def split(self): """Split the phase. When a phase is exhausted, it gets split into a pair of phases to be further solved. The split happens like so: 1) Select the first unsolved package scope. 2) Find some common dependency in the first N variants of the scope. 3) Split the scope into two: [:N] and [N:]. 4) Create two copies of the phase, containing each half of the split scope. The result of this split is that we have a new phase (the first phase), which contains a package scope with a common dependency. This dependency can now be intersected with the current resolve, thus progressing it. Returns: A 2-tuple of _ResolvePhase objects, where the first phase is the best contender for resolving. """ assert(self.status == SolverStatus.exhausted) scopes = [] next_scopes = [] split_i = None for i, scope in enumerate(self.scopes): if split_i is None: r = scope.split() if r is not None: scope_, next_scope = r scopes.append(scope_) next_scopes.append(next_scope) split_i = i continue scopes.append(scope) next_scopes.append(scope) assert split_i is not None phase = copy.copy(self) phase.scopes = scopes phase.status = SolverStatus.pending phase.changed_scopes_i = set([split_i]) # because a scope was narrowed by a split, other scopes need to be # reduced against it #for i in range(len(phase.scopes)): # if i != split_i: # phase.pending_reducts.add((i, split_i)) next_phase = copy.copy(phase) next_phase.scopes = next_scopes return (phase, next_phase)
[ "def", "split", "(", "self", ")", ":", "assert", "(", "self", ".", "status", "==", "SolverStatus", ".", "exhausted", ")", "scopes", "=", "[", "]", "next_scopes", "=", "[", "]", "split_i", "=", "None", "for", "i", ",", "scope", "in", "enumerate", "(", "self", ".", "scopes", ")", ":", "if", "split_i", "is", "None", ":", "r", "=", "scope", ".", "split", "(", ")", "if", "r", "is", "not", "None", ":", "scope_", ",", "next_scope", "=", "r", "scopes", ".", "append", "(", "scope_", ")", "next_scopes", ".", "append", "(", "next_scope", ")", "split_i", "=", "i", "continue", "scopes", ".", "append", "(", "scope", ")", "next_scopes", ".", "append", "(", "scope", ")", "assert", "split_i", "is", "not", "None", "phase", "=", "copy", ".", "copy", "(", "self", ")", "phase", ".", "scopes", "=", "scopes", "phase", ".", "status", "=", "SolverStatus", ".", "pending", "phase", ".", "changed_scopes_i", "=", "set", "(", "[", "split_i", "]", ")", "# because a scope was narrowed by a split, other scopes need to be", "# reduced against it", "#for i in range(len(phase.scopes)):", "# if i != split_i:", "# phase.pending_reducts.add((i, split_i))", "next_phase", "=", "copy", ".", "copy", "(", "phase", ")", "next_phase", ".", "scopes", "=", "next_scopes", "return", "(", "phase", ",", "next_phase", ")" ]
Split the phase. When a phase is exhausted, it gets split into a pair of phases to be further solved. The split happens like so: 1) Select the first unsolved package scope. 2) Find some common dependency in the first N variants of the scope. 3) Split the scope into two: [:N] and [N:]. 4) Create two copies of the phase, containing each half of the split scope. The result of this split is that we have a new phase (the first phase), which contains a package scope with a common dependency. This dependency can now be intersected with the current resolve, thus progressing it. Returns: A 2-tuple of _ResolvePhase objects, where the first phase is the best contender for resolving.
[ "Split", "the", "phase", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L1412-L1466
232,456
nerdvegas/rez
src/rez/solver.py
Solver.status
def status(self): """Return the current status of the solve. Returns: SolverStatus: Enum representation of the state of the solver. """ if self.request_list.conflict: return SolverStatus.failed if self.callback_return == SolverCallbackReturn.fail: # the solve has failed because a callback has nominated the most # recent failure as the reason. return SolverStatus.failed st = self.phase_stack[-1].status if st == SolverStatus.cyclic: return SolverStatus.failed elif len(self.phase_stack) > 1: if st == SolverStatus.solved: return SolverStatus.solved else: return SolverStatus.unsolved elif st in (SolverStatus.pending, SolverStatus.exhausted): return SolverStatus.unsolved else: return st
python
def status(self): """Return the current status of the solve. Returns: SolverStatus: Enum representation of the state of the solver. """ if self.request_list.conflict: return SolverStatus.failed if self.callback_return == SolverCallbackReturn.fail: # the solve has failed because a callback has nominated the most # recent failure as the reason. return SolverStatus.failed st = self.phase_stack[-1].status if st == SolverStatus.cyclic: return SolverStatus.failed elif len(self.phase_stack) > 1: if st == SolverStatus.solved: return SolverStatus.solved else: return SolverStatus.unsolved elif st in (SolverStatus.pending, SolverStatus.exhausted): return SolverStatus.unsolved else: return st
[ "def", "status", "(", "self", ")", ":", "if", "self", ".", "request_list", ".", "conflict", ":", "return", "SolverStatus", ".", "failed", "if", "self", ".", "callback_return", "==", "SolverCallbackReturn", ".", "fail", ":", "# the solve has failed because a callback has nominated the most", "# recent failure as the reason.", "return", "SolverStatus", ".", "failed", "st", "=", "self", ".", "phase_stack", "[", "-", "1", "]", ".", "status", "if", "st", "==", "SolverStatus", ".", "cyclic", ":", "return", "SolverStatus", ".", "failed", "elif", "len", "(", "self", ".", "phase_stack", ")", ">", "1", ":", "if", "st", "==", "SolverStatus", ".", "solved", ":", "return", "SolverStatus", ".", "solved", "else", ":", "return", "SolverStatus", ".", "unsolved", "elif", "st", "in", "(", "SolverStatus", ".", "pending", ",", "SolverStatus", ".", "exhausted", ")", ":", "return", "SolverStatus", ".", "unsolved", "else", ":", "return", "st" ]
Return the current status of the solve. Returns: SolverStatus: Enum representation of the state of the solver.
[ "Return", "the", "current", "status", "of", "the", "solve", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L1881-L1906
232,457
nerdvegas/rez
src/rez/solver.py
Solver.num_fails
def num_fails(self): """Return the number of failed solve steps that have been executed. Note that num_solves is inclusive of failures.""" n = len(self.failed_phase_list) if self.phase_stack[-1].status in (SolverStatus.failed, SolverStatus.cyclic): n += 1 return n
python
def num_fails(self): """Return the number of failed solve steps that have been executed. Note that num_solves is inclusive of failures.""" n = len(self.failed_phase_list) if self.phase_stack[-1].status in (SolverStatus.failed, SolverStatus.cyclic): n += 1 return n
[ "def", "num_fails", "(", "self", ")", ":", "n", "=", "len", "(", "self", ".", "failed_phase_list", ")", "if", "self", ".", "phase_stack", "[", "-", "1", "]", ".", "status", "in", "(", "SolverStatus", ".", "failed", ",", "SolverStatus", ".", "cyclic", ")", ":", "n", "+=", "1", "return", "n" ]
Return the number of failed solve steps that have been executed. Note that num_solves is inclusive of failures.
[ "Return", "the", "number", "of", "failed", "solve", "steps", "that", "have", "been", "executed", ".", "Note", "that", "num_solves", "is", "inclusive", "of", "failures", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L1914-L1920
232,458
nerdvegas/rez
src/rez/solver.py
Solver.resolved_packages
def resolved_packages(self): """Return a list of PackageVariant objects, or None if the resolve did not complete or was unsuccessful. """ if (self.status != SolverStatus.solved): return None final_phase = self.phase_stack[-1] return final_phase._get_solved_variants()
python
def resolved_packages(self): """Return a list of PackageVariant objects, or None if the resolve did not complete or was unsuccessful. """ if (self.status != SolverStatus.solved): return None final_phase = self.phase_stack[-1] return final_phase._get_solved_variants()
[ "def", "resolved_packages", "(", "self", ")", ":", "if", "(", "self", ".", "status", "!=", "SolverStatus", ".", "solved", ")", ":", "return", "None", "final_phase", "=", "self", ".", "phase_stack", "[", "-", "1", "]", "return", "final_phase", ".", "_get_solved_variants", "(", ")" ]
Return a list of PackageVariant objects, or None if the resolve did not complete or was unsuccessful.
[ "Return", "a", "list", "of", "PackageVariant", "objects", "or", "None", "if", "the", "resolve", "did", "not", "complete", "or", "was", "unsuccessful", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L1928-L1936
232,459
nerdvegas/rez
src/rez/solver.py
Solver.reset
def reset(self): """Reset the solver, removing any current solve.""" if not self.request_list.conflict: phase = _ResolvePhase(self.request_list.requirements, solver=self) self.pr("resetting...") self._init() self._push_phase(phase)
python
def reset(self): """Reset the solver, removing any current solve.""" if not self.request_list.conflict: phase = _ResolvePhase(self.request_list.requirements, solver=self) self.pr("resetting...") self._init() self._push_phase(phase)
[ "def", "reset", "(", "self", ")", ":", "if", "not", "self", ".", "request_list", ".", "conflict", ":", "phase", "=", "_ResolvePhase", "(", "self", ".", "request_list", ".", "requirements", ",", "solver", "=", "self", ")", "self", ".", "pr", "(", "\"resetting...\"", ")", "self", ".", "_init", "(", ")", "self", ".", "_push_phase", "(", "phase", ")" ]
Reset the solver, removing any current solve.
[ "Reset", "the", "solver", "removing", "any", "current", "solve", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L1938-L1944
232,460
nerdvegas/rez
src/rez/solver.py
Solver.solve
def solve(self): """Attempt to solve the request. """ if self.solve_begun: raise ResolveError("cannot run solve() on a solve that has " "already been started") t1 = time.time() pt1 = package_repo_stats.package_load_time # iteratively solve phases while self.status == SolverStatus.unsolved: self.solve_step() if self.status == SolverStatus.unsolved and not self._do_callback(): break self.load_time = package_repo_stats.package_load_time - pt1 self.solve_time = time.time() - t1 # print stats if self.pr.verbosity > 2: from pprint import pformat self.pr.subheader("SOLVE STATS:") self.pr(pformat(self.solve_stats)) elif self.print_stats: from pprint import pformat data = {"solve_stats": self.solve_stats} print >> (self.buf or sys.stdout), pformat(data)
python
def solve(self): """Attempt to solve the request. """ if self.solve_begun: raise ResolveError("cannot run solve() on a solve that has " "already been started") t1 = time.time() pt1 = package_repo_stats.package_load_time # iteratively solve phases while self.status == SolverStatus.unsolved: self.solve_step() if self.status == SolverStatus.unsolved and not self._do_callback(): break self.load_time = package_repo_stats.package_load_time - pt1 self.solve_time = time.time() - t1 # print stats if self.pr.verbosity > 2: from pprint import pformat self.pr.subheader("SOLVE STATS:") self.pr(pformat(self.solve_stats)) elif self.print_stats: from pprint import pformat data = {"solve_stats": self.solve_stats} print >> (self.buf or sys.stdout), pformat(data)
[ "def", "solve", "(", "self", ")", ":", "if", "self", ".", "solve_begun", ":", "raise", "ResolveError", "(", "\"cannot run solve() on a solve that has \"", "\"already been started\"", ")", "t1", "=", "time", ".", "time", "(", ")", "pt1", "=", "package_repo_stats", ".", "package_load_time", "# iteratively solve phases", "while", "self", ".", "status", "==", "SolverStatus", ".", "unsolved", ":", "self", ".", "solve_step", "(", ")", "if", "self", ".", "status", "==", "SolverStatus", ".", "unsolved", "and", "not", "self", ".", "_do_callback", "(", ")", ":", "break", "self", ".", "load_time", "=", "package_repo_stats", ".", "package_load_time", "-", "pt1", "self", ".", "solve_time", "=", "time", ".", "time", "(", ")", "-", "t1", "# print stats", "if", "self", ".", "pr", ".", "verbosity", ">", "2", ":", "from", "pprint", "import", "pformat", "self", ".", "pr", ".", "subheader", "(", "\"SOLVE STATS:\"", ")", "self", ".", "pr", "(", "pformat", "(", "self", ".", "solve_stats", ")", ")", "elif", "self", ".", "print_stats", ":", "from", "pprint", "import", "pformat", "data", "=", "{", "\"solve_stats\"", ":", "self", ".", "solve_stats", "}", "print", ">>", "(", "self", ".", "buf", "or", "sys", ".", "stdout", ")", ",", "pformat", "(", "data", ")" ]
Attempt to solve the request.
[ "Attempt", "to", "solve", "the", "request", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L1946-L1974
232,461
nerdvegas/rez
src/rez/solver.py
Solver.solve_step
def solve_step(self): """Perform a single solve step. """ self.solve_begun = True if self.status != SolverStatus.unsolved: return if self.pr: self.pr.header("SOLVE #%d (%d fails so far)...", self.solve_count + 1, self.num_fails) phase = self._pop_phase() if phase.status == SolverStatus.failed: # a previously failed phase self.pr("discarded failed phase, fetching previous unsolved phase...") self.failed_phase_list.append(phase) phase = self._pop_phase() if phase.status == SolverStatus.exhausted: self.pr.subheader("SPLITTING:") phase, next_phase = phase.split() self._push_phase(next_phase) if self.pr: self.pr("new phase: %s", phase) new_phase = phase.solve() self.solve_count += 1 if new_phase.status == SolverStatus.failed: self.pr.subheader("FAILED:") self._push_phase(new_phase) if self.pr and len(self.phase_stack) == 1: self.pr.header("FAIL: there is no solution") elif new_phase.status == SolverStatus.solved: # solved, but there may be cyclic dependencies self.pr.subheader("SOLVED:") final_phase = new_phase.finalise() self._push_phase(final_phase) if self.pr: if final_phase.status == SolverStatus.cyclic: self.pr.header("FAIL: a cycle was detected") else: self.pr.header("SUCCESS") else: self.pr.subheader("EXHAUSTED:") assert(new_phase.status == SolverStatus.exhausted) self._push_phase(new_phase)
python
def solve_step(self): """Perform a single solve step. """ self.solve_begun = True if self.status != SolverStatus.unsolved: return if self.pr: self.pr.header("SOLVE #%d (%d fails so far)...", self.solve_count + 1, self.num_fails) phase = self._pop_phase() if phase.status == SolverStatus.failed: # a previously failed phase self.pr("discarded failed phase, fetching previous unsolved phase...") self.failed_phase_list.append(phase) phase = self._pop_phase() if phase.status == SolverStatus.exhausted: self.pr.subheader("SPLITTING:") phase, next_phase = phase.split() self._push_phase(next_phase) if self.pr: self.pr("new phase: %s", phase) new_phase = phase.solve() self.solve_count += 1 if new_phase.status == SolverStatus.failed: self.pr.subheader("FAILED:") self._push_phase(new_phase) if self.pr and len(self.phase_stack) == 1: self.pr.header("FAIL: there is no solution") elif new_phase.status == SolverStatus.solved: # solved, but there may be cyclic dependencies self.pr.subheader("SOLVED:") final_phase = new_phase.finalise() self._push_phase(final_phase) if self.pr: if final_phase.status == SolverStatus.cyclic: self.pr.header("FAIL: a cycle was detected") else: self.pr.header("SUCCESS") else: self.pr.subheader("EXHAUSTED:") assert(new_phase.status == SolverStatus.exhausted) self._push_phase(new_phase)
[ "def", "solve_step", "(", "self", ")", ":", "self", ".", "solve_begun", "=", "True", "if", "self", ".", "status", "!=", "SolverStatus", ".", "unsolved", ":", "return", "if", "self", ".", "pr", ":", "self", ".", "pr", ".", "header", "(", "\"SOLVE #%d (%d fails so far)...\"", ",", "self", ".", "solve_count", "+", "1", ",", "self", ".", "num_fails", ")", "phase", "=", "self", ".", "_pop_phase", "(", ")", "if", "phase", ".", "status", "==", "SolverStatus", ".", "failed", ":", "# a previously failed phase", "self", ".", "pr", "(", "\"discarded failed phase, fetching previous unsolved phase...\"", ")", "self", ".", "failed_phase_list", ".", "append", "(", "phase", ")", "phase", "=", "self", ".", "_pop_phase", "(", ")", "if", "phase", ".", "status", "==", "SolverStatus", ".", "exhausted", ":", "self", ".", "pr", ".", "subheader", "(", "\"SPLITTING:\"", ")", "phase", ",", "next_phase", "=", "phase", ".", "split", "(", ")", "self", ".", "_push_phase", "(", "next_phase", ")", "if", "self", ".", "pr", ":", "self", ".", "pr", "(", "\"new phase: %s\"", ",", "phase", ")", "new_phase", "=", "phase", ".", "solve", "(", ")", "self", ".", "solve_count", "+=", "1", "if", "new_phase", ".", "status", "==", "SolverStatus", ".", "failed", ":", "self", ".", "pr", ".", "subheader", "(", "\"FAILED:\"", ")", "self", ".", "_push_phase", "(", "new_phase", ")", "if", "self", ".", "pr", "and", "len", "(", "self", ".", "phase_stack", ")", "==", "1", ":", "self", ".", "pr", ".", "header", "(", "\"FAIL: there is no solution\"", ")", "elif", "new_phase", ".", "status", "==", "SolverStatus", ".", "solved", ":", "# solved, but there may be cyclic dependencies", "self", ".", "pr", ".", "subheader", "(", "\"SOLVED:\"", ")", "final_phase", "=", "new_phase", ".", "finalise", "(", ")", "self", ".", "_push_phase", "(", "final_phase", ")", "if", "self", ".", "pr", ":", "if", "final_phase", ".", "status", "==", "SolverStatus", ".", "cyclic", ":", "self", ".", "pr", ".", "header", "(", "\"FAIL: a cycle was detected\"", ")", "else", ":", "self", ".", "pr", ".", "header", "(", "\"SUCCESS\"", ")", "else", ":", "self", ".", "pr", ".", "subheader", "(", "\"EXHAUSTED:\"", ")", "assert", "(", "new_phase", ".", "status", "==", "SolverStatus", ".", "exhausted", ")", "self", ".", "_push_phase", "(", "new_phase", ")" ]
Perform a single solve step.
[ "Perform", "a", "single", "solve", "step", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L2013-L2062
232,462
nerdvegas/rez
src/rez/solver.py
Solver.failure_reason
def failure_reason(self, failure_index=None): """Get the reason for a failure. Args: failure_index: Index of the fail to return the graph for (can be negative). If None, the most appropriate failure is chosen according to these rules: - If the fail is cyclic, the most recent fail (the one containing the cycle) is used; - If a callback has caused a failure, the most recent fail is used; - Otherwise, the first fail is used. Returns: A `FailureReason` subclass instance describing the failure. """ phase, _ = self._get_failed_phase(failure_index) return phase.failure_reason
python
def failure_reason(self, failure_index=None): """Get the reason for a failure. Args: failure_index: Index of the fail to return the graph for (can be negative). If None, the most appropriate failure is chosen according to these rules: - If the fail is cyclic, the most recent fail (the one containing the cycle) is used; - If a callback has caused a failure, the most recent fail is used; - Otherwise, the first fail is used. Returns: A `FailureReason` subclass instance describing the failure. """ phase, _ = self._get_failed_phase(failure_index) return phase.failure_reason
[ "def", "failure_reason", "(", "self", ",", "failure_index", "=", "None", ")", ":", "phase", ",", "_", "=", "self", ".", "_get_failed_phase", "(", "failure_index", ")", "return", "phase", ".", "failure_reason" ]
Get the reason for a failure. Args: failure_index: Index of the fail to return the graph for (can be negative). If None, the most appropriate failure is chosen according to these rules: - If the fail is cyclic, the most recent fail (the one containing the cycle) is used; - If a callback has caused a failure, the most recent fail is used; - Otherwise, the first fail is used. Returns: A `FailureReason` subclass instance describing the failure.
[ "Get", "the", "reason", "for", "a", "failure", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L2064-L2080
232,463
nerdvegas/rez
src/rez/solver.py
Solver.failure_packages
def failure_packages(self, failure_index=None): """Get packages involved in a failure. Args: failure_index: See `failure_reason`. Returns: A list of Requirement objects. """ phase, _ = self._get_failed_phase(failure_index) fr = phase.failure_reason return fr.involved_requirements() if fr else None
python
def failure_packages(self, failure_index=None): """Get packages involved in a failure. Args: failure_index: See `failure_reason`. Returns: A list of Requirement objects. """ phase, _ = self._get_failed_phase(failure_index) fr = phase.failure_reason return fr.involved_requirements() if fr else None
[ "def", "failure_packages", "(", "self", ",", "failure_index", "=", "None", ")", ":", "phase", ",", "_", "=", "self", ".", "_get_failed_phase", "(", "failure_index", ")", "fr", "=", "phase", ".", "failure_reason", "return", "fr", ".", "involved_requirements", "(", ")", "if", "fr", "else", "None" ]
Get packages involved in a failure. Args: failure_index: See `failure_reason`. Returns: A list of Requirement objects.
[ "Get", "packages", "involved", "in", "a", "failure", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L2092-L2103
232,464
nerdvegas/rez
src/rez/solver.py
Solver.get_graph
def get_graph(self): """Returns the most recent solve graph. This gives a graph showing the latest state of the solve. The specific graph returned depends on the solve status. When status is: unsolved: latest unsolved graph is returned; solved: final solved graph is returned; failed: most appropriate failure graph is returned (see `failure_reason`); cyclic: last failure is returned (contains cycle). Returns: A pygraph.digraph object. """ st = self.status if st in (SolverStatus.solved, SolverStatus.unsolved): phase = self._latest_nonfailed_phase() return phase.get_graph() else: return self.get_fail_graph()
python
def get_graph(self): """Returns the most recent solve graph. This gives a graph showing the latest state of the solve. The specific graph returned depends on the solve status. When status is: unsolved: latest unsolved graph is returned; solved: final solved graph is returned; failed: most appropriate failure graph is returned (see `failure_reason`); cyclic: last failure is returned (contains cycle). Returns: A pygraph.digraph object. """ st = self.status if st in (SolverStatus.solved, SolverStatus.unsolved): phase = self._latest_nonfailed_phase() return phase.get_graph() else: return self.get_fail_graph()
[ "def", "get_graph", "(", "self", ")", ":", "st", "=", "self", ".", "status", "if", "st", "in", "(", "SolverStatus", ".", "solved", ",", "SolverStatus", ".", "unsolved", ")", ":", "phase", "=", "self", ".", "_latest_nonfailed_phase", "(", ")", "return", "phase", ".", "get_graph", "(", ")", "else", ":", "return", "self", ".", "get_fail_graph", "(", ")" ]
Returns the most recent solve graph. This gives a graph showing the latest state of the solve. The specific graph returned depends on the solve status. When status is: unsolved: latest unsolved graph is returned; solved: final solved graph is returned; failed: most appropriate failure graph is returned (see `failure_reason`); cyclic: last failure is returned (contains cycle). Returns: A pygraph.digraph object.
[ "Returns", "the", "most", "recent", "solve", "graph", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L2105-L2123
232,465
nerdvegas/rez
src/rez/solver.py
Solver.get_fail_graph
def get_fail_graph(self, failure_index=None): """Returns a graph showing a solve failure. Args: failure_index: See `failure_reason` Returns: A pygraph.digraph object. """ phase, _ = self._get_failed_phase(failure_index) return phase.get_graph()
python
def get_fail_graph(self, failure_index=None): """Returns a graph showing a solve failure. Args: failure_index: See `failure_reason` Returns: A pygraph.digraph object. """ phase, _ = self._get_failed_phase(failure_index) return phase.get_graph()
[ "def", "get_fail_graph", "(", "self", ",", "failure_index", "=", "None", ")", ":", "phase", ",", "_", "=", "self", ".", "_get_failed_phase", "(", "failure_index", ")", "return", "phase", ".", "get_graph", "(", ")" ]
Returns a graph showing a solve failure. Args: failure_index: See `failure_reason` Returns: A pygraph.digraph object.
[ "Returns", "a", "graph", "showing", "a", "solve", "failure", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L2125-L2135
232,466
nerdvegas/rez
src/rez/solver.py
Solver.dump
def dump(self): """Print a formatted summary of the current solve state.""" from rez.utils.formatting import columnise rows = [] for i, phase in enumerate(self.phase_stack): rows.append((self._depth_label(i), phase.status, str(phase))) print "status: %s (%s)" % (self.status.name, self.status.description) print "initial request: %s" % str(self.request_list) print print "solve stack:" print '\n'.join(columnise(rows)) if self.failed_phase_list: rows = [] for i, phase in enumerate(self.failed_phase_list): rows.append(("#%d" % i, phase.status, str(phase))) print print "previous failures:" print '\n'.join(columnise(rows))
python
def dump(self): """Print a formatted summary of the current solve state.""" from rez.utils.formatting import columnise rows = [] for i, phase in enumerate(self.phase_stack): rows.append((self._depth_label(i), phase.status, str(phase))) print "status: %s (%s)" % (self.status.name, self.status.description) print "initial request: %s" % str(self.request_list) print print "solve stack:" print '\n'.join(columnise(rows)) if self.failed_phase_list: rows = [] for i, phase in enumerate(self.failed_phase_list): rows.append(("#%d" % i, phase.status, str(phase))) print print "previous failures:" print '\n'.join(columnise(rows))
[ "def", "dump", "(", "self", ")", ":", "from", "rez", ".", "utils", ".", "formatting", "import", "columnise", "rows", "=", "[", "]", "for", "i", ",", "phase", "in", "enumerate", "(", "self", ".", "phase_stack", ")", ":", "rows", ".", "append", "(", "(", "self", ".", "_depth_label", "(", "i", ")", ",", "phase", ".", "status", ",", "str", "(", "phase", ")", ")", ")", "print", "\"status: %s (%s)\"", "%", "(", "self", ".", "status", ".", "name", ",", "self", ".", "status", ".", "description", ")", "print", "\"initial request: %s\"", "%", "str", "(", "self", ".", "request_list", ")", "print", "print", "\"solve stack:\"", "print", "'\\n'", ".", "join", "(", "columnise", "(", "rows", ")", ")", "if", "self", ".", "failed_phase_list", ":", "rows", "=", "[", "]", "for", "i", ",", "phase", "in", "enumerate", "(", "self", ".", "failed_phase_list", ")", ":", "rows", ".", "append", "(", "(", "\"#%d\"", "%", "i", ",", "phase", ".", "status", ",", "str", "(", "phase", ")", ")", ")", "print", "print", "\"previous failures:\"", "print", "'\\n'", ".", "join", "(", "columnise", "(", "rows", ")", ")" ]
Print a formatted summary of the current solve state.
[ "Print", "a", "formatted", "summary", "of", "the", "current", "solve", "state", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/solver.py#L2137-L2157
232,467
nerdvegas/rez
src/rez/utils/filesystem.py
make_path_writable
def make_path_writable(path): """Temporarily make `path` writable, if possible. Does nothing if: - config setting 'make_package_temporarily_writable' is False; - this can't be done (eg we don't own `path`). Args: path (str): Path to make temporarily writable """ from rez.config import config try: orig_mode = os.stat(path).st_mode new_mode = orig_mode if config.make_package_temporarily_writable and \ not os.access(path, os.W_OK): new_mode = orig_mode | stat.S_IWUSR # make writable if new_mode != orig_mode: os.chmod(path, new_mode) except OSError: # ignore access errors here, and just do nothing. It will be more # intuitive for the calling code to fail on access instead. # orig_mode = None new_mode = None # yield, then reset mode back to original try: yield finally: if new_mode != orig_mode: os.chmod(path, orig_mode)
python
def make_path_writable(path): """Temporarily make `path` writable, if possible. Does nothing if: - config setting 'make_package_temporarily_writable' is False; - this can't be done (eg we don't own `path`). Args: path (str): Path to make temporarily writable """ from rez.config import config try: orig_mode = os.stat(path).st_mode new_mode = orig_mode if config.make_package_temporarily_writable and \ not os.access(path, os.W_OK): new_mode = orig_mode | stat.S_IWUSR # make writable if new_mode != orig_mode: os.chmod(path, new_mode) except OSError: # ignore access errors here, and just do nothing. It will be more # intuitive for the calling code to fail on access instead. # orig_mode = None new_mode = None # yield, then reset mode back to original try: yield finally: if new_mode != orig_mode: os.chmod(path, orig_mode)
[ "def", "make_path_writable", "(", "path", ")", ":", "from", "rez", ".", "config", "import", "config", "try", ":", "orig_mode", "=", "os", ".", "stat", "(", "path", ")", ".", "st_mode", "new_mode", "=", "orig_mode", "if", "config", ".", "make_package_temporarily_writable", "and", "not", "os", ".", "access", "(", "path", ",", "os", ".", "W_OK", ")", ":", "new_mode", "=", "orig_mode", "|", "stat", ".", "S_IWUSR", "# make writable", "if", "new_mode", "!=", "orig_mode", ":", "os", ".", "chmod", "(", "path", ",", "new_mode", ")", "except", "OSError", ":", "# ignore access errors here, and just do nothing. It will be more", "# intuitive for the calling code to fail on access instead.", "#", "orig_mode", "=", "None", "new_mode", "=", "None", "# yield, then reset mode back to original", "try", ":", "yield", "finally", ":", "if", "new_mode", "!=", "orig_mode", ":", "os", ".", "chmod", "(", "path", ",", "orig_mode", ")" ]
Temporarily make `path` writable, if possible. Does nothing if: - config setting 'make_package_temporarily_writable' is False; - this can't be done (eg we don't own `path`). Args: path (str): Path to make temporarily writable
[ "Temporarily", "make", "path", "writable", "if", "possible", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L76-L112
232,468
nerdvegas/rez
src/rez/utils/filesystem.py
get_existing_path
def get_existing_path(path, topmost_path=None): """Get the longest parent path in `path` that exists. If `path` exists, it is returned. Args: path (str): Path to test topmost_path (str): Do not test this path or above Returns: str: Existing path, or None if no path was found. """ prev_path = None if topmost_path: topmost_path = os.path.normpath(topmost_path) while True: if os.path.exists(path): return path path = os.path.dirname(path) if path == prev_path: return None if topmost_path and os.path.normpath(path) == topmost_path: return None prev_path = path
python
def get_existing_path(path, topmost_path=None): """Get the longest parent path in `path` that exists. If `path` exists, it is returned. Args: path (str): Path to test topmost_path (str): Do not test this path or above Returns: str: Existing path, or None if no path was found. """ prev_path = None if topmost_path: topmost_path = os.path.normpath(topmost_path) while True: if os.path.exists(path): return path path = os.path.dirname(path) if path == prev_path: return None if topmost_path and os.path.normpath(path) == topmost_path: return None prev_path = path
[ "def", "get_existing_path", "(", "path", ",", "topmost_path", "=", "None", ")", ":", "prev_path", "=", "None", "if", "topmost_path", ":", "topmost_path", "=", "os", ".", "path", ".", "normpath", "(", "topmost_path", ")", "while", "True", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "path", "path", "=", "os", ".", "path", ".", "dirname", "(", "path", ")", "if", "path", "==", "prev_path", ":", "return", "None", "if", "topmost_path", "and", "os", ".", "path", ".", "normpath", "(", "path", ")", "==", "topmost_path", ":", "return", "None", "prev_path", "=", "path" ]
Get the longest parent path in `path` that exists. If `path` exists, it is returned. Args: path (str): Path to test topmost_path (str): Do not test this path or above Returns: str: Existing path, or None if no path was found.
[ "Get", "the", "longest", "parent", "path", "in", "path", "that", "exists", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L126-L154
232,469
nerdvegas/rez
src/rez/utils/filesystem.py
safe_makedirs
def safe_makedirs(path): """Safe makedirs. Works in a multithreaded scenario. """ if not os.path.exists(path): try: os.makedirs(path) except OSError: if not os.path.exists(path): raise
python
def safe_makedirs(path): """Safe makedirs. Works in a multithreaded scenario. """ if not os.path.exists(path): try: os.makedirs(path) except OSError: if not os.path.exists(path): raise
[ "def", "safe_makedirs", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "try", ":", "os", ".", "makedirs", "(", "path", ")", "except", "OSError", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise" ]
Safe makedirs. Works in a multithreaded scenario.
[ "Safe", "makedirs", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L157-L167
232,470
nerdvegas/rez
src/rez/utils/filesystem.py
safe_remove
def safe_remove(path): """Safely remove the given file or directory. Works in a multithreaded scenario. """ if not os.path.exists(path): return try: if os.path.isdir(path) and not os.path.islink(path): shutil.rmtree(path) else: os.remove(path) except OSError: if os.path.exists(path): raise
python
def safe_remove(path): """Safely remove the given file or directory. Works in a multithreaded scenario. """ if not os.path.exists(path): return try: if os.path.isdir(path) and not os.path.islink(path): shutil.rmtree(path) else: os.remove(path) except OSError: if os.path.exists(path): raise
[ "def", "safe_remove", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "try", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", "and", "not", "os", ".", "path", ".", "islink", "(", "path", ")", ":", "shutil", ".", "rmtree", "(", "path", ")", "else", ":", "os", ".", "remove", "(", "path", ")", "except", "OSError", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise" ]
Safely remove the given file or directory. Works in a multithreaded scenario.
[ "Safely", "remove", "the", "given", "file", "or", "directory", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L170-L185
232,471
nerdvegas/rez
src/rez/utils/filesystem.py
replacing_symlink
def replacing_symlink(source, link_name): """Create symlink that overwrites any existing target. """ with make_tmp_name(link_name) as tmp_link_name: os.symlink(source, tmp_link_name) replace_file_or_dir(link_name, tmp_link_name)
python
def replacing_symlink(source, link_name): """Create symlink that overwrites any existing target. """ with make_tmp_name(link_name) as tmp_link_name: os.symlink(source, tmp_link_name) replace_file_or_dir(link_name, tmp_link_name)
[ "def", "replacing_symlink", "(", "source", ",", "link_name", ")", ":", "with", "make_tmp_name", "(", "link_name", ")", "as", "tmp_link_name", ":", "os", ".", "symlink", "(", "source", ",", "tmp_link_name", ")", "replace_file_or_dir", "(", "link_name", ",", "tmp_link_name", ")" ]
Create symlink that overwrites any existing target.
[ "Create", "symlink", "that", "overwrites", "any", "existing", "target", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L188-L193
232,472
nerdvegas/rez
src/rez/utils/filesystem.py
replacing_copy
def replacing_copy(src, dest, follow_symlinks=False): """Perform copy that overwrites any existing target. Will copy/copytree `src` to `dest`, and will remove `dest` if it exists, regardless of what it is. If `follow_symlinks` is False, symlinks are preserved, otherwise their contents are copied. Note that this behavior is different to `shutil.copy`, which copies src into dest if dest is an existing dir. """ with make_tmp_name(dest) as tmp_dest: if os.path.islink(src) and not follow_symlinks: # special case - copy just a symlink src_ = os.readlink(src) os.symlink(src_, tmp_dest) elif os.path.isdir(src): # copy a dir shutil.copytree(src, tmp_dest, symlinks=(not follow_symlinks)) else: # copy a file shutil.copy2(src, tmp_dest) replace_file_or_dir(dest, tmp_dest)
python
def replacing_copy(src, dest, follow_symlinks=False): """Perform copy that overwrites any existing target. Will copy/copytree `src` to `dest`, and will remove `dest` if it exists, regardless of what it is. If `follow_symlinks` is False, symlinks are preserved, otherwise their contents are copied. Note that this behavior is different to `shutil.copy`, which copies src into dest if dest is an existing dir. """ with make_tmp_name(dest) as tmp_dest: if os.path.islink(src) and not follow_symlinks: # special case - copy just a symlink src_ = os.readlink(src) os.symlink(src_, tmp_dest) elif os.path.isdir(src): # copy a dir shutil.copytree(src, tmp_dest, symlinks=(not follow_symlinks)) else: # copy a file shutil.copy2(src, tmp_dest) replace_file_or_dir(dest, tmp_dest)
[ "def", "replacing_copy", "(", "src", ",", "dest", ",", "follow_symlinks", "=", "False", ")", ":", "with", "make_tmp_name", "(", "dest", ")", "as", "tmp_dest", ":", "if", "os", ".", "path", ".", "islink", "(", "src", ")", "and", "not", "follow_symlinks", ":", "# special case - copy just a symlink", "src_", "=", "os", ".", "readlink", "(", "src", ")", "os", ".", "symlink", "(", "src_", ",", "tmp_dest", ")", "elif", "os", ".", "path", ".", "isdir", "(", "src", ")", ":", "# copy a dir", "shutil", ".", "copytree", "(", "src", ",", "tmp_dest", ",", "symlinks", "=", "(", "not", "follow_symlinks", ")", ")", "else", ":", "# copy a file", "shutil", ".", "copy2", "(", "src", ",", "tmp_dest", ")", "replace_file_or_dir", "(", "dest", ",", "tmp_dest", ")" ]
Perform copy that overwrites any existing target. Will copy/copytree `src` to `dest`, and will remove `dest` if it exists, regardless of what it is. If `follow_symlinks` is False, symlinks are preserved, otherwise their contents are copied. Note that this behavior is different to `shutil.copy`, which copies src into dest if dest is an existing dir.
[ "Perform", "copy", "that", "overwrites", "any", "existing", "target", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L196-L220
232,473
nerdvegas/rez
src/rez/utils/filesystem.py
replace_file_or_dir
def replace_file_or_dir(dest, source): """Replace `dest` with `source`. Acts like an `os.rename` if `dest` does not exist. Otherwise, `dest` is deleted and `src` is renamed to `dest`. """ from rez.vendor.atomicwrites import replace_atomic if not os.path.exists(dest): try: os.rename(source, dest) return except: if not os.path.exists(dest): raise try: replace_atomic(source, dest) return except: pass with make_tmp_name(dest) as tmp_dest: os.rename(dest, tmp_dest) os.rename(source, dest)
python
def replace_file_or_dir(dest, source): """Replace `dest` with `source`. Acts like an `os.rename` if `dest` does not exist. Otherwise, `dest` is deleted and `src` is renamed to `dest`. """ from rez.vendor.atomicwrites import replace_atomic if not os.path.exists(dest): try: os.rename(source, dest) return except: if not os.path.exists(dest): raise try: replace_atomic(source, dest) return except: pass with make_tmp_name(dest) as tmp_dest: os.rename(dest, tmp_dest) os.rename(source, dest)
[ "def", "replace_file_or_dir", "(", "dest", ",", "source", ")", ":", "from", "rez", ".", "vendor", ".", "atomicwrites", "import", "replace_atomic", "if", "not", "os", ".", "path", ".", "exists", "(", "dest", ")", ":", "try", ":", "os", ".", "rename", "(", "source", ",", "dest", ")", "return", "except", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "dest", ")", ":", "raise", "try", ":", "replace_atomic", "(", "source", ",", "dest", ")", "return", "except", ":", "pass", "with", "make_tmp_name", "(", "dest", ")", "as", "tmp_dest", ":", "os", ".", "rename", "(", "dest", ",", "tmp_dest", ")", "os", ".", "rename", "(", "source", ",", "dest", ")" ]
Replace `dest` with `source`. Acts like an `os.rename` if `dest` does not exist. Otherwise, `dest` is deleted and `src` is renamed to `dest`.
[ "Replace", "dest", "with", "source", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L223-L247
232,474
nerdvegas/rez
src/rez/utils/filesystem.py
make_tmp_name
def make_tmp_name(name): """Generates a tmp name for a file or dir. This is a tempname that sits in the same dir as `name`. If it exists on disk at context exit time, it is deleted. """ path, base = os.path.split(name) tmp_base = ".tmp-%s-%s" % (base, uuid4().hex) tmp_name = os.path.join(path, tmp_base) try: yield tmp_name finally: safe_remove(tmp_name)
python
def make_tmp_name(name): """Generates a tmp name for a file or dir. This is a tempname that sits in the same dir as `name`. If it exists on disk at context exit time, it is deleted. """ path, base = os.path.split(name) tmp_base = ".tmp-%s-%s" % (base, uuid4().hex) tmp_name = os.path.join(path, tmp_base) try: yield tmp_name finally: safe_remove(tmp_name)
[ "def", "make_tmp_name", "(", "name", ")", ":", "path", ",", "base", "=", "os", ".", "path", ".", "split", "(", "name", ")", "tmp_base", "=", "\".tmp-%s-%s\"", "%", "(", "base", ",", "uuid4", "(", ")", ".", "hex", ")", "tmp_name", "=", "os", ".", "path", ".", "join", "(", "path", ",", "tmp_base", ")", "try", ":", "yield", "tmp_name", "finally", ":", "safe_remove", "(", "tmp_name", ")" ]
Generates a tmp name for a file or dir. This is a tempname that sits in the same dir as `name`. If it exists on disk at context exit time, it is deleted.
[ "Generates", "a", "tmp", "name", "for", "a", "file", "or", "dir", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L267-L280
232,475
nerdvegas/rez
src/rez/utils/filesystem.py
is_subdirectory
def is_subdirectory(path_a, path_b): """Returns True if `path_a` is a subdirectory of `path_b`.""" path_a = os.path.realpath(path_a) path_b = os.path.realpath(path_b) relative = os.path.relpath(path_a, path_b) return (not relative.startswith(os.pardir + os.sep))
python
def is_subdirectory(path_a, path_b): """Returns True if `path_a` is a subdirectory of `path_b`.""" path_a = os.path.realpath(path_a) path_b = os.path.realpath(path_b) relative = os.path.relpath(path_a, path_b) return (not relative.startswith(os.pardir + os.sep))
[ "def", "is_subdirectory", "(", "path_a", ",", "path_b", ")", ":", "path_a", "=", "os", ".", "path", ".", "realpath", "(", "path_a", ")", "path_b", "=", "os", ".", "path", ".", "realpath", "(", "path_b", ")", "relative", "=", "os", ".", "path", ".", "relpath", "(", "path_a", ",", "path_b", ")", "return", "(", "not", "relative", ".", "startswith", "(", "os", ".", "pardir", "+", "os", ".", "sep", ")", ")" ]
Returns True if `path_a` is a subdirectory of `path_b`.
[ "Returns", "True", "if", "path_a", "is", "a", "subdirectory", "of", "path_b", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L283-L288
232,476
nerdvegas/rez
src/rez/utils/filesystem.py
find_matching_symlink
def find_matching_symlink(path, source): """Find a symlink under `path` that points at `source`. If source is relative, it is considered relative to `path`. Returns: str: Name of symlink found, or None. """ def to_abs(target): if os.path.isabs(target): return target else: return os.path.normpath(os.path.join(path, target)) abs_source = to_abs(source) for name in os.listdir(path): linkpath = os.path.join(path, name) if os.path.islink: source_ = os.readlink(linkpath) if to_abs(source_) == abs_source: return name return None
python
def find_matching_symlink(path, source): """Find a symlink under `path` that points at `source`. If source is relative, it is considered relative to `path`. Returns: str: Name of symlink found, or None. """ def to_abs(target): if os.path.isabs(target): return target else: return os.path.normpath(os.path.join(path, target)) abs_source = to_abs(source) for name in os.listdir(path): linkpath = os.path.join(path, name) if os.path.islink: source_ = os.readlink(linkpath) if to_abs(source_) == abs_source: return name return None
[ "def", "find_matching_symlink", "(", "path", ",", "source", ")", ":", "def", "to_abs", "(", "target", ")", ":", "if", "os", ".", "path", ".", "isabs", "(", "target", ")", ":", "return", "target", "else", ":", "return", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "path", ",", "target", ")", ")", "abs_source", "=", "to_abs", "(", "source", ")", "for", "name", "in", "os", ".", "listdir", "(", "path", ")", ":", "linkpath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "name", ")", "if", "os", ".", "path", ".", "islink", ":", "source_", "=", "os", ".", "readlink", "(", "linkpath", ")", "if", "to_abs", "(", "source_", ")", "==", "abs_source", ":", "return", "name", "return", "None" ]
Find a symlink under `path` that points at `source`. If source is relative, it is considered relative to `path`. Returns: str: Name of symlink found, or None.
[ "Find", "a", "symlink", "under", "path", "that", "points", "at", "source", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L291-L314
232,477
nerdvegas/rez
src/rez/utils/filesystem.py
copy_or_replace
def copy_or_replace(src, dst): '''try to copy with mode, and if it fails, try replacing ''' try: shutil.copy(src, dst) except (OSError, IOError), e: # It's possible that the file existed, but was owned by someone # else - in that situation, shutil.copy might then fail when it # tries to copy perms. # However, it's possible that we have write perms to the dir - # in which case, we can just delete and replace import errno if e.errno == errno.EPERM: import tempfile # try copying into a temporary location beside the old # file - if we have perms to do that, we should have perms # to then delete the old file, and move the new one into # place if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) dst_dir, dst_name = os.path.split(dst) dst_temp = tempfile.mktemp(prefix=dst_name + '.', dir=dst_dir) shutil.copy(src, dst_temp) if not os.path.isfile(dst_temp): raise RuntimeError( "shutil.copy completed successfully, but path" " '%s' still did not exist" % dst_temp) os.remove(dst) shutil.move(dst_temp, dst)
python
def copy_or_replace(src, dst): '''try to copy with mode, and if it fails, try replacing ''' try: shutil.copy(src, dst) except (OSError, IOError), e: # It's possible that the file existed, but was owned by someone # else - in that situation, shutil.copy might then fail when it # tries to copy perms. # However, it's possible that we have write perms to the dir - # in which case, we can just delete and replace import errno if e.errno == errno.EPERM: import tempfile # try copying into a temporary location beside the old # file - if we have perms to do that, we should have perms # to then delete the old file, and move the new one into # place if os.path.isdir(dst): dst = os.path.join(dst, os.path.basename(src)) dst_dir, dst_name = os.path.split(dst) dst_temp = tempfile.mktemp(prefix=dst_name + '.', dir=dst_dir) shutil.copy(src, dst_temp) if not os.path.isfile(dst_temp): raise RuntimeError( "shutil.copy completed successfully, but path" " '%s' still did not exist" % dst_temp) os.remove(dst) shutil.move(dst_temp, dst)
[ "def", "copy_or_replace", "(", "src", ",", "dst", ")", ":", "try", ":", "shutil", ".", "copy", "(", "src", ",", "dst", ")", "except", "(", "OSError", ",", "IOError", ")", ",", "e", ":", "# It's possible that the file existed, but was owned by someone", "# else - in that situation, shutil.copy might then fail when it", "# tries to copy perms.", "# However, it's possible that we have write perms to the dir -", "# in which case, we can just delete and replace", "import", "errno", "if", "e", ".", "errno", "==", "errno", ".", "EPERM", ":", "import", "tempfile", "# try copying into a temporary location beside the old", "# file - if we have perms to do that, we should have perms", "# to then delete the old file, and move the new one into", "# place", "if", "os", ".", "path", ".", "isdir", "(", "dst", ")", ":", "dst", "=", "os", ".", "path", ".", "join", "(", "dst", ",", "os", ".", "path", ".", "basename", "(", "src", ")", ")", "dst_dir", ",", "dst_name", "=", "os", ".", "path", ".", "split", "(", "dst", ")", "dst_temp", "=", "tempfile", ".", "mktemp", "(", "prefix", "=", "dst_name", "+", "'.'", ",", "dir", "=", "dst_dir", ")", "shutil", ".", "copy", "(", "src", ",", "dst_temp", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "dst_temp", ")", ":", "raise", "RuntimeError", "(", "\"shutil.copy completed successfully, but path\"", "\" '%s' still did not exist\"", "%", "dst_temp", ")", "os", ".", "remove", "(", "dst", ")", "shutil", ".", "move", "(", "dst_temp", ",", "dst", ")" ]
try to copy with mode, and if it fails, try replacing
[ "try", "to", "copy", "with", "mode", "and", "if", "it", "fails", "try", "replacing" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L317-L347
232,478
nerdvegas/rez
src/rez/utils/filesystem.py
movetree
def movetree(src, dst): """Attempts a move, and falls back to a copy+delete if this fails """ try: shutil.move(src, dst) except: copytree(src, dst, symlinks=True, hardlinks=True) shutil.rmtree(src)
python
def movetree(src, dst): """Attempts a move, and falls back to a copy+delete if this fails """ try: shutil.move(src, dst) except: copytree(src, dst, symlinks=True, hardlinks=True) shutil.rmtree(src)
[ "def", "movetree", "(", "src", ",", "dst", ")", ":", "try", ":", "shutil", ".", "move", "(", "src", ",", "dst", ")", "except", ":", "copytree", "(", "src", ",", "dst", ",", "symlinks", "=", "True", ",", "hardlinks", "=", "True", ")", "shutil", ".", "rmtree", "(", "src", ")" ]
Attempts a move, and falls back to a copy+delete if this fails
[ "Attempts", "a", "move", "and", "falls", "back", "to", "a", "copy", "+", "delete", "if", "this", "fails" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L404-L411
232,479
nerdvegas/rez
src/rez/utils/filesystem.py
safe_chmod
def safe_chmod(path, mode): """Set the permissions mode on path, but only if it differs from the current mode. """ if stat.S_IMODE(os.stat(path).st_mode) != mode: os.chmod(path, mode)
python
def safe_chmod(path, mode): """Set the permissions mode on path, but only if it differs from the current mode. """ if stat.S_IMODE(os.stat(path).st_mode) != mode: os.chmod(path, mode)
[ "def", "safe_chmod", "(", "path", ",", "mode", ")", ":", "if", "stat", ".", "S_IMODE", "(", "os", ".", "stat", "(", "path", ")", ".", "st_mode", ")", "!=", "mode", ":", "os", ".", "chmod", "(", "path", ",", "mode", ")" ]
Set the permissions mode on path, but only if it differs from the current mode.
[ "Set", "the", "permissions", "mode", "on", "path", "but", "only", "if", "it", "differs", "from", "the", "current", "mode", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L414-L418
232,480
nerdvegas/rez
src/rez/utils/filesystem.py
encode_filesystem_name
def encode_filesystem_name(input_str): """Encodes an arbitrary unicode string to a generic filesystem-compatible non-unicode filename. The result after encoding will only contain the standard ascii lowercase letters (a-z), the digits (0-9), or periods, underscores, or dashes (".", "_", or "-"). No uppercase letters will be used, for comaptibility with case-insensitive filesystems. The rules for the encoding are: 1) Any lowercase letter, digit, period, or dash (a-z, 0-9, ., or -) is encoded as-is. 2) Any underscore is encoded as a double-underscore ("__") 3) Any uppercase ascii letter (A-Z) is encoded as an underscore followed by the corresponding lowercase letter (ie, "A" => "_a") 4) All other characters are encoded using their UTF-8 encoded unicode representation, in the following format: "_NHH..., where: a) N represents the number of bytes needed for the UTF-8 encoding, except with N=0 for one-byte representation (the exception for N=1 is made both because it means that for "standard" ascii characters in the range 0-127, their encoding will be _0xx, where xx is their ascii hex code; and because it mirrors the ways UTF-8 encoding itself works, where the number of bytes needed for the character can be determined by counting the number of leading "1"s in the binary representation of the character, except that if it is a 1-byte sequence, there are 0 leading 1's). b) HH represents the bytes of the corresponding UTF-8 encoding, in hexadecimal (using lower-case letters) As an example, the character "*", whose (hex) UTF-8 representation of 2A, would be encoded as "_02a", while the "euro" symbol, which has a UTF-8 representation of E2 82 AC, would be encoded as "_3e282ac". (Note that, strictly speaking, the "N" part of the encoding is redundant information, since it is essentially encoded in the UTF-8 representation itself, but it makes the resulting string more human-readable, and easier to decode). As an example, the string "Foo_Bar (fun).txt" would get encoded as: _foo___bar_020_028fun_029.txt """ if isinstance(input_str, str): input_str = unicode(input_str) elif not isinstance(input_str, unicode): raise TypeError("input_str must be a basestring") as_is = u'abcdefghijklmnopqrstuvwxyz0123456789.-' uppercase = u'ABCDEFGHIJKLMNOPQRSTUVWXYZ' result = [] for char in input_str: if char in as_is: result.append(char) elif char == u'_': result.append('__') elif char in uppercase: result.append('_%s' % char.lower()) else: utf8 = char.encode('utf8') N = len(utf8) if N == 1: N = 0 HH = ''.join('%x' % ord(c) for c in utf8) result.append('_%d%s' % (N, HH)) return ''.join(result)
python
def encode_filesystem_name(input_str): """Encodes an arbitrary unicode string to a generic filesystem-compatible non-unicode filename. The result after encoding will only contain the standard ascii lowercase letters (a-z), the digits (0-9), or periods, underscores, or dashes (".", "_", or "-"). No uppercase letters will be used, for comaptibility with case-insensitive filesystems. The rules for the encoding are: 1) Any lowercase letter, digit, period, or dash (a-z, 0-9, ., or -) is encoded as-is. 2) Any underscore is encoded as a double-underscore ("__") 3) Any uppercase ascii letter (A-Z) is encoded as an underscore followed by the corresponding lowercase letter (ie, "A" => "_a") 4) All other characters are encoded using their UTF-8 encoded unicode representation, in the following format: "_NHH..., where: a) N represents the number of bytes needed for the UTF-8 encoding, except with N=0 for one-byte representation (the exception for N=1 is made both because it means that for "standard" ascii characters in the range 0-127, their encoding will be _0xx, where xx is their ascii hex code; and because it mirrors the ways UTF-8 encoding itself works, where the number of bytes needed for the character can be determined by counting the number of leading "1"s in the binary representation of the character, except that if it is a 1-byte sequence, there are 0 leading 1's). b) HH represents the bytes of the corresponding UTF-8 encoding, in hexadecimal (using lower-case letters) As an example, the character "*", whose (hex) UTF-8 representation of 2A, would be encoded as "_02a", while the "euro" symbol, which has a UTF-8 representation of E2 82 AC, would be encoded as "_3e282ac". (Note that, strictly speaking, the "N" part of the encoding is redundant information, since it is essentially encoded in the UTF-8 representation itself, but it makes the resulting string more human-readable, and easier to decode). As an example, the string "Foo_Bar (fun).txt" would get encoded as: _foo___bar_020_028fun_029.txt """ if isinstance(input_str, str): input_str = unicode(input_str) elif not isinstance(input_str, unicode): raise TypeError("input_str must be a basestring") as_is = u'abcdefghijklmnopqrstuvwxyz0123456789.-' uppercase = u'ABCDEFGHIJKLMNOPQRSTUVWXYZ' result = [] for char in input_str: if char in as_is: result.append(char) elif char == u'_': result.append('__') elif char in uppercase: result.append('_%s' % char.lower()) else: utf8 = char.encode('utf8') N = len(utf8) if N == 1: N = 0 HH = ''.join('%x' % ord(c) for c in utf8) result.append('_%d%s' % (N, HH)) return ''.join(result)
[ "def", "encode_filesystem_name", "(", "input_str", ")", ":", "if", "isinstance", "(", "input_str", ",", "str", ")", ":", "input_str", "=", "unicode", "(", "input_str", ")", "elif", "not", "isinstance", "(", "input_str", ",", "unicode", ")", ":", "raise", "TypeError", "(", "\"input_str must be a basestring\"", ")", "as_is", "=", "u'abcdefghijklmnopqrstuvwxyz0123456789.-'", "uppercase", "=", "u'ABCDEFGHIJKLMNOPQRSTUVWXYZ'", "result", "=", "[", "]", "for", "char", "in", "input_str", ":", "if", "char", "in", "as_is", ":", "result", ".", "append", "(", "char", ")", "elif", "char", "==", "u'_'", ":", "result", ".", "append", "(", "'__'", ")", "elif", "char", "in", "uppercase", ":", "result", ".", "append", "(", "'_%s'", "%", "char", ".", "lower", "(", ")", ")", "else", ":", "utf8", "=", "char", ".", "encode", "(", "'utf8'", ")", "N", "=", "len", "(", "utf8", ")", "if", "N", "==", "1", ":", "N", "=", "0", "HH", "=", "''", ".", "join", "(", "'%x'", "%", "ord", "(", "c", ")", "for", "c", "in", "utf8", ")", "result", ".", "append", "(", "'_%d%s'", "%", "(", "N", ",", "HH", ")", ")", "return", "''", ".", "join", "(", "result", ")" ]
Encodes an arbitrary unicode string to a generic filesystem-compatible non-unicode filename. The result after encoding will only contain the standard ascii lowercase letters (a-z), the digits (0-9), or periods, underscores, or dashes (".", "_", or "-"). No uppercase letters will be used, for comaptibility with case-insensitive filesystems. The rules for the encoding are: 1) Any lowercase letter, digit, period, or dash (a-z, 0-9, ., or -) is encoded as-is. 2) Any underscore is encoded as a double-underscore ("__") 3) Any uppercase ascii letter (A-Z) is encoded as an underscore followed by the corresponding lowercase letter (ie, "A" => "_a") 4) All other characters are encoded using their UTF-8 encoded unicode representation, in the following format: "_NHH..., where: a) N represents the number of bytes needed for the UTF-8 encoding, except with N=0 for one-byte representation (the exception for N=1 is made both because it means that for "standard" ascii characters in the range 0-127, their encoding will be _0xx, where xx is their ascii hex code; and because it mirrors the ways UTF-8 encoding itself works, where the number of bytes needed for the character can be determined by counting the number of leading "1"s in the binary representation of the character, except that if it is a 1-byte sequence, there are 0 leading 1's). b) HH represents the bytes of the corresponding UTF-8 encoding, in hexadecimal (using lower-case letters) As an example, the character "*", whose (hex) UTF-8 representation of 2A, would be encoded as "_02a", while the "euro" symbol, which has a UTF-8 representation of E2 82 AC, would be encoded as "_3e282ac". (Note that, strictly speaking, the "N" part of the encoding is redundant information, since it is essentially encoded in the UTF-8 representation itself, but it makes the resulting string more human-readable, and easier to decode). As an example, the string "Foo_Bar (fun).txt" would get encoded as: _foo___bar_020_028fun_029.txt
[ "Encodes", "an", "arbitrary", "unicode", "string", "to", "a", "generic", "filesystem", "-", "compatible", "non", "-", "unicode", "filename", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L433-L499
232,481
nerdvegas/rez
src/rez/utils/filesystem.py
decode_filesystem_name
def decode_filesystem_name(filename): """Decodes a filename encoded using the rules given in encode_filesystem_name to a unicode string. """ result = [] remain = filename i = 0 while remain: # use match, to ensure it matches from the start of the string... match = _FILESYSTEM_TOKEN_RE.match(remain) if not match: raise ValueError("incorrectly encoded filesystem name %r" " (bad index: %d - %r)" % (filename, i, remain[:2])) match_str = match.group(0) match_len = len(match_str) i += match_len remain = remain[match_len:] match_dict = match.groupdict() if match_dict['as_is']: result.append(unicode(match_str)) elif match_dict['underscore']: result.append(u'_') elif match_dict['uppercase']: result.append(unicode(match_dict['uppercase'].upper())) elif match_dict['N']: N = int(match_dict['N']) if N == 0: N = 1 # hex-encoded, so need to grab 2*N chars bytes_len = 2 * N i += bytes_len bytes = remain[:bytes_len] remain = remain[bytes_len:] # need this check to ensure that we don't end up eval'ing # something nasty... if not _HEX_RE.match(bytes): raise ValueError("Bad utf8 encoding in name %r" " (bad index: %d - %r)" % (filename, i, bytes)) bytes_repr = ''.join('\\x%s' % bytes[i:i + 2] for i in xrange(0, bytes_len, 2)) bytes_repr = "'%s'" % bytes_repr result.append(eval(bytes_repr).decode('utf8')) else: raise ValueError("Unrecognized match type in filesystem name %r" " (bad index: %d - %r)" % (filename, i, remain[:2])) return u''.join(result)
python
def decode_filesystem_name(filename): """Decodes a filename encoded using the rules given in encode_filesystem_name to a unicode string. """ result = [] remain = filename i = 0 while remain: # use match, to ensure it matches from the start of the string... match = _FILESYSTEM_TOKEN_RE.match(remain) if not match: raise ValueError("incorrectly encoded filesystem name %r" " (bad index: %d - %r)" % (filename, i, remain[:2])) match_str = match.group(0) match_len = len(match_str) i += match_len remain = remain[match_len:] match_dict = match.groupdict() if match_dict['as_is']: result.append(unicode(match_str)) elif match_dict['underscore']: result.append(u'_') elif match_dict['uppercase']: result.append(unicode(match_dict['uppercase'].upper())) elif match_dict['N']: N = int(match_dict['N']) if N == 0: N = 1 # hex-encoded, so need to grab 2*N chars bytes_len = 2 * N i += bytes_len bytes = remain[:bytes_len] remain = remain[bytes_len:] # need this check to ensure that we don't end up eval'ing # something nasty... if not _HEX_RE.match(bytes): raise ValueError("Bad utf8 encoding in name %r" " (bad index: %d - %r)" % (filename, i, bytes)) bytes_repr = ''.join('\\x%s' % bytes[i:i + 2] for i in xrange(0, bytes_len, 2)) bytes_repr = "'%s'" % bytes_repr result.append(eval(bytes_repr).decode('utf8')) else: raise ValueError("Unrecognized match type in filesystem name %r" " (bad index: %d - %r)" % (filename, i, remain[:2])) return u''.join(result)
[ "def", "decode_filesystem_name", "(", "filename", ")", ":", "result", "=", "[", "]", "remain", "=", "filename", "i", "=", "0", "while", "remain", ":", "# use match, to ensure it matches from the start of the string...", "match", "=", "_FILESYSTEM_TOKEN_RE", ".", "match", "(", "remain", ")", "if", "not", "match", ":", "raise", "ValueError", "(", "\"incorrectly encoded filesystem name %r\"", "\" (bad index: %d - %r)\"", "%", "(", "filename", ",", "i", ",", "remain", "[", ":", "2", "]", ")", ")", "match_str", "=", "match", ".", "group", "(", "0", ")", "match_len", "=", "len", "(", "match_str", ")", "i", "+=", "match_len", "remain", "=", "remain", "[", "match_len", ":", "]", "match_dict", "=", "match", ".", "groupdict", "(", ")", "if", "match_dict", "[", "'as_is'", "]", ":", "result", ".", "append", "(", "unicode", "(", "match_str", ")", ")", "elif", "match_dict", "[", "'underscore'", "]", ":", "result", ".", "append", "(", "u'_'", ")", "elif", "match_dict", "[", "'uppercase'", "]", ":", "result", ".", "append", "(", "unicode", "(", "match_dict", "[", "'uppercase'", "]", ".", "upper", "(", ")", ")", ")", "elif", "match_dict", "[", "'N'", "]", ":", "N", "=", "int", "(", "match_dict", "[", "'N'", "]", ")", "if", "N", "==", "0", ":", "N", "=", "1", "# hex-encoded, so need to grab 2*N chars", "bytes_len", "=", "2", "*", "N", "i", "+=", "bytes_len", "bytes", "=", "remain", "[", ":", "bytes_len", "]", "remain", "=", "remain", "[", "bytes_len", ":", "]", "# need this check to ensure that we don't end up eval'ing", "# something nasty...", "if", "not", "_HEX_RE", ".", "match", "(", "bytes", ")", ":", "raise", "ValueError", "(", "\"Bad utf8 encoding in name %r\"", "\" (bad index: %d - %r)\"", "%", "(", "filename", ",", "i", ",", "bytes", ")", ")", "bytes_repr", "=", "''", ".", "join", "(", "'\\\\x%s'", "%", "bytes", "[", "i", ":", "i", "+", "2", "]", "for", "i", "in", "xrange", "(", "0", ",", "bytes_len", ",", "2", ")", ")", "bytes_repr", "=", "\"'%s'\"", "%", "bytes_repr", "result", ".", "append", "(", "eval", "(", "bytes_repr", ")", ".", "decode", "(", "'utf8'", ")", ")", "else", ":", "raise", "ValueError", "(", "\"Unrecognized match type in filesystem name %r\"", "\" (bad index: %d - %r)\"", "%", "(", "filename", ",", "i", ",", "remain", "[", ":", "2", "]", ")", ")", "return", "u''", ".", "join", "(", "result", ")" ]
Decodes a filename encoded using the rules given in encode_filesystem_name to a unicode string.
[ "Decodes", "a", "filename", "encoded", "using", "the", "rules", "given", "in", "encode_filesystem_name", "to", "a", "unicode", "string", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L506-L555
232,482
nerdvegas/rez
src/rez/utils/filesystem.py
walk_up_dirs
def walk_up_dirs(path): """Yields absolute directories starting with the given path, and iterating up through all it's parents, until it reaches a root directory""" prev_path = None current_path = os.path.abspath(path) while current_path != prev_path: yield current_path prev_path = current_path current_path = os.path.dirname(prev_path)
python
def walk_up_dirs(path): """Yields absolute directories starting with the given path, and iterating up through all it's parents, until it reaches a root directory""" prev_path = None current_path = os.path.abspath(path) while current_path != prev_path: yield current_path prev_path = current_path current_path = os.path.dirname(prev_path)
[ "def", "walk_up_dirs", "(", "path", ")", ":", "prev_path", "=", "None", "current_path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "while", "current_path", "!=", "prev_path", ":", "yield", "current_path", "prev_path", "=", "current_path", "current_path", "=", "os", ".", "path", ".", "dirname", "(", "prev_path", ")" ]
Yields absolute directories starting with the given path, and iterating up through all it's parents, until it reaches a root directory
[ "Yields", "absolute", "directories", "starting", "with", "the", "given", "path", "and", "iterating", "up", "through", "all", "it", "s", "parents", "until", "it", "reaches", "a", "root", "directory" ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/filesystem.py#L575-L583
232,483
nerdvegas/rez
src/rez/wrapper.py
Wrapper.run
def run(self, *args): """Invoke the wrapped script. Returns: Return code of the command, or 0 if the command is not run. """ if self.prefix_char is None: prefix_char = config.suite_alias_prefix_char else: prefix_char = self.prefix_char if prefix_char == '': # empty prefix char means we don't support the '+' args return self._run_no_args(args) else: return self._run(prefix_char, args)
python
def run(self, *args): """Invoke the wrapped script. Returns: Return code of the command, or 0 if the command is not run. """ if self.prefix_char is None: prefix_char = config.suite_alias_prefix_char else: prefix_char = self.prefix_char if prefix_char == '': # empty prefix char means we don't support the '+' args return self._run_no_args(args) else: return self._run(prefix_char, args)
[ "def", "run", "(", "self", ",", "*", "args", ")", ":", "if", "self", ".", "prefix_char", "is", "None", ":", "prefix_char", "=", "config", ".", "suite_alias_prefix_char", "else", ":", "prefix_char", "=", "self", ".", "prefix_char", "if", "prefix_char", "==", "''", ":", "# empty prefix char means we don't support the '+' args", "return", "self", ".", "_run_no_args", "(", "args", ")", "else", ":", "return", "self", ".", "_run", "(", "prefix_char", ",", "args", ")" ]
Invoke the wrapped script. Returns: Return code of the command, or 0 if the command is not run.
[ "Invoke", "the", "wrapped", "script", "." ]
1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/wrapper.py#L66-L81
232,484
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): """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
[ "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" ]
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
232,485
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): """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
[ "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" ]
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
232,486
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): """ 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
[ "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" ]
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
232,487
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): """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_)))
[ "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_", ")", ")", ")" ]
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
232,488
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): """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
[ "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" ]
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
232,489
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): """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
[ "def", "construct", "(", "cls", ",", "name", ",", "version", "=", "None", ")", ":", "other", "=", "VersionedObject", "(", "None", ")", "other", ".", "name_", "=", "name", "other", ".", "version_", "=", "Version", "(", ")", "if", "version", "is", "None", "else", "version", "return", "other" ]
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
232,490
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): """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
[ "def", "construct", "(", "cls", ",", "name", ",", "range", "=", "None", ")", ":", "other", "=", "Requirement", "(", "None", ")", "other", ".", "name_", "=", "name", "other", ".", "range_", "=", "VersionRange", "(", ")", "if", "range", "is", "None", "else", "range", "return", "other" ]
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
232,491
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): """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_)
[ "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_", ")" ]
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
232,492
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): """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
[ "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" ]
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
232,493
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): """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
[ "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" ]
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
232,494
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): """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
[ "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" ]
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
232,495
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): """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)
[ "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", ")" ]
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
232,496
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): """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)
[ "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", ")" ]
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
232,497
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): """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
[ "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" ]
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
232,498
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): """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)
[ "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", ")" ]
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
232,499
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): """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
[ "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" ]
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