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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
nerdvegas/rez | src/rez/backport/zipfile.py | _EndRecData | def _EndRecData(fpin):
"""Return data from the "End of Central Directory" record, or None.
The data is a list of the nine items in the ZIP "End of central dir"
record followed by a tenth item, the file seek offset of this record."""
# Determine file size
fpin.seek(0, 2)
filesize = fpin.tell()
# Check to see if this is ZIP file with no archive comment (the
# "end of central directory" structure should be the last item in the
# file if this is the case).
try:
fpin.seek(-sizeEndCentDir, 2)
except IOError:
return None
data = fpin.read()
if data[0:4] == stringEndArchive and data[-2:] == "\000\000":
# the signature is correct and there's no comment, unpack structure
endrec = struct.unpack(structEndArchive, data)
endrec=list(endrec)
# Append a blank comment and record start offset
endrec.append("")
endrec.append(filesize - sizeEndCentDir)
# Try to read the "Zip64 end of central directory" structure
return _EndRecData64(fpin, -sizeEndCentDir, endrec)
# Either this is not a ZIP file, or it is a ZIP file with an archive
# comment. Search the end of the file for the "end of central directory"
# record signature. The comment is the last item in the ZIP file and may be
# up to 64K long. It is assumed that the "end of central directory" magic
# number does not appear in the comment.
maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0)
fpin.seek(maxCommentStart, 0)
data = fpin.read()
start = data.rfind(stringEndArchive)
if start >= 0:
# found the magic number; attempt to unpack and interpret
recData = data[start:start+sizeEndCentDir]
endrec = list(struct.unpack(structEndArchive, recData))
comment = data[start+sizeEndCentDir:]
# check that comment length is correct
if endrec[_ECD_COMMENT_SIZE] == len(comment):
# Append the archive comment and start offset
endrec.append(comment)
endrec.append(maxCommentStart + start)
# Try to read the "Zip64 end of central directory" structure
return _EndRecData64(fpin, maxCommentStart + start - filesize,
endrec)
# Unable to find a valid end of central directory structure
return | python | def _EndRecData(fpin):
"""Return data from the "End of Central Directory" record, or None.
The data is a list of the nine items in the ZIP "End of central dir"
record followed by a tenth item, the file seek offset of this record."""
# Determine file size
fpin.seek(0, 2)
filesize = fpin.tell()
# Check to see if this is ZIP file with no archive comment (the
# "end of central directory" structure should be the last item in the
# file if this is the case).
try:
fpin.seek(-sizeEndCentDir, 2)
except IOError:
return None
data = fpin.read()
if data[0:4] == stringEndArchive and data[-2:] == "\000\000":
# the signature is correct and there's no comment, unpack structure
endrec = struct.unpack(structEndArchive, data)
endrec=list(endrec)
# Append a blank comment and record start offset
endrec.append("")
endrec.append(filesize - sizeEndCentDir)
# Try to read the "Zip64 end of central directory" structure
return _EndRecData64(fpin, -sizeEndCentDir, endrec)
# Either this is not a ZIP file, or it is a ZIP file with an archive
# comment. Search the end of the file for the "end of central directory"
# record signature. The comment is the last item in the ZIP file and may be
# up to 64K long. It is assumed that the "end of central directory" magic
# number does not appear in the comment.
maxCommentStart = max(filesize - (1 << 16) - sizeEndCentDir, 0)
fpin.seek(maxCommentStart, 0)
data = fpin.read()
start = data.rfind(stringEndArchive)
if start >= 0:
# found the magic number; attempt to unpack and interpret
recData = data[start:start+sizeEndCentDir]
endrec = list(struct.unpack(structEndArchive, recData))
comment = data[start+sizeEndCentDir:]
# check that comment length is correct
if endrec[_ECD_COMMENT_SIZE] == len(comment):
# Append the archive comment and start offset
endrec.append(comment)
endrec.append(maxCommentStart + start)
# Try to read the "Zip64 end of central directory" structure
return _EndRecData64(fpin, maxCommentStart + start - filesize,
endrec)
# Unable to find a valid end of central directory structure
return | [
"def",
"_EndRecData",
"(",
"fpin",
")",
":",
"# Determine file size",
"fpin",
".",
"seek",
"(",
"0",
",",
"2",
")",
"filesize",
"=",
"fpin",
".",
"tell",
"(",
")",
"# Check to see if this is ZIP file with no archive comment (the",
"# \"end of central directory\" structu... | Return data from the "End of Central Directory" record, or None.
The data is a list of the nine items in the ZIP "End of central dir"
record followed by a tenth item, the file seek offset of this record. | [
"Return",
"data",
"from",
"the",
"End",
"of",
"Central",
"Directory",
"record",
"or",
"None",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L178-L233 | train | 227,400 |
nerdvegas/rez | src/rez/backport/zipfile.py | _ZipDecrypter._GenerateCRCTable | def _GenerateCRCTable():
"""Generate a CRC-32 table.
ZIP encryption uses the CRC32 one-byte primitive for scrambling some
internal keys. We noticed that a direct implementation is faster than
relying on binascii.crc32().
"""
poly = 0xedb88320
table = [0] * 256
for i in range(256):
crc = i
for j in range(8):
if crc & 1:
crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly
else:
crc = ((crc >> 1) & 0x7FFFFFFF)
table[i] = crc
return table | python | def _GenerateCRCTable():
"""Generate a CRC-32 table.
ZIP encryption uses the CRC32 one-byte primitive for scrambling some
internal keys. We noticed that a direct implementation is faster than
relying on binascii.crc32().
"""
poly = 0xedb88320
table = [0] * 256
for i in range(256):
crc = i
for j in range(8):
if crc & 1:
crc = ((crc >> 1) & 0x7FFFFFFF) ^ poly
else:
crc = ((crc >> 1) & 0x7FFFFFFF)
table[i] = crc
return table | [
"def",
"_GenerateCRCTable",
"(",
")",
":",
"poly",
"=",
"0xedb88320",
"table",
"=",
"[",
"0",
"]",
"*",
"256",
"for",
"i",
"in",
"range",
"(",
"256",
")",
":",
"crc",
"=",
"i",
"for",
"j",
"in",
"range",
"(",
"8",
")",
":",
"if",
"crc",
"&",
... | Generate a CRC-32 table.
ZIP encryption uses the CRC32 one-byte primitive for scrambling some
internal keys. We noticed that a direct implementation is faster than
relying on binascii.crc32(). | [
"Generate",
"a",
"CRC",
"-",
"32",
"table",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L398-L415 | train | 227,401 |
nerdvegas/rez | src/rez/backport/zipfile.py | _ZipDecrypter._crc32 | def _crc32(self, ch, crc):
"""Compute the CRC32 primitive on one byte."""
return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff] | python | def _crc32(self, ch, crc):
"""Compute the CRC32 primitive on one byte."""
return ((crc >> 8) & 0xffffff) ^ self.crctable[(crc ^ ord(ch)) & 0xff] | [
"def",
"_crc32",
"(",
"self",
",",
"ch",
",",
"crc",
")",
":",
"return",
"(",
"(",
"crc",
">>",
"8",
")",
"&",
"0xffffff",
")",
"^",
"self",
".",
"crctable",
"[",
"(",
"crc",
"^",
"ord",
"(",
"ch",
")",
")",
"&",
"0xff",
"]"
] | Compute the CRC32 primitive on one byte. | [
"Compute",
"the",
"CRC32",
"primitive",
"on",
"one",
"byte",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L418-L420 | train | 227,402 |
nerdvegas/rez | src/rez/backport/zipfile.py | ZipExtFile.readline | def readline(self, size = -1):
"""Read a line with approx. size. If size is negative,
read a whole line.
"""
if size < 0:
size = sys.maxint
elif size == 0:
return ''
# check for a newline already in buffer
nl, nllen = self._checkfornewline()
if nl >= 0:
# the next line was already in the buffer
nl = min(nl, size)
else:
# no line break in buffer - try to read more
size -= len(self.linebuffer)
while nl < 0 and size > 0:
buf = self.read(min(size, 100))
if not buf:
break
self.linebuffer += buf
size -= len(buf)
# check for a newline in buffer
nl, nllen = self._checkfornewline()
# we either ran out of bytes in the file, or
# met the specified size limit without finding a newline,
# so return current buffer
if nl < 0:
s = self.linebuffer
self.linebuffer = ''
return s
buf = self.linebuffer[:nl]
self.lastdiscard = self.linebuffer[nl:nl + nllen]
self.linebuffer = self.linebuffer[nl + nllen:]
# line is always returned with \n as newline char (except possibly
# for a final incomplete line in the file, which is handled above).
return buf + "\n" | python | def readline(self, size = -1):
"""Read a line with approx. size. If size is negative,
read a whole line.
"""
if size < 0:
size = sys.maxint
elif size == 0:
return ''
# check for a newline already in buffer
nl, nllen = self._checkfornewline()
if nl >= 0:
# the next line was already in the buffer
nl = min(nl, size)
else:
# no line break in buffer - try to read more
size -= len(self.linebuffer)
while nl < 0 and size > 0:
buf = self.read(min(size, 100))
if not buf:
break
self.linebuffer += buf
size -= len(buf)
# check for a newline in buffer
nl, nllen = self._checkfornewline()
# we either ran out of bytes in the file, or
# met the specified size limit without finding a newline,
# so return current buffer
if nl < 0:
s = self.linebuffer
self.linebuffer = ''
return s
buf = self.linebuffer[:nl]
self.lastdiscard = self.linebuffer[nl:nl + nllen]
self.linebuffer = self.linebuffer[nl + nllen:]
# line is always returned with \n as newline char (except possibly
# for a final incomplete line in the file, which is handled above).
return buf + "\n" | [
"def",
"readline",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"if",
"size",
"<",
"0",
":",
"size",
"=",
"sys",
".",
"maxint",
"elif",
"size",
"==",
"0",
":",
"return",
"''",
"# check for a newline already in buffer",
"nl",
",",
"nllen",
"=",
... | Read a line with approx. size. If size is negative,
read a whole line. | [
"Read",
"a",
"line",
"with",
"approx",
".",
"size",
".",
"If",
"size",
"is",
"negative",
"read",
"a",
"whole",
"line",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L511-L553 | train | 227,403 |
nerdvegas/rez | src/rez/backport/zipfile.py | ZipFile._GetContents | def _GetContents(self):
"""Read the directory, making sure we close the file if the format
is bad."""
try:
self._RealGetContents()
except BadZipfile:
if not self._filePassed:
self.fp.close()
self.fp = None
raise | python | def _GetContents(self):
"""Read the directory, making sure we close the file if the format
is bad."""
try:
self._RealGetContents()
except BadZipfile:
if not self._filePassed:
self.fp.close()
self.fp = None
raise | [
"def",
"_GetContents",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_RealGetContents",
"(",
")",
"except",
"BadZipfile",
":",
"if",
"not",
"self",
".",
"_filePassed",
":",
"self",
".",
"fp",
".",
"close",
"(",
")",
"self",
".",
"fp",
"=",
"None",... | Read the directory, making sure we close the file if the format
is bad. | [
"Read",
"the",
"directory",
"making",
"sure",
"we",
"close",
"the",
"file",
"if",
"the",
"format",
"is",
"bad",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L714-L723 | train | 227,404 |
nerdvegas/rez | src/rez/backport/zipfile.py | ZipFile.namelist | def namelist(self):
"""Return a list of file names in the archive."""
l = []
for data in self.filelist:
l.append(data.filename)
return l | python | def namelist(self):
"""Return a list of file names in the archive."""
l = []
for data in self.filelist:
l.append(data.filename)
return l | [
"def",
"namelist",
"(",
"self",
")",
":",
"l",
"=",
"[",
"]",
"for",
"data",
"in",
"self",
".",
"filelist",
":",
"l",
".",
"append",
"(",
"data",
".",
"filename",
")",
"return",
"l"
] | Return a list of file names in the archive. | [
"Return",
"a",
"list",
"of",
"file",
"names",
"in",
"the",
"archive",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L789-L794 | train | 227,405 |
nerdvegas/rez | src/rez/backport/zipfile.py | ZipFile.printdir | def printdir(self):
"""Print a table of contents for the zip file."""
print "%-46s %19s %12s" % ("File Name", "Modified ", "Size")
for zinfo in self.filelist:
date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6]
print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size) | python | def printdir(self):
"""Print a table of contents for the zip file."""
print "%-46s %19s %12s" % ("File Name", "Modified ", "Size")
for zinfo in self.filelist:
date = "%d-%02d-%02d %02d:%02d:%02d" % zinfo.date_time[:6]
print "%-46s %s %12d" % (zinfo.filename, date, zinfo.file_size) | [
"def",
"printdir",
"(",
"self",
")",
":",
"print",
"\"%-46s %19s %12s\"",
"%",
"(",
"\"File Name\"",
",",
"\"Modified \"",
",",
"\"Size\"",
")",
"for",
"zinfo",
"in",
"self",
".",
"filelist",
":",
"date",
"=",
"\"%d-%02d-%02d %02d:%02d:%02d\"",
"%",
"zinfo",
... | Print a table of contents for the zip file. | [
"Print",
"a",
"table",
"of",
"contents",
"for",
"the",
"zip",
"file",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L801-L806 | train | 227,406 |
nerdvegas/rez | src/rez/backport/zipfile.py | ZipFile.getinfo | def getinfo(self, name):
"""Return the instance of ZipInfo given 'name'."""
info = self.NameToInfo.get(name)
if info is None:
raise KeyError(
'There is no item named %r in the archive' % name)
return info | python | def getinfo(self, name):
"""Return the instance of ZipInfo given 'name'."""
info = self.NameToInfo.get(name)
if info is None:
raise KeyError(
'There is no item named %r in the archive' % name)
return info | [
"def",
"getinfo",
"(",
"self",
",",
"name",
")",
":",
"info",
"=",
"self",
".",
"NameToInfo",
".",
"get",
"(",
"name",
")",
"if",
"info",
"is",
"None",
":",
"raise",
"KeyError",
"(",
"'There is no item named %r in the archive'",
"%",
"name",
")",
"return",... | Return the instance of ZipInfo given 'name'. | [
"Return",
"the",
"instance",
"of",
"ZipInfo",
"given",
"name",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L821-L828 | train | 227,407 |
nerdvegas/rez | src/rez/backport/zipfile.py | ZipFile.extract | def extract(self, member, path=None, pwd=None):
"""Extract a member from the archive to the current working directory,
using its full name. Its file information is extracted as accurately
as possible. `member' may be a filename or a ZipInfo object. You can
specify a different directory using `path'.
"""
if not isinstance(member, ZipInfo):
member = self.getinfo(member)
if path is None:
path = os.getcwd()
return self._extract_member(member, path, pwd) | python | def extract(self, member, path=None, pwd=None):
"""Extract a member from the archive to the current working directory,
using its full name. Its file information is extracted as accurately
as possible. `member' may be a filename or a ZipInfo object. You can
specify a different directory using `path'.
"""
if not isinstance(member, ZipInfo):
member = self.getinfo(member)
if path is None:
path = os.getcwd()
return self._extract_member(member, path, pwd) | [
"def",
"extract",
"(",
"self",
",",
"member",
",",
"path",
"=",
"None",
",",
"pwd",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"member",
",",
"ZipInfo",
")",
":",
"member",
"=",
"self",
".",
"getinfo",
"(",
"member",
")",
"if",
"path",
... | Extract a member from the archive to the current working directory,
using its full name. Its file information is extracted as accurately
as possible. `member' may be a filename or a ZipInfo object. You can
specify a different directory using `path'. | [
"Extract",
"a",
"member",
"from",
"the",
"archive",
"to",
"the",
"current",
"working",
"directory",
"using",
"its",
"full",
"name",
".",
"Its",
"file",
"information",
"is",
"extracted",
"as",
"accurately",
"as",
"possible",
".",
"member",
"may",
"be",
"a",
... | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L916-L928 | train | 227,408 |
nerdvegas/rez | src/rez/backport/zipfile.py | PyZipFile.writepy | def writepy(self, pathname, basename = ""):
"""Add all files from "pathname" to the ZIP archive.
If pathname is a package directory, search the directory and
all package subdirectories recursively for all *.py and enter
the modules into the archive. If pathname is a plain
directory, listdir *.py and enter all modules. Else, pathname
must be a Python *.py file and the module will be put into the
archive. Added modules are always module.pyo or module.pyc.
This method will compile the module.py into module.pyc if
necessary.
"""
dir, name = os.path.split(pathname)
if os.path.isdir(pathname):
initname = os.path.join(pathname, "__init__.py")
if os.path.isfile(initname):
# This is a package directory, add it
if basename:
basename = "%s/%s" % (basename, name)
else:
basename = name
if self.debug:
print "Adding package in", pathname, "as", basename
fname, arcname = self._get_codename(initname[0:-3], basename)
if self.debug:
print "Adding", arcname
self.write(fname, arcname)
dirlist = os.listdir(pathname)
dirlist.remove("__init__.py")
# Add all *.py files and package subdirectories
for filename in dirlist:
path = os.path.join(pathname, filename)
root, ext = os.path.splitext(filename)
if os.path.isdir(path):
if os.path.isfile(os.path.join(path, "__init__.py")):
# This is a package directory, add it
self.writepy(path, basename) # Recursive call
elif ext == ".py":
fname, arcname = self._get_codename(path[0:-3],
basename)
if self.debug:
print "Adding", arcname
self.write(fname, arcname)
else:
# This is NOT a package directory, add its files at top level
if self.debug:
print "Adding files from directory", pathname
for filename in os.listdir(pathname):
path = os.path.join(pathname, filename)
root, ext = os.path.splitext(filename)
if ext == ".py":
fname, arcname = self._get_codename(path[0:-3],
basename)
if self.debug:
print "Adding", arcname
self.write(fname, arcname)
else:
if pathname[-3:] != ".py":
raise RuntimeError, \
'Files added with writepy() must end with ".py"'
fname, arcname = self._get_codename(pathname[0:-3], basename)
if self.debug:
print "Adding file", arcname
self.write(fname, arcname) | python | def writepy(self, pathname, basename = ""):
"""Add all files from "pathname" to the ZIP archive.
If pathname is a package directory, search the directory and
all package subdirectories recursively for all *.py and enter
the modules into the archive. If pathname is a plain
directory, listdir *.py and enter all modules. Else, pathname
must be a Python *.py file and the module will be put into the
archive. Added modules are always module.pyo or module.pyc.
This method will compile the module.py into module.pyc if
necessary.
"""
dir, name = os.path.split(pathname)
if os.path.isdir(pathname):
initname = os.path.join(pathname, "__init__.py")
if os.path.isfile(initname):
# This is a package directory, add it
if basename:
basename = "%s/%s" % (basename, name)
else:
basename = name
if self.debug:
print "Adding package in", pathname, "as", basename
fname, arcname = self._get_codename(initname[0:-3], basename)
if self.debug:
print "Adding", arcname
self.write(fname, arcname)
dirlist = os.listdir(pathname)
dirlist.remove("__init__.py")
# Add all *.py files and package subdirectories
for filename in dirlist:
path = os.path.join(pathname, filename)
root, ext = os.path.splitext(filename)
if os.path.isdir(path):
if os.path.isfile(os.path.join(path, "__init__.py")):
# This is a package directory, add it
self.writepy(path, basename) # Recursive call
elif ext == ".py":
fname, arcname = self._get_codename(path[0:-3],
basename)
if self.debug:
print "Adding", arcname
self.write(fname, arcname)
else:
# This is NOT a package directory, add its files at top level
if self.debug:
print "Adding files from directory", pathname
for filename in os.listdir(pathname):
path = os.path.join(pathname, filename)
root, ext = os.path.splitext(filename)
if ext == ".py":
fname, arcname = self._get_codename(path[0:-3],
basename)
if self.debug:
print "Adding", arcname
self.write(fname, arcname)
else:
if pathname[-3:] != ".py":
raise RuntimeError, \
'Files added with writepy() must end with ".py"'
fname, arcname = self._get_codename(pathname[0:-3], basename)
if self.debug:
print "Adding file", arcname
self.write(fname, arcname) | [
"def",
"writepy",
"(",
"self",
",",
"pathname",
",",
"basename",
"=",
"\"\"",
")",
":",
"dir",
",",
"name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"pathname",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"pathname",
")",
":",
"initname",
... | Add all files from "pathname" to the ZIP archive.
If pathname is a package directory, search the directory and
all package subdirectories recursively for all *.py and enter
the modules into the archive. If pathname is a plain
directory, listdir *.py and enter all modules. Else, pathname
must be a Python *.py file and the module will be put into the
archive. Added modules are always module.pyo or module.pyc.
This method will compile the module.py into module.pyc if
necessary. | [
"Add",
"all",
"files",
"from",
"pathname",
"to",
"the",
"ZIP",
"archive",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/backport/zipfile.py#L1241-L1304 | train | 227,409 |
nerdvegas/rez | src/rez/vendor/atomicwrites/__init__.py | AtomicWriter.get_fileobject | def get_fileobject(self, dir=None, **kwargs):
'''Return the temporary file to use.'''
if dir is None:
dir = os.path.normpath(os.path.dirname(self._path))
descriptor, name = tempfile.mkstemp(dir=dir)
# io.open() will take either the descriptor or the name, but we need
# the name later for commit()/replace_atomic() and couldn't find a way
# to get the filename from the descriptor.
os.close(descriptor)
kwargs['mode'] = self._mode
kwargs['file'] = name
return io.open(**kwargs) | python | def get_fileobject(self, dir=None, **kwargs):
'''Return the temporary file to use.'''
if dir is None:
dir = os.path.normpath(os.path.dirname(self._path))
descriptor, name = tempfile.mkstemp(dir=dir)
# io.open() will take either the descriptor or the name, but we need
# the name later for commit()/replace_atomic() and couldn't find a way
# to get the filename from the descriptor.
os.close(descriptor)
kwargs['mode'] = self._mode
kwargs['file'] = name
return io.open(**kwargs) | [
"def",
"get_fileobject",
"(",
"self",
",",
"dir",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"dir",
"is",
"None",
":",
"dir",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"_path",
... | Return the temporary file to use. | [
"Return",
"the",
"temporary",
"file",
"to",
"use",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/atomicwrites/__init__.py#L163-L174 | train | 227,410 |
nerdvegas/rez | src/rez/vendor/atomicwrites/__init__.py | AtomicWriter.commit | def commit(self, f):
'''Move the temporary file to the target location.'''
if self._overwrite:
replace_atomic(f.name, self._path)
else:
move_atomic(f.name, self._path) | python | def commit(self, f):
'''Move the temporary file to the target location.'''
if self._overwrite:
replace_atomic(f.name, self._path)
else:
move_atomic(f.name, self._path) | [
"def",
"commit",
"(",
"self",
",",
"f",
")",
":",
"if",
"self",
".",
"_overwrite",
":",
"replace_atomic",
"(",
"f",
".",
"name",
",",
"self",
".",
"_path",
")",
"else",
":",
"move_atomic",
"(",
"f",
".",
"name",
",",
"self",
".",
"_path",
")"
] | Move the temporary file to the target location. | [
"Move",
"the",
"temporary",
"file",
"to",
"the",
"target",
"location",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/atomicwrites/__init__.py#L182-L187 | train | 227,411 |
nerdvegas/rez | src/rez/vendor/lockfile/pidlockfile.py | read_pid_from_pidfile | def read_pid_from_pidfile(pidfile_path):
""" Read the PID recorded in the named PID file.
Read and return the numeric PID recorded as text in the named
PID file. If the PID file cannot be read, or if the content is
not a valid PID, return ``None``.
"""
pid = None
try:
pidfile = open(pidfile_path, 'r')
except IOError:
pass
else:
# According to the FHS 2.3 section on PID files in /var/run:
#
# The file must consist of the process identifier in
# ASCII-encoded decimal, followed by a newline character.
#
# Programs that read PID files should be somewhat flexible
# in what they accept; i.e., they should ignore extra
# whitespace, leading zeroes, absence of the trailing
# newline, or additional lines in the PID file.
line = pidfile.readline().strip()
try:
pid = int(line)
except ValueError:
pass
pidfile.close()
return pid | python | def read_pid_from_pidfile(pidfile_path):
""" Read the PID recorded in the named PID file.
Read and return the numeric PID recorded as text in the named
PID file. If the PID file cannot be read, or if the content is
not a valid PID, return ``None``.
"""
pid = None
try:
pidfile = open(pidfile_path, 'r')
except IOError:
pass
else:
# According to the FHS 2.3 section on PID files in /var/run:
#
# The file must consist of the process identifier in
# ASCII-encoded decimal, followed by a newline character.
#
# Programs that read PID files should be somewhat flexible
# in what they accept; i.e., they should ignore extra
# whitespace, leading zeroes, absence of the trailing
# newline, or additional lines in the PID file.
line = pidfile.readline().strip()
try:
pid = int(line)
except ValueError:
pass
pidfile.close()
return pid | [
"def",
"read_pid_from_pidfile",
"(",
"pidfile_path",
")",
":",
"pid",
"=",
"None",
"try",
":",
"pidfile",
"=",
"open",
"(",
"pidfile_path",
",",
"'r'",
")",
"except",
"IOError",
":",
"pass",
"else",
":",
"# According to the FHS 2.3 section on PID files in /var/run:"... | Read the PID recorded in the named PID file.
Read and return the numeric PID recorded as text in the named
PID file. If the PID file cannot be read, or if the content is
not a valid PID, return ``None``. | [
"Read",
"the",
"PID",
"recorded",
"in",
"the",
"named",
"PID",
"file",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/lockfile/pidlockfile.py#L120-L151 | train | 227,412 |
nerdvegas/rez | src/rezgui/widgets/ConfiguredSplitter.py | ConfiguredSplitter.apply_saved_layout | def apply_saved_layout(self):
"""Call this after adding your child widgets."""
num_widgets = self.config.get(self.config_key + "/num_widgets", int)
if num_widgets:
sizes = []
for i in range(num_widgets):
key = "%s/size_%d" % (self.config_key, i)
size = self.config.get(key, int)
sizes.append(size)
self.setSizes(sizes)
return True
return False | python | def apply_saved_layout(self):
"""Call this after adding your child widgets."""
num_widgets = self.config.get(self.config_key + "/num_widgets", int)
if num_widgets:
sizes = []
for i in range(num_widgets):
key = "%s/size_%d" % (self.config_key, i)
size = self.config.get(key, int)
sizes.append(size)
self.setSizes(sizes)
return True
return False | [
"def",
"apply_saved_layout",
"(",
"self",
")",
":",
"num_widgets",
"=",
"self",
".",
"config",
".",
"get",
"(",
"self",
".",
"config_key",
"+",
"\"/num_widgets\"",
",",
"int",
")",
"if",
"num_widgets",
":",
"sizes",
"=",
"[",
"]",
"for",
"i",
"in",
"ra... | Call this after adding your child widgets. | [
"Call",
"this",
"after",
"adding",
"your",
"child",
"widgets",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/widgets/ConfiguredSplitter.py#L14-L25 | train | 227,413 |
nerdvegas/rez | src/rez/utils/data_utils.py | remove_nones | def remove_nones(**kwargs):
"""Return diict copy with nones removed.
"""
return dict((k, v) for k, v in kwargs.iteritems() if v is not None) | python | def remove_nones(**kwargs):
"""Return diict copy with nones removed.
"""
return dict((k, v) for k, v in kwargs.iteritems() if v is not None) | [
"def",
"remove_nones",
"(",
"*",
"*",
"kwargs",
")",
":",
"return",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"kwargs",
".",
"iteritems",
"(",
")",
"if",
"v",
"is",
"not",
"None",
")"
] | Return diict copy with nones removed. | [
"Return",
"diict",
"copy",
"with",
"nones",
"removed",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/data_utils.py#L33-L36 | train | 227,414 |
nerdvegas/rez | src/rez/utils/data_utils.py | deep_update | def deep_update(dict1, dict2):
"""Perform a deep merge of `dict2` into `dict1`.
Note that `dict2` and any nested dicts are unchanged.
Supports `ModifyList` instances.
"""
def flatten(v):
if isinstance(v, ModifyList):
return v.apply([])
elif isinstance(v, dict):
return dict((k, flatten(v_)) for k, v_ in v.iteritems())
else:
return v
def merge(v1, v2):
if isinstance(v1, dict) and isinstance(v2, dict):
deep_update(v1, v2)
return v1
elif isinstance(v2, ModifyList):
v1 = flatten(v1)
return v2.apply(v1)
else:
return flatten(v2)
for k1, v1 in dict1.iteritems():
if k1 not in dict2:
dict1[k1] = flatten(v1)
for k2, v2 in dict2.iteritems():
v1 = dict1.get(k2)
if v1 is KeyError:
dict1[k2] = flatten(v2)
else:
dict1[k2] = merge(v1, v2) | python | def deep_update(dict1, dict2):
"""Perform a deep merge of `dict2` into `dict1`.
Note that `dict2` and any nested dicts are unchanged.
Supports `ModifyList` instances.
"""
def flatten(v):
if isinstance(v, ModifyList):
return v.apply([])
elif isinstance(v, dict):
return dict((k, flatten(v_)) for k, v_ in v.iteritems())
else:
return v
def merge(v1, v2):
if isinstance(v1, dict) and isinstance(v2, dict):
deep_update(v1, v2)
return v1
elif isinstance(v2, ModifyList):
v1 = flatten(v1)
return v2.apply(v1)
else:
return flatten(v2)
for k1, v1 in dict1.iteritems():
if k1 not in dict2:
dict1[k1] = flatten(v1)
for k2, v2 in dict2.iteritems():
v1 = dict1.get(k2)
if v1 is KeyError:
dict1[k2] = flatten(v2)
else:
dict1[k2] = merge(v1, v2) | [
"def",
"deep_update",
"(",
"dict1",
",",
"dict2",
")",
":",
"def",
"flatten",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"ModifyList",
")",
":",
"return",
"v",
".",
"apply",
"(",
"[",
"]",
")",
"elif",
"isinstance",
"(",
"v",
",",
"di... | Perform a deep merge of `dict2` into `dict1`.
Note that `dict2` and any nested dicts are unchanged.
Supports `ModifyList` instances. | [
"Perform",
"a",
"deep",
"merge",
"of",
"dict2",
"into",
"dict1",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/data_utils.py#L39-L74 | train | 227,415 |
nerdvegas/rez | src/rez/utils/data_utils.py | deep_del | def deep_del(data, fn):
"""Create dict copy with removed items.
Recursively remove items where fn(value) is True.
Returns:
dict: New dict with matching items removed.
"""
result = {}
for k, v in data.iteritems():
if not fn(v):
if isinstance(v, dict):
result[k] = deep_del(v, fn)
else:
result[k] = v
return result | python | def deep_del(data, fn):
"""Create dict copy with removed items.
Recursively remove items where fn(value) is True.
Returns:
dict: New dict with matching items removed.
"""
result = {}
for k, v in data.iteritems():
if not fn(v):
if isinstance(v, dict):
result[k] = deep_del(v, fn)
else:
result[k] = v
return result | [
"def",
"deep_del",
"(",
"data",
",",
"fn",
")",
":",
"result",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"data",
".",
"iteritems",
"(",
")",
":",
"if",
"not",
"fn",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"... | Create dict copy with removed items.
Recursively remove items where fn(value) is True.
Returns:
dict: New dict with matching items removed. | [
"Create",
"dict",
"copy",
"with",
"removed",
"items",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/data_utils.py#L77-L94 | train | 227,416 |
nerdvegas/rez | src/rez/utils/data_utils.py | get_dict_diff_str | def get_dict_diff_str(d1, d2, title):
"""Returns same as `get_dict_diff`, but as a readable string.
"""
added, removed, changed = get_dict_diff(d1, d2)
lines = [title]
if added:
lines.append("Added attributes: %s"
% ['.'.join(x) for x in added])
if removed:
lines.append("Removed attributes: %s"
% ['.'.join(x) for x in removed])
if changed:
lines.append("Changed attributes: %s"
% ['.'.join(x) for x in changed])
return '\n'.join(lines) | python | def get_dict_diff_str(d1, d2, title):
"""Returns same as `get_dict_diff`, but as a readable string.
"""
added, removed, changed = get_dict_diff(d1, d2)
lines = [title]
if added:
lines.append("Added attributes: %s"
% ['.'.join(x) for x in added])
if removed:
lines.append("Removed attributes: %s"
% ['.'.join(x) for x in removed])
if changed:
lines.append("Changed attributes: %s"
% ['.'.join(x) for x in changed])
return '\n'.join(lines) | [
"def",
"get_dict_diff_str",
"(",
"d1",
",",
"d2",
",",
"title",
")",
":",
"added",
",",
"removed",
",",
"changed",
"=",
"get_dict_diff",
"(",
"d1",
",",
"d2",
")",
"lines",
"=",
"[",
"title",
"]",
"if",
"added",
":",
"lines",
".",
"append",
"(",
"\... | Returns same as `get_dict_diff`, but as a readable string. | [
"Returns",
"same",
"as",
"get_dict_diff",
"but",
"as",
"a",
"readable",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/data_utils.py#L138-L154 | train | 227,417 |
nerdvegas/rez | src/rez/utils/data_utils.py | convert_dicts | def convert_dicts(d, to_class=AttrDictWrapper, from_class=dict):
"""Recursively convert dict and UserDict types.
Note that `d` is unchanged.
Args:
to_class (type): Dict-like type to convert values to, usually UserDict
subclass, or dict.
from_class (type): Dict-like type to convert values from. If a tuple,
multiple types are converted.
Returns:
Converted data as `to_class` instance.
"""
d_ = to_class()
for key, value in d.iteritems():
if isinstance(value, from_class):
d_[key] = convert_dicts(value, to_class=to_class,
from_class=from_class)
else:
d_[key] = value
return d_ | python | def convert_dicts(d, to_class=AttrDictWrapper, from_class=dict):
"""Recursively convert dict and UserDict types.
Note that `d` is unchanged.
Args:
to_class (type): Dict-like type to convert values to, usually UserDict
subclass, or dict.
from_class (type): Dict-like type to convert values from. If a tuple,
multiple types are converted.
Returns:
Converted data as `to_class` instance.
"""
d_ = to_class()
for key, value in d.iteritems():
if isinstance(value, from_class):
d_[key] = convert_dicts(value, to_class=to_class,
from_class=from_class)
else:
d_[key] = value
return d_ | [
"def",
"convert_dicts",
"(",
"d",
",",
"to_class",
"=",
"AttrDictWrapper",
",",
"from_class",
"=",
"dict",
")",
":",
"d_",
"=",
"to_class",
"(",
")",
"for",
"key",
",",
"value",
"in",
"d",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"va... | Recursively convert dict and UserDict types.
Note that `d` is unchanged.
Args:
to_class (type): Dict-like type to convert values to, usually UserDict
subclass, or dict.
from_class (type): Dict-like type to convert values from. If a tuple,
multiple types are converted.
Returns:
Converted data as `to_class` instance. | [
"Recursively",
"convert",
"dict",
"and",
"UserDict",
"types",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/data_utils.py#L319-L340 | train | 227,418 |
nerdvegas/rez | src/rez/package_repository.py | PackageRepositoryGlobalStats.package_loading | def package_loading(self):
"""Use this around code in your package repository that is loading a
package, for example from file or cache.
"""
t1 = time.time()
yield None
t2 = time.time()
self.package_load_time += t2 - t1 | python | def package_loading(self):
"""Use this around code in your package repository that is loading a
package, for example from file or cache.
"""
t1 = time.time()
yield None
t2 = time.time()
self.package_load_time += t2 - t1 | [
"def",
"package_loading",
"(",
"self",
")",
":",
"t1",
"=",
"time",
".",
"time",
"(",
")",
"yield",
"None",
"t2",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"package_load_time",
"+=",
"t2",
"-",
"t1"
] | Use this around code in your package repository that is loading a
package, for example from file or cache. | [
"Use",
"this",
"around",
"code",
"in",
"your",
"package",
"repository",
"that",
"is",
"loading",
"a",
"package",
"for",
"example",
"from",
"file",
"or",
"cache",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_repository.py#L42-L50 | train | 227,419 |
nerdvegas/rez | src/rez/package_repository.py | PackageRepository.is_empty | def is_empty(self):
"""Determine if the repository contains any packages.
Returns:
True if there are no packages, False if there are at least one.
"""
for family in self.iter_package_families():
for pkg in self.iter_packages(family):
return False
return True | python | def is_empty(self):
"""Determine if the repository contains any packages.
Returns:
True if there are no packages, False if there are at least one.
"""
for family in self.iter_package_families():
for pkg in self.iter_packages(family):
return False
return True | [
"def",
"is_empty",
"(",
"self",
")",
":",
"for",
"family",
"in",
"self",
".",
"iter_package_families",
"(",
")",
":",
"for",
"pkg",
"in",
"self",
".",
"iter_packages",
"(",
"family",
")",
":",
"return",
"False",
"return",
"True"
] | Determine if the repository contains any packages.
Returns:
True if there are no packages, False if there are at least one. | [
"Determine",
"if",
"the",
"repository",
"contains",
"any",
"packages",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_repository.py#L119-L129 | train | 227,420 |
nerdvegas/rez | src/rez/package_repository.py | PackageRepository.make_resource_handle | def make_resource_handle(self, resource_key, **variables):
"""Create a `ResourceHandle`
Nearly all `ResourceHandle` creation should go through here, because it
gives the various resource classes a chance to normalize / standardize
the resource handles, to improve caching / comparison / etc.
"""
if variables.get("repository_type", self.name()) != self.name():
raise ResourceError("repository_type mismatch - requested %r, "
"repository_type is %r"
% (variables["repository_type"], self.name()))
variables["repository_type"] = self.name()
if variables.get("location", self.location) != self.location:
raise ResourceError("location mismatch - requested %r, repository "
"location is %r" % (variables["location"],
self.location))
variables["location"] = self.location
resource_cls = self.pool.get_resource_class(resource_key)
variables = resource_cls.normalize_variables(variables)
return ResourceHandle(resource_key, variables) | python | def make_resource_handle(self, resource_key, **variables):
"""Create a `ResourceHandle`
Nearly all `ResourceHandle` creation should go through here, because it
gives the various resource classes a chance to normalize / standardize
the resource handles, to improve caching / comparison / etc.
"""
if variables.get("repository_type", self.name()) != self.name():
raise ResourceError("repository_type mismatch - requested %r, "
"repository_type is %r"
% (variables["repository_type"], self.name()))
variables["repository_type"] = self.name()
if variables.get("location", self.location) != self.location:
raise ResourceError("location mismatch - requested %r, repository "
"location is %r" % (variables["location"],
self.location))
variables["location"] = self.location
resource_cls = self.pool.get_resource_class(resource_key)
variables = resource_cls.normalize_variables(variables)
return ResourceHandle(resource_key, variables) | [
"def",
"make_resource_handle",
"(",
"self",
",",
"resource_key",
",",
"*",
"*",
"variables",
")",
":",
"if",
"variables",
".",
"get",
"(",
"\"repository_type\"",
",",
"self",
".",
"name",
"(",
")",
")",
"!=",
"self",
".",
"name",
"(",
")",
":",
"raise"... | Create a `ResourceHandle`
Nearly all `ResourceHandle` creation should go through here, because it
gives the various resource classes a chance to normalize / standardize
the resource handles, to improve caching / comparison / etc. | [
"Create",
"a",
"ResourceHandle"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_repository.py#L256-L278 | train | 227,421 |
nerdvegas/rez | src/rez/package_repository.py | PackageRepositoryManager.get_repository | def get_repository(self, path):
"""Get a package repository.
Args:
path (str): Entry from the 'packages_path' config setting. This may
simply be a path (which is managed by the 'filesystem' package
repository plugin), or a string in the form "type@location",
where 'type' identifies the repository plugin type to use.
Returns:
`PackageRepository` instance.
"""
# normalise
parts = path.split('@', 1)
if len(parts) == 1:
parts = ("filesystem", parts[0])
repo_type, location = parts
if repo_type == "filesystem":
# choice of abspath here vs realpath is deliberate. Realpath gives
# canonical path, which can be a problem if two studios are sharing
# packages, and have mirrored package paths, but some are actually
# different paths, symlinked to look the same. It happened!
location = os.path.abspath(location)
normalised_path = "%s@%s" % (repo_type, location)
return self._get_repository(normalised_path) | python | def get_repository(self, path):
"""Get a package repository.
Args:
path (str): Entry from the 'packages_path' config setting. This may
simply be a path (which is managed by the 'filesystem' package
repository plugin), or a string in the form "type@location",
where 'type' identifies the repository plugin type to use.
Returns:
`PackageRepository` instance.
"""
# normalise
parts = path.split('@', 1)
if len(parts) == 1:
parts = ("filesystem", parts[0])
repo_type, location = parts
if repo_type == "filesystem":
# choice of abspath here vs realpath is deliberate. Realpath gives
# canonical path, which can be a problem if two studios are sharing
# packages, and have mirrored package paths, but some are actually
# different paths, symlinked to look the same. It happened!
location = os.path.abspath(location)
normalised_path = "%s@%s" % (repo_type, location)
return self._get_repository(normalised_path) | [
"def",
"get_repository",
"(",
"self",
",",
"path",
")",
":",
"# normalise",
"parts",
"=",
"path",
".",
"split",
"(",
"'@'",
",",
"1",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
":",
"parts",
"=",
"(",
"\"filesystem\"",
",",
"parts",
"[",
"0",
... | Get a package repository.
Args:
path (str): Entry from the 'packages_path' config setting. This may
simply be a path (which is managed by the 'filesystem' package
repository plugin), or a string in the form "type@location",
where 'type' identifies the repository plugin type to use.
Returns:
`PackageRepository` instance. | [
"Get",
"a",
"package",
"repository",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_repository.py#L368-L394 | train | 227,422 |
nerdvegas/rez | src/rez/package_repository.py | PackageRepositoryManager.are_same | def are_same(self, path_1, path_2):
"""Test that `path_1` and `path_2` refer to the same repository.
This is more reliable than testing that the strings match, since slightly
different strings might refer to the same repository (consider small
differences in a filesystem path for example, eg '//svr/foo', '/svr/foo').
Returns:
True if the paths refer to the same repository, False otherwise.
"""
if path_1 == path_2:
return True
repo_1 = self.get_repository(path_1)
repo_2 = self.get_repository(path_2)
return (repo_1.uid == repo_2.uid) | python | def are_same(self, path_1, path_2):
"""Test that `path_1` and `path_2` refer to the same repository.
This is more reliable than testing that the strings match, since slightly
different strings might refer to the same repository (consider small
differences in a filesystem path for example, eg '//svr/foo', '/svr/foo').
Returns:
True if the paths refer to the same repository, False otherwise.
"""
if path_1 == path_2:
return True
repo_1 = self.get_repository(path_1)
repo_2 = self.get_repository(path_2)
return (repo_1.uid == repo_2.uid) | [
"def",
"are_same",
"(",
"self",
",",
"path_1",
",",
"path_2",
")",
":",
"if",
"path_1",
"==",
"path_2",
":",
"return",
"True",
"repo_1",
"=",
"self",
".",
"get_repository",
"(",
"path_1",
")",
"repo_2",
"=",
"self",
".",
"get_repository",
"(",
"path_2",
... | Test that `path_1` and `path_2` refer to the same repository.
This is more reliable than testing that the strings match, since slightly
different strings might refer to the same repository (consider small
differences in a filesystem path for example, eg '//svr/foo', '/svr/foo').
Returns:
True if the paths refer to the same repository, False otherwise. | [
"Test",
"that",
"path_1",
"and",
"path_2",
"refer",
"to",
"the",
"same",
"repository",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/package_repository.py#L396-L411 | train | 227,423 |
nerdvegas/rez | src/rez/vendor/amqp/transport.py | create_transport | def create_transport(host, connect_timeout, ssl=False):
"""Given a few parameters from the Connection constructor,
select and create a subclass of _AbstractTransport."""
if ssl:
return SSLTransport(host, connect_timeout, ssl)
else:
return TCPTransport(host, connect_timeout) | python | def create_transport(host, connect_timeout, ssl=False):
"""Given a few parameters from the Connection constructor,
select and create a subclass of _AbstractTransport."""
if ssl:
return SSLTransport(host, connect_timeout, ssl)
else:
return TCPTransport(host, connect_timeout) | [
"def",
"create_transport",
"(",
"host",
",",
"connect_timeout",
",",
"ssl",
"=",
"False",
")",
":",
"if",
"ssl",
":",
"return",
"SSLTransport",
"(",
"host",
",",
"connect_timeout",
",",
"ssl",
")",
"else",
":",
"return",
"TCPTransport",
"(",
"host",
",",
... | Given a few parameters from the Connection constructor,
select and create a subclass of _AbstractTransport. | [
"Given",
"a",
"few",
"parameters",
"from",
"the",
"Connection",
"constructor",
"select",
"and",
"create",
"a",
"subclass",
"of",
"_AbstractTransport",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/amqp/transport.py#L293-L299 | train | 227,424 |
nerdvegas/rez | src/rez/plugin_managers.py | RezPluginType.get_plugin_class | def get_plugin_class(self, plugin_name):
"""Returns the class registered under the given plugin name."""
try:
return self.plugin_classes[plugin_name]
except KeyError:
raise RezPluginError("Unrecognised %s plugin: '%s'"
% (self.pretty_type_name, plugin_name)) | python | def get_plugin_class(self, plugin_name):
"""Returns the class registered under the given plugin name."""
try:
return self.plugin_classes[plugin_name]
except KeyError:
raise RezPluginError("Unrecognised %s plugin: '%s'"
% (self.pretty_type_name, plugin_name)) | [
"def",
"get_plugin_class",
"(",
"self",
",",
"plugin_name",
")",
":",
"try",
":",
"return",
"self",
".",
"plugin_classes",
"[",
"plugin_name",
"]",
"except",
"KeyError",
":",
"raise",
"RezPluginError",
"(",
"\"Unrecognised %s plugin: '%s'\"",
"%",
"(",
"self",
"... | Returns the class registered under the given plugin name. | [
"Returns",
"the",
"class",
"registered",
"under",
"the",
"given",
"plugin",
"name",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L157-L163 | train | 227,425 |
nerdvegas/rez | src/rez/plugin_managers.py | RezPluginType.get_plugin_module | def get_plugin_module(self, plugin_name):
"""Returns the module containing the plugin of the given name."""
try:
return self.plugin_modules[plugin_name]
except KeyError:
raise RezPluginError("Unrecognised %s plugin: '%s'"
% (self.pretty_type_name, plugin_name)) | python | def get_plugin_module(self, plugin_name):
"""Returns the module containing the plugin of the given name."""
try:
return self.plugin_modules[plugin_name]
except KeyError:
raise RezPluginError("Unrecognised %s plugin: '%s'"
% (self.pretty_type_name, plugin_name)) | [
"def",
"get_plugin_module",
"(",
"self",
",",
"plugin_name",
")",
":",
"try",
":",
"return",
"self",
".",
"plugin_modules",
"[",
"plugin_name",
"]",
"except",
"KeyError",
":",
"raise",
"RezPluginError",
"(",
"\"Unrecognised %s plugin: '%s'\"",
"%",
"(",
"self",
... | Returns the module containing the plugin of the given name. | [
"Returns",
"the",
"module",
"containing",
"the",
"plugin",
"of",
"the",
"given",
"name",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L165-L171 | train | 227,426 |
nerdvegas/rez | src/rez/plugin_managers.py | RezPluginType.config_schema | def config_schema(self):
"""Returns the merged configuration data schema for this plugin
type."""
from rez.config import _plugin_config_dict
d = _plugin_config_dict.get(self.type_name, {})
for name, plugin_class in self.plugin_classes.iteritems():
if hasattr(plugin_class, "schema_dict") \
and plugin_class.schema_dict:
d_ = {name: plugin_class.schema_dict}
deep_update(d, d_)
return dict_to_schema(d, required=True, modifier=expand_system_vars) | python | def config_schema(self):
"""Returns the merged configuration data schema for this plugin
type."""
from rez.config import _plugin_config_dict
d = _plugin_config_dict.get(self.type_name, {})
for name, plugin_class in self.plugin_classes.iteritems():
if hasattr(plugin_class, "schema_dict") \
and plugin_class.schema_dict:
d_ = {name: plugin_class.schema_dict}
deep_update(d, d_)
return dict_to_schema(d, required=True, modifier=expand_system_vars) | [
"def",
"config_schema",
"(",
"self",
")",
":",
"from",
"rez",
".",
"config",
"import",
"_plugin_config_dict",
"d",
"=",
"_plugin_config_dict",
".",
"get",
"(",
"self",
".",
"type_name",
",",
"{",
"}",
")",
"for",
"name",
",",
"plugin_class",
"in",
"self",
... | Returns the merged configuration data schema for this plugin
type. | [
"Returns",
"the",
"merged",
"configuration",
"data",
"schema",
"for",
"this",
"plugin",
"type",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L174-L185 | train | 227,427 |
nerdvegas/rez | src/rez/plugin_managers.py | RezPluginManager.get_plugin_class | def get_plugin_class(self, plugin_type, plugin_name):
"""Return the class registered under the given plugin name."""
plugin = self._get_plugin_type(plugin_type)
return plugin.get_plugin_class(plugin_name) | python | def get_plugin_class(self, plugin_type, plugin_name):
"""Return the class registered under the given plugin name."""
plugin = self._get_plugin_type(plugin_type)
return plugin.get_plugin_class(plugin_name) | [
"def",
"get_plugin_class",
"(",
"self",
",",
"plugin_type",
",",
"plugin_name",
")",
":",
"plugin",
"=",
"self",
".",
"_get_plugin_type",
"(",
"plugin_type",
")",
"return",
"plugin",
".",
"get_plugin_class",
"(",
"plugin_name",
")"
] | Return the class registered under the given plugin name. | [
"Return",
"the",
"class",
"registered",
"under",
"the",
"given",
"plugin",
"name",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L278-L281 | train | 227,428 |
nerdvegas/rez | src/rez/plugin_managers.py | RezPluginManager.get_plugin_module | def get_plugin_module(self, plugin_type, plugin_name):
"""Return the module defining the class registered under the given
plugin name."""
plugin = self._get_plugin_type(plugin_type)
return plugin.get_plugin_module(plugin_name) | python | def get_plugin_module(self, plugin_type, plugin_name):
"""Return the module defining the class registered under the given
plugin name."""
plugin = self._get_plugin_type(plugin_type)
return plugin.get_plugin_module(plugin_name) | [
"def",
"get_plugin_module",
"(",
"self",
",",
"plugin_type",
",",
"plugin_name",
")",
":",
"plugin",
"=",
"self",
".",
"_get_plugin_type",
"(",
"plugin_type",
")",
"return",
"plugin",
".",
"get_plugin_module",
"(",
"plugin_name",
")"
] | Return the module defining the class registered under the given
plugin name. | [
"Return",
"the",
"module",
"defining",
"the",
"class",
"registered",
"under",
"the",
"given",
"plugin",
"name",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L283-L287 | train | 227,429 |
nerdvegas/rez | src/rez/plugin_managers.py | RezPluginManager.create_instance | def create_instance(self, plugin_type, plugin_name, **instance_kwargs):
"""Create and return an instance of the given plugin."""
plugin_type = self._get_plugin_type(plugin_type)
return plugin_type.create_instance(plugin_name, **instance_kwargs) | python | def create_instance(self, plugin_type, plugin_name, **instance_kwargs):
"""Create and return an instance of the given plugin."""
plugin_type = self._get_plugin_type(plugin_type)
return plugin_type.create_instance(plugin_name, **instance_kwargs) | [
"def",
"create_instance",
"(",
"self",
",",
"plugin_type",
",",
"plugin_name",
",",
"*",
"*",
"instance_kwargs",
")",
":",
"plugin_type",
"=",
"self",
".",
"_get_plugin_type",
"(",
"plugin_type",
")",
"return",
"plugin_type",
".",
"create_instance",
"(",
"plugin... | Create and return an instance of the given plugin. | [
"Create",
"and",
"return",
"an",
"instance",
"of",
"the",
"given",
"plugin",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L308-L311 | train | 227,430 |
nerdvegas/rez | src/rez/plugin_managers.py | RezPluginManager.get_summary_string | def get_summary_string(self):
"""Get a formatted string summarising the plugins that were loaded."""
rows = [["PLUGIN TYPE", "NAME", "DESCRIPTION", "STATUS"],
["-----------", "----", "-----------", "------"]]
for plugin_type in sorted(self.get_plugin_types()):
type_name = plugin_type.replace('_', ' ')
for name in sorted(self.get_plugins(plugin_type)):
module = self.get_plugin_module(plugin_type, name)
desc = (getattr(module, "__doc__", None) or '').strip()
rows.append((type_name, name, desc, "loaded"))
for (name, reason) in sorted(self.get_failed_plugins(plugin_type)):
msg = "FAILED: %s" % reason
rows.append((type_name, name, '', msg))
return '\n'.join(columnise(rows)) | python | def get_summary_string(self):
"""Get a formatted string summarising the plugins that were loaded."""
rows = [["PLUGIN TYPE", "NAME", "DESCRIPTION", "STATUS"],
["-----------", "----", "-----------", "------"]]
for plugin_type in sorted(self.get_plugin_types()):
type_name = plugin_type.replace('_', ' ')
for name in sorted(self.get_plugins(plugin_type)):
module = self.get_plugin_module(plugin_type, name)
desc = (getattr(module, "__doc__", None) or '').strip()
rows.append((type_name, name, desc, "loaded"))
for (name, reason) in sorted(self.get_failed_plugins(plugin_type)):
msg = "FAILED: %s" % reason
rows.append((type_name, name, '', msg))
return '\n'.join(columnise(rows)) | [
"def",
"get_summary_string",
"(",
"self",
")",
":",
"rows",
"=",
"[",
"[",
"\"PLUGIN TYPE\"",
",",
"\"NAME\"",
",",
"\"DESCRIPTION\"",
",",
"\"STATUS\"",
"]",
",",
"[",
"\"-----------\"",
",",
"\"----\"",
",",
"\"-----------\"",
",",
"\"------\"",
"]",
"]",
... | Get a formatted string summarising the plugins that were loaded. | [
"Get",
"a",
"formatted",
"string",
"summarising",
"the",
"plugins",
"that",
"were",
"loaded",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/plugin_managers.py#L313-L326 | train | 227,431 |
nerdvegas/rez | src/rez/vendor/distlib/markers.py | Evaluator.get_fragment | def get_fragment(self, offset):
"""
Get the part of the source which is causing a problem.
"""
fragment_len = 10
s = '%r' % (self.source[offset:offset + fragment_len])
if offset + fragment_len < len(self.source):
s += '...'
return s | python | def get_fragment(self, offset):
"""
Get the part of the source which is causing a problem.
"""
fragment_len = 10
s = '%r' % (self.source[offset:offset + fragment_len])
if offset + fragment_len < len(self.source):
s += '...'
return s | [
"def",
"get_fragment",
"(",
"self",
",",
"offset",
")",
":",
"fragment_len",
"=",
"10",
"s",
"=",
"'%r'",
"%",
"(",
"self",
".",
"source",
"[",
"offset",
":",
"offset",
"+",
"fragment_len",
"]",
")",
"if",
"offset",
"+",
"fragment_len",
"<",
"len",
"... | Get the part of the source which is causing a problem. | [
"Get",
"the",
"part",
"of",
"the",
"source",
"which",
"is",
"causing",
"a",
"problem",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/distlib/markers.py#L60-L68 | train | 227,432 |
nerdvegas/rez | src/rez/vendor/distlib/markers.py | Evaluator.evaluate | def evaluate(self, node, filename=None):
"""
Evaluate a source string or node, using ``filename`` when
displaying errors.
"""
if isinstance(node, string_types):
self.source = node
kwargs = {'mode': 'eval'}
if filename:
kwargs['filename'] = filename
try:
node = ast.parse(node, **kwargs)
except SyntaxError as e:
s = self.get_fragment(e.offset)
raise SyntaxError('syntax error %s' % s)
node_type = node.__class__.__name__.lower()
handler = self.get_handler(node_type)
if handler is None:
if self.source is None:
s = '(source not available)'
else:
s = self.get_fragment(node.col_offset)
raise SyntaxError("don't know how to evaluate %r %s" % (
node_type, s))
return handler(node) | python | def evaluate(self, node, filename=None):
"""
Evaluate a source string or node, using ``filename`` when
displaying errors.
"""
if isinstance(node, string_types):
self.source = node
kwargs = {'mode': 'eval'}
if filename:
kwargs['filename'] = filename
try:
node = ast.parse(node, **kwargs)
except SyntaxError as e:
s = self.get_fragment(e.offset)
raise SyntaxError('syntax error %s' % s)
node_type = node.__class__.__name__.lower()
handler = self.get_handler(node_type)
if handler is None:
if self.source is None:
s = '(source not available)'
else:
s = self.get_fragment(node.col_offset)
raise SyntaxError("don't know how to evaluate %r %s" % (
node_type, s))
return handler(node) | [
"def",
"evaluate",
"(",
"self",
",",
"node",
",",
"filename",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"string_types",
")",
":",
"self",
".",
"source",
"=",
"node",
"kwargs",
"=",
"{",
"'mode'",
":",
"'eval'",
"}",
"if",
"filename... | Evaluate a source string or node, using ``filename`` when
displaying errors. | [
"Evaluate",
"a",
"source",
"string",
"or",
"node",
"using",
"filename",
"when",
"displaying",
"errors",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/distlib/markers.py#L76-L100 | train | 227,433 |
nerdvegas/rez | src/rez/vendor/sortedcontainers/sortedlist.py | recursive_repr | def recursive_repr(func):
"""Decorator to prevent infinite repr recursion."""
repr_running = set()
@wraps(func)
def wrapper(self):
"Return ellipsis on recursive re-entry to function."
key = id(self), get_ident()
if key in repr_running:
return '...'
repr_running.add(key)
try:
return func(self)
finally:
repr_running.discard(key)
return wrapper | python | def recursive_repr(func):
"""Decorator to prevent infinite repr recursion."""
repr_running = set()
@wraps(func)
def wrapper(self):
"Return ellipsis on recursive re-entry to function."
key = id(self), get_ident()
if key in repr_running:
return '...'
repr_running.add(key)
try:
return func(self)
finally:
repr_running.discard(key)
return wrapper | [
"def",
"recursive_repr",
"(",
"func",
")",
":",
"repr_running",
"=",
"set",
"(",
")",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
")",
":",
"\"Return ellipsis on recursive re-entry to function.\"",
"key",
"=",
"id",
"(",
"self",
")",
",",
... | Decorator to prevent infinite repr recursion. | [
"Decorator",
"to",
"prevent",
"infinite",
"repr",
"recursion",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedlist.py#L33-L52 | train | 227,434 |
nerdvegas/rez | src/rez/vendor/sortedcontainers/sortedlist.py | SortedList._reset | def _reset(self, load):
"""
Reset sorted list load.
The *load* specifies the load-factor of the list. The default load
factor of '1000' works well for lists from tens to tens of millions of
elements. Good practice is to use a value that is the cube root of the
list size. With billions of elements, the best load factor depends on
your usage. It's best to leave the load factor at the default until
you start benchmarking.
"""
values = reduce(iadd, self._lists, [])
self._clear()
self._load = load
self._half = load >> 1
self._dual = load << 1
self._update(values) | python | def _reset(self, load):
"""
Reset sorted list load.
The *load* specifies the load-factor of the list. The default load
factor of '1000' works well for lists from tens to tens of millions of
elements. Good practice is to use a value that is the cube root of the
list size. With billions of elements, the best load factor depends on
your usage. It's best to leave the load factor at the default until
you start benchmarking.
"""
values = reduce(iadd, self._lists, [])
self._clear()
self._load = load
self._half = load >> 1
self._dual = load << 1
self._update(values) | [
"def",
"_reset",
"(",
"self",
",",
"load",
")",
":",
"values",
"=",
"reduce",
"(",
"iadd",
",",
"self",
".",
"_lists",
",",
"[",
"]",
")",
"self",
".",
"_clear",
"(",
")",
"self",
".",
"_load",
"=",
"load",
"self",
".",
"_half",
"=",
"load",
">... | Reset sorted list load.
The *load* specifies the load-factor of the list. The default load
factor of '1000' works well for lists from tens to tens of millions of
elements. Good practice is to use a value that is the cube root of the
list size. With billions of elements, the best load factor depends on
your usage. It's best to leave the load factor at the default until
you start benchmarking. | [
"Reset",
"sorted",
"list",
"load",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedlist.py#L105-L121 | train | 227,435 |
nerdvegas/rez | src/rez/vendor/sortedcontainers/sortedlist.py | SortedList._build_index | def _build_index(self):
"""Build an index for indexing the sorted list.
Indexes are represented as binary trees in a dense array notation
similar to a binary heap.
For example, given a _lists representation storing integers:
[0]: 1 2 3
[1]: 4 5
[2]: 6 7 8 9
[3]: 10 11 12 13 14
The first transformation maps the sub-lists by their length. The
first row of the index is the length of the sub-lists.
[0]: 3 2 4 5
Each row after that is the sum of consecutive pairs of the previous row:
[1]: 5 9
[2]: 14
Finally, the index is built by concatenating these lists together:
_index = 14 5 9 3 2 4 5
An offset storing the start of the first row is also stored:
_offset = 3
When built, the index can be used for efficient indexing into the list.
See the comment and notes on self._pos for details.
"""
row0 = list(map(len, self._lists))
if len(row0) == 1:
self._index[:] = row0
self._offset = 0
return
head = iter(row0)
tail = iter(head)
row1 = list(starmap(add, zip(head, tail)))
if len(row0) & 1:
row1.append(row0[-1])
if len(row1) == 1:
self._index[:] = row1 + row0
self._offset = 1
return
size = 2 ** (int(log_e(len(row1) - 1, 2)) + 1)
row1.extend(repeat(0, size - len(row1)))
tree = [row0, row1]
while len(tree[-1]) > 1:
head = iter(tree[-1])
tail = iter(head)
row = list(starmap(add, zip(head, tail)))
tree.append(row)
reduce(iadd, reversed(tree), self._index)
self._offset = size * 2 - 1 | python | def _build_index(self):
"""Build an index for indexing the sorted list.
Indexes are represented as binary trees in a dense array notation
similar to a binary heap.
For example, given a _lists representation storing integers:
[0]: 1 2 3
[1]: 4 5
[2]: 6 7 8 9
[3]: 10 11 12 13 14
The first transformation maps the sub-lists by their length. The
first row of the index is the length of the sub-lists.
[0]: 3 2 4 5
Each row after that is the sum of consecutive pairs of the previous row:
[1]: 5 9
[2]: 14
Finally, the index is built by concatenating these lists together:
_index = 14 5 9 3 2 4 5
An offset storing the start of the first row is also stored:
_offset = 3
When built, the index can be used for efficient indexing into the list.
See the comment and notes on self._pos for details.
"""
row0 = list(map(len, self._lists))
if len(row0) == 1:
self._index[:] = row0
self._offset = 0
return
head = iter(row0)
tail = iter(head)
row1 = list(starmap(add, zip(head, tail)))
if len(row0) & 1:
row1.append(row0[-1])
if len(row1) == 1:
self._index[:] = row1 + row0
self._offset = 1
return
size = 2 ** (int(log_e(len(row1) - 1, 2)) + 1)
row1.extend(repeat(0, size - len(row1)))
tree = [row0, row1]
while len(tree[-1]) > 1:
head = iter(tree[-1])
tail = iter(head)
row = list(starmap(add, zip(head, tail)))
tree.append(row)
reduce(iadd, reversed(tree), self._index)
self._offset = size * 2 - 1 | [
"def",
"_build_index",
"(",
"self",
")",
":",
"row0",
"=",
"list",
"(",
"map",
"(",
"len",
",",
"self",
".",
"_lists",
")",
")",
"if",
"len",
"(",
"row0",
")",
"==",
"1",
":",
"self",
".",
"_index",
"[",
":",
"]",
"=",
"row0",
"self",
".",
"_... | Build an index for indexing the sorted list.
Indexes are represented as binary trees in a dense array notation
similar to a binary heap.
For example, given a _lists representation storing integers:
[0]: 1 2 3
[1]: 4 5
[2]: 6 7 8 9
[3]: 10 11 12 13 14
The first transformation maps the sub-lists by their length. The
first row of the index is the length of the sub-lists.
[0]: 3 2 4 5
Each row after that is the sum of consecutive pairs of the previous row:
[1]: 5 9
[2]: 14
Finally, the index is built by concatenating these lists together:
_index = 14 5 9 3 2 4 5
An offset storing the start of the first row is also stored:
_offset = 3
When built, the index can be used for efficient indexing into the list.
See the comment and notes on self._pos for details. | [
"Build",
"an",
"index",
"for",
"indexing",
"the",
"sorted",
"list",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedlist.py#L494-L558 | train | 227,436 |
nerdvegas/rez | src/rez/vendor/sortedcontainers/sortedlist.py | SortedListWithKey.irange_key | def irange_key(self, min_key=None, max_key=None, inclusive=(True, True),
reverse=False):
"""
Create an iterator of values between `min_key` and `max_key`.
`inclusive` is a pair of booleans that indicates whether the min_key
and max_key ought to be included in the range, respectively. The
default is (True, True) such that the range is inclusive of both
`min_key` and `max_key`.
Both `min_key` and `max_key` default to `None` which is automatically
inclusive of the start and end of the list, respectively.
When `reverse` is `True` the values are yielded from the iterator in
reverse order; `reverse` defaults to `False`.
"""
_maxes = self._maxes
if not _maxes:
return iter(())
_keys = self._keys
# Calculate the minimum (pos, idx) pair. By default this location
# will be inclusive in our calculation.
if min_key is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_keys[min_pos], min_key)
else:
min_pos = bisect_right(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_keys[min_pos], min_key)
# Calculate the maximum (pos, idx) pair. By default this location
# will be exclusive in our calculation.
if max_key is None:
max_pos = len(_maxes) - 1
max_idx = len(_keys[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_right(_keys[max_pos], max_key)
else:
max_pos = bisect_left(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_left(_keys[max_pos], max_key)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) | python | def irange_key(self, min_key=None, max_key=None, inclusive=(True, True),
reverse=False):
"""
Create an iterator of values between `min_key` and `max_key`.
`inclusive` is a pair of booleans that indicates whether the min_key
and max_key ought to be included in the range, respectively. The
default is (True, True) such that the range is inclusive of both
`min_key` and `max_key`.
Both `min_key` and `max_key` default to `None` which is automatically
inclusive of the start and end of the list, respectively.
When `reverse` is `True` the values are yielded from the iterator in
reverse order; `reverse` defaults to `False`.
"""
_maxes = self._maxes
if not _maxes:
return iter(())
_keys = self._keys
# Calculate the minimum (pos, idx) pair. By default this location
# will be inclusive in our calculation.
if min_key is None:
min_pos = 0
min_idx = 0
else:
if inclusive[0]:
min_pos = bisect_left(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_left(_keys[min_pos], min_key)
else:
min_pos = bisect_right(_maxes, min_key)
if min_pos == len(_maxes):
return iter(())
min_idx = bisect_right(_keys[min_pos], min_key)
# Calculate the maximum (pos, idx) pair. By default this location
# will be exclusive in our calculation.
if max_key is None:
max_pos = len(_maxes) - 1
max_idx = len(_keys[max_pos])
else:
if inclusive[1]:
max_pos = bisect_right(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_right(_keys[max_pos], max_key)
else:
max_pos = bisect_left(_maxes, max_key)
if max_pos == len(_maxes):
max_pos -= 1
max_idx = len(_keys[max_pos])
else:
max_idx = bisect_left(_keys[max_pos], max_key)
return self._islice(min_pos, min_idx, max_pos, max_idx, reverse) | [
"def",
"irange_key",
"(",
"self",
",",
"min_key",
"=",
"None",
",",
"max_key",
"=",
"None",
",",
"inclusive",
"=",
"(",
"True",
",",
"True",
")",
",",
"reverse",
"=",
"False",
")",
":",
"_maxes",
"=",
"self",
".",
"_maxes",
"if",
"not",
"_maxes",
"... | Create an iterator of values between `min_key` and `max_key`.
`inclusive` is a pair of booleans that indicates whether the min_key
and max_key ought to be included in the range, respectively. The
default is (True, True) such that the range is inclusive of both
`min_key` and `max_key`.
Both `min_key` and `max_key` default to `None` which is automatically
inclusive of the start and end of the list, respectively.
When `reverse` is `True` the values are yielded from the iterator in
reverse order; `reverse` defaults to `False`. | [
"Create",
"an",
"iterator",
"of",
"values",
"between",
"min_key",
"and",
"max_key",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedlist.py#L1966-L2035 | train | 227,437 |
nerdvegas/rez | src/rezgui/dialogs/WriteGraphDialog.py | view_graph | def view_graph(graph_str, parent=None, prune_to=None):
"""View a graph."""
from rezgui.dialogs.ImageViewerDialog import ImageViewerDialog
from rez.config import config
# check for already written tempfile
h = hash((graph_str, prune_to))
filepath = graph_file_lookup.get(h)
if filepath and not os.path.exists(filepath):
filepath = None
# write graph to tempfile
if filepath is None:
suffix = ".%s" % config.dot_image_format
fd, filepath = tempfile.mkstemp(suffix=suffix, prefix="rez-graph-")
os.close(fd)
dlg = WriteGraphDialog(graph_str, filepath, parent, prune_to=prune_to)
if not dlg.write_graph():
return
# display graph
graph_file_lookup[h] = filepath
dlg = ImageViewerDialog(filepath, parent)
dlg.exec_() | python | def view_graph(graph_str, parent=None, prune_to=None):
"""View a graph."""
from rezgui.dialogs.ImageViewerDialog import ImageViewerDialog
from rez.config import config
# check for already written tempfile
h = hash((graph_str, prune_to))
filepath = graph_file_lookup.get(h)
if filepath and not os.path.exists(filepath):
filepath = None
# write graph to tempfile
if filepath is None:
suffix = ".%s" % config.dot_image_format
fd, filepath = tempfile.mkstemp(suffix=suffix, prefix="rez-graph-")
os.close(fd)
dlg = WriteGraphDialog(graph_str, filepath, parent, prune_to=prune_to)
if not dlg.write_graph():
return
# display graph
graph_file_lookup[h] = filepath
dlg = ImageViewerDialog(filepath, parent)
dlg.exec_() | [
"def",
"view_graph",
"(",
"graph_str",
",",
"parent",
"=",
"None",
",",
"prune_to",
"=",
"None",
")",
":",
"from",
"rezgui",
".",
"dialogs",
".",
"ImageViewerDialog",
"import",
"ImageViewerDialog",
"from",
"rez",
".",
"config",
"import",
"config",
"# check for... | View a graph. | [
"View",
"a",
"graph",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/dialogs/WriteGraphDialog.py#L109-L133 | train | 227,438 |
nerdvegas/rez | src/rezgui/widgets/PackageVersionsTable.py | PackageVersionsTable.select_version | def select_version(self, version_range):
"""Select the latest versioned package in the given range.
If there are no packages in the range, the selection is cleared.
"""
row = -1
version = None
for i, package in self.packages.iteritems():
if package.version in version_range \
and (version is None or version < package.version):
version = package.version
row = i
self.clearSelection()
if row != -1:
self.selectRow(row)
return version | python | def select_version(self, version_range):
"""Select the latest versioned package in the given range.
If there are no packages in the range, the selection is cleared.
"""
row = -1
version = None
for i, package in self.packages.iteritems():
if package.version in version_range \
and (version is None or version < package.version):
version = package.version
row = i
self.clearSelection()
if row != -1:
self.selectRow(row)
return version | [
"def",
"select_version",
"(",
"self",
",",
"version_range",
")",
":",
"row",
"=",
"-",
"1",
"version",
"=",
"None",
"for",
"i",
",",
"package",
"in",
"self",
".",
"packages",
".",
"iteritems",
"(",
")",
":",
"if",
"package",
".",
"version",
"in",
"ve... | Select the latest versioned package in the given range.
If there are no packages in the range, the selection is cleared. | [
"Select",
"the",
"latest",
"versioned",
"package",
"in",
"the",
"given",
"range",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/widgets/PackageVersionsTable.py#L46-L62 | train | 227,439 |
nerdvegas/rez | src/rez/vendor/sortedcontainers/sortedset.py | SortedSet._fromset | def _fromset(cls, values, key=None):
"""Initialize sorted set from existing set."""
sorted_set = object.__new__(cls)
sorted_set._set = values # pylint: disable=protected-access
sorted_set.__init__(key=key)
return sorted_set | python | def _fromset(cls, values, key=None):
"""Initialize sorted set from existing set."""
sorted_set = object.__new__(cls)
sorted_set._set = values # pylint: disable=protected-access
sorted_set.__init__(key=key)
return sorted_set | [
"def",
"_fromset",
"(",
"cls",
",",
"values",
",",
"key",
"=",
"None",
")",
":",
"sorted_set",
"=",
"object",
".",
"__new__",
"(",
"cls",
")",
"sorted_set",
".",
"_set",
"=",
"values",
"# pylint: disable=protected-access",
"sorted_set",
".",
"__init__",
"(",... | Initialize sorted set from existing set. | [
"Initialize",
"sorted",
"set",
"from",
"existing",
"set",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/sortedcontainers/sortedset.py#L73-L78 | train | 227,440 |
nerdvegas/rez | src/rez/cli/build.py | setup_parser_common | def setup_parser_common(parser):
"""Parser setup common to both rez-build and rez-release."""
from rez.build_process_ import get_build_process_types
from rez.build_system import get_valid_build_systems
process_types = get_build_process_types()
parser.add_argument(
"--process", type=str, choices=process_types, default="local",
help="the build process to use (default: %(default)s).")
# add build system choices valid for this package
package = get_current_developer_package()
clss = get_valid_build_systems(os.getcwd(), package=package)
if clss:
if len(clss) == 1:
cls_ = clss[0]
title = "%s build system arguments" % cls_.name()
group = parser.add_argument_group(title)
cls_.bind_cli(parser, group)
types = [x.name() for x in clss]
else:
types = None
parser.add_argument(
"-b", "--build-system", dest="buildsys", choices=types,
help="the build system to use. If not specified, it is detected. Set "
"'build_system' or 'build_command' to specify the build system in the "
"package itself.")
parser.add_argument(
"--variants", nargs='+', type=int, metavar="INDEX",
help="select variants to build (zero-indexed).")
parser.add_argument(
"--ba", "--build-args", dest="build_args", metavar="ARGS",
help="arguments to pass to the build system. Alternatively, list these "
"after a '--'.")
parser.add_argument(
"--cba", "--child-build-args", dest="child_build_args", metavar="ARGS",
help="arguments to pass to the child build system, if any. "
"Alternatively, list these after a second '--'.") | python | def setup_parser_common(parser):
"""Parser setup common to both rez-build and rez-release."""
from rez.build_process_ import get_build_process_types
from rez.build_system import get_valid_build_systems
process_types = get_build_process_types()
parser.add_argument(
"--process", type=str, choices=process_types, default="local",
help="the build process to use (default: %(default)s).")
# add build system choices valid for this package
package = get_current_developer_package()
clss = get_valid_build_systems(os.getcwd(), package=package)
if clss:
if len(clss) == 1:
cls_ = clss[0]
title = "%s build system arguments" % cls_.name()
group = parser.add_argument_group(title)
cls_.bind_cli(parser, group)
types = [x.name() for x in clss]
else:
types = None
parser.add_argument(
"-b", "--build-system", dest="buildsys", choices=types,
help="the build system to use. If not specified, it is detected. Set "
"'build_system' or 'build_command' to specify the build system in the "
"package itself.")
parser.add_argument(
"--variants", nargs='+', type=int, metavar="INDEX",
help="select variants to build (zero-indexed).")
parser.add_argument(
"--ba", "--build-args", dest="build_args", metavar="ARGS",
help="arguments to pass to the build system. Alternatively, list these "
"after a '--'.")
parser.add_argument(
"--cba", "--child-build-args", dest="child_build_args", metavar="ARGS",
help="arguments to pass to the child build system, if any. "
"Alternatively, list these after a second '--'.") | [
"def",
"setup_parser_common",
"(",
"parser",
")",
":",
"from",
"rez",
".",
"build_process_",
"import",
"get_build_process_types",
"from",
"rez",
".",
"build_system",
"import",
"get_valid_build_systems",
"process_types",
"=",
"get_build_process_types",
"(",
")",
"parser"... | Parser setup common to both rez-build and rez-release. | [
"Parser",
"setup",
"common",
"to",
"both",
"rez",
"-",
"build",
"and",
"rez",
"-",
"release",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/cli/build.py#L30-L71 | train | 227,441 |
nerdvegas/rez | src/rez/utils/scope.py | scoped_format | def scoped_format(txt, **objects):
"""Format a string with respect to a set of objects' attributes.
Example:
>>> Class Foo(object):
>>> def __init__(self):
>>> self.name = "Dave"
>>> print scoped_format("hello {foo.name}", foo=Foo())
hello Dave
Args:
objects (dict): Dict of objects to format with. If a value is a dict,
its values, and any further neted dicts, will also format with dot
notation.
pretty (bool): See `ObjectStringFormatter`.
expand (bool): See `ObjectStringFormatter`.
"""
pretty = objects.pop("pretty", RecursiveAttribute.format_pretty)
expand = objects.pop("expand", RecursiveAttribute.format_expand)
attr = RecursiveAttribute(objects, read_only=True)
formatter = scoped_formatter(**objects)
return formatter.format(txt, pretty=pretty, expand=expand) | python | def scoped_format(txt, **objects):
"""Format a string with respect to a set of objects' attributes.
Example:
>>> Class Foo(object):
>>> def __init__(self):
>>> self.name = "Dave"
>>> print scoped_format("hello {foo.name}", foo=Foo())
hello Dave
Args:
objects (dict): Dict of objects to format with. If a value is a dict,
its values, and any further neted dicts, will also format with dot
notation.
pretty (bool): See `ObjectStringFormatter`.
expand (bool): See `ObjectStringFormatter`.
"""
pretty = objects.pop("pretty", RecursiveAttribute.format_pretty)
expand = objects.pop("expand", RecursiveAttribute.format_expand)
attr = RecursiveAttribute(objects, read_only=True)
formatter = scoped_formatter(**objects)
return formatter.format(txt, pretty=pretty, expand=expand) | [
"def",
"scoped_format",
"(",
"txt",
",",
"*",
"*",
"objects",
")",
":",
"pretty",
"=",
"objects",
".",
"pop",
"(",
"\"pretty\"",
",",
"RecursiveAttribute",
".",
"format_pretty",
")",
"expand",
"=",
"objects",
".",
"pop",
"(",
"\"expand\"",
",",
"RecursiveA... | Format a string with respect to a set of objects' attributes.
Example:
>>> Class Foo(object):
>>> def __init__(self):
>>> self.name = "Dave"
>>> print scoped_format("hello {foo.name}", foo=Foo())
hello Dave
Args:
objects (dict): Dict of objects to format with. If a value is a dict,
its values, and any further neted dicts, will also format with dot
notation.
pretty (bool): See `ObjectStringFormatter`.
expand (bool): See `ObjectStringFormatter`. | [
"Format",
"a",
"string",
"with",
"respect",
"to",
"a",
"set",
"of",
"objects",
"attributes",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/scope.py#L238-L260 | train | 227,442 |
nerdvegas/rez | src/rez/utils/scope.py | RecursiveAttribute.to_dict | def to_dict(self):
"""Get an equivalent dict representation."""
d = {}
for k, v in self.__dict__["data"].iteritems():
if isinstance(v, RecursiveAttribute):
d[k] = v.to_dict()
else:
d[k] = v
return d | python | def to_dict(self):
"""Get an equivalent dict representation."""
d = {}
for k, v in self.__dict__["data"].iteritems():
if isinstance(v, RecursiveAttribute):
d[k] = v.to_dict()
else:
d[k] = v
return d | [
"def",
"to_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"__dict__",
"[",
"\"data\"",
"]",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"RecursiveAttribute",
")",
":",
"d",
"[",
... | Get an equivalent dict representation. | [
"Get",
"an",
"equivalent",
"dict",
"representation",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/scope.py#L89-L97 | train | 227,443 |
nerdvegas/rez | src/rezgui/objects/Config.py | Config.value | def value(self, key, type_=None):
"""Get the value of a setting.
If `type` is not provided, the key must be for a known setting,
present in `self.default_settings`. Conversely if `type` IS provided,
the key must be for an unknown setting.
"""
if type_ is None:
default = self._default_value(key)
val = self._value(key, default)
if type(val) == type(default):
return val
else:
return self._convert_value(val, type(default))
else:
val = self._value(key, None)
if val is None:
return None
return self._convert_value(val, type_) | python | def value(self, key, type_=None):
"""Get the value of a setting.
If `type` is not provided, the key must be for a known setting,
present in `self.default_settings`. Conversely if `type` IS provided,
the key must be for an unknown setting.
"""
if type_ is None:
default = self._default_value(key)
val = self._value(key, default)
if type(val) == type(default):
return val
else:
return self._convert_value(val, type(default))
else:
val = self._value(key, None)
if val is None:
return None
return self._convert_value(val, type_) | [
"def",
"value",
"(",
"self",
",",
"key",
",",
"type_",
"=",
"None",
")",
":",
"if",
"type_",
"is",
"None",
":",
"default",
"=",
"self",
".",
"_default_value",
"(",
"key",
")",
"val",
"=",
"self",
".",
"_value",
"(",
"key",
",",
"default",
")",
"i... | Get the value of a setting.
If `type` is not provided, the key must be for a known setting,
present in `self.default_settings`. Conversely if `type` IS provided,
the key must be for an unknown setting. | [
"Get",
"the",
"value",
"of",
"a",
"setting",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/objects/Config.py#L15-L33 | train | 227,444 |
nerdvegas/rez | src/rezgui/objects/Config.py | Config.get_string_list | def get_string_list(self, key):
"""Get a list of strings."""
strings = []
size = self.beginReadArray(key)
for i in range(size):
self.setArrayIndex(i)
entry = str(self._value("entry"))
strings.append(entry)
self.endArray()
return strings | python | def get_string_list(self, key):
"""Get a list of strings."""
strings = []
size = self.beginReadArray(key)
for i in range(size):
self.setArrayIndex(i)
entry = str(self._value("entry"))
strings.append(entry)
self.endArray()
return strings | [
"def",
"get_string_list",
"(",
"self",
",",
"key",
")",
":",
"strings",
"=",
"[",
"]",
"size",
"=",
"self",
".",
"beginReadArray",
"(",
"key",
")",
"for",
"i",
"in",
"range",
"(",
"size",
")",
":",
"self",
".",
"setArrayIndex",
"(",
"i",
")",
"entr... | Get a list of strings. | [
"Get",
"a",
"list",
"of",
"strings",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/objects/Config.py#L38-L47 | train | 227,445 |
nerdvegas/rez | src/rezgui/objects/Config.py | Config.prepend_string_list | def prepend_string_list(self, key, value, max_length_key):
"""Prepend a fixed-length string list with a new string.
The oldest string will be removed from the list. If the string is
already in the list, it is shuffled to the top. Use this to implement
things like a 'most recent files' entry.
"""
max_len = self.get(max_length_key)
strings = self.get_string_list(key)
strings = [value] + [x for x in strings if x != value]
strings = strings[:max_len]
self.beginWriteArray(key)
for i in range(len(strings)):
self.setArrayIndex(i)
self.setValue("entry", strings[i])
self.endArray() | python | def prepend_string_list(self, key, value, max_length_key):
"""Prepend a fixed-length string list with a new string.
The oldest string will be removed from the list. If the string is
already in the list, it is shuffled to the top. Use this to implement
things like a 'most recent files' entry.
"""
max_len = self.get(max_length_key)
strings = self.get_string_list(key)
strings = [value] + [x for x in strings if x != value]
strings = strings[:max_len]
self.beginWriteArray(key)
for i in range(len(strings)):
self.setArrayIndex(i)
self.setValue("entry", strings[i])
self.endArray() | [
"def",
"prepend_string_list",
"(",
"self",
",",
"key",
",",
"value",
",",
"max_length_key",
")",
":",
"max_len",
"=",
"self",
".",
"get",
"(",
"max_length_key",
")",
"strings",
"=",
"self",
".",
"get_string_list",
"(",
"key",
")",
"strings",
"=",
"[",
"v... | Prepend a fixed-length string list with a new string.
The oldest string will be removed from the list. If the string is
already in the list, it is shuffled to the top. Use this to implement
things like a 'most recent files' entry. | [
"Prepend",
"a",
"fixed",
"-",
"length",
"string",
"list",
"with",
"a",
"new",
"string",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rezgui/objects/Config.py#L49-L65 | train | 227,446 |
nerdvegas/rez | src/rez/vendor/pygraph/algorithms/utils.py | priority_queue.insert | def insert(self, item, priority):
"""
Insert item into the queue, with the given priority.
"""
heappush(self.heap, HeapItem(item, priority)) | python | def insert(self, item, priority):
"""
Insert item into the queue, with the given priority.
"""
heappush(self.heap, HeapItem(item, priority)) | [
"def",
"insert",
"(",
"self",
",",
"item",
",",
"priority",
")",
":",
"heappush",
"(",
"self",
".",
"heap",
",",
"HeapItem",
"(",
"item",
",",
"priority",
")",
")"
] | Insert item into the queue, with the given priority. | [
"Insert",
"item",
"into",
"the",
"queue",
"with",
"the",
"given",
"priority",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/utils.py#L57-L61 | train | 227,447 |
nerdvegas/rez | src/rez/vendor/pygraph/algorithms/accessibility.py | connected_components | def connected_components(graph):
"""
Connected components.
@type graph: graph, hypergraph
@param graph: Graph.
@rtype: dictionary
@return: Pairing that associates each node to its connected component.
"""
recursionlimit = getrecursionlimit()
setrecursionlimit(max(len(graph.nodes())*2,recursionlimit))
visited = {}
count = 1
# For 'each' node not found to belong to a connected component, find its connected
# component.
for each in graph:
if (each not in visited):
_dfs(graph, visited, count, each)
count = count + 1
setrecursionlimit(recursionlimit)
return visited | python | def connected_components(graph):
"""
Connected components.
@type graph: graph, hypergraph
@param graph: Graph.
@rtype: dictionary
@return: Pairing that associates each node to its connected component.
"""
recursionlimit = getrecursionlimit()
setrecursionlimit(max(len(graph.nodes())*2,recursionlimit))
visited = {}
count = 1
# For 'each' node not found to belong to a connected component, find its connected
# component.
for each in graph:
if (each not in visited):
_dfs(graph, visited, count, each)
count = count + 1
setrecursionlimit(recursionlimit)
return visited | [
"def",
"connected_components",
"(",
"graph",
")",
":",
"recursionlimit",
"=",
"getrecursionlimit",
"(",
")",
"setrecursionlimit",
"(",
"max",
"(",
"len",
"(",
"graph",
".",
"nodes",
"(",
")",
")",
"*",
"2",
",",
"recursionlimit",
")",
")",
"visited",
"=",
... | Connected components.
@type graph: graph, hypergraph
@param graph: Graph.
@rtype: dictionary
@return: Pairing that associates each node to its connected component. | [
"Connected",
"components",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/accessibility.py#L114-L138 | train | 227,448 |
nerdvegas/rez | src/rez/vendor/pygraph/algorithms/accessibility.py | cut_edges | def cut_edges(graph):
"""
Return the cut-edges of the given graph.
A cut edge, or bridge, is an edge of a graph whose removal increases the number of connected
components in the graph.
@type graph: graph, hypergraph
@param graph: Graph.
@rtype: list
@return: List of cut-edges.
"""
recursionlimit = getrecursionlimit()
setrecursionlimit(max(len(graph.nodes())*2,recursionlimit))
# Dispatch if we have a hypergraph
if 'hypergraph' == graph.__class__.__name__:
return _cut_hyperedges(graph)
pre = {} # Pre-ordering
low = {} # Lowest pre[] reachable from this node going down the spanning tree + one backedge
spanning_tree = {}
reply = []
pre[None] = 0
for each in graph:
if (each not in pre):
spanning_tree[each] = None
_cut_dfs(graph, spanning_tree, pre, low, reply, each)
setrecursionlimit(recursionlimit)
return reply | python | def cut_edges(graph):
"""
Return the cut-edges of the given graph.
A cut edge, or bridge, is an edge of a graph whose removal increases the number of connected
components in the graph.
@type graph: graph, hypergraph
@param graph: Graph.
@rtype: list
@return: List of cut-edges.
"""
recursionlimit = getrecursionlimit()
setrecursionlimit(max(len(graph.nodes())*2,recursionlimit))
# Dispatch if we have a hypergraph
if 'hypergraph' == graph.__class__.__name__:
return _cut_hyperedges(graph)
pre = {} # Pre-ordering
low = {} # Lowest pre[] reachable from this node going down the spanning tree + one backedge
spanning_tree = {}
reply = []
pre[None] = 0
for each in graph:
if (each not in pre):
spanning_tree[each] = None
_cut_dfs(graph, spanning_tree, pre, low, reply, each)
setrecursionlimit(recursionlimit)
return reply | [
"def",
"cut_edges",
"(",
"graph",
")",
":",
"recursionlimit",
"=",
"getrecursionlimit",
"(",
")",
"setrecursionlimit",
"(",
"max",
"(",
"len",
"(",
"graph",
".",
"nodes",
"(",
")",
")",
"*",
"2",
",",
"recursionlimit",
")",
")",
"# Dispatch if we have a hype... | Return the cut-edges of the given graph.
A cut edge, or bridge, is an edge of a graph whose removal increases the number of connected
components in the graph.
@type graph: graph, hypergraph
@param graph: Graph.
@rtype: list
@return: List of cut-edges. | [
"Return",
"the",
"cut",
"-",
"edges",
"of",
"the",
"given",
"graph",
".",
"A",
"cut",
"edge",
"or",
"bridge",
"is",
"an",
"edge",
"of",
"a",
"graph",
"whose",
"removal",
"increases",
"the",
"number",
"of",
"connected",
"components",
"in",
"the",
"graph",... | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/accessibility.py#L182-L214 | train | 227,449 |
nerdvegas/rez | src/rez/vendor/pygraph/algorithms/accessibility.py | _cut_hyperedges | def _cut_hyperedges(hypergraph):
"""
Return the cut-hyperedges of the given hypergraph.
@type hypergraph: hypergraph
@param hypergraph: Hypergraph
@rtype: list
@return: List of cut-nodes.
"""
edges_ = cut_nodes(hypergraph.graph)
edges = []
for each in edges_:
if (each[1] == 'h'):
edges.append(each[0])
return edges | python | def _cut_hyperedges(hypergraph):
"""
Return the cut-hyperedges of the given hypergraph.
@type hypergraph: hypergraph
@param hypergraph: Hypergraph
@rtype: list
@return: List of cut-nodes.
"""
edges_ = cut_nodes(hypergraph.graph)
edges = []
for each in edges_:
if (each[1] == 'h'):
edges.append(each[0])
return edges | [
"def",
"_cut_hyperedges",
"(",
"hypergraph",
")",
":",
"edges_",
"=",
"cut_nodes",
"(",
"hypergraph",
".",
"graph",
")",
"edges",
"=",
"[",
"]",
"for",
"each",
"in",
"edges_",
":",
"if",
"(",
"each",
"[",
"1",
"]",
"==",
"'h'",
")",
":",
"edges",
"... | Return the cut-hyperedges of the given hypergraph.
@type hypergraph: hypergraph
@param hypergraph: Hypergraph
@rtype: list
@return: List of cut-nodes. | [
"Return",
"the",
"cut",
"-",
"hyperedges",
"of",
"the",
"given",
"hypergraph",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/accessibility.py#L217-L234 | train | 227,450 |
nerdvegas/rez | src/rez/vendor/pygraph/algorithms/accessibility.py | cut_nodes | def cut_nodes(graph):
"""
Return the cut-nodes of the given graph.
A cut node, or articulation point, is a node of a graph whose removal increases the number of
connected components in the graph.
@type graph: graph, hypergraph
@param graph: Graph.
@rtype: list
@return: List of cut-nodes.
"""
recursionlimit = getrecursionlimit()
setrecursionlimit(max(len(graph.nodes())*2,recursionlimit))
# Dispatch if we have a hypergraph
if 'hypergraph' == graph.__class__.__name__:
return _cut_hypernodes(graph)
pre = {} # Pre-ordering
low = {} # Lowest pre[] reachable from this node going down the spanning tree + one backedge
reply = {}
spanning_tree = {}
pre[None] = 0
# Create spanning trees, calculate pre[], low[]
for each in graph:
if (each not in pre):
spanning_tree[each] = None
_cut_dfs(graph, spanning_tree, pre, low, [], each)
# Find cuts
for each in graph:
# If node is not a root
if (spanning_tree[each] is not None):
for other in graph[each]:
# If there is no back-edge from descendent to a ancestral of each
if (low[other] >= pre[each] and spanning_tree[other] == each):
reply[each] = 1
# If node is a root
else:
children = 0
for other in graph:
if (spanning_tree[other] == each):
children = children + 1
# root is cut-vertex iff it has two or more children
if (children >= 2):
reply[each] = 1
setrecursionlimit(recursionlimit)
return list(reply.keys()) | python | def cut_nodes(graph):
"""
Return the cut-nodes of the given graph.
A cut node, or articulation point, is a node of a graph whose removal increases the number of
connected components in the graph.
@type graph: graph, hypergraph
@param graph: Graph.
@rtype: list
@return: List of cut-nodes.
"""
recursionlimit = getrecursionlimit()
setrecursionlimit(max(len(graph.nodes())*2,recursionlimit))
# Dispatch if we have a hypergraph
if 'hypergraph' == graph.__class__.__name__:
return _cut_hypernodes(graph)
pre = {} # Pre-ordering
low = {} # Lowest pre[] reachable from this node going down the spanning tree + one backedge
reply = {}
spanning_tree = {}
pre[None] = 0
# Create spanning trees, calculate pre[], low[]
for each in graph:
if (each not in pre):
spanning_tree[each] = None
_cut_dfs(graph, spanning_tree, pre, low, [], each)
# Find cuts
for each in graph:
# If node is not a root
if (spanning_tree[each] is not None):
for other in graph[each]:
# If there is no back-edge from descendent to a ancestral of each
if (low[other] >= pre[each] and spanning_tree[other] == each):
reply[each] = 1
# If node is a root
else:
children = 0
for other in graph:
if (spanning_tree[other] == each):
children = children + 1
# root is cut-vertex iff it has two or more children
if (children >= 2):
reply[each] = 1
setrecursionlimit(recursionlimit)
return list(reply.keys()) | [
"def",
"cut_nodes",
"(",
"graph",
")",
":",
"recursionlimit",
"=",
"getrecursionlimit",
"(",
")",
"setrecursionlimit",
"(",
"max",
"(",
"len",
"(",
"graph",
".",
"nodes",
"(",
")",
")",
"*",
"2",
",",
"recursionlimit",
")",
")",
"# Dispatch if we have a hype... | Return the cut-nodes of the given graph.
A cut node, or articulation point, is a node of a graph whose removal increases the number of
connected components in the graph.
@type graph: graph, hypergraph
@param graph: Graph.
@rtype: list
@return: List of cut-nodes. | [
"Return",
"the",
"cut",
"-",
"nodes",
"of",
"the",
"given",
"graph",
".",
"A",
"cut",
"node",
"or",
"articulation",
"point",
"is",
"a",
"node",
"of",
"a",
"graph",
"whose",
"removal",
"increases",
"the",
"number",
"of",
"connected",
"components",
"in",
"... | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/accessibility.py#L237-L288 | train | 227,451 |
nerdvegas/rez | src/rez/vendor/pygraph/algorithms/accessibility.py | _cut_hypernodes | def _cut_hypernodes(hypergraph):
"""
Return the cut-nodes of the given hypergraph.
@type hypergraph: hypergraph
@param hypergraph: Hypergraph
@rtype: list
@return: List of cut-nodes.
"""
nodes_ = cut_nodes(hypergraph.graph)
nodes = []
for each in nodes_:
if (each[1] == 'n'):
nodes.append(each[0])
return nodes | python | def _cut_hypernodes(hypergraph):
"""
Return the cut-nodes of the given hypergraph.
@type hypergraph: hypergraph
@param hypergraph: Hypergraph
@rtype: list
@return: List of cut-nodes.
"""
nodes_ = cut_nodes(hypergraph.graph)
nodes = []
for each in nodes_:
if (each[1] == 'n'):
nodes.append(each[0])
return nodes | [
"def",
"_cut_hypernodes",
"(",
"hypergraph",
")",
":",
"nodes_",
"=",
"cut_nodes",
"(",
"hypergraph",
".",
"graph",
")",
"nodes",
"=",
"[",
"]",
"for",
"each",
"in",
"nodes_",
":",
"if",
"(",
"each",
"[",
"1",
"]",
"==",
"'n'",
")",
":",
"nodes",
"... | Return the cut-nodes of the given hypergraph.
@type hypergraph: hypergraph
@param hypergraph: Hypergraph
@rtype: list
@return: List of cut-nodes. | [
"Return",
"the",
"cut",
"-",
"nodes",
"of",
"the",
"given",
"hypergraph",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/algorithms/accessibility.py#L291-L308 | train | 227,452 |
nerdvegas/rez | src/rez/vendor/pygraph/classes/graph.py | graph.del_edge | def del_edge(self, edge):
"""
Remove an edge from the graph.
@type edge: tuple
@param edge: Edge.
"""
u, v = edge
self.node_neighbors[u].remove(v)
self.del_edge_labeling((u, v))
if (u != v):
self.node_neighbors[v].remove(u)
self.del_edge_labeling((v, u)) | python | def del_edge(self, edge):
"""
Remove an edge from the graph.
@type edge: tuple
@param edge: Edge.
"""
u, v = edge
self.node_neighbors[u].remove(v)
self.del_edge_labeling((u, v))
if (u != v):
self.node_neighbors[v].remove(u)
self.del_edge_labeling((v, u)) | [
"def",
"del_edge",
"(",
"self",
",",
"edge",
")",
":",
"u",
",",
"v",
"=",
"edge",
"self",
".",
"node_neighbors",
"[",
"u",
"]",
".",
"remove",
"(",
"v",
")",
"self",
".",
"del_edge_labeling",
"(",
"(",
"u",
",",
"v",
")",
")",
"if",
"(",
"u",
... | Remove an edge from the graph.
@type edge: tuple
@param edge: Edge. | [
"Remove",
"an",
"edge",
"from",
"the",
"graph",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/classes/graph.py#L170-L182 | train | 227,453 |
nerdvegas/rez | src/rez/vendor/pygraph/mixins/labeling.py | labeling.edge_weight | def edge_weight(self, edge):
"""
Get the weight of an edge.
@type edge: edge
@param edge: One edge.
@rtype: number
@return: Edge weight.
"""
return self.get_edge_properties( edge ).setdefault( self.WEIGHT_ATTRIBUTE_NAME, self.DEFAULT_WEIGHT ) | python | def edge_weight(self, edge):
"""
Get the weight of an edge.
@type edge: edge
@param edge: One edge.
@rtype: number
@return: Edge weight.
"""
return self.get_edge_properties( edge ).setdefault( self.WEIGHT_ATTRIBUTE_NAME, self.DEFAULT_WEIGHT ) | [
"def",
"edge_weight",
"(",
"self",
",",
"edge",
")",
":",
"return",
"self",
".",
"get_edge_properties",
"(",
"edge",
")",
".",
"setdefault",
"(",
"self",
".",
"WEIGHT_ATTRIBUTE_NAME",
",",
"self",
".",
"DEFAULT_WEIGHT",
")"
] | Get the weight of an edge.
@type edge: edge
@param edge: One edge.
@rtype: number
@return: Edge weight. | [
"Get",
"the",
"weight",
"of",
"an",
"edge",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/labeling.py#L66-L76 | train | 227,454 |
nerdvegas/rez | src/rez/vendor/pygraph/mixins/labeling.py | labeling.set_edge_weight | def set_edge_weight(self, edge, wt):
"""
Set the weight of an edge.
@type edge: edge
@param edge: One edge.
@type wt: number
@param wt: Edge weight.
"""
self.set_edge_properties(edge, weight=wt )
if not self.DIRECTED:
self.set_edge_properties((edge[1], edge[0]) , weight=wt ) | python | def set_edge_weight(self, edge, wt):
"""
Set the weight of an edge.
@type edge: edge
@param edge: One edge.
@type wt: number
@param wt: Edge weight.
"""
self.set_edge_properties(edge, weight=wt )
if not self.DIRECTED:
self.set_edge_properties((edge[1], edge[0]) , weight=wt ) | [
"def",
"set_edge_weight",
"(",
"self",
",",
"edge",
",",
"wt",
")",
":",
"self",
".",
"set_edge_properties",
"(",
"edge",
",",
"weight",
"=",
"wt",
")",
"if",
"not",
"self",
".",
"DIRECTED",
":",
"self",
".",
"set_edge_properties",
"(",
"(",
"edge",
"[... | Set the weight of an edge.
@type edge: edge
@param edge: One edge.
@type wt: number
@param wt: Edge weight. | [
"Set",
"the",
"weight",
"of",
"an",
"edge",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/labeling.py#L79-L91 | train | 227,455 |
nerdvegas/rez | src/rez/vendor/pygraph/mixins/labeling.py | labeling.edge_label | def edge_label(self, edge):
"""
Get the label of an edge.
@type edge: edge
@param edge: One edge.
@rtype: string
@return: Edge label
"""
return self.get_edge_properties( edge ).setdefault( self.LABEL_ATTRIBUTE_NAME, self.DEFAULT_LABEL ) | python | def edge_label(self, edge):
"""
Get the label of an edge.
@type edge: edge
@param edge: One edge.
@rtype: string
@return: Edge label
"""
return self.get_edge_properties( edge ).setdefault( self.LABEL_ATTRIBUTE_NAME, self.DEFAULT_LABEL ) | [
"def",
"edge_label",
"(",
"self",
",",
"edge",
")",
":",
"return",
"self",
".",
"get_edge_properties",
"(",
"edge",
")",
".",
"setdefault",
"(",
"self",
".",
"LABEL_ATTRIBUTE_NAME",
",",
"self",
".",
"DEFAULT_LABEL",
")"
] | Get the label of an edge.
@type edge: edge
@param edge: One edge.
@rtype: string
@return: Edge label | [
"Get",
"the",
"label",
"of",
"an",
"edge",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/labeling.py#L94-L104 | train | 227,456 |
nerdvegas/rez | src/rez/vendor/pygraph/mixins/labeling.py | labeling.set_edge_label | def set_edge_label(self, edge, label):
"""
Set the label of an edge.
@type edge: edge
@param edge: One edge.
@type label: string
@param label: Edge label.
"""
self.set_edge_properties(edge, label=label )
if not self.DIRECTED:
self.set_edge_properties((edge[1], edge[0]) , label=label ) | python | def set_edge_label(self, edge, label):
"""
Set the label of an edge.
@type edge: edge
@param edge: One edge.
@type label: string
@param label: Edge label.
"""
self.set_edge_properties(edge, label=label )
if not self.DIRECTED:
self.set_edge_properties((edge[1], edge[0]) , label=label ) | [
"def",
"set_edge_label",
"(",
"self",
",",
"edge",
",",
"label",
")",
":",
"self",
".",
"set_edge_properties",
"(",
"edge",
",",
"label",
"=",
"label",
")",
"if",
"not",
"self",
".",
"DIRECTED",
":",
"self",
".",
"set_edge_properties",
"(",
"(",
"edge",
... | Set the label of an edge.
@type edge: edge
@param edge: One edge.
@type label: string
@param label: Edge label. | [
"Set",
"the",
"label",
"of",
"an",
"edge",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/labeling.py#L106-L118 | train | 227,457 |
nerdvegas/rez | src/rez/vendor/pygraph/mixins/labeling.py | labeling.add_edge_attribute | def add_edge_attribute(self, edge, attr):
"""
Add attribute to the given edge.
@type edge: edge
@param edge: One edge.
@type attr: tuple
@param attr: Node attribute specified as a tuple in the form (attribute, value).
"""
self.edge_attr[edge] = self.edge_attributes(edge) + [attr]
if (not self.DIRECTED and edge[0] != edge[1]):
self.edge_attr[(edge[1],edge[0])] = self.edge_attributes((edge[1], edge[0])) + [attr] | python | def add_edge_attribute(self, edge, attr):
"""
Add attribute to the given edge.
@type edge: edge
@param edge: One edge.
@type attr: tuple
@param attr: Node attribute specified as a tuple in the form (attribute, value).
"""
self.edge_attr[edge] = self.edge_attributes(edge) + [attr]
if (not self.DIRECTED and edge[0] != edge[1]):
self.edge_attr[(edge[1],edge[0])] = self.edge_attributes((edge[1], edge[0])) + [attr] | [
"def",
"add_edge_attribute",
"(",
"self",
",",
"edge",
",",
"attr",
")",
":",
"self",
".",
"edge_attr",
"[",
"edge",
"]",
"=",
"self",
".",
"edge_attributes",
"(",
"edge",
")",
"+",
"[",
"attr",
"]",
"if",
"(",
"not",
"self",
".",
"DIRECTED",
"and",
... | Add attribute to the given edge.
@type edge: edge
@param edge: One edge.
@type attr: tuple
@param attr: Node attribute specified as a tuple in the form (attribute, value). | [
"Add",
"attribute",
"to",
"the",
"given",
"edge",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/labeling.py#L128-L141 | train | 227,458 |
nerdvegas/rez | src/rez/vendor/pygraph/mixins/labeling.py | labeling.add_node_attribute | def add_node_attribute(self, node, attr):
"""
Add attribute to the given node.
@type node: node
@param node: Node identifier
@type attr: tuple
@param attr: Node attribute specified as a tuple in the form (attribute, value).
"""
self.node_attr[node] = self.node_attr[node] + [attr] | python | def add_node_attribute(self, node, attr):
"""
Add attribute to the given node.
@type node: node
@param node: Node identifier
@type attr: tuple
@param attr: Node attribute specified as a tuple in the form (attribute, value).
"""
self.node_attr[node] = self.node_attr[node] + [attr] | [
"def",
"add_node_attribute",
"(",
"self",
",",
"node",
",",
"attr",
")",
":",
"self",
".",
"node_attr",
"[",
"node",
"]",
"=",
"self",
".",
"node_attr",
"[",
"node",
"]",
"+",
"[",
"attr",
"]"
] | Add attribute to the given node.
@type node: node
@param node: Node identifier
@type attr: tuple
@param attr: Node attribute specified as a tuple in the form (attribute, value). | [
"Add",
"attribute",
"to",
"the",
"given",
"node",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/labeling.py#L157-L167 | train | 227,459 |
nerdvegas/rez | src/rez/suite.py | Suite.activation_shell_code | def activation_shell_code(self, shell=None):
"""Get shell code that should be run to activate this suite."""
from rez.shells import create_shell
from rez.rex import RexExecutor
executor = RexExecutor(interpreter=create_shell(shell),
parent_variables=["PATH"],
shebang=False)
executor.env.PATH.append(self.tools_path)
return executor.get_output().strip() | python | def activation_shell_code(self, shell=None):
"""Get shell code that should be run to activate this suite."""
from rez.shells import create_shell
from rez.rex import RexExecutor
executor = RexExecutor(interpreter=create_shell(shell),
parent_variables=["PATH"],
shebang=False)
executor.env.PATH.append(self.tools_path)
return executor.get_output().strip() | [
"def",
"activation_shell_code",
"(",
"self",
",",
"shell",
"=",
"None",
")",
":",
"from",
"rez",
".",
"shells",
"import",
"create_shell",
"from",
"rez",
".",
"rex",
"import",
"RexExecutor",
"executor",
"=",
"RexExecutor",
"(",
"interpreter",
"=",
"create_shell... | Get shell code that should be run to activate this suite. | [
"Get",
"shell",
"code",
"that",
"should",
"be",
"run",
"to",
"activate",
"this",
"suite",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L68-L77 | train | 227,460 |
nerdvegas/rez | src/rez/suite.py | Suite.context | def context(self, name):
"""Get a context.
Args:
name (str): Name to store the context under.
Returns:
`ResolvedContext` object.
"""
data = self._context(name)
context = data.get("context")
if context:
return context
assert self.load_path
context_path = os.path.join(self.load_path, "contexts", "%s.rxt" % name)
context = ResolvedContext.load(context_path)
data["context"] = context
data["loaded"] = True
return context | python | def context(self, name):
"""Get a context.
Args:
name (str): Name to store the context under.
Returns:
`ResolvedContext` object.
"""
data = self._context(name)
context = data.get("context")
if context:
return context
assert self.load_path
context_path = os.path.join(self.load_path, "contexts", "%s.rxt" % name)
context = ResolvedContext.load(context_path)
data["context"] = context
data["loaded"] = True
return context | [
"def",
"context",
"(",
"self",
",",
"name",
")",
":",
"data",
"=",
"self",
".",
"_context",
"(",
"name",
")",
"context",
"=",
"data",
".",
"get",
"(",
"\"context\"",
")",
"if",
"context",
":",
"return",
"context",
"assert",
"self",
".",
"load_path",
... | Get a context.
Args:
name (str): Name to store the context under.
Returns:
`ResolvedContext` object. | [
"Get",
"a",
"context",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L82-L101 | train | 227,461 |
nerdvegas/rez | src/rez/suite.py | Suite.add_context | def add_context(self, name, context, prefix_char=None):
"""Add a context to the suite.
Args:
name (str): Name to store the context under.
context (ResolvedContext): Context to add.
"""
if name in self.contexts:
raise SuiteError("Context already in suite: %r" % name)
if not context.success:
raise SuiteError("Context is not resolved: %r" % name)
self.contexts[name] = dict(name=name,
context=context.copy(),
tool_aliases={},
hidden_tools=set(),
priority=self._next_priority,
prefix_char=prefix_char)
self._flush_tools() | python | def add_context(self, name, context, prefix_char=None):
"""Add a context to the suite.
Args:
name (str): Name to store the context under.
context (ResolvedContext): Context to add.
"""
if name in self.contexts:
raise SuiteError("Context already in suite: %r" % name)
if not context.success:
raise SuiteError("Context is not resolved: %r" % name)
self.contexts[name] = dict(name=name,
context=context.copy(),
tool_aliases={},
hidden_tools=set(),
priority=self._next_priority,
prefix_char=prefix_char)
self._flush_tools() | [
"def",
"add_context",
"(",
"self",
",",
"name",
",",
"context",
",",
"prefix_char",
"=",
"None",
")",
":",
"if",
"name",
"in",
"self",
".",
"contexts",
":",
"raise",
"SuiteError",
"(",
"\"Context already in suite: %r\"",
"%",
"name",
")",
"if",
"not",
"con... | Add a context to the suite.
Args:
name (str): Name to store the context under.
context (ResolvedContext): Context to add. | [
"Add",
"a",
"context",
"to",
"the",
"suite",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L103-L121 | train | 227,462 |
nerdvegas/rez | src/rez/suite.py | Suite.find_contexts | def find_contexts(self, in_request=None, in_resolve=None):
"""Find contexts in the suite based on search criteria.
Args:
in_request (str): Match contexts that contain the given package in
their request.
in_resolve (str or `Requirement`): Match contexts that contain the
given package in their resolve. You can also supply a conflict
requirement - '!foo' will match any contexts whos resolve does
not contain any version of package 'foo'.
Returns:
List of context names that match the search criteria.
"""
names = self.context_names
if in_request:
def _in_request(name):
context = self.context(name)
packages = set(x.name for x in context.requested_packages(True))
return (in_request in packages)
names = [x for x in names if _in_request(x)]
if in_resolve:
if isinstance(in_resolve, basestring):
in_resolve = PackageRequest(in_resolve)
def _in_resolve(name):
context = self.context(name)
variant = context.get_resolved_package(in_resolve.name)
if variant:
overlap = (variant.version in in_resolve.range)
return ((in_resolve.conflict and not overlap)
or (overlap and not in_resolve.conflict))
else:
return in_resolve.conflict
names = [x for x in names if _in_resolve(x)]
return names | python | def find_contexts(self, in_request=None, in_resolve=None):
"""Find contexts in the suite based on search criteria.
Args:
in_request (str): Match contexts that contain the given package in
their request.
in_resolve (str or `Requirement`): Match contexts that contain the
given package in their resolve. You can also supply a conflict
requirement - '!foo' will match any contexts whos resolve does
not contain any version of package 'foo'.
Returns:
List of context names that match the search criteria.
"""
names = self.context_names
if in_request:
def _in_request(name):
context = self.context(name)
packages = set(x.name for x in context.requested_packages(True))
return (in_request in packages)
names = [x for x in names if _in_request(x)]
if in_resolve:
if isinstance(in_resolve, basestring):
in_resolve = PackageRequest(in_resolve)
def _in_resolve(name):
context = self.context(name)
variant = context.get_resolved_package(in_resolve.name)
if variant:
overlap = (variant.version in in_resolve.range)
return ((in_resolve.conflict and not overlap)
or (overlap and not in_resolve.conflict))
else:
return in_resolve.conflict
names = [x for x in names if _in_resolve(x)]
return names | [
"def",
"find_contexts",
"(",
"self",
",",
"in_request",
"=",
"None",
",",
"in_resolve",
"=",
"None",
")",
":",
"names",
"=",
"self",
".",
"context_names",
"if",
"in_request",
":",
"def",
"_in_request",
"(",
"name",
")",
":",
"context",
"=",
"self",
".",
... | Find contexts in the suite based on search criteria.
Args:
in_request (str): Match contexts that contain the given package in
their request.
in_resolve (str or `Requirement`): Match contexts that contain the
given package in their resolve. You can also supply a conflict
requirement - '!foo' will match any contexts whos resolve does
not contain any version of package 'foo'.
Returns:
List of context names that match the search criteria. | [
"Find",
"contexts",
"in",
"the",
"suite",
"based",
"on",
"search",
"criteria",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L123-L161 | train | 227,463 |
nerdvegas/rez | src/rez/suite.py | Suite.remove_context | def remove_context(self, name):
"""Remove a context from the suite.
Args:
name (str): Name of the context to remove.
"""
self._context(name)
del self.contexts[name]
self._flush_tools() | python | def remove_context(self, name):
"""Remove a context from the suite.
Args:
name (str): Name of the context to remove.
"""
self._context(name)
del self.contexts[name]
self._flush_tools() | [
"def",
"remove_context",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_context",
"(",
"name",
")",
"del",
"self",
".",
"contexts",
"[",
"name",
"]",
"self",
".",
"_flush_tools",
"(",
")"
] | Remove a context from the suite.
Args:
name (str): Name of the context to remove. | [
"Remove",
"a",
"context",
"from",
"the",
"suite",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L163-L171 | train | 227,464 |
nerdvegas/rez | src/rez/suite.py | Suite.set_context_prefix | def set_context_prefix(self, name, prefix):
"""Set a context's prefix.
This will be applied to all wrappers for the tools in this context. For
example, a tool called 'foo' would appear as '<prefix>foo' in the
suite's bin path.
Args:
name (str): Name of the context to prefix.
prefix (str): Prefix to apply to tools.
"""
data = self._context(name)
data["prefix"] = prefix
self._flush_tools() | python | def set_context_prefix(self, name, prefix):
"""Set a context's prefix.
This will be applied to all wrappers for the tools in this context. For
example, a tool called 'foo' would appear as '<prefix>foo' in the
suite's bin path.
Args:
name (str): Name of the context to prefix.
prefix (str): Prefix to apply to tools.
"""
data = self._context(name)
data["prefix"] = prefix
self._flush_tools() | [
"def",
"set_context_prefix",
"(",
"self",
",",
"name",
",",
"prefix",
")",
":",
"data",
"=",
"self",
".",
"_context",
"(",
"name",
")",
"data",
"[",
"\"prefix\"",
"]",
"=",
"prefix",
"self",
".",
"_flush_tools",
"(",
")"
] | Set a context's prefix.
This will be applied to all wrappers for the tools in this context. For
example, a tool called 'foo' would appear as '<prefix>foo' in the
suite's bin path.
Args:
name (str): Name of the context to prefix.
prefix (str): Prefix to apply to tools. | [
"Set",
"a",
"context",
"s",
"prefix",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L173-L186 | train | 227,465 |
nerdvegas/rez | src/rez/suite.py | Suite.set_context_suffix | def set_context_suffix(self, name, suffix):
"""Set a context's suffix.
This will be applied to all wrappers for the tools in this context. For
example, a tool called 'foo' would appear as 'foo<suffix>' in the
suite's bin path.
Args:
name (str): Name of the context to suffix.
suffix (str): Suffix to apply to tools.
"""
data = self._context(name)
data["suffix"] = suffix
self._flush_tools() | python | def set_context_suffix(self, name, suffix):
"""Set a context's suffix.
This will be applied to all wrappers for the tools in this context. For
example, a tool called 'foo' would appear as 'foo<suffix>' in the
suite's bin path.
Args:
name (str): Name of the context to suffix.
suffix (str): Suffix to apply to tools.
"""
data = self._context(name)
data["suffix"] = suffix
self._flush_tools() | [
"def",
"set_context_suffix",
"(",
"self",
",",
"name",
",",
"suffix",
")",
":",
"data",
"=",
"self",
".",
"_context",
"(",
"name",
")",
"data",
"[",
"\"suffix\"",
"]",
"=",
"suffix",
"self",
".",
"_flush_tools",
"(",
")"
] | Set a context's suffix.
This will be applied to all wrappers for the tools in this context. For
example, a tool called 'foo' would appear as 'foo<suffix>' in the
suite's bin path.
Args:
name (str): Name of the context to suffix.
suffix (str): Suffix to apply to tools. | [
"Set",
"a",
"context",
"s",
"suffix",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L196-L209 | train | 227,466 |
nerdvegas/rez | src/rez/suite.py | Suite.bump_context | def bump_context(self, name):
"""Causes the context's tools to take priority over all others."""
data = self._context(name)
data["priority"] = self._next_priority
self._flush_tools() | python | def bump_context(self, name):
"""Causes the context's tools to take priority over all others."""
data = self._context(name)
data["priority"] = self._next_priority
self._flush_tools() | [
"def",
"bump_context",
"(",
"self",
",",
"name",
")",
":",
"data",
"=",
"self",
".",
"_context",
"(",
"name",
")",
"data",
"[",
"\"priority\"",
"]",
"=",
"self",
".",
"_next_priority",
"self",
".",
"_flush_tools",
"(",
")"
] | Causes the context's tools to take priority over all others. | [
"Causes",
"the",
"context",
"s",
"tools",
"to",
"take",
"priority",
"over",
"all",
"others",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L219-L223 | train | 227,467 |
nerdvegas/rez | src/rez/suite.py | Suite.hide_tool | def hide_tool(self, context_name, tool_name):
"""Hide a tool so that it is not exposed in the suite.
Args:
context_name (str): Context containing the tool.
tool_name (str): Name of tool to hide.
"""
data = self._context(context_name)
hidden_tools = data["hidden_tools"]
if tool_name not in hidden_tools:
self._validate_tool(context_name, tool_name)
hidden_tools.add(tool_name)
self._flush_tools() | python | def hide_tool(self, context_name, tool_name):
"""Hide a tool so that it is not exposed in the suite.
Args:
context_name (str): Context containing the tool.
tool_name (str): Name of tool to hide.
"""
data = self._context(context_name)
hidden_tools = data["hidden_tools"]
if tool_name not in hidden_tools:
self._validate_tool(context_name, tool_name)
hidden_tools.add(tool_name)
self._flush_tools() | [
"def",
"hide_tool",
"(",
"self",
",",
"context_name",
",",
"tool_name",
")",
":",
"data",
"=",
"self",
".",
"_context",
"(",
"context_name",
")",
"hidden_tools",
"=",
"data",
"[",
"\"hidden_tools\"",
"]",
"if",
"tool_name",
"not",
"in",
"hidden_tools",
":",
... | Hide a tool so that it is not exposed in the suite.
Args:
context_name (str): Context containing the tool.
tool_name (str): Name of tool to hide. | [
"Hide",
"a",
"tool",
"so",
"that",
"it",
"is",
"not",
"exposed",
"in",
"the",
"suite",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L225-L237 | train | 227,468 |
nerdvegas/rez | src/rez/suite.py | Suite.unhide_tool | def unhide_tool(self, context_name, tool_name):
"""Unhide a tool so that it may be exposed in a suite.
Note that unhiding a tool doesn't guarantee it can be seen - a tool of
the same name from a different context may be overriding it.
Args:
context_name (str): Context containing the tool.
tool_name (str): Name of tool to unhide.
"""
data = self._context(context_name)
hidden_tools = data["hidden_tools"]
if tool_name in hidden_tools:
hidden_tools.remove(tool_name)
self._flush_tools() | python | def unhide_tool(self, context_name, tool_name):
"""Unhide a tool so that it may be exposed in a suite.
Note that unhiding a tool doesn't guarantee it can be seen - a tool of
the same name from a different context may be overriding it.
Args:
context_name (str): Context containing the tool.
tool_name (str): Name of tool to unhide.
"""
data = self._context(context_name)
hidden_tools = data["hidden_tools"]
if tool_name in hidden_tools:
hidden_tools.remove(tool_name)
self._flush_tools() | [
"def",
"unhide_tool",
"(",
"self",
",",
"context_name",
",",
"tool_name",
")",
":",
"data",
"=",
"self",
".",
"_context",
"(",
"context_name",
")",
"hidden_tools",
"=",
"data",
"[",
"\"hidden_tools\"",
"]",
"if",
"tool_name",
"in",
"hidden_tools",
":",
"hidd... | Unhide a tool so that it may be exposed in a suite.
Note that unhiding a tool doesn't guarantee it can be seen - a tool of
the same name from a different context may be overriding it.
Args:
context_name (str): Context containing the tool.
tool_name (str): Name of tool to unhide. | [
"Unhide",
"a",
"tool",
"so",
"that",
"it",
"may",
"be",
"exposed",
"in",
"a",
"suite",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L239-L253 | train | 227,469 |
nerdvegas/rez | src/rez/suite.py | Suite.alias_tool | def alias_tool(self, context_name, tool_name, tool_alias):
"""Register an alias for a specific tool.
Note that a tool alias takes precedence over a context prefix/suffix.
Args:
context_name (str): Context containing the tool.
tool_name (str): Name of tool to alias.
tool_alias (str): Alias to give the tool.
"""
data = self._context(context_name)
aliases = data["tool_aliases"]
if tool_name in aliases:
raise SuiteError("Tool %r in context %r is already aliased to %r"
% (tool_name, context_name, aliases[tool_name]))
self._validate_tool(context_name, tool_name)
aliases[tool_name] = tool_alias
self._flush_tools() | python | def alias_tool(self, context_name, tool_name, tool_alias):
"""Register an alias for a specific tool.
Note that a tool alias takes precedence over a context prefix/suffix.
Args:
context_name (str): Context containing the tool.
tool_name (str): Name of tool to alias.
tool_alias (str): Alias to give the tool.
"""
data = self._context(context_name)
aliases = data["tool_aliases"]
if tool_name in aliases:
raise SuiteError("Tool %r in context %r is already aliased to %r"
% (tool_name, context_name, aliases[tool_name]))
self._validate_tool(context_name, tool_name)
aliases[tool_name] = tool_alias
self._flush_tools() | [
"def",
"alias_tool",
"(",
"self",
",",
"context_name",
",",
"tool_name",
",",
"tool_alias",
")",
":",
"data",
"=",
"self",
".",
"_context",
"(",
"context_name",
")",
"aliases",
"=",
"data",
"[",
"\"tool_aliases\"",
"]",
"if",
"tool_name",
"in",
"aliases",
... | Register an alias for a specific tool.
Note that a tool alias takes precedence over a context prefix/suffix.
Args:
context_name (str): Context containing the tool.
tool_name (str): Name of tool to alias.
tool_alias (str): Alias to give the tool. | [
"Register",
"an",
"alias",
"for",
"a",
"specific",
"tool",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L255-L272 | train | 227,470 |
nerdvegas/rez | src/rez/suite.py | Suite.unalias_tool | def unalias_tool(self, context_name, tool_name):
"""Deregister an alias for a specific tool.
Args:
context_name (str): Context containing the tool.
tool_name (str): Name of tool to unalias.
"""
data = self._context(context_name)
aliases = data["tool_aliases"]
if tool_name in aliases:
del aliases[tool_name]
self._flush_tools() | python | def unalias_tool(self, context_name, tool_name):
"""Deregister an alias for a specific tool.
Args:
context_name (str): Context containing the tool.
tool_name (str): Name of tool to unalias.
"""
data = self._context(context_name)
aliases = data["tool_aliases"]
if tool_name in aliases:
del aliases[tool_name]
self._flush_tools() | [
"def",
"unalias_tool",
"(",
"self",
",",
"context_name",
",",
"tool_name",
")",
":",
"data",
"=",
"self",
".",
"_context",
"(",
"context_name",
")",
"aliases",
"=",
"data",
"[",
"\"tool_aliases\"",
"]",
"if",
"tool_name",
"in",
"aliases",
":",
"del",
"alia... | Deregister an alias for a specific tool.
Args:
context_name (str): Context containing the tool.
tool_name (str): Name of tool to unalias. | [
"Deregister",
"an",
"alias",
"for",
"a",
"specific",
"tool",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L274-L285 | train | 227,471 |
nerdvegas/rez | src/rez/suite.py | Suite.get_tool_filepath | def get_tool_filepath(self, tool_alias):
"""Given a visible tool alias, return the full path to the executable.
Args:
tool_alias (str): Tool alias to search for.
Returns:
(str): Filepath of executable, or None if the tool is not in the
suite. May also return None because this suite has not been saved
to disk, so a filepath hasn't yet been established.
"""
tools_dict = self.get_tools()
if tool_alias in tools_dict:
if self.tools_path is None:
return None
else:
return os.path.join(self.tools_path, tool_alias)
else:
return None | python | def get_tool_filepath(self, tool_alias):
"""Given a visible tool alias, return the full path to the executable.
Args:
tool_alias (str): Tool alias to search for.
Returns:
(str): Filepath of executable, or None if the tool is not in the
suite. May also return None because this suite has not been saved
to disk, so a filepath hasn't yet been established.
"""
tools_dict = self.get_tools()
if tool_alias in tools_dict:
if self.tools_path is None:
return None
else:
return os.path.join(self.tools_path, tool_alias)
else:
return None | [
"def",
"get_tool_filepath",
"(",
"self",
",",
"tool_alias",
")",
":",
"tools_dict",
"=",
"self",
".",
"get_tools",
"(",
")",
"if",
"tool_alias",
"in",
"tools_dict",
":",
"if",
"self",
".",
"tools_path",
"is",
"None",
":",
"return",
"None",
"else",
":",
"... | Given a visible tool alias, return the full path to the executable.
Args:
tool_alias (str): Tool alias to search for.
Returns:
(str): Filepath of executable, or None if the tool is not in the
suite. May also return None because this suite has not been saved
to disk, so a filepath hasn't yet been established. | [
"Given",
"a",
"visible",
"tool",
"alias",
"return",
"the",
"full",
"path",
"to",
"the",
"executable",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L302-L320 | train | 227,472 |
nerdvegas/rez | src/rez/suite.py | Suite.get_tool_context | def get_tool_context(self, tool_alias):
"""Given a visible tool alias, return the name of the context it
belongs to.
Args:
tool_alias (str): Tool alias to search for.
Returns:
(str): Name of the context that exposes a visible instance of this
tool alias, or None if the alias is not available.
"""
tools_dict = self.get_tools()
data = tools_dict.get(tool_alias)
if data:
return data["context_name"]
return None | python | def get_tool_context(self, tool_alias):
"""Given a visible tool alias, return the name of the context it
belongs to.
Args:
tool_alias (str): Tool alias to search for.
Returns:
(str): Name of the context that exposes a visible instance of this
tool alias, or None if the alias is not available.
"""
tools_dict = self.get_tools()
data = tools_dict.get(tool_alias)
if data:
return data["context_name"]
return None | [
"def",
"get_tool_context",
"(",
"self",
",",
"tool_alias",
")",
":",
"tools_dict",
"=",
"self",
".",
"get_tools",
"(",
")",
"data",
"=",
"tools_dict",
".",
"get",
"(",
"tool_alias",
")",
"if",
"data",
":",
"return",
"data",
"[",
"\"context_name\"",
"]",
... | Given a visible tool alias, return the name of the context it
belongs to.
Args:
tool_alias (str): Tool alias to search for.
Returns:
(str): Name of the context that exposes a visible instance of this
tool alias, or None if the alias is not available. | [
"Given",
"a",
"visible",
"tool",
"alias",
"return",
"the",
"name",
"of",
"the",
"context",
"it",
"belongs",
"to",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L322-L337 | train | 227,473 |
nerdvegas/rez | src/rez/suite.py | Suite.validate | def validate(self):
"""Validate the suite."""
for context_name in self.context_names:
context = self.context(context_name)
try:
context.validate()
except ResolvedContextError as e:
raise SuiteError("Error in context %r: %s"
% (context_name, str(e))) | python | def validate(self):
"""Validate the suite."""
for context_name in self.context_names:
context = self.context(context_name)
try:
context.validate()
except ResolvedContextError as e:
raise SuiteError("Error in context %r: %s"
% (context_name, str(e))) | [
"def",
"validate",
"(",
"self",
")",
":",
"for",
"context_name",
"in",
"self",
".",
"context_names",
":",
"context",
"=",
"self",
".",
"context",
"(",
"context_name",
")",
"try",
":",
"context",
".",
"validate",
"(",
")",
"except",
"ResolvedContextError",
... | Validate the suite. | [
"Validate",
"the",
"suite",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L379-L387 | train | 227,474 |
nerdvegas/rez | src/rez/suite.py | Suite.save | def save(self, path, verbose=False):
"""Save the suite to disk.
Args:
path (str): Path to save the suite to. If a suite is already saved
at `path`, then it will be overwritten. Otherwise, if `path`
exists, an error is raised.
"""
path = os.path.realpath(path)
if os.path.exists(path):
if self.load_path and self.load_path == path:
if verbose:
print "saving over previous suite..."
for context_name in self.context_names:
self.context(context_name) # load before dir deleted
shutil.rmtree(path)
else:
raise SuiteError("Cannot save, path exists: %r" % path)
contexts_path = os.path.join(path, "contexts")
os.makedirs(contexts_path)
# write suite data
data = self.to_dict()
filepath = os.path.join(path, "suite.yaml")
with open(filepath, "w") as f:
f.write(dump_yaml(data))
# write contexts
for context_name in self.context_names:
context = self.context(context_name)
context._set_parent_suite(path, context_name)
filepath = self._context_path(context_name, path)
if verbose:
print "writing %r..." % filepath
context.save(filepath)
# create alias wrappers
tools_path = os.path.join(path, "bin")
os.makedirs(tools_path)
if verbose:
print "creating alias wrappers in %r..." % tools_path
tools = self.get_tools()
for tool_alias, d in tools.iteritems():
tool_name = d["tool_name"]
context_name = d["context_name"]
data = self._context(context_name)
prefix_char = data.get("prefix_char")
if verbose:
print ("creating %r -> %r (%s context)..."
% (tool_alias, tool_name, context_name))
filepath = os.path.join(tools_path, tool_alias)
create_forwarding_script(filepath,
module="suite",
func_name="_FWD__invoke_suite_tool_alias",
context_name=context_name,
tool_name=tool_name,
prefix_char=prefix_char) | python | def save(self, path, verbose=False):
"""Save the suite to disk.
Args:
path (str): Path to save the suite to. If a suite is already saved
at `path`, then it will be overwritten. Otherwise, if `path`
exists, an error is raised.
"""
path = os.path.realpath(path)
if os.path.exists(path):
if self.load_path and self.load_path == path:
if verbose:
print "saving over previous suite..."
for context_name in self.context_names:
self.context(context_name) # load before dir deleted
shutil.rmtree(path)
else:
raise SuiteError("Cannot save, path exists: %r" % path)
contexts_path = os.path.join(path, "contexts")
os.makedirs(contexts_path)
# write suite data
data = self.to_dict()
filepath = os.path.join(path, "suite.yaml")
with open(filepath, "w") as f:
f.write(dump_yaml(data))
# write contexts
for context_name in self.context_names:
context = self.context(context_name)
context._set_parent_suite(path, context_name)
filepath = self._context_path(context_name, path)
if verbose:
print "writing %r..." % filepath
context.save(filepath)
# create alias wrappers
tools_path = os.path.join(path, "bin")
os.makedirs(tools_path)
if verbose:
print "creating alias wrappers in %r..." % tools_path
tools = self.get_tools()
for tool_alias, d in tools.iteritems():
tool_name = d["tool_name"]
context_name = d["context_name"]
data = self._context(context_name)
prefix_char = data.get("prefix_char")
if verbose:
print ("creating %r -> %r (%s context)..."
% (tool_alias, tool_name, context_name))
filepath = os.path.join(tools_path, tool_alias)
create_forwarding_script(filepath,
module="suite",
func_name="_FWD__invoke_suite_tool_alias",
context_name=context_name,
tool_name=tool_name,
prefix_char=prefix_char) | [
"def",
"save",
"(",
"self",
",",
"path",
",",
"verbose",
"=",
"False",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"path",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"if",
"self",
".",
"load_path",
"... | Save the suite to disk.
Args:
path (str): Path to save the suite to. If a suite is already saved
at `path`, then it will be overwritten. Otherwise, if `path`
exists, an error is raised. | [
"Save",
"the",
"suite",
"to",
"disk",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L415-L476 | train | 227,475 |
nerdvegas/rez | src/rez/suite.py | Suite.print_info | def print_info(self, buf=sys.stdout, verbose=False):
"""Prints a message summarising the contents of the suite."""
_pr = Printer(buf)
if not self.contexts:
_pr("Suite is empty.")
return
context_names = sorted(self.contexts.iterkeys())
_pr("Suite contains %d contexts:" % len(context_names))
if not verbose:
_pr(' '.join(context_names))
return
tools = self.get_tools().values()
context_tools = defaultdict(set)
context_variants = defaultdict(set)
for entry in tools:
context_name = entry["context_name"]
context_tools[context_name].add(entry["tool_name"])
context_variants[context_name].add(str(entry["variant"]))
_pr()
rows = [["NAME", "VISIBLE TOOLS", "PATH"],
["----", "-------------", "----"]]
for context_name in context_names:
context_path = self._context_path(context_name) or '-'
ntools = len(context_tools.get(context_name, []))
if ntools:
nvariants = len(context_variants[context_name])
short_desc = "%d tools from %d packages" % (ntools, nvariants)
else:
short_desc = "no tools"
rows.append((context_name, short_desc, context_path))
_pr("\n".join(columnise(rows))) | python | def print_info(self, buf=sys.stdout, verbose=False):
"""Prints a message summarising the contents of the suite."""
_pr = Printer(buf)
if not self.contexts:
_pr("Suite is empty.")
return
context_names = sorted(self.contexts.iterkeys())
_pr("Suite contains %d contexts:" % len(context_names))
if not verbose:
_pr(' '.join(context_names))
return
tools = self.get_tools().values()
context_tools = defaultdict(set)
context_variants = defaultdict(set)
for entry in tools:
context_name = entry["context_name"]
context_tools[context_name].add(entry["tool_name"])
context_variants[context_name].add(str(entry["variant"]))
_pr()
rows = [["NAME", "VISIBLE TOOLS", "PATH"],
["----", "-------------", "----"]]
for context_name in context_names:
context_path = self._context_path(context_name) or '-'
ntools = len(context_tools.get(context_name, []))
if ntools:
nvariants = len(context_variants[context_name])
short_desc = "%d tools from %d packages" % (ntools, nvariants)
else:
short_desc = "no tools"
rows.append((context_name, short_desc, context_path))
_pr("\n".join(columnise(rows))) | [
"def",
"print_info",
"(",
"self",
",",
"buf",
"=",
"sys",
".",
"stdout",
",",
"verbose",
"=",
"False",
")",
":",
"_pr",
"=",
"Printer",
"(",
"buf",
")",
"if",
"not",
"self",
".",
"contexts",
":",
"_pr",
"(",
"\"Suite is empty.\"",
")",
"return",
"con... | Prints a message summarising the contents of the suite. | [
"Prints",
"a",
"message",
"summarising",
"the",
"contents",
"of",
"the",
"suite",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/suite.py#L525-L562 | train | 227,476 |
nerdvegas/rez | src/rez/build_system.py | get_valid_build_systems | def get_valid_build_systems(working_dir, package=None):
"""Returns the build system classes that could build the source in given dir.
Args:
working_dir (str): Dir containing the package definition and potentially
build files.
package (`Package`): Package to be built. This may or may not be needed
to determine the build system. For eg, cmake just has to look for
a CMakeLists.txt file, whereas the 'build_command' package field
must be present for the 'custom' build system type.
Returns:
List of class: Valid build system class types.
"""
from rez.plugin_managers import plugin_manager
from rez.exceptions import PackageMetadataError
try:
package = package or get_developer_package(working_dir)
except PackageMetadataError:
# no package, or bad package
pass
if package:
if getattr(package, "build_command", None) is not None:
buildsys_name = "custom"
else:
buildsys_name = getattr(package, "build_system", None)
# package explicitly specifies build system
if buildsys_name:
cls = plugin_manager.get_plugin_class('build_system', buildsys_name)
return [cls]
# detect valid build systems
clss = []
for buildsys_name in get_buildsys_types():
cls = plugin_manager.get_plugin_class('build_system', buildsys_name)
if cls.is_valid_root(working_dir, package=package):
clss.append(cls)
# Sometimes files for multiple build systems can be present, because one
# build system uses another (a 'child' build system) - eg, cmake uses
# make. Detect this case and ignore files from the child build system.
#
child_clss = set(x.child_build_system() for x in clss)
clss = list(set(clss) - child_clss)
return clss | python | def get_valid_build_systems(working_dir, package=None):
"""Returns the build system classes that could build the source in given dir.
Args:
working_dir (str): Dir containing the package definition and potentially
build files.
package (`Package`): Package to be built. This may or may not be needed
to determine the build system. For eg, cmake just has to look for
a CMakeLists.txt file, whereas the 'build_command' package field
must be present for the 'custom' build system type.
Returns:
List of class: Valid build system class types.
"""
from rez.plugin_managers import plugin_manager
from rez.exceptions import PackageMetadataError
try:
package = package or get_developer_package(working_dir)
except PackageMetadataError:
# no package, or bad package
pass
if package:
if getattr(package, "build_command", None) is not None:
buildsys_name = "custom"
else:
buildsys_name = getattr(package, "build_system", None)
# package explicitly specifies build system
if buildsys_name:
cls = plugin_manager.get_plugin_class('build_system', buildsys_name)
return [cls]
# detect valid build systems
clss = []
for buildsys_name in get_buildsys_types():
cls = plugin_manager.get_plugin_class('build_system', buildsys_name)
if cls.is_valid_root(working_dir, package=package):
clss.append(cls)
# Sometimes files for multiple build systems can be present, because one
# build system uses another (a 'child' build system) - eg, cmake uses
# make. Detect this case and ignore files from the child build system.
#
child_clss = set(x.child_build_system() for x in clss)
clss = list(set(clss) - child_clss)
return clss | [
"def",
"get_valid_build_systems",
"(",
"working_dir",
",",
"package",
"=",
"None",
")",
":",
"from",
"rez",
".",
"plugin_managers",
"import",
"plugin_manager",
"from",
"rez",
".",
"exceptions",
"import",
"PackageMetadataError",
"try",
":",
"package",
"=",
"package... | Returns the build system classes that could build the source in given dir.
Args:
working_dir (str): Dir containing the package definition and potentially
build files.
package (`Package`): Package to be built. This may or may not be needed
to determine the build system. For eg, cmake just has to look for
a CMakeLists.txt file, whereas the 'build_command' package field
must be present for the 'custom' build system type.
Returns:
List of class: Valid build system class types. | [
"Returns",
"the",
"build",
"system",
"classes",
"that",
"could",
"build",
"the",
"source",
"in",
"given",
"dir",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_system.py#L14-L62 | train | 227,477 |
nerdvegas/rez | src/rez/build_system.py | create_build_system | def create_build_system(working_dir, buildsys_type=None, package=None, opts=None,
write_build_scripts=False, verbose=False,
build_args=[], child_build_args=[]):
"""Return a new build system that can build the source in working_dir."""
from rez.plugin_managers import plugin_manager
# detect build system if necessary
if not buildsys_type:
clss = get_valid_build_systems(working_dir, package=package)
if not clss:
raise BuildSystemError(
"No build system is associated with the path %s" % working_dir)
if len(clss) != 1:
s = ', '.join(x.name() for x in clss)
raise BuildSystemError(("Source could be built with one of: %s; "
"Please specify a build system") % s)
buildsys_type = iter(clss).next().name()
# create instance of build system
cls_ = plugin_manager.get_plugin_class('build_system', buildsys_type)
return cls_(working_dir,
opts=opts,
package=package,
write_build_scripts=write_build_scripts,
verbose=verbose,
build_args=build_args,
child_build_args=child_build_args) | python | def create_build_system(working_dir, buildsys_type=None, package=None, opts=None,
write_build_scripts=False, verbose=False,
build_args=[], child_build_args=[]):
"""Return a new build system that can build the source in working_dir."""
from rez.plugin_managers import plugin_manager
# detect build system if necessary
if not buildsys_type:
clss = get_valid_build_systems(working_dir, package=package)
if not clss:
raise BuildSystemError(
"No build system is associated with the path %s" % working_dir)
if len(clss) != 1:
s = ', '.join(x.name() for x in clss)
raise BuildSystemError(("Source could be built with one of: %s; "
"Please specify a build system") % s)
buildsys_type = iter(clss).next().name()
# create instance of build system
cls_ = plugin_manager.get_plugin_class('build_system', buildsys_type)
return cls_(working_dir,
opts=opts,
package=package,
write_build_scripts=write_build_scripts,
verbose=verbose,
build_args=build_args,
child_build_args=child_build_args) | [
"def",
"create_build_system",
"(",
"working_dir",
",",
"buildsys_type",
"=",
"None",
",",
"package",
"=",
"None",
",",
"opts",
"=",
"None",
",",
"write_build_scripts",
"=",
"False",
",",
"verbose",
"=",
"False",
",",
"build_args",
"=",
"[",
"]",
",",
"chil... | Return a new build system that can build the source in working_dir. | [
"Return",
"a",
"new",
"build",
"system",
"that",
"can",
"build",
"the",
"source",
"in",
"working_dir",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_system.py#L65-L95 | train | 227,478 |
nerdvegas/rez | src/rez/build_system.py | BuildSystem.build | def build(self, context, variant, build_path, install_path, install=False,
build_type=BuildType.local):
"""Implement this method to perform the actual build.
Args:
context: A ResolvedContext object that the build process must be
executed within.
variant (`Variant`): The variant being built.
build_path: Where to write temporary build files. May be relative
to working_dir.
install_path (str): The package repository path to install the
package to, if installing. If None, defaults to
`config.local_packages_path`.
install: If True, install the build.
build_type: A BuildType (i.e local or central).
Returns:
A dict containing the following information:
- success: Bool indicating if the build was successful.
- extra_files: List of created files of interest, not including
build targets. A good example is the interpreted context file,
usually named 'build.rxt.sh' or similar. These files should be
located under build_path. Rez may install them for debugging
purposes.
- build_env_script: If this instance was created with write_build_scripts
as True, then the build should generate a script which, when run
by the user, places them in the build environment.
"""
raise NotImplementedError | python | def build(self, context, variant, build_path, install_path, install=False,
build_type=BuildType.local):
"""Implement this method to perform the actual build.
Args:
context: A ResolvedContext object that the build process must be
executed within.
variant (`Variant`): The variant being built.
build_path: Where to write temporary build files. May be relative
to working_dir.
install_path (str): The package repository path to install the
package to, if installing. If None, defaults to
`config.local_packages_path`.
install: If True, install the build.
build_type: A BuildType (i.e local or central).
Returns:
A dict containing the following information:
- success: Bool indicating if the build was successful.
- extra_files: List of created files of interest, not including
build targets. A good example is the interpreted context file,
usually named 'build.rxt.sh' or similar. These files should be
located under build_path. Rez may install them for debugging
purposes.
- build_env_script: If this instance was created with write_build_scripts
as True, then the build should generate a script which, when run
by the user, places them in the build environment.
"""
raise NotImplementedError | [
"def",
"build",
"(",
"self",
",",
"context",
",",
"variant",
",",
"build_path",
",",
"install_path",
",",
"install",
"=",
"False",
",",
"build_type",
"=",
"BuildType",
".",
"local",
")",
":",
"raise",
"NotImplementedError"
] | Implement this method to perform the actual build.
Args:
context: A ResolvedContext object that the build process must be
executed within.
variant (`Variant`): The variant being built.
build_path: Where to write temporary build files. May be relative
to working_dir.
install_path (str): The package repository path to install the
package to, if installing. If None, defaults to
`config.local_packages_path`.
install: If True, install the build.
build_type: A BuildType (i.e local or central).
Returns:
A dict containing the following information:
- success: Bool indicating if the build was successful.
- extra_files: List of created files of interest, not including
build targets. A good example is the interpreted context file,
usually named 'build.rxt.sh' or similar. These files should be
located under build_path. Rez may install them for debugging
purposes.
- build_env_script: If this instance was created with write_build_scripts
as True, then the build should generate a script which, when run
by the user, places them in the build environment. | [
"Implement",
"this",
"method",
"to",
"perform",
"the",
"actual",
"build",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_system.py#L167-L195 | train | 227,479 |
nerdvegas/rez | src/rez/build_system.py | BuildSystem.get_standard_vars | def get_standard_vars(cls, context, variant, build_type, install,
build_path, install_path=None):
"""Returns a standard set of environment variables that can be set
for the build system to use
"""
from rez.config import config
package = variant.parent
variant_requires = map(str, variant.variant_requires)
if variant.index is None:
variant_subpath = ''
else:
variant_subpath = variant._non_shortlinked_subpath
vars_ = {
'REZ_BUILD_ENV': 1,
'REZ_BUILD_PATH': build_path,
'REZ_BUILD_THREAD_COUNT': package.config.build_thread_count,
'REZ_BUILD_VARIANT_INDEX': variant.index or 0,
'REZ_BUILD_VARIANT_REQUIRES': ' '.join(variant_requires),
'REZ_BUILD_VARIANT_SUBPATH': variant_subpath,
'REZ_BUILD_PROJECT_VERSION': str(package.version),
'REZ_BUILD_PROJECT_NAME': package.name,
'REZ_BUILD_PROJECT_DESCRIPTION': (package.description or '').strip(),
'REZ_BUILD_PROJECT_FILE': package.filepath,
'REZ_BUILD_SOURCE_PATH': os.path.dirname(package.filepath),
'REZ_BUILD_REQUIRES': ' '.join(
str(x) for x in context.requested_packages(True)
),
'REZ_BUILD_REQUIRES_UNVERSIONED': ' '.join(
x.name for x in context.requested_packages(True)
),
'REZ_BUILD_TYPE': build_type.name,
'REZ_BUILD_INSTALL': 1 if install else 0,
}
if install_path:
vars_['REZ_BUILD_INSTALL_PATH'] = install_path
if config.rez_1_environment_variables and \
not config.disable_rez_1_compatibility and \
build_type == BuildType.central:
vars_['REZ_IN_REZ_RELEASE'] = 1
return vars_ | python | def get_standard_vars(cls, context, variant, build_type, install,
build_path, install_path=None):
"""Returns a standard set of environment variables that can be set
for the build system to use
"""
from rez.config import config
package = variant.parent
variant_requires = map(str, variant.variant_requires)
if variant.index is None:
variant_subpath = ''
else:
variant_subpath = variant._non_shortlinked_subpath
vars_ = {
'REZ_BUILD_ENV': 1,
'REZ_BUILD_PATH': build_path,
'REZ_BUILD_THREAD_COUNT': package.config.build_thread_count,
'REZ_BUILD_VARIANT_INDEX': variant.index or 0,
'REZ_BUILD_VARIANT_REQUIRES': ' '.join(variant_requires),
'REZ_BUILD_VARIANT_SUBPATH': variant_subpath,
'REZ_BUILD_PROJECT_VERSION': str(package.version),
'REZ_BUILD_PROJECT_NAME': package.name,
'REZ_BUILD_PROJECT_DESCRIPTION': (package.description or '').strip(),
'REZ_BUILD_PROJECT_FILE': package.filepath,
'REZ_BUILD_SOURCE_PATH': os.path.dirname(package.filepath),
'REZ_BUILD_REQUIRES': ' '.join(
str(x) for x in context.requested_packages(True)
),
'REZ_BUILD_REQUIRES_UNVERSIONED': ' '.join(
x.name for x in context.requested_packages(True)
),
'REZ_BUILD_TYPE': build_type.name,
'REZ_BUILD_INSTALL': 1 if install else 0,
}
if install_path:
vars_['REZ_BUILD_INSTALL_PATH'] = install_path
if config.rez_1_environment_variables and \
not config.disable_rez_1_compatibility and \
build_type == BuildType.central:
vars_['REZ_IN_REZ_RELEASE'] = 1
return vars_ | [
"def",
"get_standard_vars",
"(",
"cls",
",",
"context",
",",
"variant",
",",
"build_type",
",",
"install",
",",
"build_path",
",",
"install_path",
"=",
"None",
")",
":",
"from",
"rez",
".",
"config",
"import",
"config",
"package",
"=",
"variant",
".",
"par... | Returns a standard set of environment variables that can be set
for the build system to use | [
"Returns",
"a",
"standard",
"set",
"of",
"environment",
"variables",
"that",
"can",
"be",
"set",
"for",
"the",
"build",
"system",
"to",
"use"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_system.py#L198-L243 | train | 227,480 |
nerdvegas/rez | src/rez/build_system.py | BuildSystem.set_standard_vars | def set_standard_vars(cls, executor, context, variant, build_type,
install, build_path, install_path=None):
"""Sets a standard set of environment variables for the build system to
use
"""
vars = cls.get_standard_vars(context=context,
variant=variant,
build_type=build_type,
install=install,
build_path=build_path,
install_path=install_path)
for var, value in vars.iteritems():
executor.env[var] = value | python | def set_standard_vars(cls, executor, context, variant, build_type,
install, build_path, install_path=None):
"""Sets a standard set of environment variables for the build system to
use
"""
vars = cls.get_standard_vars(context=context,
variant=variant,
build_type=build_type,
install=install,
build_path=build_path,
install_path=install_path)
for var, value in vars.iteritems():
executor.env[var] = value | [
"def",
"set_standard_vars",
"(",
"cls",
",",
"executor",
",",
"context",
",",
"variant",
",",
"build_type",
",",
"install",
",",
"build_path",
",",
"install_path",
"=",
"None",
")",
":",
"vars",
"=",
"cls",
".",
"get_standard_vars",
"(",
"context",
"=",
"c... | Sets a standard set of environment variables for the build system to
use | [
"Sets",
"a",
"standard",
"set",
"of",
"environment",
"variables",
"for",
"the",
"build",
"system",
"to",
"use"
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/build_system.py#L246-L259 | train | 227,481 |
nerdvegas/rez | src/rez/pip.py | run_pip_command | def run_pip_command(command_args, pip_version=None, python_version=None):
"""Run a pip command.
Args:
command_args (list of str): Args to pip.
Returns:
`subprocess.Popen`: Pip process.
"""
pip_exe, context = find_pip(pip_version, python_version)
command = [pip_exe] + list(command_args)
if context is None:
return popen(command)
else:
return context.execute_shell(command=command, block=False) | python | def run_pip_command(command_args, pip_version=None, python_version=None):
"""Run a pip command.
Args:
command_args (list of str): Args to pip.
Returns:
`subprocess.Popen`: Pip process.
"""
pip_exe, context = find_pip(pip_version, python_version)
command = [pip_exe] + list(command_args)
if context is None:
return popen(command)
else:
return context.execute_shell(command=command, block=False) | [
"def",
"run_pip_command",
"(",
"command_args",
",",
"pip_version",
"=",
"None",
",",
"python_version",
"=",
"None",
")",
":",
"pip_exe",
",",
"context",
"=",
"find_pip",
"(",
"pip_version",
",",
"python_version",
")",
"command",
"=",
"[",
"pip_exe",
"]",
"+"... | Run a pip command.
Args:
command_args (list of str): Args to pip.
Returns:
`subprocess.Popen`: Pip process. | [
"Run",
"a",
"pip",
"command",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/pip.py#L88-L103 | train | 227,482 |
nerdvegas/rez | src/rez/pip.py | find_pip | def find_pip(pip_version=None, python_version=None):
"""Find a pip exe using the given python version.
Returns:
2-tuple:
str: pip executable;
`ResolvedContext`: Context containing pip, or None if we fell back
to system pip.
"""
pip_exe = "pip"
try:
context = create_context(pip_version, python_version)
except BuildError as e:
# fall back on system pip. Not ideal but at least it's something
from rez.backport.shutilwhich import which
pip_exe = which("pip")
if pip_exe:
print_warning(
"pip rez package could not be found; system 'pip' command (%s) "
"will be used instead." % pip_exe)
context = None
else:
raise e
return pip_exe, context | python | def find_pip(pip_version=None, python_version=None):
"""Find a pip exe using the given python version.
Returns:
2-tuple:
str: pip executable;
`ResolvedContext`: Context containing pip, or None if we fell back
to system pip.
"""
pip_exe = "pip"
try:
context = create_context(pip_version, python_version)
except BuildError as e:
# fall back on system pip. Not ideal but at least it's something
from rez.backport.shutilwhich import which
pip_exe = which("pip")
if pip_exe:
print_warning(
"pip rez package could not be found; system 'pip' command (%s) "
"will be used instead." % pip_exe)
context = None
else:
raise e
return pip_exe, context | [
"def",
"find_pip",
"(",
"pip_version",
"=",
"None",
",",
"python_version",
"=",
"None",
")",
":",
"pip_exe",
"=",
"\"pip\"",
"try",
":",
"context",
"=",
"create_context",
"(",
"pip_version",
",",
"python_version",
")",
"except",
"BuildError",
"as",
"e",
":",... | Find a pip exe using the given python version.
Returns:
2-tuple:
str: pip executable;
`ResolvedContext`: Context containing pip, or None if we fell back
to system pip. | [
"Find",
"a",
"pip",
"exe",
"using",
"the",
"given",
"python",
"version",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/pip.py#L106-L133 | train | 227,483 |
nerdvegas/rez | src/rez/pip.py | create_context | def create_context(pip_version=None, python_version=None):
"""Create a context containing the specific pip and python.
Args:
pip_version (str or `Version`): Version of pip to use, or latest if None.
python_version (str or `Version`): Python version to use, or latest if
None.
Returns:
`ResolvedContext`: Context containing pip and python.
"""
# determine pip pkg to use for install, and python variants to install on
if pip_version:
pip_req = "pip-%s" % str(pip_version)
else:
pip_req = "pip"
if python_version:
ver = Version(str(python_version))
major_minor_ver = ver.trim(2)
py_req = "python-%s" % str(major_minor_ver)
else:
# use latest major.minor
package = get_latest_package("python")
if package:
major_minor_ver = package.version.trim(2)
else:
# no python package. We're gonna fail, let's just choose current
# python version (and fail at context creation time)
major_minor_ver = '.'.join(map(str, sys.version_info[:2]))
py_req = "python-%s" % str(major_minor_ver)
# use pip + latest python to perform pip download operations
request = [pip_req, py_req]
with convert_errors(from_=(PackageFamilyNotFoundError, PackageNotFoundError),
to=BuildError, msg="Cannot run - pip or python rez "
"package is not present"):
context = ResolvedContext(request)
# print pip package used to perform the install
pip_variant = context.get_resolved_package("pip")
pip_package = pip_variant.parent
print_info("Using %s (%s)" % (pip_package.qualified_name, pip_variant.uri))
return context | python | def create_context(pip_version=None, python_version=None):
"""Create a context containing the specific pip and python.
Args:
pip_version (str or `Version`): Version of pip to use, or latest if None.
python_version (str or `Version`): Python version to use, or latest if
None.
Returns:
`ResolvedContext`: Context containing pip and python.
"""
# determine pip pkg to use for install, and python variants to install on
if pip_version:
pip_req = "pip-%s" % str(pip_version)
else:
pip_req = "pip"
if python_version:
ver = Version(str(python_version))
major_minor_ver = ver.trim(2)
py_req = "python-%s" % str(major_minor_ver)
else:
# use latest major.minor
package = get_latest_package("python")
if package:
major_minor_ver = package.version.trim(2)
else:
# no python package. We're gonna fail, let's just choose current
# python version (and fail at context creation time)
major_minor_ver = '.'.join(map(str, sys.version_info[:2]))
py_req = "python-%s" % str(major_minor_ver)
# use pip + latest python to perform pip download operations
request = [pip_req, py_req]
with convert_errors(from_=(PackageFamilyNotFoundError, PackageNotFoundError),
to=BuildError, msg="Cannot run - pip or python rez "
"package is not present"):
context = ResolvedContext(request)
# print pip package used to perform the install
pip_variant = context.get_resolved_package("pip")
pip_package = pip_variant.parent
print_info("Using %s (%s)" % (pip_package.qualified_name, pip_variant.uri))
return context | [
"def",
"create_context",
"(",
"pip_version",
"=",
"None",
",",
"python_version",
"=",
"None",
")",
":",
"# determine pip pkg to use for install, and python variants to install on",
"if",
"pip_version",
":",
"pip_req",
"=",
"\"pip-%s\"",
"%",
"str",
"(",
"pip_version",
"... | Create a context containing the specific pip and python.
Args:
pip_version (str or `Version`): Version of pip to use, or latest if None.
python_version (str or `Version`): Python version to use, or latest if
None.
Returns:
`ResolvedContext`: Context containing pip and python. | [
"Create",
"a",
"context",
"containing",
"the",
"specific",
"pip",
"and",
"python",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/pip.py#L136-L182 | train | 227,484 |
nerdvegas/rez | src/rez/utils/backcompat.py | convert_old_variant_handle | def convert_old_variant_handle(handle_dict):
"""Convert a variant handle from serialize_version < 4.0."""
old_variables = handle_dict.get("variables", {})
variables = dict(repository_type="filesystem")
for old_key, key in variant_key_conversions.iteritems():
value = old_variables.get(old_key)
#if value is not None:
variables[key] = value
path = handle_dict["path"]
filename = os.path.basename(path)
if os.path.splitext(filename)[0] == "package":
key = "filesystem.variant"
else:
key = "filesystem.variant.combined"
return dict(key=key, variables=variables) | python | def convert_old_variant_handle(handle_dict):
"""Convert a variant handle from serialize_version < 4.0."""
old_variables = handle_dict.get("variables", {})
variables = dict(repository_type="filesystem")
for old_key, key in variant_key_conversions.iteritems():
value = old_variables.get(old_key)
#if value is not None:
variables[key] = value
path = handle_dict["path"]
filename = os.path.basename(path)
if os.path.splitext(filename)[0] == "package":
key = "filesystem.variant"
else:
key = "filesystem.variant.combined"
return dict(key=key, variables=variables) | [
"def",
"convert_old_variant_handle",
"(",
"handle_dict",
")",
":",
"old_variables",
"=",
"handle_dict",
".",
"get",
"(",
"\"variables\"",
",",
"{",
"}",
")",
"variables",
"=",
"dict",
"(",
"repository_type",
"=",
"\"filesystem\"",
")",
"for",
"old_key",
",",
"... | Convert a variant handle from serialize_version < 4.0. | [
"Convert",
"a",
"variant",
"handle",
"from",
"serialize_version",
"<",
"4",
".",
"0",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/backcompat.py#L20-L37 | train | 227,485 |
nerdvegas/rez | src/rez/utils/py_dist.py | convert_requirement | def convert_requirement(req):
"""
Converts a pkg_resources.Requirement object into a list of Rez package
request strings.
"""
pkg_name = convert_name(req.project_name)
if not req.specs:
return [pkg_name]
req_strs = []
for spec in req.specs:
op, ver = spec
ver = convert_version(ver)
if op == "<":
r = "%s-0+<%s" % (pkg_name, ver)
req_strs.append(r)
elif op == "<=":
r = "%s-0+<%s|%s" % (pkg_name, ver, ver)
req_strs.append(r)
elif op == "==":
r = "%s-%s" % (pkg_name, ver)
req_strs.append(r)
elif op == ">=":
r = "%s-%s+" % (pkg_name, ver)
req_strs.append(r)
elif op == ">":
r1 = "%s-%s+" % (pkg_name, ver)
r2 = "!%s-%s" % (pkg_name, ver)
req_strs.append(r1)
req_strs.append(r2)
elif op == "!=":
r = "!%s-%s" % (pkg_name, ver)
req_strs.append(r)
else:
print >> sys.stderr, \
"Warning: Can't understand op '%s', just depending on unversioned package..." % op
req_strs.append(pkg_name)
return req_strs | python | def convert_requirement(req):
"""
Converts a pkg_resources.Requirement object into a list of Rez package
request strings.
"""
pkg_name = convert_name(req.project_name)
if not req.specs:
return [pkg_name]
req_strs = []
for spec in req.specs:
op, ver = spec
ver = convert_version(ver)
if op == "<":
r = "%s-0+<%s" % (pkg_name, ver)
req_strs.append(r)
elif op == "<=":
r = "%s-0+<%s|%s" % (pkg_name, ver, ver)
req_strs.append(r)
elif op == "==":
r = "%s-%s" % (pkg_name, ver)
req_strs.append(r)
elif op == ">=":
r = "%s-%s+" % (pkg_name, ver)
req_strs.append(r)
elif op == ">":
r1 = "%s-%s+" % (pkg_name, ver)
r2 = "!%s-%s" % (pkg_name, ver)
req_strs.append(r1)
req_strs.append(r2)
elif op == "!=":
r = "!%s-%s" % (pkg_name, ver)
req_strs.append(r)
else:
print >> sys.stderr, \
"Warning: Can't understand op '%s', just depending on unversioned package..." % op
req_strs.append(pkg_name)
return req_strs | [
"def",
"convert_requirement",
"(",
"req",
")",
":",
"pkg_name",
"=",
"convert_name",
"(",
"req",
".",
"project_name",
")",
"if",
"not",
"req",
".",
"specs",
":",
"return",
"[",
"pkg_name",
"]",
"req_strs",
"=",
"[",
"]",
"for",
"spec",
"in",
"req",
"."... | Converts a pkg_resources.Requirement object into a list of Rez package
request strings. | [
"Converts",
"a",
"pkg_resources",
".",
"Requirement",
"object",
"into",
"a",
"list",
"of",
"Rez",
"package",
"request",
"strings",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/py_dist.py#L42-L80 | train | 227,486 |
nerdvegas/rez | src/rez/utils/py_dist.py | get_dist_dependencies | def get_dist_dependencies(name, recurse=True):
"""
Get the dependencies of the given, already installed distribution.
@param recurse If True, recursively find all dependencies.
@returns A set of package names.
@note The first entry in the list is always the top-level package itself.
"""
dist = pkg_resources.get_distribution(name)
pkg_name = convert_name(dist.project_name)
reqs = set()
working = set([dist])
depth = 0
while working:
deps = set()
for distname in working:
dist = pkg_resources.get_distribution(distname)
pkg_name = convert_name(dist.project_name)
reqs.add(pkg_name)
for req in dist.requires():
reqs_ = convert_requirement(req)
deps |= set(x.split('-', 1)[0] for x in reqs_
if not x.startswith('!'))
working = deps - reqs
depth += 1
if (not recurse) and (depth >= 2):
break
return reqs | python | def get_dist_dependencies(name, recurse=True):
"""
Get the dependencies of the given, already installed distribution.
@param recurse If True, recursively find all dependencies.
@returns A set of package names.
@note The first entry in the list is always the top-level package itself.
"""
dist = pkg_resources.get_distribution(name)
pkg_name = convert_name(dist.project_name)
reqs = set()
working = set([dist])
depth = 0
while working:
deps = set()
for distname in working:
dist = pkg_resources.get_distribution(distname)
pkg_name = convert_name(dist.project_name)
reqs.add(pkg_name)
for req in dist.requires():
reqs_ = convert_requirement(req)
deps |= set(x.split('-', 1)[0] for x in reqs_
if not x.startswith('!'))
working = deps - reqs
depth += 1
if (not recurse) and (depth >= 2):
break
return reqs | [
"def",
"get_dist_dependencies",
"(",
"name",
",",
"recurse",
"=",
"True",
")",
":",
"dist",
"=",
"pkg_resources",
".",
"get_distribution",
"(",
"name",
")",
"pkg_name",
"=",
"convert_name",
"(",
"dist",
".",
"project_name",
")",
"reqs",
"=",
"set",
"(",
")... | Get the dependencies of the given, already installed distribution.
@param recurse If True, recursively find all dependencies.
@returns A set of package names.
@note The first entry in the list is always the top-level package itself. | [
"Get",
"the",
"dependencies",
"of",
"the",
"given",
"already",
"installed",
"distribution",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/utils/py_dist.py#L83-L114 | train | 227,487 |
nerdvegas/rez | src/rez/vendor/pygraph/mixins/common.py | common.add_graph | def add_graph(self, other):
"""
Add other graph to this graph.
@attention: Attributes and labels are not preserved.
@type other: graph
@param other: Graph
"""
self.add_nodes( n for n in other.nodes() if not n in self.nodes() )
for each_node in other.nodes():
for each_edge in other.neighbors(each_node):
if (not self.has_edge((each_node, each_edge))):
self.add_edge((each_node, each_edge)) | python | def add_graph(self, other):
"""
Add other graph to this graph.
@attention: Attributes and labels are not preserved.
@type other: graph
@param other: Graph
"""
self.add_nodes( n for n in other.nodes() if not n in self.nodes() )
for each_node in other.nodes():
for each_edge in other.neighbors(each_node):
if (not self.has_edge((each_node, each_edge))):
self.add_edge((each_node, each_edge)) | [
"def",
"add_graph",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"add_nodes",
"(",
"n",
"for",
"n",
"in",
"other",
".",
"nodes",
"(",
")",
"if",
"not",
"n",
"in",
"self",
".",
"nodes",
"(",
")",
")",
"for",
"each_node",
"in",
"other",
".",
... | Add other graph to this graph.
@attention: Attributes and labels are not preserved.
@type other: graph
@param other: Graph | [
"Add",
"other",
"graph",
"to",
"this",
"graph",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/common.py#L107-L121 | train | 227,488 |
nerdvegas/rez | src/rez/vendor/pygraph/mixins/common.py | common.add_spanning_tree | def add_spanning_tree(self, st):
"""
Add a spanning tree to the graph.
@type st: dictionary
@param st: Spanning tree.
"""
self.add_nodes(list(st.keys()))
for each in st:
if (st[each] is not None):
self.add_edge((st[each], each)) | python | def add_spanning_tree(self, st):
"""
Add a spanning tree to the graph.
@type st: dictionary
@param st: Spanning tree.
"""
self.add_nodes(list(st.keys()))
for each in st:
if (st[each] is not None):
self.add_edge((st[each], each)) | [
"def",
"add_spanning_tree",
"(",
"self",
",",
"st",
")",
":",
"self",
".",
"add_nodes",
"(",
"list",
"(",
"st",
".",
"keys",
"(",
")",
")",
")",
"for",
"each",
"in",
"st",
":",
"if",
"(",
"st",
"[",
"each",
"]",
"is",
"not",
"None",
")",
":",
... | Add a spanning tree to the graph.
@type st: dictionary
@param st: Spanning tree. | [
"Add",
"a",
"spanning",
"tree",
"to",
"the",
"graph",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/common.py#L124-L134 | train | 227,489 |
nerdvegas/rez | src/rez/vendor/pygraph/mixins/common.py | common.complete | def complete(self):
"""
Make the graph a complete graph.
@attention: This will modify the current graph.
"""
for each in self.nodes():
for other in self.nodes():
if (each != other and not self.has_edge((each, other))):
self.add_edge((each, other)) | python | def complete(self):
"""
Make the graph a complete graph.
@attention: This will modify the current graph.
"""
for each in self.nodes():
for other in self.nodes():
if (each != other and not self.has_edge((each, other))):
self.add_edge((each, other)) | [
"def",
"complete",
"(",
"self",
")",
":",
"for",
"each",
"in",
"self",
".",
"nodes",
"(",
")",
":",
"for",
"other",
"in",
"self",
".",
"nodes",
"(",
")",
":",
"if",
"(",
"each",
"!=",
"other",
"and",
"not",
"self",
".",
"has_edge",
"(",
"(",
"e... | Make the graph a complete graph.
@attention: This will modify the current graph. | [
"Make",
"the",
"graph",
"a",
"complete",
"graph",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/common.py#L137-L146 | train | 227,490 |
nerdvegas/rez | src/rez/vendor/pygraph/mixins/common.py | common.inverse | def inverse(self):
"""
Return the inverse of the graph.
@rtype: graph
@return: Complement graph for the graph.
"""
inv = self.__class__()
inv.add_nodes(self.nodes())
inv.complete()
for each in self.edges():
if (inv.has_edge(each)):
inv.del_edge(each)
return inv | python | def inverse(self):
"""
Return the inverse of the graph.
@rtype: graph
@return: Complement graph for the graph.
"""
inv = self.__class__()
inv.add_nodes(self.nodes())
inv.complete()
for each in self.edges():
if (inv.has_edge(each)):
inv.del_edge(each)
return inv | [
"def",
"inverse",
"(",
"self",
")",
":",
"inv",
"=",
"self",
".",
"__class__",
"(",
")",
"inv",
".",
"add_nodes",
"(",
"self",
".",
"nodes",
"(",
")",
")",
"inv",
".",
"complete",
"(",
")",
"for",
"each",
"in",
"self",
".",
"edges",
"(",
")",
"... | Return the inverse of the graph.
@rtype: graph
@return: Complement graph for the graph. | [
"Return",
"the",
"inverse",
"of",
"the",
"graph",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/common.py#L149-L162 | train | 227,491 |
nerdvegas/rez | src/rez/vendor/pygraph/mixins/common.py | common.reverse | def reverse(self):
"""
Generate the reverse of a directed graph, returns an identical graph if not directed.
Attributes & weights are preserved.
@rtype: digraph
@return: The directed graph that should be reversed.
"""
assert self.DIRECTED, "Undirected graph types such as %s cannot be reversed" % self.__class__.__name__
N = self.__class__()
#- Add the nodes
N.add_nodes( n for n in self.nodes() )
#- Add the reversed edges
for (u, v) in self.edges():
wt = self.edge_weight((u, v))
label = self.edge_label((u, v))
attributes = self.edge_attributes((u, v))
N.add_edge((v, u), wt, label, attributes)
return N | python | def reverse(self):
"""
Generate the reverse of a directed graph, returns an identical graph if not directed.
Attributes & weights are preserved.
@rtype: digraph
@return: The directed graph that should be reversed.
"""
assert self.DIRECTED, "Undirected graph types such as %s cannot be reversed" % self.__class__.__name__
N = self.__class__()
#- Add the nodes
N.add_nodes( n for n in self.nodes() )
#- Add the reversed edges
for (u, v) in self.edges():
wt = self.edge_weight((u, v))
label = self.edge_label((u, v))
attributes = self.edge_attributes((u, v))
N.add_edge((v, u), wt, label, attributes)
return N | [
"def",
"reverse",
"(",
"self",
")",
":",
"assert",
"self",
".",
"DIRECTED",
",",
"\"Undirected graph types such as %s cannot be reversed\"",
"%",
"self",
".",
"__class__",
".",
"__name__",
"N",
"=",
"self",
".",
"__class__",
"(",
")",
"#- Add the nodes",
"N",
".... | Generate the reverse of a directed graph, returns an identical graph if not directed.
Attributes & weights are preserved.
@rtype: digraph
@return: The directed graph that should be reversed. | [
"Generate",
"the",
"reverse",
"of",
"a",
"directed",
"graph",
"returns",
"an",
"identical",
"graph",
"if",
"not",
"directed",
".",
"Attributes",
"&",
"weights",
"are",
"preserved",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/vendor/pygraph/mixins/common.py#L164-L185 | train | 227,492 |
nerdvegas/rez | src/rez/resolved_context.py | get_lock_request | def get_lock_request(name, version, patch_lock, weak=True):
"""Given a package and patch lock, return the equivalent request.
For example, for object 'foo-1.2.1' and lock type 'lock_3', the equivalent
request is '~foo-1.2'. This restricts updates to foo to patch-or-lower
version changes only.
For objects not versioned down to a given lock level, the closest possible
lock is applied. So 'lock_3' applied to 'foo-1' would give '~foo-1'.
Args:
name (str): Package name.
version (Version): Package version.
patch_lock (PatchLock): Lock type to apply.
Returns:
`PackageRequest` object, or None if there is no equivalent request.
"""
ch = '~' if weak else ''
if patch_lock == PatchLock.lock:
s = "%s%s==%s" % (ch, name, str(version))
return PackageRequest(s)
elif (patch_lock == PatchLock.no_lock) or (not version):
return None
version_ = version.trim(patch_lock.rank)
s = "%s%s-%s" % (ch, name, str(version_))
return PackageRequest(s) | python | def get_lock_request(name, version, patch_lock, weak=True):
"""Given a package and patch lock, return the equivalent request.
For example, for object 'foo-1.2.1' and lock type 'lock_3', the equivalent
request is '~foo-1.2'. This restricts updates to foo to patch-or-lower
version changes only.
For objects not versioned down to a given lock level, the closest possible
lock is applied. So 'lock_3' applied to 'foo-1' would give '~foo-1'.
Args:
name (str): Package name.
version (Version): Package version.
patch_lock (PatchLock): Lock type to apply.
Returns:
`PackageRequest` object, or None if there is no equivalent request.
"""
ch = '~' if weak else ''
if patch_lock == PatchLock.lock:
s = "%s%s==%s" % (ch, name, str(version))
return PackageRequest(s)
elif (patch_lock == PatchLock.no_lock) or (not version):
return None
version_ = version.trim(patch_lock.rank)
s = "%s%s-%s" % (ch, name, str(version_))
return PackageRequest(s) | [
"def",
"get_lock_request",
"(",
"name",
",",
"version",
",",
"patch_lock",
",",
"weak",
"=",
"True",
")",
":",
"ch",
"=",
"'~'",
"if",
"weak",
"else",
"''",
"if",
"patch_lock",
"==",
"PatchLock",
".",
"lock",
":",
"s",
"=",
"\"%s%s==%s\"",
"%",
"(",
... | Given a package and patch lock, return the equivalent request.
For example, for object 'foo-1.2.1' and lock type 'lock_3', the equivalent
request is '~foo-1.2'. This restricts updates to foo to patch-or-lower
version changes only.
For objects not versioned down to a given lock level, the closest possible
lock is applied. So 'lock_3' applied to 'foo-1' would give '~foo-1'.
Args:
name (str): Package name.
version (Version): Package version.
patch_lock (PatchLock): Lock type to apply.
Returns:
`PackageRequest` object, or None if there is no equivalent request. | [
"Given",
"a",
"package",
"and",
"patch",
"lock",
"return",
"the",
"equivalent",
"request",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L76-L102 | train | 227,493 |
nerdvegas/rez | src/rez/resolved_context.py | ResolvedContext.requested_packages | def requested_packages(self, include_implicit=False):
"""Get packages in the request.
Args:
include_implicit (bool): If True, implicit packages are appended
to the result.
Returns:
List of `PackageRequest` objects.
"""
if include_implicit:
return self._package_requests + self.implicit_packages
else:
return self._package_requests | python | def requested_packages(self, include_implicit=False):
"""Get packages in the request.
Args:
include_implicit (bool): If True, implicit packages are appended
to the result.
Returns:
List of `PackageRequest` objects.
"""
if include_implicit:
return self._package_requests + self.implicit_packages
else:
return self._package_requests | [
"def",
"requested_packages",
"(",
"self",
",",
"include_implicit",
"=",
"False",
")",
":",
"if",
"include_implicit",
":",
"return",
"self",
".",
"_package_requests",
"+",
"self",
".",
"implicit_packages",
"else",
":",
"return",
"self",
".",
"_package_requests"
] | Get packages in the request.
Args:
include_implicit (bool): If True, implicit packages are appended
to the result.
Returns:
List of `PackageRequest` objects. | [
"Get",
"packages",
"in",
"the",
"request",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L322-L335 | train | 227,494 |
nerdvegas/rez | src/rez/resolved_context.py | ResolvedContext.get_resolved_package | def get_resolved_package(self, name):
"""Returns a `Variant` object or None if the package is not in the
resolve.
"""
pkgs = [x for x in self._resolved_packages if x.name == name]
return pkgs[0] if pkgs else None | python | def get_resolved_package(self, name):
"""Returns a `Variant` object or None if the package is not in the
resolve.
"""
pkgs = [x for x in self._resolved_packages if x.name == name]
return pkgs[0] if pkgs else None | [
"def",
"get_resolved_package",
"(",
"self",
",",
"name",
")",
":",
"pkgs",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"_resolved_packages",
"if",
"x",
".",
"name",
"==",
"name",
"]",
"return",
"pkgs",
"[",
"0",
"]",
"if",
"pkgs",
"else",
"None"
] | Returns a `Variant` object or None if the package is not in the
resolve. | [
"Returns",
"a",
"Variant",
"object",
"or",
"None",
"if",
"the",
"package",
"is",
"not",
"in",
"the",
"resolve",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L384-L389 | train | 227,495 |
nerdvegas/rez | src/rez/resolved_context.py | ResolvedContext.get_patched_request | def get_patched_request(self, package_requests=None,
package_subtractions=None, strict=False, rank=0):
"""Get a 'patched' request.
A patched request is a copy of this context's request, but with some
changes applied. This can then be used to create a new, 'patched'
context.
New package requests override original requests based on the type -
normal, conflict or weak. So 'foo-2' overrides 'foo-1', '!foo-2'
overrides '!foo-1' and '~foo-2' overrides '~foo-1', but a request such
as '!foo-2' would not replace 'foo-1' - it would be added instead.
Note that requests in `package_requests` can have the form '^foo'. This
is another way of supplying package subtractions.
Any new requests that don't override original requests are appended,
in the order that they appear in `package_requests`.
Args:
package_requests (list of str or list of `PackageRequest`):
Overriding requests.
package_subtractions (list of str): Any original request with a
package name in this list is removed, before the new requests
are added.
strict (bool): If True, the current context's resolve is used as the
original request list, rather than the request.
rank (int): If > 1, package versions can only increase in this rank
and further - for example, rank=3 means that only version patch
numbers are allowed to increase, major and minor versions will
not change. This is only applied to packages that have not been
explicitly overridden in `package_requests`. If rank <= 1, or
`strict` is True, rank is ignored.
Returns:
List of `PackageRequest` objects that can be used to construct a
new `ResolvedContext` object.
"""
# assemble source request
if strict:
request = []
for variant in self.resolved_packages:
req = PackageRequest(variant.qualified_package_name)
request.append(req)
else:
request = self.requested_packages()[:]
# convert '^foo'-style requests to subtractions
if package_requests:
package_subtractions = package_subtractions or []
indexes = []
for i, req in enumerate(package_requests):
name = str(req)
if name.startswith('^'):
package_subtractions.append(name[1:])
indexes.append(i)
for i in reversed(indexes):
del package_requests[i]
# apply subtractions
if package_subtractions:
request = [x for x in request if x.name not in package_subtractions]
# apply overrides
if package_requests:
request_dict = dict((x.name, (i, x)) for i, x in enumerate(request))
request_ = []
for req in package_requests:
if isinstance(req, basestring):
req = PackageRequest(req)
if req.name in request_dict:
i, req_ = request_dict[req.name]
if (req_ is not None) and (req_.conflict == req.conflict) \
and (req_.weak == req.weak):
request[i] = req
del request_dict[req.name]
else:
request_.append(req)
else:
request_.append(req)
request += request_
# add rank limiters
if not strict and rank > 1:
overrides = set(x.name for x in package_requests if not x.conflict)
rank_limiters = []
for variant in self.resolved_packages:
if variant.name not in overrides:
if len(variant.version) >= rank:
version = variant.version.trim(rank - 1)
version = version.next()
req = "~%s<%s" % (variant.name, str(version))
rank_limiters.append(req)
request += rank_limiters
return request | python | def get_patched_request(self, package_requests=None,
package_subtractions=None, strict=False, rank=0):
"""Get a 'patched' request.
A patched request is a copy of this context's request, but with some
changes applied. This can then be used to create a new, 'patched'
context.
New package requests override original requests based on the type -
normal, conflict or weak. So 'foo-2' overrides 'foo-1', '!foo-2'
overrides '!foo-1' and '~foo-2' overrides '~foo-1', but a request such
as '!foo-2' would not replace 'foo-1' - it would be added instead.
Note that requests in `package_requests` can have the form '^foo'. This
is another way of supplying package subtractions.
Any new requests that don't override original requests are appended,
in the order that they appear in `package_requests`.
Args:
package_requests (list of str or list of `PackageRequest`):
Overriding requests.
package_subtractions (list of str): Any original request with a
package name in this list is removed, before the new requests
are added.
strict (bool): If True, the current context's resolve is used as the
original request list, rather than the request.
rank (int): If > 1, package versions can only increase in this rank
and further - for example, rank=3 means that only version patch
numbers are allowed to increase, major and minor versions will
not change. This is only applied to packages that have not been
explicitly overridden in `package_requests`. If rank <= 1, or
`strict` is True, rank is ignored.
Returns:
List of `PackageRequest` objects that can be used to construct a
new `ResolvedContext` object.
"""
# assemble source request
if strict:
request = []
for variant in self.resolved_packages:
req = PackageRequest(variant.qualified_package_name)
request.append(req)
else:
request = self.requested_packages()[:]
# convert '^foo'-style requests to subtractions
if package_requests:
package_subtractions = package_subtractions or []
indexes = []
for i, req in enumerate(package_requests):
name = str(req)
if name.startswith('^'):
package_subtractions.append(name[1:])
indexes.append(i)
for i in reversed(indexes):
del package_requests[i]
# apply subtractions
if package_subtractions:
request = [x for x in request if x.name not in package_subtractions]
# apply overrides
if package_requests:
request_dict = dict((x.name, (i, x)) for i, x in enumerate(request))
request_ = []
for req in package_requests:
if isinstance(req, basestring):
req = PackageRequest(req)
if req.name in request_dict:
i, req_ = request_dict[req.name]
if (req_ is not None) and (req_.conflict == req.conflict) \
and (req_.weak == req.weak):
request[i] = req
del request_dict[req.name]
else:
request_.append(req)
else:
request_.append(req)
request += request_
# add rank limiters
if not strict and rank > 1:
overrides = set(x.name for x in package_requests if not x.conflict)
rank_limiters = []
for variant in self.resolved_packages:
if variant.name not in overrides:
if len(variant.version) >= rank:
version = variant.version.trim(rank - 1)
version = version.next()
req = "~%s<%s" % (variant.name, str(version))
rank_limiters.append(req)
request += rank_limiters
return request | [
"def",
"get_patched_request",
"(",
"self",
",",
"package_requests",
"=",
"None",
",",
"package_subtractions",
"=",
"None",
",",
"strict",
"=",
"False",
",",
"rank",
"=",
"0",
")",
":",
"# assemble source request",
"if",
"strict",
":",
"request",
"=",
"[",
"]... | Get a 'patched' request.
A patched request is a copy of this context's request, but with some
changes applied. This can then be used to create a new, 'patched'
context.
New package requests override original requests based on the type -
normal, conflict or weak. So 'foo-2' overrides 'foo-1', '!foo-2'
overrides '!foo-1' and '~foo-2' overrides '~foo-1', but a request such
as '!foo-2' would not replace 'foo-1' - it would be added instead.
Note that requests in `package_requests` can have the form '^foo'. This
is another way of supplying package subtractions.
Any new requests that don't override original requests are appended,
in the order that they appear in `package_requests`.
Args:
package_requests (list of str or list of `PackageRequest`):
Overriding requests.
package_subtractions (list of str): Any original request with a
package name in this list is removed, before the new requests
are added.
strict (bool): If True, the current context's resolve is used as the
original request list, rather than the request.
rank (int): If > 1, package versions can only increase in this rank
and further - for example, rank=3 means that only version patch
numbers are allowed to increase, major and minor versions will
not change. This is only applied to packages that have not been
explicitly overridden in `package_requests`. If rank <= 1, or
`strict` is True, rank is ignored.
Returns:
List of `PackageRequest` objects that can be used to construct a
new `ResolvedContext` object. | [
"Get",
"a",
"patched",
"request",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L397-L495 | train | 227,496 |
nerdvegas/rez | src/rez/resolved_context.py | ResolvedContext.write_to_buffer | def write_to_buffer(self, buf):
"""Save the context to a buffer."""
doc = self.to_dict()
if config.rxt_as_yaml:
content = dump_yaml(doc)
else:
content = json.dumps(doc, indent=4, separators=(",", ": "))
buf.write(content) | python | def write_to_buffer(self, buf):
"""Save the context to a buffer."""
doc = self.to_dict()
if config.rxt_as_yaml:
content = dump_yaml(doc)
else:
content = json.dumps(doc, indent=4, separators=(",", ": "))
buf.write(content) | [
"def",
"write_to_buffer",
"(",
"self",
",",
"buf",
")",
":",
"doc",
"=",
"self",
".",
"to_dict",
"(",
")",
"if",
"config",
".",
"rxt_as_yaml",
":",
"content",
"=",
"dump_yaml",
"(",
"doc",
")",
"else",
":",
"content",
"=",
"json",
".",
"dumps",
"(",
... | Save the context to a buffer. | [
"Save",
"the",
"context",
"to",
"a",
"buffer",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L533-L542 | train | 227,497 |
nerdvegas/rez | src/rez/resolved_context.py | ResolvedContext.get_current | def get_current(cls):
"""Get the context for the current env, if there is one.
Returns:
`ResolvedContext`: Current context, or None if not in a resolved env.
"""
filepath = os.getenv("REZ_RXT_FILE")
if not filepath or not os.path.exists(filepath):
return None
return cls.load(filepath) | python | def get_current(cls):
"""Get the context for the current env, if there is one.
Returns:
`ResolvedContext`: Current context, or None if not in a resolved env.
"""
filepath = os.getenv("REZ_RXT_FILE")
if not filepath or not os.path.exists(filepath):
return None
return cls.load(filepath) | [
"def",
"get_current",
"(",
"cls",
")",
":",
"filepath",
"=",
"os",
".",
"getenv",
"(",
"\"REZ_RXT_FILE\"",
")",
"if",
"not",
"filepath",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filepath",
")",
":",
"return",
"None",
"return",
"cls",
".",
... | Get the context for the current env, if there is one.
Returns:
`ResolvedContext`: Current context, or None if not in a resolved env. | [
"Get",
"the",
"context",
"for",
"the",
"current",
"env",
"if",
"there",
"is",
"one",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L545-L555 | train | 227,498 |
nerdvegas/rez | src/rez/resolved_context.py | ResolvedContext.load | def load(cls, path):
"""Load a resolved context from file."""
with open(path) as f:
context = cls.read_from_buffer(f, path)
context.set_load_path(path)
return context | python | def load(cls, path):
"""Load a resolved context from file."""
with open(path) as f:
context = cls.read_from_buffer(f, path)
context.set_load_path(path)
return context | [
"def",
"load",
"(",
"cls",
",",
"path",
")",
":",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"context",
"=",
"cls",
".",
"read_from_buffer",
"(",
"f",
",",
"path",
")",
"context",
".",
"set_load_path",
"(",
"path",
")",
"return",
"context"
] | Load a resolved context from file. | [
"Load",
"a",
"resolved",
"context",
"from",
"file",
"."
] | 1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7 | https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/resolved_context.py#L558-L563 | train | 227,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.