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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Dot.py | Dot.all_node_style | def all_node_style(self, **kwargs):
'''
Modifies all node styles
'''
for node in self.nodes:
self.node_style(node, **kwargs) | python | def all_node_style(self, **kwargs):
'''
Modifies all node styles
'''
for node in self.nodes:
self.node_style(node, **kwargs) | [
"def",
"all_node_style",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"self",
".",
"node_style",
"(",
"node",
",",
"*",
"*",
"kwargs",
")"
] | Modifies all node styles | [
"Modifies",
"all",
"node",
"styles"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Dot.py#L200-L205 | train | 32,100 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Dot.py | Dot.edge_style | def edge_style(self, head, tail, **kwargs):
'''
Modifies an edge style to the dot representation.
'''
if tail not in self.nodes:
raise GraphError("invalid node %s" % (tail,))
try:
if tail not in self.edges[head]:
self.edges[head][tail]= {}
self.edges[head][tail] = kwargs
except KeyError:
raise GraphError("invalid edge %s -> %s " % (head, tail) ) | python | def edge_style(self, head, tail, **kwargs):
'''
Modifies an edge style to the dot representation.
'''
if tail not in self.nodes:
raise GraphError("invalid node %s" % (tail,))
try:
if tail not in self.edges[head]:
self.edges[head][tail]= {}
self.edges[head][tail] = kwargs
except KeyError:
raise GraphError("invalid edge %s -> %s " % (head, tail) ) | [
"def",
"edge_style",
"(",
"self",
",",
"head",
",",
"tail",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"tail",
"not",
"in",
"self",
".",
"nodes",
":",
"raise",
"GraphError",
"(",
"\"invalid node %s\"",
"%",
"(",
"tail",
",",
")",
")",
"try",
":",
"if... | Modifies an edge style to the dot representation. | [
"Modifies",
"an",
"edge",
"style",
"to",
"the",
"dot",
"representation",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Dot.py#L207-L219 | train | 32,101 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Dot.py | Dot.save_dot | def save_dot(self, file_name=None):
'''
Saves the current graph representation into a file
'''
if not file_name:
warnings.warn(DeprecationWarning, "always pass a file_name")
file_name = self.temp_dot
fp = open(file_name, "w")
try:
for chunk in self.iterdot():
fp.write(chunk)
finally:
fp.close() | python | def save_dot(self, file_name=None):
'''
Saves the current graph representation into a file
'''
if not file_name:
warnings.warn(DeprecationWarning, "always pass a file_name")
file_name = self.temp_dot
fp = open(file_name, "w")
try:
for chunk in self.iterdot():
fp.write(chunk)
finally:
fp.close() | [
"def",
"save_dot",
"(",
"self",
",",
"file_name",
"=",
"None",
")",
":",
"if",
"not",
"file_name",
":",
"warnings",
".",
"warn",
"(",
"DeprecationWarning",
",",
"\"always pass a file_name\"",
")",
"file_name",
"=",
"self",
".",
"temp_dot",
"fp",
"=",
"open",... | Saves the current graph representation into a file | [
"Saves",
"the",
"current",
"graph",
"representation",
"into",
"a",
"file"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Dot.py#L264-L278 | train | 32,102 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Dot.py | Dot.save_img | def save_img(self, file_name=None, file_type="gif", mode='dot'):
'''
Saves the dot file as an image file
'''
if not file_name:
warnings.warn(DeprecationWarning, "always pass a file_name")
file_name = "out"
if mode == 'neato':
self.save_dot(self.temp_neo)
neato_cmd = "%s -o %s %s" % (self.neato, self.temp_dot, self.temp_neo)
os.system(neato_cmd)
plot_cmd = self.dot
else:
self.save_dot(self.temp_dot)
plot_cmd = self.dot
file_name = "%s.%s" % (file_name, file_type)
create_cmd = "%s -T%s %s -o %s" % (plot_cmd, file_type, self.temp_dot, file_name)
os.system(create_cmd) | python | def save_img(self, file_name=None, file_type="gif", mode='dot'):
'''
Saves the dot file as an image file
'''
if not file_name:
warnings.warn(DeprecationWarning, "always pass a file_name")
file_name = "out"
if mode == 'neato':
self.save_dot(self.temp_neo)
neato_cmd = "%s -o %s %s" % (self.neato, self.temp_dot, self.temp_neo)
os.system(neato_cmd)
plot_cmd = self.dot
else:
self.save_dot(self.temp_dot)
plot_cmd = self.dot
file_name = "%s.%s" % (file_name, file_type)
create_cmd = "%s -T%s %s -o %s" % (plot_cmd, file_type, self.temp_dot, file_name)
os.system(create_cmd) | [
"def",
"save_img",
"(",
"self",
",",
"file_name",
"=",
"None",
",",
"file_type",
"=",
"\"gif\"",
",",
"mode",
"=",
"'dot'",
")",
":",
"if",
"not",
"file_name",
":",
"warnings",
".",
"warn",
"(",
"DeprecationWarning",
",",
"\"always pass a file_name\"",
")",
... | Saves the dot file as an image file | [
"Saves",
"the",
"dot",
"file",
"as",
"an",
"image",
"file"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Dot.py#L280-L300 | train | 32,103 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/hg.py | get_repo_revision | def get_repo_revision():
'''
Returns mercurial revision string somelike `hg identify` does.
Format is rev1:short-id1+;rev2:short-id2+
Returns an empty string if anything goes wrong, such as missing
.hg files or an unexpected format of internal HG files or no
mercurial repository found.
'''
repopath = _findrepo()
if not repopath:
return ''
# first try to use mercurial itself
try:
import mercurial.hg, mercurial.ui, mercurial.scmutil
from mercurial.node import short as hexfunc
except ImportError:
pass
else:
ui = mercurial.ui.ui()
repo = mercurial.hg.repository(ui, repopath)
parents = repo[None].parents()
changed = filter(None, repo.status()) and "+" or ""
return ';'.join(['%s:%s%s' % (p.rev(), hexfunc(p.node()), changed)
for p in parents])
# todo: mercurial not found, try to retrieve the information
# ourselves
return '' | python | def get_repo_revision():
'''
Returns mercurial revision string somelike `hg identify` does.
Format is rev1:short-id1+;rev2:short-id2+
Returns an empty string if anything goes wrong, such as missing
.hg files or an unexpected format of internal HG files or no
mercurial repository found.
'''
repopath = _findrepo()
if not repopath:
return ''
# first try to use mercurial itself
try:
import mercurial.hg, mercurial.ui, mercurial.scmutil
from mercurial.node import short as hexfunc
except ImportError:
pass
else:
ui = mercurial.ui.ui()
repo = mercurial.hg.repository(ui, repopath)
parents = repo[None].parents()
changed = filter(None, repo.status()) and "+" or ""
return ';'.join(['%s:%s%s' % (p.rev(), hexfunc(p.node()), changed)
for p in parents])
# todo: mercurial not found, try to retrieve the information
# ourselves
return '' | [
"def",
"get_repo_revision",
"(",
")",
":",
"repopath",
"=",
"_findrepo",
"(",
")",
"if",
"not",
"repopath",
":",
"return",
"''",
"# first try to use mercurial itself",
"try",
":",
"import",
"mercurial",
".",
"hg",
",",
"mercurial",
".",
"ui",
",",
"mercurial",... | Returns mercurial revision string somelike `hg identify` does.
Format is rev1:short-id1+;rev2:short-id2+
Returns an empty string if anything goes wrong, such as missing
.hg files or an unexpected format of internal HG files or no
mercurial repository found. | [
"Returns",
"mercurial",
"revision",
"string",
"somelike",
"hg",
"identify",
"does",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/hg.py#L35-L64 | train | 32,104 |
bwhite/hadoopy | examples/l4-vision-and-image-processing-with-hadoop/ex1-haystack/haystack.py | Reducer.reduce | def reduce(self, key, values):
"""Select the image with the minimum distance
Args:
key: (see mapper)
values: (see mapper)
Yields:
A tuple in the form of (key, value)
key: Image name
value: Image as jpeg byte data
"""
dist, key, value = min(values, key=lambda x: x[0])
print('MinDist[%f]' % dist)
yield key, value | python | def reduce(self, key, values):
"""Select the image with the minimum distance
Args:
key: (see mapper)
values: (see mapper)
Yields:
A tuple in the form of (key, value)
key: Image name
value: Image as jpeg byte data
"""
dist, key, value = min(values, key=lambda x: x[0])
print('MinDist[%f]' % dist)
yield key, value | [
"def",
"reduce",
"(",
"self",
",",
"key",
",",
"values",
")",
":",
"dist",
",",
"key",
",",
"value",
"=",
"min",
"(",
"values",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
"print",
"(",
"'MinDist[%f]'",
"%",
"dist",
")",
"yiel... | Select the image with the minimum distance
Args:
key: (see mapper)
values: (see mapper)
Yields:
A tuple in the form of (key, value)
key: Image name
value: Image as jpeg byte data | [
"Select",
"the",
"image",
"with",
"the",
"minimum",
"distance"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/examples/l4-vision-and-image-processing-with-hadoop/ex1-haystack/haystack.py#L64-L79 | train | 32,105 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/loader/archive.py | Archive.checkmagic | def checkmagic(self):
"""
Overridable.
Check to see if the file object self.lib actually has a file
we understand.
"""
self.lib.seek(self.start) # default - magic is at start of file
if self.lib.read(len(self.MAGIC)) != self.MAGIC:
raise ArchiveReadError("%s is not a valid %s archive file"
% (self.path, self.__class__.__name__))
if self.lib.read(len(self.pymagic)) != self.pymagic:
raise ArchiveReadError("%s has version mismatch to dll" %
(self.path))
self.lib.read(4) | python | def checkmagic(self):
"""
Overridable.
Check to see if the file object self.lib actually has a file
we understand.
"""
self.lib.seek(self.start) # default - magic is at start of file
if self.lib.read(len(self.MAGIC)) != self.MAGIC:
raise ArchiveReadError("%s is not a valid %s archive file"
% (self.path, self.__class__.__name__))
if self.lib.read(len(self.pymagic)) != self.pymagic:
raise ArchiveReadError("%s has version mismatch to dll" %
(self.path))
self.lib.read(4) | [
"def",
"checkmagic",
"(",
"self",
")",
":",
"self",
".",
"lib",
".",
"seek",
"(",
"self",
".",
"start",
")",
"# default - magic is at start of file",
"if",
"self",
".",
"lib",
".",
"read",
"(",
"len",
"(",
"self",
".",
"MAGIC",
")",
")",
"!=",
"self",
... | Overridable.
Check to see if the file object self.lib actually has a file
we understand. | [
"Overridable",
".",
"Check",
"to",
"see",
"if",
"the",
"file",
"object",
"self",
".",
"lib",
"actually",
"has",
"a",
"file",
"we",
"understand",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/loader/archive.py#L105-L121 | train | 32,106 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/loader/archive.py | Archive.update_headers | def update_headers(self, tocpos):
"""
Default - MAGIC + Python's magic + tocpos
"""
self.lib.seek(self.start)
self.lib.write(self.MAGIC)
self.lib.write(self.pymagic)
self.lib.write(struct.pack('!i', tocpos)) | python | def update_headers(self, tocpos):
"""
Default - MAGIC + Python's magic + tocpos
"""
self.lib.seek(self.start)
self.lib.write(self.MAGIC)
self.lib.write(self.pymagic)
self.lib.write(struct.pack('!i', tocpos)) | [
"def",
"update_headers",
"(",
"self",
",",
"tocpos",
")",
":",
"self",
".",
"lib",
".",
"seek",
"(",
"self",
".",
"start",
")",
"self",
".",
"lib",
".",
"write",
"(",
"self",
".",
"MAGIC",
")",
"self",
".",
"lib",
".",
"write",
"(",
"self",
".",
... | Default - MAGIC + Python's magic + tocpos | [
"Default",
"-",
"MAGIC",
"+",
"Python",
"s",
"magic",
"+",
"tocpos"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/loader/archive.py#L243-L250 | train | 32,107 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/util.py | flipwritable | def flipwritable(fn, mode=None):
"""
Flip the writability of a file and return the old mode. Returns None
if the file is already writable.
"""
if os.access(fn, os.W_OK):
return None
old_mode = os.stat(fn).st_mode
os.chmod(fn, stat.S_IWRITE | old_mode)
return old_mode | python | def flipwritable(fn, mode=None):
"""
Flip the writability of a file and return the old mode. Returns None
if the file is already writable.
"""
if os.access(fn, os.W_OK):
return None
old_mode = os.stat(fn).st_mode
os.chmod(fn, stat.S_IWRITE | old_mode)
return old_mode | [
"def",
"flipwritable",
"(",
"fn",
",",
"mode",
"=",
"None",
")",
":",
"if",
"os",
".",
"access",
"(",
"fn",
",",
"os",
".",
"W_OK",
")",
":",
"return",
"None",
"old_mode",
"=",
"os",
".",
"stat",
"(",
"fn",
")",
".",
"st_mode",
"os",
".",
"chmo... | Flip the writability of a file and return the old mode. Returns None
if the file is already writable. | [
"Flip",
"the",
"writability",
"of",
"a",
"file",
"and",
"return",
"the",
"old",
"mode",
".",
"Returns",
"None",
"if",
"the",
"file",
"is",
"already",
"writable",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/util.py#L44-L53 | train | 32,108 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/util.py | mergecopy | def mergecopy(src, dest):
"""
copy2, but only if the destination isn't up to date
"""
if os.path.exists(dest) and os.stat(dest).st_mtime >= os.stat(src).st_mtime:
return
copy2(src, dest) | python | def mergecopy(src, dest):
"""
copy2, but only if the destination isn't up to date
"""
if os.path.exists(dest) and os.stat(dest).st_mtime >= os.stat(src).st_mtime:
return
copy2(src, dest) | [
"def",
"mergecopy",
"(",
"src",
",",
"dest",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dest",
")",
"and",
"os",
".",
"stat",
"(",
"dest",
")",
".",
"st_mtime",
">=",
"os",
".",
"stat",
"(",
"src",
")",
".",
"st_mtime",
":",
"retur... | copy2, but only if the destination isn't up to date | [
"copy2",
"but",
"only",
"if",
"the",
"destination",
"isn",
"t",
"up",
"to",
"date"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/util.py#L104-L110 | train | 32,109 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/util.py | sdk_normalize | def sdk_normalize(filename):
"""
Normalize a path to strip out the SDK portion, normally so that it
can be decided whether it is in a system path or not.
"""
if filename.startswith('/Developer/SDKs/'):
pathcomp = filename.split('/')
del pathcomp[1:4]
filename = '/'.join(pathcomp)
return filename | python | def sdk_normalize(filename):
"""
Normalize a path to strip out the SDK portion, normally so that it
can be decided whether it is in a system path or not.
"""
if filename.startswith('/Developer/SDKs/'):
pathcomp = filename.split('/')
del pathcomp[1:4]
filename = '/'.join(pathcomp)
return filename | [
"def",
"sdk_normalize",
"(",
"filename",
")",
":",
"if",
"filename",
".",
"startswith",
"(",
"'/Developer/SDKs/'",
")",
":",
"pathcomp",
"=",
"filename",
".",
"split",
"(",
"'/'",
")",
"del",
"pathcomp",
"[",
"1",
":",
"4",
"]",
"filename",
"=",
"'/'",
... | Normalize a path to strip out the SDK portion, normally so that it
can be decided whether it is in a system path or not. | [
"Normalize",
"a",
"path",
"to",
"strip",
"out",
"the",
"SDK",
"portion",
"normally",
"so",
"that",
"it",
"can",
"be",
"decided",
"whether",
"it",
"is",
"in",
"a",
"system",
"path",
"or",
"not",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/util.py#L146-L155 | train | 32,110 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/util.py | in_system_path | def in_system_path(filename):
"""
Return True if the file is in a system path
"""
fn = sdk_normalize(os.path.realpath(filename))
if fn.startswith('/usr/local/'):
return False
elif fn.startswith('/System/') or fn.startswith('/usr/'):
return True
else:
return False | python | def in_system_path(filename):
"""
Return True if the file is in a system path
"""
fn = sdk_normalize(os.path.realpath(filename))
if fn.startswith('/usr/local/'):
return False
elif fn.startswith('/System/') or fn.startswith('/usr/'):
return True
else:
return False | [
"def",
"in_system_path",
"(",
"filename",
")",
":",
"fn",
"=",
"sdk_normalize",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"filename",
")",
")",
"if",
"fn",
".",
"startswith",
"(",
"'/usr/local/'",
")",
":",
"return",
"False",
"elif",
"fn",
".",
"st... | Return True if the file is in a system path | [
"Return",
"True",
"if",
"the",
"file",
"is",
"in",
"a",
"system",
"path"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/util.py#L157-L167 | train | 32,111 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/util.py | is_platform_file | def is_platform_file(path):
"""
Return True if the file is Mach-O
"""
if not os.path.exists(path) or os.path.islink(path):
return False
# If the header is fat, we need to read into the first arch
fileobj = open(path, 'rb')
bytes = fileobj.read(MAGIC_LEN)
if bytes == FAT_MAGIC_BYTES:
# Read in the fat header
fileobj.seek(0)
header = mach_o.fat_header.from_fileobj(fileobj, _endian_='>')
if header.nfat_arch < 1:
return False
# Read in the first fat arch header
arch = mach_o.fat_arch.from_fileobj(fileobj, _endian_='>')
fileobj.seek(arch.offset)
# Read magic off the first header
bytes = fileobj.read(MAGIC_LEN)
fileobj.close()
for magic in MAGIC:
if bytes == magic:
return True
return False | python | def is_platform_file(path):
"""
Return True if the file is Mach-O
"""
if not os.path.exists(path) or os.path.islink(path):
return False
# If the header is fat, we need to read into the first arch
fileobj = open(path, 'rb')
bytes = fileobj.read(MAGIC_LEN)
if bytes == FAT_MAGIC_BYTES:
# Read in the fat header
fileobj.seek(0)
header = mach_o.fat_header.from_fileobj(fileobj, _endian_='>')
if header.nfat_arch < 1:
return False
# Read in the first fat arch header
arch = mach_o.fat_arch.from_fileobj(fileobj, _endian_='>')
fileobj.seek(arch.offset)
# Read magic off the first header
bytes = fileobj.read(MAGIC_LEN)
fileobj.close()
for magic in MAGIC:
if bytes == magic:
return True
return False | [
"def",
"is_platform_file",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
"or",
"os",
".",
"path",
".",
"islink",
"(",
"path",
")",
":",
"return",
"False",
"# If the header is fat, we need to read into the first arch",
... | Return True if the file is Mach-O | [
"Return",
"True",
"if",
"the",
"file",
"is",
"Mach",
"-",
"O"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/util.py#L181-L205 | train | 32,112 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/util.py | iter_platform_files | def iter_platform_files(dst):
"""
Walk a directory and yield each full path that is a Mach-O file
"""
for root, dirs, files in os.walk(dst):
for fn in files:
fn = os.path.join(root, fn)
if is_platform_file(fn):
yield fn | python | def iter_platform_files(dst):
"""
Walk a directory and yield each full path that is a Mach-O file
"""
for root, dirs, files in os.walk(dst):
for fn in files:
fn = os.path.join(root, fn)
if is_platform_file(fn):
yield fn | [
"def",
"iter_platform_files",
"(",
"dst",
")",
":",
"for",
"root",
",",
"dirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"dst",
")",
":",
"for",
"fn",
"in",
"files",
":",
"fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root",
",",
"fn",
")"... | Walk a directory and yield each full path that is a Mach-O file | [
"Walk",
"a",
"directory",
"and",
"yield",
"each",
"full",
"path",
"that",
"is",
"a",
"Mach",
"-",
"O",
"file"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/util.py#L207-L215 | train | 32,113 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/util.py | strip_files | def strip_files(files, argv_max=(256 * 1024)):
"""
Strip a list of files
"""
tostrip = [(fn, flipwritable(fn)) for fn in files]
while tostrip:
cmd = list(STRIPCMD)
flips = []
pathlen = reduce(operator.add, [len(s) + 1 for s in cmd])
while pathlen < argv_max:
if not tostrip:
break
added, flip = tostrip.pop()
pathlen += len(added) + 1
cmd.append(added)
flips.append((added, flip))
else:
cmd.pop()
tostrip.append(flips.pop())
os.spawnv(os.P_WAIT, cmd[0], cmd)
for args in flips:
flipwritable(*args) | python | def strip_files(files, argv_max=(256 * 1024)):
"""
Strip a list of files
"""
tostrip = [(fn, flipwritable(fn)) for fn in files]
while tostrip:
cmd = list(STRIPCMD)
flips = []
pathlen = reduce(operator.add, [len(s) + 1 for s in cmd])
while pathlen < argv_max:
if not tostrip:
break
added, flip = tostrip.pop()
pathlen += len(added) + 1
cmd.append(added)
flips.append((added, flip))
else:
cmd.pop()
tostrip.append(flips.pop())
os.spawnv(os.P_WAIT, cmd[0], cmd)
for args in flips:
flipwritable(*args) | [
"def",
"strip_files",
"(",
"files",
",",
"argv_max",
"=",
"(",
"256",
"*",
"1024",
")",
")",
":",
"tostrip",
"=",
"[",
"(",
"fn",
",",
"flipwritable",
"(",
"fn",
")",
")",
"for",
"fn",
"in",
"files",
"]",
"while",
"tostrip",
":",
"cmd",
"=",
"lis... | Strip a list of files | [
"Strip",
"a",
"list",
"of",
"files"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/util.py#L217-L238 | train | 32,114 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/__subprocess.py | check_call | def check_call(*popenargs, **kwargs):
"""Run command with arguments. Wait for command to complete. If
the exit code was zero then return, otherwise raise
CalledProcessError. The CalledProcessError object will have the
return code in the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
check_call(["ls", "-l"])
"""
retcode = call(*popenargs, **kwargs)
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
if retcode:
raise CalledProcessError(retcode, cmd)
return retcode | python | def check_call(*popenargs, **kwargs):
"""Run command with arguments. Wait for command to complete. If
the exit code was zero then return, otherwise raise
CalledProcessError. The CalledProcessError object will have the
return code in the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
check_call(["ls", "-l"])
"""
retcode = call(*popenargs, **kwargs)
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
if retcode:
raise CalledProcessError(retcode, cmd)
return retcode | [
"def",
"check_call",
"(",
"*",
"popenargs",
",",
"*",
"*",
"kwargs",
")",
":",
"retcode",
"=",
"call",
"(",
"*",
"popenargs",
",",
"*",
"*",
"kwargs",
")",
"cmd",
"=",
"kwargs",
".",
"get",
"(",
"\"args\"",
")",
"if",
"cmd",
"is",
"None",
":",
"c... | Run command with arguments. Wait for command to complete. If
the exit code was zero then return, otherwise raise
CalledProcessError. The CalledProcessError object will have the
return code in the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
check_call(["ls", "-l"]) | [
"Run",
"command",
"with",
"arguments",
".",
"Wait",
"for",
"command",
"to",
"complete",
".",
"If",
"the",
"exit",
"code",
"was",
"zero",
"then",
"return",
"otherwise",
"raise",
"CalledProcessError",
".",
"The",
"CalledProcessError",
"object",
"will",
"have",
"... | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/__subprocess.py#L493-L509 | train | 32,115 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/hooks/hookutils.py | __exec_python_cmd | def __exec_python_cmd(cmd):
"""
Executes an externally spawned Python interpreter and returns
anything that was emitted in the standard output as a single
string.
"""
# Prepend PYTHONPATH with pathex
pp = os.pathsep.join(PyInstaller.__pathex__)
old_pp = compat.getenv('PYTHONPATH')
if old_pp:
pp = os.pathsep.join([pp, old_pp])
compat.setenv("PYTHONPATH", pp)
try:
try:
txt = compat.exec_python(*cmd)
except OSError, e:
raise SystemExit("Execution failed: %s" % e)
finally:
if old_pp is not None:
compat.setenv("PYTHONPATH", old_pp)
else:
compat.unsetenv("PYTHONPATH")
return txt.strip() | python | def __exec_python_cmd(cmd):
"""
Executes an externally spawned Python interpreter and returns
anything that was emitted in the standard output as a single
string.
"""
# Prepend PYTHONPATH with pathex
pp = os.pathsep.join(PyInstaller.__pathex__)
old_pp = compat.getenv('PYTHONPATH')
if old_pp:
pp = os.pathsep.join([pp, old_pp])
compat.setenv("PYTHONPATH", pp)
try:
try:
txt = compat.exec_python(*cmd)
except OSError, e:
raise SystemExit("Execution failed: %s" % e)
finally:
if old_pp is not None:
compat.setenv("PYTHONPATH", old_pp)
else:
compat.unsetenv("PYTHONPATH")
return txt.strip() | [
"def",
"__exec_python_cmd",
"(",
"cmd",
")",
":",
"# Prepend PYTHONPATH with pathex",
"pp",
"=",
"os",
".",
"pathsep",
".",
"join",
"(",
"PyInstaller",
".",
"__pathex__",
")",
"old_pp",
"=",
"compat",
".",
"getenv",
"(",
"'PYTHONPATH'",
")",
"if",
"old_pp",
... | Executes an externally spawned Python interpreter and returns
anything that was emitted in the standard output as a single
string. | [
"Executes",
"an",
"externally",
"spawned",
"Python",
"interpreter",
"and",
"returns",
"anything",
"that",
"was",
"emitted",
"in",
"the",
"standard",
"output",
"as",
"a",
"single",
"string",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/hooks/hookutils.py#L14-L36 | train | 32,116 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/hooks/hookutils.py | exec_script | def exec_script(scriptfilename, *args):
"""
Executes a Python script in an externally spawned interpreter, and
returns anything that was emitted in the standard output as a
single string.
To prevent missuse, the script passed to hookutils.exec-script
must be located in the `hooks` directory.
"""
if scriptfilename != os.path.basename(scriptfilename):
raise SystemError("To prevent missuse, the script passed to "
"hookutils.exec-script must be located in "
"the `hooks` directory.")
cmd = [os.path.join(os.path.dirname(__file__), scriptfilename)]
cmd.extend(args)
return __exec_python_cmd(cmd) | python | def exec_script(scriptfilename, *args):
"""
Executes a Python script in an externally spawned interpreter, and
returns anything that was emitted in the standard output as a
single string.
To prevent missuse, the script passed to hookutils.exec-script
must be located in the `hooks` directory.
"""
if scriptfilename != os.path.basename(scriptfilename):
raise SystemError("To prevent missuse, the script passed to "
"hookutils.exec-script must be located in "
"the `hooks` directory.")
cmd = [os.path.join(os.path.dirname(__file__), scriptfilename)]
cmd.extend(args)
return __exec_python_cmd(cmd) | [
"def",
"exec_script",
"(",
"scriptfilename",
",",
"*",
"args",
")",
":",
"if",
"scriptfilename",
"!=",
"os",
".",
"path",
".",
"basename",
"(",
"scriptfilename",
")",
":",
"raise",
"SystemError",
"(",
"\"To prevent missuse, the script passed to \"",
"\"hookutils.exe... | Executes a Python script in an externally spawned interpreter, and
returns anything that was emitted in the standard output as a
single string.
To prevent missuse, the script passed to hookutils.exec-script
must be located in the `hooks` directory. | [
"Executes",
"a",
"Python",
"script",
"in",
"an",
"externally",
"spawned",
"interpreter",
"and",
"returns",
"anything",
"that",
"was",
"emitted",
"in",
"the",
"standard",
"output",
"as",
"a",
"single",
"string",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/hooks/hookutils.py#L47-L64 | train | 32,117 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/hooks/hookutils.py | qt4_plugins_binaries | def qt4_plugins_binaries(plugin_type):
"""Return list of dynamic libraries formated for mod.binaries."""
binaries = []
pdir = qt4_plugins_dir()
files = misc.dlls_in_dir(os.path.join(pdir, plugin_type))
for f in files:
binaries.append((
os.path.join('qt4_plugins', plugin_type, os.path.basename(f)),
f, 'BINARY'))
return binaries | python | def qt4_plugins_binaries(plugin_type):
"""Return list of dynamic libraries formated for mod.binaries."""
binaries = []
pdir = qt4_plugins_dir()
files = misc.dlls_in_dir(os.path.join(pdir, plugin_type))
for f in files:
binaries.append((
os.path.join('qt4_plugins', plugin_type, os.path.basename(f)),
f, 'BINARY'))
return binaries | [
"def",
"qt4_plugins_binaries",
"(",
"plugin_type",
")",
":",
"binaries",
"=",
"[",
"]",
"pdir",
"=",
"qt4_plugins_dir",
"(",
")",
"files",
"=",
"misc",
".",
"dlls_in_dir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"pdir",
",",
"plugin_type",
")",
")",
... | Return list of dynamic libraries formated for mod.binaries. | [
"Return",
"list",
"of",
"dynamic",
"libraries",
"formated",
"for",
"mod",
".",
"binaries",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/hooks/hookutils.py#L115-L124 | train | 32,118 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/hooks/hookutils.py | qt4_menu_nib_dir | def qt4_menu_nib_dir():
"""Return path to Qt resource dir qt_menu.nib."""
menu_dir = ''
# Detect MacPorts prefix (usually /opt/local).
# Suppose that PyInstaller is using python from macports.
macports_prefix = sys.executable.split('/Library')[0]
# list of directories where to look for qt_menu.nib
dirs = [
# Qt4 from MacPorts not compiled as framework.
os.path.join(macports_prefix, 'lib', 'Resources'),
# Qt4 from MacPorts compiled as framework.
os.path.join(macports_prefix, 'libexec', 'qt4-mac', 'lib',
'QtGui.framework', 'Versions', '4', 'Resources'),
# Qt4 installed into default location.
'/Library/Frameworks/QtGui.framework/Resources',
'/Library/Frameworks/QtGui.framework/Versions/4/Resources',
'/Library/Frameworks/QtGui.Framework/Versions/Current/Resources',
]
# Check directory existence
for d in dirs:
d = os.path.join(d, 'qt_menu.nib')
if os.path.exists(d):
menu_dir = d
break
if not menu_dir:
logger.error('Cannont find qt_menu.nib directory')
return menu_dir | python | def qt4_menu_nib_dir():
"""Return path to Qt resource dir qt_menu.nib."""
menu_dir = ''
# Detect MacPorts prefix (usually /opt/local).
# Suppose that PyInstaller is using python from macports.
macports_prefix = sys.executable.split('/Library')[0]
# list of directories where to look for qt_menu.nib
dirs = [
# Qt4 from MacPorts not compiled as framework.
os.path.join(macports_prefix, 'lib', 'Resources'),
# Qt4 from MacPorts compiled as framework.
os.path.join(macports_prefix, 'libexec', 'qt4-mac', 'lib',
'QtGui.framework', 'Versions', '4', 'Resources'),
# Qt4 installed into default location.
'/Library/Frameworks/QtGui.framework/Resources',
'/Library/Frameworks/QtGui.framework/Versions/4/Resources',
'/Library/Frameworks/QtGui.Framework/Versions/Current/Resources',
]
# Check directory existence
for d in dirs:
d = os.path.join(d, 'qt_menu.nib')
if os.path.exists(d):
menu_dir = d
break
if not menu_dir:
logger.error('Cannont find qt_menu.nib directory')
return menu_dir | [
"def",
"qt4_menu_nib_dir",
"(",
")",
":",
"menu_dir",
"=",
"''",
"# Detect MacPorts prefix (usually /opt/local).",
"# Suppose that PyInstaller is using python from macports.",
"macports_prefix",
"=",
"sys",
".",
"executable",
".",
"split",
"(",
"'/Library'",
")",
"[",
"0",
... | Return path to Qt resource dir qt_menu.nib. | [
"Return",
"path",
"to",
"Qt",
"resource",
"dir",
"qt_menu",
".",
"nib",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/hooks/hookutils.py#L127-L154 | train | 32,119 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/dyld.py | dyld_find | def dyld_find(name, executable_path=None, env=None):
"""
Find a library or framework using dyld semantics
"""
name = _ensure_utf8(name)
executable_path = _ensure_utf8(executable_path)
for path in dyld_image_suffix_search(chain(
dyld_override_search(name, env),
dyld_executable_path_search(name, executable_path),
dyld_default_search(name, env),
), env):
if os.path.isfile(path):
return path
raise ValueError, "dylib %s could not be found" % (name,) | python | def dyld_find(name, executable_path=None, env=None):
"""
Find a library or framework using dyld semantics
"""
name = _ensure_utf8(name)
executable_path = _ensure_utf8(executable_path)
for path in dyld_image_suffix_search(chain(
dyld_override_search(name, env),
dyld_executable_path_search(name, executable_path),
dyld_default_search(name, env),
), env):
if os.path.isfile(path):
return path
raise ValueError, "dylib %s could not be found" % (name,) | [
"def",
"dyld_find",
"(",
"name",
",",
"executable_path",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"name",
"=",
"_ensure_utf8",
"(",
"name",
")",
"executable_path",
"=",
"_ensure_utf8",
"(",
"executable_path",
")",
"for",
"path",
"in",
"dyld_image_suff... | Find a library or framework using dyld semantics | [
"Find",
"a",
"library",
"or",
"framework",
"using",
"dyld",
"semantics"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/dyld.py#L135-L148 | train | 32,120 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/dyld.py | framework_find | def framework_find(fn, executable_path=None, env=None):
"""
Find a framework using dyld semantics in a very loose manner.
Will take input such as:
Python
Python.framework
Python.framework/Versions/Current
"""
try:
return dyld_find(fn, executable_path=executable_path, env=env)
except ValueError:
pass
fmwk_index = fn.rfind('.framework')
if fmwk_index == -1:
fmwk_index = len(fn)
fn += '.framework'
fn = os.path.join(fn, os.path.basename(fn[:fmwk_index]))
return dyld_find(fn, executable_path=executable_path, env=env) | python | def framework_find(fn, executable_path=None, env=None):
"""
Find a framework using dyld semantics in a very loose manner.
Will take input such as:
Python
Python.framework
Python.framework/Versions/Current
"""
try:
return dyld_find(fn, executable_path=executable_path, env=env)
except ValueError:
pass
fmwk_index = fn.rfind('.framework')
if fmwk_index == -1:
fmwk_index = len(fn)
fn += '.framework'
fn = os.path.join(fn, os.path.basename(fn[:fmwk_index]))
return dyld_find(fn, executable_path=executable_path, env=env) | [
"def",
"framework_find",
"(",
"fn",
",",
"executable_path",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"try",
":",
"return",
"dyld_find",
"(",
"fn",
",",
"executable_path",
"=",
"executable_path",
",",
"env",
"=",
"env",
")",
"except",
"ValueError",
... | Find a framework using dyld semantics in a very loose manner.
Will take input such as:
Python
Python.framework
Python.framework/Versions/Current | [
"Find",
"a",
"framework",
"using",
"dyld",
"semantics",
"in",
"a",
"very",
"loose",
"manner",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/dyld.py#L150-L168 | train | 32,121 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/svn.py | get_repo_revision | def get_repo_revision():
'''
Returns SVN revision number.
Returns 0 if anything goes wrong, such as missing .svn files or
an unexpected format of internal SVN files or folder is not
a svn working copy.
See http://stackoverflow.com/questions/1449935/getting-svn-revision-number-into-a-program-automatically
'''
rev = 0
path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
entries_path = os.path.join(path, '.svn', 'entries')
try:
entries = open(entries_path, 'rU').read()
except IOError:
pass
else:
# Versions >= 7 of the entries file are flat text. The first line is
# the version number. The next set of digits after 'dir' is the revision.
if re.match('(\d+)', entries):
rev_match = re.search('\d+\s+dir\s+(\d+)', entries)
if rev_match:
rev = rev_match.groups()[0]
# Older XML versions of the file specify revision as an attribute of
# the first entries node.
else:
from xml.dom import minidom
dom = minidom.parse(entries_path)
rev = dom.getElementsByTagName('entry')[0].getAttribute('revision')
return rev | python | def get_repo_revision():
'''
Returns SVN revision number.
Returns 0 if anything goes wrong, such as missing .svn files or
an unexpected format of internal SVN files or folder is not
a svn working copy.
See http://stackoverflow.com/questions/1449935/getting-svn-revision-number-into-a-program-automatically
'''
rev = 0
path = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
entries_path = os.path.join(path, '.svn', 'entries')
try:
entries = open(entries_path, 'rU').read()
except IOError:
pass
else:
# Versions >= 7 of the entries file are flat text. The first line is
# the version number. The next set of digits after 'dir' is the revision.
if re.match('(\d+)', entries):
rev_match = re.search('\d+\s+dir\s+(\d+)', entries)
if rev_match:
rev = rev_match.groups()[0]
# Older XML versions of the file specify revision as an attribute of
# the first entries node.
else:
from xml.dom import minidom
dom = minidom.parse(entries_path)
rev = dom.getElementsByTagName('entry')[0].getAttribute('revision')
return rev | [
"def",
"get_repo_revision",
"(",
")",
":",
"rev",
"=",
"0",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
")",
"entries_path",
"=",
"os",
... | Returns SVN revision number.
Returns 0 if anything goes wrong, such as missing .svn files or
an unexpected format of internal SVN files or folder is not
a svn working copy.
See http://stackoverflow.com/questions/1449935/getting-svn-revision-number-into-a-program-automatically | [
"Returns",
"SVN",
"revision",
"number",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/svn.py#L23-L55 | train | 32,122 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winutils.py | get_system_path | def get_system_path():
"""Return the path that Windows will search for dlls."""
_bpath = []
if is_win:
try:
import win32api
except ImportError:
logger.warn("Cannot determine your Windows or System directories")
logger.warn("Please add them to your PATH if .dlls are not found")
logger.warn("or install http://sourceforge.net/projects/pywin32/")
else:
sysdir = win32api.GetSystemDirectory()
sysdir2 = os.path.normpath(os.path.join(sysdir, '..', 'SYSTEM'))
windir = win32api.GetWindowsDirectory()
_bpath = [sysdir, sysdir2, windir]
_bpath.extend(compat.getenv('PATH', '').split(os.pathsep))
return _bpath | python | def get_system_path():
"""Return the path that Windows will search for dlls."""
_bpath = []
if is_win:
try:
import win32api
except ImportError:
logger.warn("Cannot determine your Windows or System directories")
logger.warn("Please add them to your PATH if .dlls are not found")
logger.warn("or install http://sourceforge.net/projects/pywin32/")
else:
sysdir = win32api.GetSystemDirectory()
sysdir2 = os.path.normpath(os.path.join(sysdir, '..', 'SYSTEM'))
windir = win32api.GetWindowsDirectory()
_bpath = [sysdir, sysdir2, windir]
_bpath.extend(compat.getenv('PATH', '').split(os.pathsep))
return _bpath | [
"def",
"get_system_path",
"(",
")",
":",
"_bpath",
"=",
"[",
"]",
"if",
"is_win",
":",
"try",
":",
"import",
"win32api",
"except",
"ImportError",
":",
"logger",
".",
"warn",
"(",
"\"Cannot determine your Windows or System directories\"",
")",
"logger",
".",
"war... | Return the path that Windows will search for dlls. | [
"Return",
"the",
"path",
"that",
"Windows",
"will",
"search",
"for",
"dlls",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winutils.py#L48-L64 | train | 32,123 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py | getFirstChildElementByTagName | def getFirstChildElementByTagName(self, tagName):
""" Return the first element of type tagName if found, else None """
for child in self.childNodes:
if isinstance(child, Element):
if child.tagName == tagName:
return child
return None | python | def getFirstChildElementByTagName(self, tagName):
""" Return the first element of type tagName if found, else None """
for child in self.childNodes:
if isinstance(child, Element):
if child.tagName == tagName:
return child
return None | [
"def",
"getFirstChildElementByTagName",
"(",
"self",
",",
"tagName",
")",
":",
"for",
"child",
"in",
"self",
".",
"childNodes",
":",
"if",
"isinstance",
"(",
"child",
",",
"Element",
")",
":",
"if",
"child",
".",
"tagName",
"==",
"tagName",
":",
"return",
... | Return the first element of type tagName if found, else None | [
"Return",
"the",
"first",
"element",
"of",
"type",
"tagName",
"if",
"found",
"else",
"None"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py#L143-L149 | train | 32,124 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py | GetManifestResources | def GetManifestResources(filename, names=None, languages=None):
""" Get manifest resources from file """
return winresource.GetResources(filename, [RT_MANIFEST], names, languages) | python | def GetManifestResources(filename, names=None, languages=None):
""" Get manifest resources from file """
return winresource.GetResources(filename, [RT_MANIFEST], names, languages) | [
"def",
"GetManifestResources",
"(",
"filename",
",",
"names",
"=",
"None",
",",
"languages",
"=",
"None",
")",
":",
"return",
"winresource",
".",
"GetResources",
"(",
"filename",
",",
"[",
"RT_MANIFEST",
"]",
",",
"names",
",",
"languages",
")"
] | Get manifest resources from file | [
"Get",
"manifest",
"resources",
"from",
"file"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py#L951-L953 | train | 32,125 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py | UpdateManifestResourcesFromXML | def UpdateManifestResourcesFromXML(dstpath, xmlstr, names=None,
languages=None):
""" Update or add manifest XML as resource in dstpath """
logger.info("Updating manifest in %s", dstpath)
if dstpath.lower().endswith(".exe"):
name = 1
else:
name = 2
winresource.UpdateResources(dstpath, xmlstr, RT_MANIFEST, names or [name],
languages or [0, "*"]) | python | def UpdateManifestResourcesFromXML(dstpath, xmlstr, names=None,
languages=None):
""" Update or add manifest XML as resource in dstpath """
logger.info("Updating manifest in %s", dstpath)
if dstpath.lower().endswith(".exe"):
name = 1
else:
name = 2
winresource.UpdateResources(dstpath, xmlstr, RT_MANIFEST, names or [name],
languages or [0, "*"]) | [
"def",
"UpdateManifestResourcesFromXML",
"(",
"dstpath",
",",
"xmlstr",
",",
"names",
"=",
"None",
",",
"languages",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"\"Updating manifest in %s\"",
",",
"dstpath",
")",
"if",
"dstpath",
".",
"lower",
"(",
")... | Update or add manifest XML as resource in dstpath | [
"Update",
"or",
"add",
"manifest",
"XML",
"as",
"resource",
"in",
"dstpath"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py#L956-L965 | train | 32,126 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py | UpdateManifestResourcesFromXMLFile | def UpdateManifestResourcesFromXMLFile(dstpath, srcpath, names=None,
languages=None):
""" Update or add manifest XML from srcpath as resource in dstpath """
logger.info("Updating manifest from %s in %s", srcpath, dstpath)
if dstpath.lower().endswith(".exe"):
name = 1
else:
name = 2
winresource.UpdateResourcesFromDataFile(dstpath, srcpath, RT_MANIFEST,
names or [name],
languages or [0, "*"]) | python | def UpdateManifestResourcesFromXMLFile(dstpath, srcpath, names=None,
languages=None):
""" Update or add manifest XML from srcpath as resource in dstpath """
logger.info("Updating manifest from %s in %s", srcpath, dstpath)
if dstpath.lower().endswith(".exe"):
name = 1
else:
name = 2
winresource.UpdateResourcesFromDataFile(dstpath, srcpath, RT_MANIFEST,
names or [name],
languages or [0, "*"]) | [
"def",
"UpdateManifestResourcesFromXMLFile",
"(",
"dstpath",
",",
"srcpath",
",",
"names",
"=",
"None",
",",
"languages",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"\"Updating manifest from %s in %s\"",
",",
"srcpath",
",",
"dstpath",
")",
"if",
"dstpat... | Update or add manifest XML from srcpath as resource in dstpath | [
"Update",
"or",
"add",
"manifest",
"XML",
"from",
"srcpath",
"as",
"resource",
"in",
"dstpath"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py#L968-L978 | train | 32,127 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py | create_manifest | def create_manifest(filename, manifest, console):
"""
Create assembly manifest.
"""
if not manifest:
manifest = ManifestFromXMLFile(filename)
# /path/NAME.exe.manifest - split extension twice to get NAME.
name = os.path.basename(filename)
manifest.name = os.path.splitext(os.path.splitext(name)[0])[0]
elif isinstance(manifest, basestring) and "<" in manifest:
# Assume XML string
manifest = ManifestFromXML(manifest)
elif not isinstance(manifest, Manifest):
# Assume filename
manifest = ManifestFromXMLFile(manifest)
dep_names = set([dep.name for dep in manifest.dependentAssemblies])
if manifest.filename != filename:
# Update dependent assemblies
depmanifest = ManifestFromXMLFile(filename)
for assembly in depmanifest.dependentAssemblies:
if not assembly.name in dep_names:
manifest.dependentAssemblies.append(assembly)
dep_names.add(assembly.name)
if (not console and
not "Microsoft.Windows.Common-Controls" in dep_names):
# Add Microsoft.Windows.Common-Controls to dependent assemblies
manifest.dependentAssemblies.append(
Manifest(type_="win32",
name="Microsoft.Windows.Common-Controls",
language="*",
processorArchitecture=processor_architecture(),
version=(6, 0, 0, 0),
publicKeyToken="6595b64144ccf1df")
)
manifest.writeprettyxml(filename)
return manifest | python | def create_manifest(filename, manifest, console):
"""
Create assembly manifest.
"""
if not manifest:
manifest = ManifestFromXMLFile(filename)
# /path/NAME.exe.manifest - split extension twice to get NAME.
name = os.path.basename(filename)
manifest.name = os.path.splitext(os.path.splitext(name)[0])[0]
elif isinstance(manifest, basestring) and "<" in manifest:
# Assume XML string
manifest = ManifestFromXML(manifest)
elif not isinstance(manifest, Manifest):
# Assume filename
manifest = ManifestFromXMLFile(manifest)
dep_names = set([dep.name for dep in manifest.dependentAssemblies])
if manifest.filename != filename:
# Update dependent assemblies
depmanifest = ManifestFromXMLFile(filename)
for assembly in depmanifest.dependentAssemblies:
if not assembly.name in dep_names:
manifest.dependentAssemblies.append(assembly)
dep_names.add(assembly.name)
if (not console and
not "Microsoft.Windows.Common-Controls" in dep_names):
# Add Microsoft.Windows.Common-Controls to dependent assemblies
manifest.dependentAssemblies.append(
Manifest(type_="win32",
name="Microsoft.Windows.Common-Controls",
language="*",
processorArchitecture=processor_architecture(),
version=(6, 0, 0, 0),
publicKeyToken="6595b64144ccf1df")
)
manifest.writeprettyxml(filename)
return manifest | [
"def",
"create_manifest",
"(",
"filename",
",",
"manifest",
",",
"console",
")",
":",
"if",
"not",
"manifest",
":",
"manifest",
"=",
"ManifestFromXMLFile",
"(",
"filename",
")",
"# /path/NAME.exe.manifest - split extension twice to get NAME.",
"name",
"=",
"os",
".",
... | Create assembly manifest. | [
"Create",
"assembly",
"manifest",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py#L981-L1016 | train | 32,128 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py | Manifest.add_file | def add_file(self, name="", hashalg="", hash="", comClasses=None,
typelibs=None, comInterfaceProxyStubs=None,
windowClasses=None):
""" Shortcut for manifest.files.append """
self.files.append(File(name, hashalg, hash, comClasses,
typelibs, comInterfaceProxyStubs, windowClasses)) | python | def add_file(self, name="", hashalg="", hash="", comClasses=None,
typelibs=None, comInterfaceProxyStubs=None,
windowClasses=None):
""" Shortcut for manifest.files.append """
self.files.append(File(name, hashalg, hash, comClasses,
typelibs, comInterfaceProxyStubs, windowClasses)) | [
"def",
"add_file",
"(",
"self",
",",
"name",
"=",
"\"\"",
",",
"hashalg",
"=",
"\"\"",
",",
"hash",
"=",
"\"\"",
",",
"comClasses",
"=",
"None",
",",
"typelibs",
"=",
"None",
",",
"comInterfaceProxyStubs",
"=",
"None",
",",
"windowClasses",
"=",
"None",
... | Shortcut for manifest.files.append | [
"Shortcut",
"for",
"manifest",
".",
"files",
".",
"append"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py#L305-L310 | train | 32,129 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py | Manifest.getid | def getid(self, language=None, version=None):
"""
Return an identification string which uniquely names a manifest.
This string is a combination of the manifest's processorArchitecture,
name, publicKeyToken, version and language.
Arguments:
version (tuple or list of integers) - If version is given, use it
instead of the manifest's
version.
"""
if not self.name:
logger.warn("Assembly metadata incomplete")
return ""
id = []
if self.processorArchitecture:
id.append(self.processorArchitecture)
id.append(self.name)
if self.publicKeyToken:
id.append(self.publicKeyToken)
if version or self.version:
id.append(".".join([str(i) for i in version or self.version]))
if not language:
language = self.getlanguage()
if language:
id.append(language)
return "_".join(id) | python | def getid(self, language=None, version=None):
"""
Return an identification string which uniquely names a manifest.
This string is a combination of the manifest's processorArchitecture,
name, publicKeyToken, version and language.
Arguments:
version (tuple or list of integers) - If version is given, use it
instead of the manifest's
version.
"""
if not self.name:
logger.warn("Assembly metadata incomplete")
return ""
id = []
if self.processorArchitecture:
id.append(self.processorArchitecture)
id.append(self.name)
if self.publicKeyToken:
id.append(self.publicKeyToken)
if version or self.version:
id.append(".".join([str(i) for i in version or self.version]))
if not language:
language = self.getlanguage()
if language:
id.append(language)
return "_".join(id) | [
"def",
"getid",
"(",
"self",
",",
"language",
"=",
"None",
",",
"version",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"name",
":",
"logger",
".",
"warn",
"(",
"\"Assembly metadata incomplete\"",
")",
"return",
"\"\"",
"id",
"=",
"[",
"]",
"if",
... | Return an identification string which uniquely names a manifest.
This string is a combination of the manifest's processorArchitecture,
name, publicKeyToken, version and language.
Arguments:
version (tuple or list of integers) - If version is given, use it
instead of the manifest's
version. | [
"Return",
"an",
"identification",
"string",
"which",
"uniquely",
"names",
"a",
"manifest",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py#L514-L542 | train | 32,130 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py | Manifest.getpolicyid | def getpolicyid(self, fuzzy=True, language=None, windowsversion=None):
"""
Return an identification string which can be used to find a policy.
This string is a combination of the manifest's processorArchitecture,
major and minor version, name, publicKeyToken and language.
Arguments:
fuzzy (boolean) - If False, insert the full version in
the id string. Default is True (omit).
windowsversion - If not specified (or None), default to
(tuple or list of integers) sys.getwindowsversion().
"""
if not self.name:
logger.warn("Assembly metadata incomplete")
return ""
id = []
if self.processorArchitecture:
id.append(self.processorArchitecture)
name = []
name.append("policy")
if self.version:
name.append(str(self.version[0]))
name.append(str(self.version[1]))
name.append(self.name)
id.append(".".join(name))
if self.publicKeyToken:
id.append(self.publicKeyToken)
if self.version and (windowsversion or sys.getwindowsversion()) >= (6, ):
# Vista and later
if fuzzy:
id.append("*")
else:
id.append(".".join([str(i) for i in self.version]))
if not language:
language = self.getlanguage(windowsversion=windowsversion)
if language:
id.append(language)
id.append("*")
id = "_".join(id)
if self.version and (windowsversion or sys.getwindowsversion()) < (6, ):
# Windows XP
if fuzzy:
id = os.path.join(id, "*")
else:
id = os.path.join(id, ".".join([str(i) for i in self.version]))
return id | python | def getpolicyid(self, fuzzy=True, language=None, windowsversion=None):
"""
Return an identification string which can be used to find a policy.
This string is a combination of the manifest's processorArchitecture,
major and minor version, name, publicKeyToken and language.
Arguments:
fuzzy (boolean) - If False, insert the full version in
the id string. Default is True (omit).
windowsversion - If not specified (or None), default to
(tuple or list of integers) sys.getwindowsversion().
"""
if not self.name:
logger.warn("Assembly metadata incomplete")
return ""
id = []
if self.processorArchitecture:
id.append(self.processorArchitecture)
name = []
name.append("policy")
if self.version:
name.append(str(self.version[0]))
name.append(str(self.version[1]))
name.append(self.name)
id.append(".".join(name))
if self.publicKeyToken:
id.append(self.publicKeyToken)
if self.version and (windowsversion or sys.getwindowsversion()) >= (6, ):
# Vista and later
if fuzzy:
id.append("*")
else:
id.append(".".join([str(i) for i in self.version]))
if not language:
language = self.getlanguage(windowsversion=windowsversion)
if language:
id.append(language)
id.append("*")
id = "_".join(id)
if self.version and (windowsversion or sys.getwindowsversion()) < (6, ):
# Windows XP
if fuzzy:
id = os.path.join(id, "*")
else:
id = os.path.join(id, ".".join([str(i) for i in self.version]))
return id | [
"def",
"getpolicyid",
"(",
"self",
",",
"fuzzy",
"=",
"True",
",",
"language",
"=",
"None",
",",
"windowsversion",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"name",
":",
"logger",
".",
"warn",
"(",
"\"Assembly metadata incomplete\"",
")",
"return",
... | Return an identification string which can be used to find a policy.
This string is a combination of the manifest's processorArchitecture,
major and minor version, name, publicKeyToken and language.
Arguments:
fuzzy (boolean) - If False, insert the full version in
the id string. Default is True (omit).
windowsversion - If not specified (or None), default to
(tuple or list of integers) sys.getwindowsversion(). | [
"Return",
"an",
"identification",
"string",
"which",
"can",
"be",
"used",
"to",
"find",
"a",
"policy",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py#L561-L608 | train | 32,131 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py | Manifest.parse | def parse(self, filename_or_file, initialize=True):
""" Load manifest from file or file object """
if isinstance(filename_or_file, (str, unicode)):
filename = filename_or_file
else:
filename = filename_or_file.name
try:
domtree = minidom.parse(filename_or_file)
except xml.parsers.expat.ExpatError, e:
args = [e.args[0]]
if isinstance(filename, unicode):
filename = filename.encode(sys.getdefaultencoding(), "replace")
args.insert(0, '\n File "%s"\n ' % filename)
raise ManifestXMLParseError(" ".join([str(arg) for arg in args]))
if initialize:
self.__init__()
self.filename = filename
self.load_dom(domtree, False) | python | def parse(self, filename_or_file, initialize=True):
""" Load manifest from file or file object """
if isinstance(filename_or_file, (str, unicode)):
filename = filename_or_file
else:
filename = filename_or_file.name
try:
domtree = minidom.parse(filename_or_file)
except xml.parsers.expat.ExpatError, e:
args = [e.args[0]]
if isinstance(filename, unicode):
filename = filename.encode(sys.getdefaultencoding(), "replace")
args.insert(0, '\n File "%s"\n ' % filename)
raise ManifestXMLParseError(" ".join([str(arg) for arg in args]))
if initialize:
self.__init__()
self.filename = filename
self.load_dom(domtree, False) | [
"def",
"parse",
"(",
"self",
",",
"filename_or_file",
",",
"initialize",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"filename_or_file",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"filename",
"=",
"filename_or_file",
"else",
":",
"filename",
"=",
... | Load manifest from file or file object | [
"Load",
"manifest",
"from",
"file",
"or",
"file",
"object"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py#L702-L719 | train | 32,132 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py | Manifest.parse_string | def parse_string(self, xmlstr, initialize=True):
""" Load manifest from XML string """
try:
domtree = minidom.parseString(xmlstr)
except xml.parsers.expat.ExpatError, e:
raise ManifestXMLParseError(e)
self.load_dom(domtree, initialize) | python | def parse_string(self, xmlstr, initialize=True):
""" Load manifest from XML string """
try:
domtree = minidom.parseString(xmlstr)
except xml.parsers.expat.ExpatError, e:
raise ManifestXMLParseError(e)
self.load_dom(domtree, initialize) | [
"def",
"parse_string",
"(",
"self",
",",
"xmlstr",
",",
"initialize",
"=",
"True",
")",
":",
"try",
":",
"domtree",
"=",
"minidom",
".",
"parseString",
"(",
"xmlstr",
")",
"except",
"xml",
".",
"parsers",
".",
"expat",
".",
"ExpatError",
",",
"e",
":",... | Load manifest from XML string | [
"Load",
"manifest",
"from",
"XML",
"string"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py#L721-L727 | train | 32,133 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py | Manifest.same_id | def same_id(self, manifest, skip_version_check=False):
"""
Return a bool indicating if another manifest has the same identitiy.
This is done by comparing language, name, processorArchitecture,
publicKeyToken, type and version.
"""
if skip_version_check:
version_check = True
else:
version_check = self.version == manifest.version
return (self.language == manifest.language and
self.name == manifest.name and
self.processorArchitecture == manifest.processorArchitecture and
self.publicKeyToken == manifest.publicKeyToken and
self.type == manifest.type and
version_check) | python | def same_id(self, manifest, skip_version_check=False):
"""
Return a bool indicating if another manifest has the same identitiy.
This is done by comparing language, name, processorArchitecture,
publicKeyToken, type and version.
"""
if skip_version_check:
version_check = True
else:
version_check = self.version == manifest.version
return (self.language == manifest.language and
self.name == manifest.name and
self.processorArchitecture == manifest.processorArchitecture and
self.publicKeyToken == manifest.publicKeyToken and
self.type == manifest.type and
version_check) | [
"def",
"same_id",
"(",
"self",
",",
"manifest",
",",
"skip_version_check",
"=",
"False",
")",
":",
"if",
"skip_version_check",
":",
"version_check",
"=",
"True",
"else",
":",
"version_check",
"=",
"self",
".",
"version",
"==",
"manifest",
".",
"version",
"re... | Return a bool indicating if another manifest has the same identitiy.
This is done by comparing language, name, processorArchitecture,
publicKeyToken, type and version. | [
"Return",
"a",
"bool",
"indicating",
"if",
"another",
"manifest",
"has",
"the",
"same",
"identitiy",
".",
"This",
"is",
"done",
"by",
"comparing",
"language",
"name",
"processorArchitecture",
"publicKeyToken",
"type",
"and",
"version",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py#L729-L746 | train | 32,134 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py | Manifest.toprettyxml | def toprettyxml(self, indent=" ", newl=os.linesep, encoding="UTF-8"):
""" Return the manifest as pretty-printed XML """
domtree = self.todom()
# WARNING: The XML declaration has to follow the order
# version-encoding-standalone (standalone being optional), otherwise
# if it is embedded in an exe the exe will fail to launch!
# ('application configuration incorrect')
if sys.version_info >= (2,3):
xmlstr = domtree.toprettyxml(indent, newl, encoding)
else:
xmlstr = domtree.toprettyxml(indent, newl)
xmlstr = xmlstr.strip(os.linesep).replace(
'<?xml version="1.0" encoding="%s"?>' % encoding,
'<?xml version="1.0" encoding="%s" standalone="yes"?>' %
encoding)
domtree.unlink()
return xmlstr | python | def toprettyxml(self, indent=" ", newl=os.linesep, encoding="UTF-8"):
""" Return the manifest as pretty-printed XML """
domtree = self.todom()
# WARNING: The XML declaration has to follow the order
# version-encoding-standalone (standalone being optional), otherwise
# if it is embedded in an exe the exe will fail to launch!
# ('application configuration incorrect')
if sys.version_info >= (2,3):
xmlstr = domtree.toprettyxml(indent, newl, encoding)
else:
xmlstr = domtree.toprettyxml(indent, newl)
xmlstr = xmlstr.strip(os.linesep).replace(
'<?xml version="1.0" encoding="%s"?>' % encoding,
'<?xml version="1.0" encoding="%s" standalone="yes"?>' %
encoding)
domtree.unlink()
return xmlstr | [
"def",
"toprettyxml",
"(",
"self",
",",
"indent",
"=",
"\" \"",
",",
"newl",
"=",
"os",
".",
"linesep",
",",
"encoding",
"=",
"\"UTF-8\"",
")",
":",
"domtree",
"=",
"self",
".",
"todom",
"(",
")",
"# WARNING: The XML declaration has to follow the order ",
"# ... | Return the manifest as pretty-printed XML | [
"Return",
"the",
"manifest",
"as",
"pretty",
"-",
"printed",
"XML"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py#L853-L869 | train | 32,135 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py | Manifest.toxml | def toxml(self, encoding="UTF-8"):
""" Return the manifest as XML """
domtree = self.todom()
# WARNING: The XML declaration has to follow the order
# version-encoding-standalone (standalone being optional), otherwise
# if it is embedded in an exe the exe will fail to launch!
# ('application configuration incorrect')
xmlstr = domtree.toxml(encoding).replace(
'<?xml version="1.0" encoding="%s"?>' % encoding,
'<?xml version="1.0" encoding="%s" standalone="yes"?>' % encoding)
domtree.unlink()
return xmlstr | python | def toxml(self, encoding="UTF-8"):
""" Return the manifest as XML """
domtree = self.todom()
# WARNING: The XML declaration has to follow the order
# version-encoding-standalone (standalone being optional), otherwise
# if it is embedded in an exe the exe will fail to launch!
# ('application configuration incorrect')
xmlstr = domtree.toxml(encoding).replace(
'<?xml version="1.0" encoding="%s"?>' % encoding,
'<?xml version="1.0" encoding="%s" standalone="yes"?>' % encoding)
domtree.unlink()
return xmlstr | [
"def",
"toxml",
"(",
"self",
",",
"encoding",
"=",
"\"UTF-8\"",
")",
":",
"domtree",
"=",
"self",
".",
"todom",
"(",
")",
"# WARNING: The XML declaration has to follow the order ",
"# version-encoding-standalone (standalone being optional), otherwise ",
"# if it is embedded in ... | Return the manifest as XML | [
"Return",
"the",
"manifest",
"as",
"XML"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/utils/winmanifest.py#L871-L882 | train | 32,136 |
bwhite/hadoopy | hadoopy/_local.py | launch_local | def launch_local(in_name, out_name, script_path, poll=None, max_input=None,
files=(), cmdenvs=(), pipe=True, python_cmd='python', remove_tempdir=True,
identity_mapper=False, num_reducers=None,
**kw):
"""A simple local emulation of hadoop
This doesn't run hadoop and it doesn't support many advanced features, it
is intended for simple debugging. The input/output uses HDFS if an
HDFS path is given. This allows for small tasks to be run locally
(primarily while debugging). A temporary working directory is used and
removed.
Support
* Environmental variables
* Map-only tasks
* Combiner
* Files
* Pipe (see below)
* Display of stdout/stderr
* Iterator of KV pairs as input or output (bypassing HDFS)
:param in_name: Input path (string or list of strings) or Iterator of (key, value). If it is an iterator then no input is taken from HDFS.
:param out_name: Output path or None. If None then output is not placed on HDFS, it is available through the 'output' key of the return value.
:param script_path: Path to the script (e.g., script.py)
:param poll: If not None, then only attempt to get a kv pair from kvs if when called, poll returns True.
:param max_input: Maximum number of Mapper inputs, None (default) then unlimited.
:param files: Extra files (other than the script) (iterator). NOTE: Hadoop copies the files into working directory
:param cmdenvs: Extra cmdenv parameters (iterator)
:param pipe: If true (default) then call user code through a pipe to isolate it and stop bugs when printing to stdout. See project docs.
:param python_cmd: The python command to use. The default is "python". Can be used to override the system default python, e.g. python_cmd = "python2.6"
:param remove_tempdir: If True (default), then rmtree the temporary dir, else print its location. Useful if you need to see temporary files or how input files are copied.
:param identity_mapper: If True, use an identity mapper, regardless of what is in the script.
:param num_reducers: If 0, don't run the reducer even if one exists, else obey what is in the script.
:rtype: Dictionary with some of the following entries (depending on options)
:returns: freeze_cmds: Freeze command(s) ran
:returns: frozen_tar_path: HDFS path to frozen file
:returns: hadoop_cmds: Hadoopy command(s) ran
:returns: process: subprocess.Popen object
:returns: output: Iterator of (key, value) pairs
:raises: subprocess.CalledProcessError: Hadoop error.
:raises: OSError: Hadoop streaming not found.
:raises: TypeError: Input types are not correct.
:raises: ValueError: Script not found
"""
if isinstance(files, (str, unicode)) or isinstance(cmdenvs, (str, unicode)) or ('cmdenvs' in kw and isinstance(kw['cmdenvs'], (str, unicode))):
raise TypeError('files and cmdenvs must be iterators of strings and not strings!')
logging.info('Local[%s]' % script_path)
script_info = hadoopy._runner._parse_info(script_path, python_cmd)
if isinstance(in_name, (str, unicode)) or (in_name and isinstance(in_name, (list, tuple)) and isinstance(in_name[0], (str, unicode))):
in_kvs = hadoopy.readtb(in_name)
else:
in_kvs = in_name
if 'reduce' in script_info['tasks'] and num_reducers != 0:
if identity_mapper:
kvs = in_kvs
else:
kvs = list(LocalTask(script_path, 'map', files, max_input, pipe,
python_cmd, remove_tempdir).run_task(in_kvs, cmdenvs, poll))
if 'combine' in script_info['tasks']:
kvs = hadoopy.Test.sort_kv(kvs)
kvs = list(LocalTask(script_path, 'combine', files, max_input, pipe,
python_cmd, remove_tempdir).run_task(kvs, cmdenvs))
kvs = hadoopy.Test.sort_kv(kvs)
kvs = LocalTask(script_path, 'reduce', files, max_input, pipe,
python_cmd, remove_tempdir).run_task(kvs, cmdenvs)
else:
if identity_mapper:
kvs = in_kvs
else:
kvs = LocalTask(script_path, 'map', files, max_input, pipe,
python_cmd, remove_tempdir).run_task(in_kvs, cmdenvs, poll)
out = {}
if out_name is not None:
hadoopy.writetb(out_name, kvs)
out['output'] = hadoopy.readtb(out_name)
else:
out['output'] = kvs
return out | python | def launch_local(in_name, out_name, script_path, poll=None, max_input=None,
files=(), cmdenvs=(), pipe=True, python_cmd='python', remove_tempdir=True,
identity_mapper=False, num_reducers=None,
**kw):
"""A simple local emulation of hadoop
This doesn't run hadoop and it doesn't support many advanced features, it
is intended for simple debugging. The input/output uses HDFS if an
HDFS path is given. This allows for small tasks to be run locally
(primarily while debugging). A temporary working directory is used and
removed.
Support
* Environmental variables
* Map-only tasks
* Combiner
* Files
* Pipe (see below)
* Display of stdout/stderr
* Iterator of KV pairs as input or output (bypassing HDFS)
:param in_name: Input path (string or list of strings) or Iterator of (key, value). If it is an iterator then no input is taken from HDFS.
:param out_name: Output path or None. If None then output is not placed on HDFS, it is available through the 'output' key of the return value.
:param script_path: Path to the script (e.g., script.py)
:param poll: If not None, then only attempt to get a kv pair from kvs if when called, poll returns True.
:param max_input: Maximum number of Mapper inputs, None (default) then unlimited.
:param files: Extra files (other than the script) (iterator). NOTE: Hadoop copies the files into working directory
:param cmdenvs: Extra cmdenv parameters (iterator)
:param pipe: If true (default) then call user code through a pipe to isolate it and stop bugs when printing to stdout. See project docs.
:param python_cmd: The python command to use. The default is "python". Can be used to override the system default python, e.g. python_cmd = "python2.6"
:param remove_tempdir: If True (default), then rmtree the temporary dir, else print its location. Useful if you need to see temporary files or how input files are copied.
:param identity_mapper: If True, use an identity mapper, regardless of what is in the script.
:param num_reducers: If 0, don't run the reducer even if one exists, else obey what is in the script.
:rtype: Dictionary with some of the following entries (depending on options)
:returns: freeze_cmds: Freeze command(s) ran
:returns: frozen_tar_path: HDFS path to frozen file
:returns: hadoop_cmds: Hadoopy command(s) ran
:returns: process: subprocess.Popen object
:returns: output: Iterator of (key, value) pairs
:raises: subprocess.CalledProcessError: Hadoop error.
:raises: OSError: Hadoop streaming not found.
:raises: TypeError: Input types are not correct.
:raises: ValueError: Script not found
"""
if isinstance(files, (str, unicode)) or isinstance(cmdenvs, (str, unicode)) or ('cmdenvs' in kw and isinstance(kw['cmdenvs'], (str, unicode))):
raise TypeError('files and cmdenvs must be iterators of strings and not strings!')
logging.info('Local[%s]' % script_path)
script_info = hadoopy._runner._parse_info(script_path, python_cmd)
if isinstance(in_name, (str, unicode)) or (in_name and isinstance(in_name, (list, tuple)) and isinstance(in_name[0], (str, unicode))):
in_kvs = hadoopy.readtb(in_name)
else:
in_kvs = in_name
if 'reduce' in script_info['tasks'] and num_reducers != 0:
if identity_mapper:
kvs = in_kvs
else:
kvs = list(LocalTask(script_path, 'map', files, max_input, pipe,
python_cmd, remove_tempdir).run_task(in_kvs, cmdenvs, poll))
if 'combine' in script_info['tasks']:
kvs = hadoopy.Test.sort_kv(kvs)
kvs = list(LocalTask(script_path, 'combine', files, max_input, pipe,
python_cmd, remove_tempdir).run_task(kvs, cmdenvs))
kvs = hadoopy.Test.sort_kv(kvs)
kvs = LocalTask(script_path, 'reduce', files, max_input, pipe,
python_cmd, remove_tempdir).run_task(kvs, cmdenvs)
else:
if identity_mapper:
kvs = in_kvs
else:
kvs = LocalTask(script_path, 'map', files, max_input, pipe,
python_cmd, remove_tempdir).run_task(in_kvs, cmdenvs, poll)
out = {}
if out_name is not None:
hadoopy.writetb(out_name, kvs)
out['output'] = hadoopy.readtb(out_name)
else:
out['output'] = kvs
return out | [
"def",
"launch_local",
"(",
"in_name",
",",
"out_name",
",",
"script_path",
",",
"poll",
"=",
"None",
",",
"max_input",
"=",
"None",
",",
"files",
"=",
"(",
")",
",",
"cmdenvs",
"=",
"(",
")",
",",
"pipe",
"=",
"True",
",",
"python_cmd",
"=",
"'pytho... | A simple local emulation of hadoop
This doesn't run hadoop and it doesn't support many advanced features, it
is intended for simple debugging. The input/output uses HDFS if an
HDFS path is given. This allows for small tasks to be run locally
(primarily while debugging). A temporary working directory is used and
removed.
Support
* Environmental variables
* Map-only tasks
* Combiner
* Files
* Pipe (see below)
* Display of stdout/stderr
* Iterator of KV pairs as input or output (bypassing HDFS)
:param in_name: Input path (string or list of strings) or Iterator of (key, value). If it is an iterator then no input is taken from HDFS.
:param out_name: Output path or None. If None then output is not placed on HDFS, it is available through the 'output' key of the return value.
:param script_path: Path to the script (e.g., script.py)
:param poll: If not None, then only attempt to get a kv pair from kvs if when called, poll returns True.
:param max_input: Maximum number of Mapper inputs, None (default) then unlimited.
:param files: Extra files (other than the script) (iterator). NOTE: Hadoop copies the files into working directory
:param cmdenvs: Extra cmdenv parameters (iterator)
:param pipe: If true (default) then call user code through a pipe to isolate it and stop bugs when printing to stdout. See project docs.
:param python_cmd: The python command to use. The default is "python". Can be used to override the system default python, e.g. python_cmd = "python2.6"
:param remove_tempdir: If True (default), then rmtree the temporary dir, else print its location. Useful if you need to see temporary files or how input files are copied.
:param identity_mapper: If True, use an identity mapper, regardless of what is in the script.
:param num_reducers: If 0, don't run the reducer even if one exists, else obey what is in the script.
:rtype: Dictionary with some of the following entries (depending on options)
:returns: freeze_cmds: Freeze command(s) ran
:returns: frozen_tar_path: HDFS path to frozen file
:returns: hadoop_cmds: Hadoopy command(s) ran
:returns: process: subprocess.Popen object
:returns: output: Iterator of (key, value) pairs
:raises: subprocess.CalledProcessError: Hadoop error.
:raises: OSError: Hadoop streaming not found.
:raises: TypeError: Input types are not correct.
:raises: ValueError: Script not found | [
"A",
"simple",
"local",
"emulation",
"of",
"hadoop"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_local.py#L119-L197 | train | 32,137 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py | getfullnameof | def getfullnameof(mod, xtrapath=None):
"""
Return the full path name of MOD.
MOD is the basename of a dll or pyd.
XTRAPATH is a path or list of paths to search first.
Return the full path name of MOD.
Will search the full Windows search path, as well as sys.path
"""
# Search sys.path first!
epath = sys.path + winutils.get_system_path()
if xtrapath is not None:
if type(xtrapath) == type(''):
epath.insert(0, xtrapath)
else:
epath = xtrapath + epath
for p in epath:
npth = os.path.join(p, mod)
if os.path.exists(npth):
return npth
# second try: lower case filename
for p in epath:
npth = os.path.join(p, mod.lower())
if os.path.exists(npth):
return npth
return '' | python | def getfullnameof(mod, xtrapath=None):
"""
Return the full path name of MOD.
MOD is the basename of a dll or pyd.
XTRAPATH is a path or list of paths to search first.
Return the full path name of MOD.
Will search the full Windows search path, as well as sys.path
"""
# Search sys.path first!
epath = sys.path + winutils.get_system_path()
if xtrapath is not None:
if type(xtrapath) == type(''):
epath.insert(0, xtrapath)
else:
epath = xtrapath + epath
for p in epath:
npth = os.path.join(p, mod)
if os.path.exists(npth):
return npth
# second try: lower case filename
for p in epath:
npth = os.path.join(p, mod.lower())
if os.path.exists(npth):
return npth
return '' | [
"def",
"getfullnameof",
"(",
"mod",
",",
"xtrapath",
"=",
"None",
")",
":",
"# Search sys.path first!",
"epath",
"=",
"sys",
".",
"path",
"+",
"winutils",
".",
"get_system_path",
"(",
")",
"if",
"xtrapath",
"is",
"not",
"None",
":",
"if",
"type",
"(",
"x... | Return the full path name of MOD.
MOD is the basename of a dll or pyd.
XTRAPATH is a path or list of paths to search first.
Return the full path name of MOD.
Will search the full Windows search path, as well as sys.path | [
"Return",
"the",
"full",
"path",
"name",
"of",
"MOD",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py#L61-L86 | train | 32,138 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py | Dependencies | def Dependencies(lTOC, xtrapath=None, manifest=None):
"""
Expand LTOC to include all the closure of binary dependencies.
LTOC is a logical table of contents, ie, a seq of tuples (name, path).
Return LTOC expanded by all the binary dependencies of the entries
in LTOC, except those listed in the module global EXCLUDES
manifest should be a winmanifest.Manifest instance on Windows, so
that all dependent assemblies can be added
"""
for nm, pth, typ in lTOC:
if seen.get(nm.upper(), 0):
continue
logger.info("Analyzing %s", pth)
seen[nm.upper()] = 1
if is_win:
for ftocnm, fn in selectAssemblies(pth, manifest):
lTOC.append((ftocnm, fn, 'BINARY'))
for lib, npth in selectImports(pth, xtrapath):
if seen.get(lib.upper(), 0) or seen.get(npth.upper(), 0):
continue
seen[npth.upper()] = 1
lTOC.append((lib, npth, 'BINARY'))
return lTOC | python | def Dependencies(lTOC, xtrapath=None, manifest=None):
"""
Expand LTOC to include all the closure of binary dependencies.
LTOC is a logical table of contents, ie, a seq of tuples (name, path).
Return LTOC expanded by all the binary dependencies of the entries
in LTOC, except those listed in the module global EXCLUDES
manifest should be a winmanifest.Manifest instance on Windows, so
that all dependent assemblies can be added
"""
for nm, pth, typ in lTOC:
if seen.get(nm.upper(), 0):
continue
logger.info("Analyzing %s", pth)
seen[nm.upper()] = 1
if is_win:
for ftocnm, fn in selectAssemblies(pth, manifest):
lTOC.append((ftocnm, fn, 'BINARY'))
for lib, npth in selectImports(pth, xtrapath):
if seen.get(lib.upper(), 0) or seen.get(npth.upper(), 0):
continue
seen[npth.upper()] = 1
lTOC.append((lib, npth, 'BINARY'))
return lTOC | [
"def",
"Dependencies",
"(",
"lTOC",
",",
"xtrapath",
"=",
"None",
",",
"manifest",
"=",
"None",
")",
":",
"for",
"nm",
",",
"pth",
",",
"typ",
"in",
"lTOC",
":",
"if",
"seen",
".",
"get",
"(",
"nm",
".",
"upper",
"(",
")",
",",
"0",
")",
":",
... | Expand LTOC to include all the closure of binary dependencies.
LTOC is a logical table of contents, ie, a seq of tuples (name, path).
Return LTOC expanded by all the binary dependencies of the entries
in LTOC, except those listed in the module global EXCLUDES
manifest should be a winmanifest.Manifest instance on Windows, so
that all dependent assemblies can be added | [
"Expand",
"LTOC",
"to",
"include",
"all",
"the",
"closure",
"of",
"binary",
"dependencies",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py#L107-L132 | train | 32,139 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py | pkg_resouces_get_default_cache | def pkg_resouces_get_default_cache():
"""
Determine the default cache location
This returns the ``PYTHON_EGG_CACHE`` environment variable, if set.
Otherwise, on Windows, it returns a 'Python-Eggs' subdirectory of the
'Application Data' directory. On all other systems, it's '~/.python-eggs'.
"""
# This function borrowed from setuptools/pkg_resources
egg_cache = compat.getenv('PYTHON_EGG_CACHE')
if egg_cache is not None:
return egg_cache
if os.name != 'nt':
return os.path.expanduser('~/.python-eggs')
app_data = 'Application Data' # XXX this may be locale-specific!
app_homes = [
(('APPDATA',), None), # best option, should be locale-safe
(('USERPROFILE',), app_data),
(('HOMEDRIVE', 'HOMEPATH'), app_data),
(('HOMEPATH',), app_data),
(('HOME',), None),
(('WINDIR',), app_data), # 95/98/ME
]
for keys, subdir in app_homes:
dirname = ''
for key in keys:
if key in os.environ:
dirname = os.path.join(dirname, compat.getenv(key))
else:
break
else:
if subdir:
dirname = os.path.join(dirname, subdir)
return os.path.join(dirname, 'Python-Eggs')
else:
raise RuntimeError(
"Please set the PYTHON_EGG_CACHE enviroment variable"
) | python | def pkg_resouces_get_default_cache():
"""
Determine the default cache location
This returns the ``PYTHON_EGG_CACHE`` environment variable, if set.
Otherwise, on Windows, it returns a 'Python-Eggs' subdirectory of the
'Application Data' directory. On all other systems, it's '~/.python-eggs'.
"""
# This function borrowed from setuptools/pkg_resources
egg_cache = compat.getenv('PYTHON_EGG_CACHE')
if egg_cache is not None:
return egg_cache
if os.name != 'nt':
return os.path.expanduser('~/.python-eggs')
app_data = 'Application Data' # XXX this may be locale-specific!
app_homes = [
(('APPDATA',), None), # best option, should be locale-safe
(('USERPROFILE',), app_data),
(('HOMEDRIVE', 'HOMEPATH'), app_data),
(('HOMEPATH',), app_data),
(('HOME',), None),
(('WINDIR',), app_data), # 95/98/ME
]
for keys, subdir in app_homes:
dirname = ''
for key in keys:
if key in os.environ:
dirname = os.path.join(dirname, compat.getenv(key))
else:
break
else:
if subdir:
dirname = os.path.join(dirname, subdir)
return os.path.join(dirname, 'Python-Eggs')
else:
raise RuntimeError(
"Please set the PYTHON_EGG_CACHE enviroment variable"
) | [
"def",
"pkg_resouces_get_default_cache",
"(",
")",
":",
"# This function borrowed from setuptools/pkg_resources",
"egg_cache",
"=",
"compat",
".",
"getenv",
"(",
"'PYTHON_EGG_CACHE'",
")",
"if",
"egg_cache",
"is",
"not",
"None",
":",
"return",
"egg_cache",
"if",
"os",
... | Determine the default cache location
This returns the ``PYTHON_EGG_CACHE`` environment variable, if set.
Otherwise, on Windows, it returns a 'Python-Eggs' subdirectory of the
'Application Data' directory. On all other systems, it's '~/.python-eggs'. | [
"Determine",
"the",
"default",
"cache",
"location"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py#L135-L175 | train | 32,140 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py | getAssemblies | def getAssemblies(pth):
"""
Return the dependent assemblies of a binary.
"""
if not os.path.isfile(pth):
pth = check_extract_from_egg(pth)[0][0]
if pth.lower().endswith(".manifest"):
return []
# check for manifest file
manifestnm = pth + ".manifest"
if os.path.isfile(manifestnm):
fd = open(manifestnm, "rb")
res = {RT_MANIFEST: {1: {0: fd.read()}}}
fd.close()
elif not winresource:
# resource access unavailable (needs pywin32)
return []
else:
# check the binary for embedded manifest
try:
res = GetManifestResources(pth)
except winresource.pywintypes.error, exc:
if exc.args[0] == winresource.ERROR_BAD_EXE_FORMAT:
logger.info('Cannot get manifest resource from non-PE '
'file %s', pth)
return []
raise
rv = []
if RT_MANIFEST in res and len(res[RT_MANIFEST]):
for name in res[RT_MANIFEST]:
for language in res[RT_MANIFEST][name]:
# check the manifest for dependent assemblies
try:
manifest = Manifest()
manifest.filename = ":".join([pth, str(RT_MANIFEST),
str(name), str(language)])
manifest.parse_string(res[RT_MANIFEST][name][language],
False)
except Exception, exc:
logger.error("Can not parse manifest resource %s, %s"
"from %s", name, language, pth)
logger.exception(exc)
else:
if manifest.dependentAssemblies:
logger.debug("Dependent assemblies of %s:", pth)
logger.debug(", ".join([assembly.getid()
for assembly in
manifest.dependentAssemblies]))
rv.extend(manifest.dependentAssemblies)
return rv | python | def getAssemblies(pth):
"""
Return the dependent assemblies of a binary.
"""
if not os.path.isfile(pth):
pth = check_extract_from_egg(pth)[0][0]
if pth.lower().endswith(".manifest"):
return []
# check for manifest file
manifestnm = pth + ".manifest"
if os.path.isfile(manifestnm):
fd = open(manifestnm, "rb")
res = {RT_MANIFEST: {1: {0: fd.read()}}}
fd.close()
elif not winresource:
# resource access unavailable (needs pywin32)
return []
else:
# check the binary for embedded manifest
try:
res = GetManifestResources(pth)
except winresource.pywintypes.error, exc:
if exc.args[0] == winresource.ERROR_BAD_EXE_FORMAT:
logger.info('Cannot get manifest resource from non-PE '
'file %s', pth)
return []
raise
rv = []
if RT_MANIFEST in res and len(res[RT_MANIFEST]):
for name in res[RT_MANIFEST]:
for language in res[RT_MANIFEST][name]:
# check the manifest for dependent assemblies
try:
manifest = Manifest()
manifest.filename = ":".join([pth, str(RT_MANIFEST),
str(name), str(language)])
manifest.parse_string(res[RT_MANIFEST][name][language],
False)
except Exception, exc:
logger.error("Can not parse manifest resource %s, %s"
"from %s", name, language, pth)
logger.exception(exc)
else:
if manifest.dependentAssemblies:
logger.debug("Dependent assemblies of %s:", pth)
logger.debug(", ".join([assembly.getid()
for assembly in
manifest.dependentAssemblies]))
rv.extend(manifest.dependentAssemblies)
return rv | [
"def",
"getAssemblies",
"(",
"pth",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"pth",
")",
":",
"pth",
"=",
"check_extract_from_egg",
"(",
"pth",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"if",
"pth",
".",
"lower",
"(",
")",
".",
"e... | Return the dependent assemblies of a binary. | [
"Return",
"the",
"dependent",
"assemblies",
"of",
"a",
"binary",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py#L231-L280 | train | 32,141 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py | selectAssemblies | def selectAssemblies(pth, manifest=None):
"""
Return a binary's dependent assemblies files that should be included.
Return a list of pairs (name, fullpath)
"""
rv = []
if not os.path.isfile(pth):
pth = check_extract_from_egg(pth)[0][0]
if manifest:
_depNames = set([dep.name for dep in manifest.dependentAssemblies])
for assembly in getAssemblies(pth):
if seen.get(assembly.getid().upper(), 0):
continue
if manifest and not assembly.name in _depNames:
# Add assembly as dependency to our final output exe's manifest
logger.info("Adding %s to dependent assemblies "
"of final executable", assembly.name)
manifest.dependentAssemblies.append(assembly)
_depNames.add(assembly.name)
if not dylib.include_library(assembly.name):
logger.debug("Skipping assembly %s", assembly.getid())
continue
if assembly.optional:
logger.debug("Skipping optional assembly %s", assembly.getid())
continue
files = assembly.find_files()
if files:
seen[assembly.getid().upper()] = 1
for fn in files:
fname, fext = os.path.splitext(fn)
if fext.lower() == ".manifest":
nm = assembly.name + fext
else:
nm = os.path.basename(fn)
ftocnm = nm
if assembly.language not in (None, "", "*", "neutral"):
ftocnm = os.path.join(assembly.getlanguage(),
ftocnm)
nm, ftocnm, fn = [item.encode(sys.getfilesystemencoding())
for item in
(nm,
ftocnm,
fn)]
if not seen.get(fn.upper(), 0):
logger.debug("Adding %s", ftocnm)
seen[nm.upper()] = 1
seen[fn.upper()] = 1
rv.append((ftocnm, fn))
else:
#logger.info("skipping %s part of assembly %s dependency of %s",
# ftocnm, assembly.name, pth)
pass
else:
logger.error("Assembly %s not found", assembly.getid())
return rv | python | def selectAssemblies(pth, manifest=None):
"""
Return a binary's dependent assemblies files that should be included.
Return a list of pairs (name, fullpath)
"""
rv = []
if not os.path.isfile(pth):
pth = check_extract_from_egg(pth)[0][0]
if manifest:
_depNames = set([dep.name for dep in manifest.dependentAssemblies])
for assembly in getAssemblies(pth):
if seen.get(assembly.getid().upper(), 0):
continue
if manifest and not assembly.name in _depNames:
# Add assembly as dependency to our final output exe's manifest
logger.info("Adding %s to dependent assemblies "
"of final executable", assembly.name)
manifest.dependentAssemblies.append(assembly)
_depNames.add(assembly.name)
if not dylib.include_library(assembly.name):
logger.debug("Skipping assembly %s", assembly.getid())
continue
if assembly.optional:
logger.debug("Skipping optional assembly %s", assembly.getid())
continue
files = assembly.find_files()
if files:
seen[assembly.getid().upper()] = 1
for fn in files:
fname, fext = os.path.splitext(fn)
if fext.lower() == ".manifest":
nm = assembly.name + fext
else:
nm = os.path.basename(fn)
ftocnm = nm
if assembly.language not in (None, "", "*", "neutral"):
ftocnm = os.path.join(assembly.getlanguage(),
ftocnm)
nm, ftocnm, fn = [item.encode(sys.getfilesystemencoding())
for item in
(nm,
ftocnm,
fn)]
if not seen.get(fn.upper(), 0):
logger.debug("Adding %s", ftocnm)
seen[nm.upper()] = 1
seen[fn.upper()] = 1
rv.append((ftocnm, fn))
else:
#logger.info("skipping %s part of assembly %s dependency of %s",
# ftocnm, assembly.name, pth)
pass
else:
logger.error("Assembly %s not found", assembly.getid())
return rv | [
"def",
"selectAssemblies",
"(",
"pth",
",",
"manifest",
"=",
"None",
")",
":",
"rv",
"=",
"[",
"]",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"pth",
")",
":",
"pth",
"=",
"check_extract_from_egg",
"(",
"pth",
")",
"[",
"0",
"]",
"[",
"0... | Return a binary's dependent assemblies files that should be included.
Return a list of pairs (name, fullpath) | [
"Return",
"a",
"binary",
"s",
"dependent",
"assemblies",
"files",
"that",
"should",
"be",
"included",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py#L283-L338 | train | 32,142 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py | selectImports | def selectImports(pth, xtrapath=None):
"""
Return the dependencies of a binary that should be included.
Return a list of pairs (name, fullpath)
"""
rv = []
if xtrapath is None:
xtrapath = [os.path.dirname(pth)]
else:
assert isinstance(xtrapath, list)
xtrapath = [os.path.dirname(pth)] + xtrapath # make a copy
dlls = getImports(pth)
for lib in dlls:
if seen.get(lib.upper(), 0):
continue
if not is_win and not is_cygwin:
# all other platforms
npth = lib
dir, lib = os.path.split(lib)
else:
# plain win case
npth = getfullnameof(lib, xtrapath)
# now npth is a candidate lib if found
# check again for excludes but with regex FIXME: split the list
if npth:
candidatelib = npth
else:
candidatelib = lib
if not dylib.include_library(candidatelib):
if (candidatelib.find('libpython') < 0 and
candidatelib.find('Python.framework') < 0):
# skip libs not containing (libpython or Python.framework)
if not seen.get(npth.upper(), 0):
logger.debug("Skipping %s dependency of %s",
lib, os.path.basename(pth))
continue
else:
pass
if npth:
if not seen.get(npth.upper(), 0):
logger.debug("Adding %s dependency of %s",
lib, os.path.basename(pth))
rv.append((lib, npth))
else:
logger.error("lib not found: %s dependency of %s", lib, pth)
return rv | python | def selectImports(pth, xtrapath=None):
"""
Return the dependencies of a binary that should be included.
Return a list of pairs (name, fullpath)
"""
rv = []
if xtrapath is None:
xtrapath = [os.path.dirname(pth)]
else:
assert isinstance(xtrapath, list)
xtrapath = [os.path.dirname(pth)] + xtrapath # make a copy
dlls = getImports(pth)
for lib in dlls:
if seen.get(lib.upper(), 0):
continue
if not is_win and not is_cygwin:
# all other platforms
npth = lib
dir, lib = os.path.split(lib)
else:
# plain win case
npth = getfullnameof(lib, xtrapath)
# now npth is a candidate lib if found
# check again for excludes but with regex FIXME: split the list
if npth:
candidatelib = npth
else:
candidatelib = lib
if not dylib.include_library(candidatelib):
if (candidatelib.find('libpython') < 0 and
candidatelib.find('Python.framework') < 0):
# skip libs not containing (libpython or Python.framework)
if not seen.get(npth.upper(), 0):
logger.debug("Skipping %s dependency of %s",
lib, os.path.basename(pth))
continue
else:
pass
if npth:
if not seen.get(npth.upper(), 0):
logger.debug("Adding %s dependency of %s",
lib, os.path.basename(pth))
rv.append((lib, npth))
else:
logger.error("lib not found: %s dependency of %s", lib, pth)
return rv | [
"def",
"selectImports",
"(",
"pth",
",",
"xtrapath",
"=",
"None",
")",
":",
"rv",
"=",
"[",
"]",
"if",
"xtrapath",
"is",
"None",
":",
"xtrapath",
"=",
"[",
"os",
".",
"path",
".",
"dirname",
"(",
"pth",
")",
"]",
"else",
":",
"assert",
"isinstance"... | Return the dependencies of a binary that should be included.
Return a list of pairs (name, fullpath) | [
"Return",
"the",
"dependencies",
"of",
"a",
"binary",
"that",
"should",
"be",
"included",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py#L341-L391 | train | 32,143 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py | getImports | def getImports(pth):
"""Forwards to the correct getImports implementation for the platform.
"""
if not os.path.isfile(pth):
pth = check_extract_from_egg(pth)[0][0]
if is_win or is_cygwin:
if pth.lower().endswith(".manifest"):
return []
try:
return _getImports_pe(pth)
except Exception, exception:
# Assemblies can pull in files which aren't necessarily PE,
# but are still needed by the assembly. Any additional binary
# dependencies should already have been handled by
# selectAssemblies in that case, so just warn, return an empty
# list and continue.
if logger.isEnabledFor(logging.WARN):
# logg excaption only if level >= warn
logger.warn('Can not get binary dependencies for file: %s', pth)
logger.exception(exception)
return []
elif is_darwin:
return _getImports_macholib(pth)
else:
return _getImports_ldd(pth) | python | def getImports(pth):
"""Forwards to the correct getImports implementation for the platform.
"""
if not os.path.isfile(pth):
pth = check_extract_from_egg(pth)[0][0]
if is_win or is_cygwin:
if pth.lower().endswith(".manifest"):
return []
try:
return _getImports_pe(pth)
except Exception, exception:
# Assemblies can pull in files which aren't necessarily PE,
# but are still needed by the assembly. Any additional binary
# dependencies should already have been handled by
# selectAssemblies in that case, so just warn, return an empty
# list and continue.
if logger.isEnabledFor(logging.WARN):
# logg excaption only if level >= warn
logger.warn('Can not get binary dependencies for file: %s', pth)
logger.exception(exception)
return []
elif is_darwin:
return _getImports_macholib(pth)
else:
return _getImports_ldd(pth) | [
"def",
"getImports",
"(",
"pth",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"pth",
")",
":",
"pth",
"=",
"check_extract_from_egg",
"(",
"pth",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"if",
"is_win",
"or",
"is_cygwin",
":",
"if",
"pt... | Forwards to the correct getImports implementation for the platform. | [
"Forwards",
"to",
"the",
"correct",
"getImports",
"implementation",
"for",
"the",
"platform",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py#L472-L496 | train | 32,144 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py | findLibrary | def findLibrary(name):
"""
Look for a library in the system.
Emulate the algorithm used by dlopen.
`name`must include the prefix, e.g. ``libpython2.4.so``
"""
assert is_unix, "Current implementation for Unix only (Linux, Solaris, AIX)"
lib = None
# Look in the LD_LIBRARY_PATH
lp = compat.getenv('LD_LIBRARY_PATH', '')
for path in lp.split(os.pathsep):
libs = glob(os.path.join(path, name + '*'))
if libs:
lib = libs[0]
break
# Look in /etc/ld.so.cache
if lib is None:
expr = r'/[^\(\)\s]*%s\.[^\(\)\s]*' % re.escape(name)
m = re.search(expr, compat.exec_command('/sbin/ldconfig', '-p'))
if m:
lib = m.group(0)
# Look in the known safe paths
if lib is None:
paths = ['/lib', '/usr/lib']
if is_aix:
paths.append('/opt/freeware/lib')
for path in paths:
libs = glob(os.path.join(path, name + '*'))
if libs:
lib = libs[0]
break
# give up :(
if lib is None:
return None
# Resolve the file name into the soname
dir, file = os.path.split(lib)
return os.path.join(dir, getSoname(lib)) | python | def findLibrary(name):
"""
Look for a library in the system.
Emulate the algorithm used by dlopen.
`name`must include the prefix, e.g. ``libpython2.4.so``
"""
assert is_unix, "Current implementation for Unix only (Linux, Solaris, AIX)"
lib = None
# Look in the LD_LIBRARY_PATH
lp = compat.getenv('LD_LIBRARY_PATH', '')
for path in lp.split(os.pathsep):
libs = glob(os.path.join(path, name + '*'))
if libs:
lib = libs[0]
break
# Look in /etc/ld.so.cache
if lib is None:
expr = r'/[^\(\)\s]*%s\.[^\(\)\s]*' % re.escape(name)
m = re.search(expr, compat.exec_command('/sbin/ldconfig', '-p'))
if m:
lib = m.group(0)
# Look in the known safe paths
if lib is None:
paths = ['/lib', '/usr/lib']
if is_aix:
paths.append('/opt/freeware/lib')
for path in paths:
libs = glob(os.path.join(path, name + '*'))
if libs:
lib = libs[0]
break
# give up :(
if lib is None:
return None
# Resolve the file name into the soname
dir, file = os.path.split(lib)
return os.path.join(dir, getSoname(lib)) | [
"def",
"findLibrary",
"(",
"name",
")",
":",
"assert",
"is_unix",
",",
"\"Current implementation for Unix only (Linux, Solaris, AIX)\"",
"lib",
"=",
"None",
"# Look in the LD_LIBRARY_PATH",
"lp",
"=",
"compat",
".",
"getenv",
"(",
"'LD_LIBRARY_PATH'",
",",
"''",
")",
... | Look for a library in the system.
Emulate the algorithm used by dlopen.
`name`must include the prefix, e.g. ``libpython2.4.so`` | [
"Look",
"for",
"a",
"library",
"in",
"the",
"system",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py#L499-L542 | train | 32,145 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py | getSoname | def getSoname(filename):
"""
Return the soname of a library.
"""
cmd = ["objdump", "-p", "-j", ".dynamic", filename]
m = re.search(r'\s+SONAME\s+([^\s]+)', compat.exec_command(*cmd))
if m:
return m.group(1) | python | def getSoname(filename):
"""
Return the soname of a library.
"""
cmd = ["objdump", "-p", "-j", ".dynamic", filename]
m = re.search(r'\s+SONAME\s+([^\s]+)', compat.exec_command(*cmd))
if m:
return m.group(1) | [
"def",
"getSoname",
"(",
"filename",
")",
":",
"cmd",
"=",
"[",
"\"objdump\"",
",",
"\"-p\"",
",",
"\"-j\"",
",",
"\".dynamic\"",
",",
"filename",
"]",
"m",
"=",
"re",
".",
"search",
"(",
"r'\\s+SONAME\\s+([^\\s]+)'",
",",
"compat",
".",
"exec_command",
"(... | Return the soname of a library. | [
"Return",
"the",
"soname",
"of",
"a",
"library",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/bindepend.py#L545-L552 | train | 32,146 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/loader/iu.py | _os_bootstrap | def _os_bootstrap():
"""
Set up 'os' module replacement functions for use during import bootstrap.
"""
global _os_stat, _os_getcwd, _os_environ, _os_listdir
global _os_path_join, _os_path_dirname, _os_path_basename
global _os_sep
names = sys.builtin_module_names
join = dirname = environ = listdir = basename = None
mindirlen = 0
# Only 'posix' and 'nt' os specific modules are supported.
# 'dos', 'os2' and 'mac' (MacOS 9) are not supported.
if 'posix' in names:
from posix import stat, getcwd, environ, listdir
sep = _os_sep = '/'
mindirlen = 1
elif 'nt' in names:
from nt import stat, getcwd, environ, listdir
sep = _os_sep = '\\'
mindirlen = 3
else:
raise ImportError('no os specific module found')
if join is None:
def join(a, b, sep=sep):
if a == '':
return b
lastchar = a[-1:]
if lastchar == '/' or lastchar == sep:
return a + b
return a + sep + b
if dirname is None:
def dirname(a, sep=sep, mindirlen=mindirlen):
for i in range(len(a) - 1, -1, -1):
c = a[i]
if c == '/' or c == sep:
if i < mindirlen:
return a[:i + 1]
return a[:i]
return ''
if basename is None:
def basename(p):
i = p.rfind(sep)
if i == -1:
return p
else:
return p[i + len(sep):]
def _listdir(dir, cache={}):
# since this function is only used by caseOk, it's fine to cache the
# results and avoid reading the whole contents of a directory each time
# we just want to check the case of a filename.
if not dir in cache:
cache[dir] = listdir(dir)
return cache[dir]
_os_stat = stat
_os_getcwd = getcwd
_os_path_join = join
_os_path_dirname = dirname
_os_environ = environ
_os_listdir = _listdir
_os_path_basename = basename | python | def _os_bootstrap():
"""
Set up 'os' module replacement functions for use during import bootstrap.
"""
global _os_stat, _os_getcwd, _os_environ, _os_listdir
global _os_path_join, _os_path_dirname, _os_path_basename
global _os_sep
names = sys.builtin_module_names
join = dirname = environ = listdir = basename = None
mindirlen = 0
# Only 'posix' and 'nt' os specific modules are supported.
# 'dos', 'os2' and 'mac' (MacOS 9) are not supported.
if 'posix' in names:
from posix import stat, getcwd, environ, listdir
sep = _os_sep = '/'
mindirlen = 1
elif 'nt' in names:
from nt import stat, getcwd, environ, listdir
sep = _os_sep = '\\'
mindirlen = 3
else:
raise ImportError('no os specific module found')
if join is None:
def join(a, b, sep=sep):
if a == '':
return b
lastchar = a[-1:]
if lastchar == '/' or lastchar == sep:
return a + b
return a + sep + b
if dirname is None:
def dirname(a, sep=sep, mindirlen=mindirlen):
for i in range(len(a) - 1, -1, -1):
c = a[i]
if c == '/' or c == sep:
if i < mindirlen:
return a[:i + 1]
return a[:i]
return ''
if basename is None:
def basename(p):
i = p.rfind(sep)
if i == -1:
return p
else:
return p[i + len(sep):]
def _listdir(dir, cache={}):
# since this function is only used by caseOk, it's fine to cache the
# results and avoid reading the whole contents of a directory each time
# we just want to check the case of a filename.
if not dir in cache:
cache[dir] = listdir(dir)
return cache[dir]
_os_stat = stat
_os_getcwd = getcwd
_os_path_join = join
_os_path_dirname = dirname
_os_environ = environ
_os_listdir = _listdir
_os_path_basename = basename | [
"def",
"_os_bootstrap",
"(",
")",
":",
"global",
"_os_stat",
",",
"_os_getcwd",
",",
"_os_environ",
",",
"_os_listdir",
"global",
"_os_path_join",
",",
"_os_path_dirname",
",",
"_os_path_basename",
"global",
"_os_sep",
"names",
"=",
"sys",
".",
"builtin_module_names... | Set up 'os' module replacement functions for use during import bootstrap. | [
"Set",
"up",
"os",
"module",
"replacement",
"functions",
"for",
"use",
"during",
"import",
"bootstrap",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/loader/iu.py#L646-L713 | train | 32,147 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/mf.py | scan_code_for_ctypes | def scan_code_for_ctypes(co, instrs, i):
"""Detects ctypes dependencies, using reasonable heuristics that should
cover most common ctypes usages; returns a tuple of two lists, one
containing names of binaries detected as dependencies, the other containing
warnings.
"""
def _libFromConst(i):
"""Extracts library name from an expected LOAD_CONST instruction and
appends it to local binaries list.
"""
op, oparg, conditional, curline = instrs[i]
if op == LOAD_CONST:
soname = co.co_consts[oparg]
b.append(soname)
b = []
op, oparg, conditional, curline = instrs[i]
if op in (LOAD_GLOBAL, LOAD_NAME):
name = co.co_names[oparg]
if name in ("CDLL", "WinDLL"):
# Guesses ctypes imports of this type: CDLL("library.so")
# LOAD_GLOBAL 0 (CDLL) <--- we "are" here right now
# LOAD_CONST 1 ('library.so')
_libFromConst(i+1)
elif name == "ctypes":
# Guesses ctypes imports of this type: ctypes.DLL("library.so")
# LOAD_GLOBAL 0 (ctypes) <--- we "are" here right now
# LOAD_ATTR 1 (CDLL)
# LOAD_CONST 1 ('library.so')
op2, oparg2, conditional2, curline2 = instrs[i+1]
if op2 == LOAD_ATTR:
if co.co_names[oparg2] in ("CDLL", "WinDLL"):
# Fetch next, and finally get the library name
_libFromConst(i+2)
elif name in ("cdll", "windll"):
# Guesses ctypes imports of these types:
# * cdll.library (only valid on Windows)
# LOAD_GLOBAL 0 (cdll) <--- we "are" here right now
# LOAD_ATTR 1 (library)
# * cdll.LoadLibrary("library.so")
# LOAD_GLOBAL 0 (cdll) <--- we "are" here right now
# LOAD_ATTR 1 (LoadLibrary)
# LOAD_CONST 1 ('library.so')
op2, oparg2, conditional2, curline2 = instrs[i+1]
if op2 == LOAD_ATTR:
if co.co_names[oparg2] != "LoadLibrary":
# First type
soname = co.co_names[oparg2] + ".dll"
b.append(soname)
else:
# Second type, needs to fetch one more instruction
_libFromConst(i+2)
# If any of the libraries has been requested with anything different from
# the bare filename, drop that entry and warn the user - pyinstaller would
# need to patch the compiled pyc file to make it work correctly!
w = []
for bin in list(b):
if bin != os.path.basename(bin):
b.remove(bin)
w.append("W: ignoring %s - ctypes imports only supported using bare filenames" % (bin,))
return b, w | python | def scan_code_for_ctypes(co, instrs, i):
"""Detects ctypes dependencies, using reasonable heuristics that should
cover most common ctypes usages; returns a tuple of two lists, one
containing names of binaries detected as dependencies, the other containing
warnings.
"""
def _libFromConst(i):
"""Extracts library name from an expected LOAD_CONST instruction and
appends it to local binaries list.
"""
op, oparg, conditional, curline = instrs[i]
if op == LOAD_CONST:
soname = co.co_consts[oparg]
b.append(soname)
b = []
op, oparg, conditional, curline = instrs[i]
if op in (LOAD_GLOBAL, LOAD_NAME):
name = co.co_names[oparg]
if name in ("CDLL", "WinDLL"):
# Guesses ctypes imports of this type: CDLL("library.so")
# LOAD_GLOBAL 0 (CDLL) <--- we "are" here right now
# LOAD_CONST 1 ('library.so')
_libFromConst(i+1)
elif name == "ctypes":
# Guesses ctypes imports of this type: ctypes.DLL("library.so")
# LOAD_GLOBAL 0 (ctypes) <--- we "are" here right now
# LOAD_ATTR 1 (CDLL)
# LOAD_CONST 1 ('library.so')
op2, oparg2, conditional2, curline2 = instrs[i+1]
if op2 == LOAD_ATTR:
if co.co_names[oparg2] in ("CDLL", "WinDLL"):
# Fetch next, and finally get the library name
_libFromConst(i+2)
elif name in ("cdll", "windll"):
# Guesses ctypes imports of these types:
# * cdll.library (only valid on Windows)
# LOAD_GLOBAL 0 (cdll) <--- we "are" here right now
# LOAD_ATTR 1 (library)
# * cdll.LoadLibrary("library.so")
# LOAD_GLOBAL 0 (cdll) <--- we "are" here right now
# LOAD_ATTR 1 (LoadLibrary)
# LOAD_CONST 1 ('library.so')
op2, oparg2, conditional2, curline2 = instrs[i+1]
if op2 == LOAD_ATTR:
if co.co_names[oparg2] != "LoadLibrary":
# First type
soname = co.co_names[oparg2] + ".dll"
b.append(soname)
else:
# Second type, needs to fetch one more instruction
_libFromConst(i+2)
# If any of the libraries has been requested with anything different from
# the bare filename, drop that entry and warn the user - pyinstaller would
# need to patch the compiled pyc file to make it work correctly!
w = []
for bin in list(b):
if bin != os.path.basename(bin):
b.remove(bin)
w.append("W: ignoring %s - ctypes imports only supported using bare filenames" % (bin,))
return b, w | [
"def",
"scan_code_for_ctypes",
"(",
"co",
",",
"instrs",
",",
"i",
")",
":",
"def",
"_libFromConst",
"(",
"i",
")",
":",
"\"\"\"Extracts library name from an expected LOAD_CONST instruction and\n appends it to local binaries list.\n \"\"\"",
"op",
",",
"oparg",
... | Detects ctypes dependencies, using reasonable heuristics that should
cover most common ctypes usages; returns a tuple of two lists, one
containing names of binaries detected as dependencies, the other containing
warnings. | [
"Detects",
"ctypes",
"dependencies",
"using",
"reasonable",
"heuristics",
"that",
"should",
"cover",
"most",
"common",
"ctypes",
"usages",
";",
"returns",
"a",
"tuple",
"of",
"two",
"lists",
"one",
"containing",
"names",
"of",
"binaries",
"detected",
"as",
"depe... | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/mf.py#L989-L1067 | train | 32,148 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/mf.py | _resolveCtypesImports | def _resolveCtypesImports(cbinaries):
"""Completes ctypes BINARY entries for modules with their full path.
"""
if is_unix:
envvar = "LD_LIBRARY_PATH"
elif is_darwin:
envvar = "DYLD_LIBRARY_PATH"
else:
envvar = "PATH"
def _setPaths():
path = os.pathsep.join(PyInstaller.__pathex__)
old = compat.getenv(envvar)
if old is not None:
path = os.pathsep.join((path, old))
compat.setenv(envvar, path)
return old
def _restorePaths(old):
if old is None:
compat.unsetenv(envvar)
else:
compat.setenv(envvar, old)
ret = []
# Try to locate the shared library on disk. This is done by
# executing ctypes.utile.find_library prepending ImportTracker's
# local paths to library search paths, then replaces original values.
old = _setPaths()
for cbin in cbinaries:
# Ignore annoying warnings like:
# 'W: library kernel32.dll required via ctypes not found'
# 'W: library coredll.dll required via ctypes not found'
if cbin in ['coredll.dll', 'kernel32.dll']:
continue
ext = os.path.splitext(cbin)[1]
# On Windows, only .dll files can be loaded.
if os.name == "nt" and ext.lower() in [".so", ".dylib"]:
continue
cpath = find_library(os.path.splitext(cbin)[0])
if is_unix:
# CAVEAT: find_library() is not the correct function. Ctype's
# documentation says that it is meant to resolve only the filename
# (as a *compiler* does) not the full path. Anyway, it works well
# enough on Windows and Mac. On Linux, we need to implement
# more code to find out the full path.
if cpath is None:
cpath = cbin
# "man ld.so" says that we should first search LD_LIBRARY_PATH
# and then the ldcache
for d in compat.getenv(envvar, '').split(os.pathsep):
if os.path.isfile(os.path.join(d, cpath)):
cpath = os.path.join(d, cpath)
break
else:
text = compat.exec_command("/sbin/ldconfig", "-p")
for L in text.strip().splitlines():
if cpath in L:
cpath = L.split("=>", 1)[1].strip()
assert os.path.isfile(cpath)
break
else:
cpath = None
if cpath is None:
logger.warn("library %s required via ctypes not found", cbin)
else:
ret.append((cbin, cpath, "BINARY"))
_restorePaths(old)
return ret | python | def _resolveCtypesImports(cbinaries):
"""Completes ctypes BINARY entries for modules with their full path.
"""
if is_unix:
envvar = "LD_LIBRARY_PATH"
elif is_darwin:
envvar = "DYLD_LIBRARY_PATH"
else:
envvar = "PATH"
def _setPaths():
path = os.pathsep.join(PyInstaller.__pathex__)
old = compat.getenv(envvar)
if old is not None:
path = os.pathsep.join((path, old))
compat.setenv(envvar, path)
return old
def _restorePaths(old):
if old is None:
compat.unsetenv(envvar)
else:
compat.setenv(envvar, old)
ret = []
# Try to locate the shared library on disk. This is done by
# executing ctypes.utile.find_library prepending ImportTracker's
# local paths to library search paths, then replaces original values.
old = _setPaths()
for cbin in cbinaries:
# Ignore annoying warnings like:
# 'W: library kernel32.dll required via ctypes not found'
# 'W: library coredll.dll required via ctypes not found'
if cbin in ['coredll.dll', 'kernel32.dll']:
continue
ext = os.path.splitext(cbin)[1]
# On Windows, only .dll files can be loaded.
if os.name == "nt" and ext.lower() in [".so", ".dylib"]:
continue
cpath = find_library(os.path.splitext(cbin)[0])
if is_unix:
# CAVEAT: find_library() is not the correct function. Ctype's
# documentation says that it is meant to resolve only the filename
# (as a *compiler* does) not the full path. Anyway, it works well
# enough on Windows and Mac. On Linux, we need to implement
# more code to find out the full path.
if cpath is None:
cpath = cbin
# "man ld.so" says that we should first search LD_LIBRARY_PATH
# and then the ldcache
for d in compat.getenv(envvar, '').split(os.pathsep):
if os.path.isfile(os.path.join(d, cpath)):
cpath = os.path.join(d, cpath)
break
else:
text = compat.exec_command("/sbin/ldconfig", "-p")
for L in text.strip().splitlines():
if cpath in L:
cpath = L.split("=>", 1)[1].strip()
assert os.path.isfile(cpath)
break
else:
cpath = None
if cpath is None:
logger.warn("library %s required via ctypes not found", cbin)
else:
ret.append((cbin, cpath, "BINARY"))
_restorePaths(old)
return ret | [
"def",
"_resolveCtypesImports",
"(",
"cbinaries",
")",
":",
"if",
"is_unix",
":",
"envvar",
"=",
"\"LD_LIBRARY_PATH\"",
"elif",
"is_darwin",
":",
"envvar",
"=",
"\"DYLD_LIBRARY_PATH\"",
"else",
":",
"envvar",
"=",
"\"PATH\"",
"def",
"_setPaths",
"(",
")",
":",
... | Completes ctypes BINARY entries for modules with their full path. | [
"Completes",
"ctypes",
"BINARY",
"entries",
"for",
"modules",
"with",
"their",
"full",
"path",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/mf.py#L1070-L1139 | train | 32,149 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/GraphStat.py | degree_dist | def degree_dist(graph, limits=(0,0), bin_num=10, mode='out'):
'''
Computes the degree distribution for a graph.
Returns a list of tuples where the first element of the tuple is the center of the bin
representing a range of degrees and the second element of the tuple are the number of nodes
with the degree falling in the range.
Example::
....
'''
deg = []
if mode == 'inc':
get_deg = graph.inc_degree
else:
get_deg = graph.out_degree
for node in graph:
deg.append( get_deg(node) )
if not deg:
return []
results = _binning(values=deg, limits=limits, bin_num=bin_num)
return results | python | def degree_dist(graph, limits=(0,0), bin_num=10, mode='out'):
'''
Computes the degree distribution for a graph.
Returns a list of tuples where the first element of the tuple is the center of the bin
representing a range of degrees and the second element of the tuple are the number of nodes
with the degree falling in the range.
Example::
....
'''
deg = []
if mode == 'inc':
get_deg = graph.inc_degree
else:
get_deg = graph.out_degree
for node in graph:
deg.append( get_deg(node) )
if not deg:
return []
results = _binning(values=deg, limits=limits, bin_num=bin_num)
return results | [
"def",
"degree_dist",
"(",
"graph",
",",
"limits",
"=",
"(",
"0",
",",
"0",
")",
",",
"bin_num",
"=",
"10",
",",
"mode",
"=",
"'out'",
")",
":",
"deg",
"=",
"[",
"]",
"if",
"mode",
"==",
"'inc'",
":",
"get_deg",
"=",
"graph",
".",
"inc_degree",
... | Computes the degree distribution for a graph.
Returns a list of tuples where the first element of the tuple is the center of the bin
representing a range of degrees and the second element of the tuple are the number of nodes
with the degree falling in the range.
Example::
.... | [
"Computes",
"the",
"degree",
"distribution",
"for",
"a",
"graph",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/GraphStat.py#L7-L34 | train | 32,150 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py | ObjectGraph.flatten | def flatten(self, condition=None, start=None):
"""
Iterate over the subgraph that is entirely reachable by condition
starting from the given start node or the ObjectGraph root
"""
if start is None:
start = self
start = self.getRawIdent(start)
return self.graph.iterdata(start=start, condition=condition) | python | def flatten(self, condition=None, start=None):
"""
Iterate over the subgraph that is entirely reachable by condition
starting from the given start node or the ObjectGraph root
"""
if start is None:
start = self
start = self.getRawIdent(start)
return self.graph.iterdata(start=start, condition=condition) | [
"def",
"flatten",
"(",
"self",
",",
"condition",
"=",
"None",
",",
"start",
"=",
"None",
")",
":",
"if",
"start",
"is",
"None",
":",
"start",
"=",
"self",
"start",
"=",
"self",
".",
"getRawIdent",
"(",
"start",
")",
"return",
"self",
".",
"graph",
... | Iterate over the subgraph that is entirely reachable by condition
starting from the given start node or the ObjectGraph root | [
"Iterate",
"over",
"the",
"subgraph",
"that",
"is",
"entirely",
"reachable",
"by",
"condition",
"starting",
"from",
"the",
"given",
"start",
"node",
"or",
"the",
"ObjectGraph",
"root"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py#L32-L40 | train | 32,151 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py | ObjectGraph.filterStack | def filterStack(self, filters):
"""
Filter the ObjectGraph in-place by removing all edges to nodes that
do not match every filter in the given filter list
Returns a tuple containing the number of: (nodes_visited, nodes_removed, nodes_orphaned)
"""
visited, removes, orphans = filter_stack(self.graph, self, filters)
for last_good, tail in orphans:
self.graph.add_edge(last_good, tail, edge_data='orphan')
for node in removes:
self.graph.hide_node(node)
return len(visited)-1, len(removes), len(orphans) | python | def filterStack(self, filters):
"""
Filter the ObjectGraph in-place by removing all edges to nodes that
do not match every filter in the given filter list
Returns a tuple containing the number of: (nodes_visited, nodes_removed, nodes_orphaned)
"""
visited, removes, orphans = filter_stack(self.graph, self, filters)
for last_good, tail in orphans:
self.graph.add_edge(last_good, tail, edge_data='orphan')
for node in removes:
self.graph.hide_node(node)
return len(visited)-1, len(removes), len(orphans) | [
"def",
"filterStack",
"(",
"self",
",",
"filters",
")",
":",
"visited",
",",
"removes",
",",
"orphans",
"=",
"filter_stack",
"(",
"self",
".",
"graph",
",",
"self",
",",
"filters",
")",
"for",
"last_good",
",",
"tail",
"in",
"orphans",
":",
"self",
"."... | Filter the ObjectGraph in-place by removing all edges to nodes that
do not match every filter in the given filter list
Returns a tuple containing the number of: (nodes_visited, nodes_removed, nodes_orphaned) | [
"Filter",
"the",
"ObjectGraph",
"in",
"-",
"place",
"by",
"removing",
"all",
"edges",
"to",
"nodes",
"that",
"do",
"not",
"match",
"every",
"filter",
"in",
"the",
"given",
"filter",
"list"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py#L61-L76 | train | 32,152 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py | ObjectGraph.removeNode | def removeNode(self, node):
"""
Remove the given node from the graph if it exists
"""
ident = self.getIdent(node)
if ident is not None:
self.graph.hide_node(ident) | python | def removeNode(self, node):
"""
Remove the given node from the graph if it exists
"""
ident = self.getIdent(node)
if ident is not None:
self.graph.hide_node(ident) | [
"def",
"removeNode",
"(",
"self",
",",
"node",
")",
":",
"ident",
"=",
"self",
".",
"getIdent",
"(",
"node",
")",
"if",
"ident",
"is",
"not",
"None",
":",
"self",
".",
"graph",
".",
"hide_node",
"(",
"ident",
")"
] | Remove the given node from the graph if it exists | [
"Remove",
"the",
"given",
"node",
"from",
"the",
"graph",
"if",
"it",
"exists"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py#L78-L84 | train | 32,153 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py | ObjectGraph.removeReference | def removeReference(self, fromnode, tonode):
"""
Remove all edges from fromnode to tonode
"""
if fromnode is None:
fromnode = self
fromident = self.getIdent(fromnode)
toident = self.getIdent(tonode)
if fromident is not None and toident is not None:
while True:
edge = self.graph.edge_by_node(fromident, toident)
if edge is None:
break
self.graph.hide_edge(edge) | python | def removeReference(self, fromnode, tonode):
"""
Remove all edges from fromnode to tonode
"""
if fromnode is None:
fromnode = self
fromident = self.getIdent(fromnode)
toident = self.getIdent(tonode)
if fromident is not None and toident is not None:
while True:
edge = self.graph.edge_by_node(fromident, toident)
if edge is None:
break
self.graph.hide_edge(edge) | [
"def",
"removeReference",
"(",
"self",
",",
"fromnode",
",",
"tonode",
")",
":",
"if",
"fromnode",
"is",
"None",
":",
"fromnode",
"=",
"self",
"fromident",
"=",
"self",
".",
"getIdent",
"(",
"fromnode",
")",
"toident",
"=",
"self",
".",
"getIdent",
"(",
... | Remove all edges from fromnode to tonode | [
"Remove",
"all",
"edges",
"from",
"fromnode",
"to",
"tonode"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py#L86-L99 | train | 32,154 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py | ObjectGraph.getIdent | def getIdent(self, node):
"""
Get the graph identifier for a node
"""
ident = self.getRawIdent(node)
if ident is not None:
return ident
node = self.findNode(node)
if node is None:
return None
return node.graphident | python | def getIdent(self, node):
"""
Get the graph identifier for a node
"""
ident = self.getRawIdent(node)
if ident is not None:
return ident
node = self.findNode(node)
if node is None:
return None
return node.graphident | [
"def",
"getIdent",
"(",
"self",
",",
"node",
")",
":",
"ident",
"=",
"self",
".",
"getRawIdent",
"(",
"node",
")",
"if",
"ident",
"is",
"not",
"None",
":",
"return",
"ident",
"node",
"=",
"self",
".",
"findNode",
"(",
"node",
")",
"if",
"node",
"is... | Get the graph identifier for a node | [
"Get",
"the",
"graph",
"identifier",
"for",
"a",
"node"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py#L101-L111 | train | 32,155 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py | ObjectGraph.getRawIdent | def getRawIdent(self, node):
"""
Get the identifier for a node object
"""
if node is self:
return node
ident = getattr(node, 'graphident', None)
return ident | python | def getRawIdent(self, node):
"""
Get the identifier for a node object
"""
if node is self:
return node
ident = getattr(node, 'graphident', None)
return ident | [
"def",
"getRawIdent",
"(",
"self",
",",
"node",
")",
":",
"if",
"node",
"is",
"self",
":",
"return",
"node",
"ident",
"=",
"getattr",
"(",
"node",
",",
"'graphident'",
",",
"None",
")",
"return",
"ident"
] | Get the identifier for a node object | [
"Get",
"the",
"identifier",
"for",
"a",
"node",
"object"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py#L113-L120 | train | 32,156 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py | ObjectGraph.findNode | def findNode(self, node):
"""
Find the node on the graph
"""
ident = self.getRawIdent(node)
if ident is None:
ident = node
try:
return self.graph.node_data(ident)
except KeyError:
return None | python | def findNode(self, node):
"""
Find the node on the graph
"""
ident = self.getRawIdent(node)
if ident is None:
ident = node
try:
return self.graph.node_data(ident)
except KeyError:
return None | [
"def",
"findNode",
"(",
"self",
",",
"node",
")",
":",
"ident",
"=",
"self",
".",
"getRawIdent",
"(",
"node",
")",
"if",
"ident",
"is",
"None",
":",
"ident",
"=",
"node",
"try",
":",
"return",
"self",
".",
"graph",
".",
"node_data",
"(",
"ident",
"... | Find the node on the graph | [
"Find",
"the",
"node",
"on",
"the",
"graph"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py#L125-L135 | train | 32,157 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py | ObjectGraph.addNode | def addNode(self, node):
"""
Add a node to the graph referenced by the root
"""
self.msg(4, "addNode", node)
try:
self.graph.restore_node(node.graphident)
except GraphError:
self.graph.add_node(node.graphident, node) | python | def addNode(self, node):
"""
Add a node to the graph referenced by the root
"""
self.msg(4, "addNode", node)
try:
self.graph.restore_node(node.graphident)
except GraphError:
self.graph.add_node(node.graphident, node) | [
"def",
"addNode",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"msg",
"(",
"4",
",",
"\"addNode\"",
",",
"node",
")",
"try",
":",
"self",
".",
"graph",
".",
"restore_node",
"(",
"node",
".",
"graphident",
")",
"except",
"GraphError",
":",
"self",... | Add a node to the graph referenced by the root | [
"Add",
"a",
"node",
"to",
"the",
"graph",
"referenced",
"by",
"the",
"root"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py#L137-L146 | train | 32,158 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py | ObjectGraph.createReference | def createReference(self, fromnode, tonode, edge_data=None):
"""
Create a reference from fromnode to tonode
"""
if fromnode is None:
fromnode = self
fromident, toident = self.getIdent(fromnode), self.getIdent(tonode)
if fromident is None or toident is None:
return
self.msg(4, "createReference", fromnode, tonode, edge_data)
self.graph.add_edge(fromident, toident, edge_data=edge_data) | python | def createReference(self, fromnode, tonode, edge_data=None):
"""
Create a reference from fromnode to tonode
"""
if fromnode is None:
fromnode = self
fromident, toident = self.getIdent(fromnode), self.getIdent(tonode)
if fromident is None or toident is None:
return
self.msg(4, "createReference", fromnode, tonode, edge_data)
self.graph.add_edge(fromident, toident, edge_data=edge_data) | [
"def",
"createReference",
"(",
"self",
",",
"fromnode",
",",
"tonode",
",",
"edge_data",
"=",
"None",
")",
":",
"if",
"fromnode",
"is",
"None",
":",
"fromnode",
"=",
"self",
"fromident",
",",
"toident",
"=",
"self",
".",
"getIdent",
"(",
"fromnode",
")",... | Create a reference from fromnode to tonode | [
"Create",
"a",
"reference",
"from",
"fromnode",
"to",
"tonode"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py#L148-L158 | train | 32,159 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py | ObjectGraph.createNode | def createNode(self, cls, name, *args, **kw):
"""
Add a node of type cls to the graph if it does not already exist
by the given name
"""
m = self.findNode(name)
if m is None:
m = cls(name, *args, **kw)
self.addNode(m)
return m | python | def createNode(self, cls, name, *args, **kw):
"""
Add a node of type cls to the graph if it does not already exist
by the given name
"""
m = self.findNode(name)
if m is None:
m = cls(name, *args, **kw)
self.addNode(m)
return m | [
"def",
"createNode",
"(",
"self",
",",
"cls",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"m",
"=",
"self",
".",
"findNode",
"(",
"name",
")",
"if",
"m",
"is",
"None",
":",
"m",
"=",
"cls",
"(",
"name",
",",
"*",
"args",
"... | Add a node of type cls to the graph if it does not already exist
by the given name | [
"Add",
"a",
"node",
"of",
"type",
"cls",
"to",
"the",
"graph",
"if",
"it",
"does",
"not",
"already",
"exist",
"by",
"the",
"given",
"name"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py#L160-L169 | train | 32,160 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py | ObjectGraph.msg | def msg(self, level, s, *args):
"""
Print a debug message with the given level
"""
if s and level <= self.debug:
print "%s%s %s" % (" " * self.indent, s, ' '.join(map(repr, args))) | python | def msg(self, level, s, *args):
"""
Print a debug message with the given level
"""
if s and level <= self.debug:
print "%s%s %s" % (" " * self.indent, s, ' '.join(map(repr, args))) | [
"def",
"msg",
"(",
"self",
",",
"level",
",",
"s",
",",
"*",
"args",
")",
":",
"if",
"s",
"and",
"level",
"<=",
"self",
".",
"debug",
":",
"print",
"\"%s%s %s\"",
"%",
"(",
"\" \"",
"*",
"self",
".",
"indent",
",",
"s",
",",
"' '",
".",
"join"... | Print a debug message with the given level | [
"Print",
"a",
"debug",
"message",
"with",
"the",
"given",
"level"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/ObjectGraph.py#L171-L176 | train | 32,161 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/GraphAlgo.py | dijkstra | def dijkstra(graph, start, end=None):
"""
Dijkstra's algorithm for shortest paths
`David Eppstein, UC Irvine, 4 April 2002 <http://www.ics.uci.edu/~eppstein/161/python/>`_
`Python Cookbook Recipe <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466>`_
Find shortest paths from the start node to all nodes nearer than or equal to the end node.
Dijkstra's algorithm is only guaranteed to work correctly when all edge lengths are positive.
This code does not verify this property for all edges (only the edges examined until the end
vertex is reached), but will correctly compute shortest paths even for some graphs with negative
edges, and will raise an exception if it discovers that a negative edge has caused it to make a mistake.
*Adapted to altgraph by Istvan Albert, Pennsylvania State University - June, 9 2004*
"""
D = {} # dictionary of final distances
P = {} # dictionary of predecessors
Q = _priorityDictionary() # estimated distances of non-final vertices
Q[start] = 0
for v in Q:
D[v] = Q[v]
if v == end: break
for w in graph.out_nbrs(v):
edge_id = graph.edge_by_node(v,w)
vwLength = D[v] + graph.edge_data(edge_id)
if w in D:
if vwLength < D[w]:
raise GraphError("Dijkstra: found better path to already-final vertex")
elif w not in Q or vwLength < Q[w]:
Q[w] = vwLength
P[w] = v
return (D,P) | python | def dijkstra(graph, start, end=None):
"""
Dijkstra's algorithm for shortest paths
`David Eppstein, UC Irvine, 4 April 2002 <http://www.ics.uci.edu/~eppstein/161/python/>`_
`Python Cookbook Recipe <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466>`_
Find shortest paths from the start node to all nodes nearer than or equal to the end node.
Dijkstra's algorithm is only guaranteed to work correctly when all edge lengths are positive.
This code does not verify this property for all edges (only the edges examined until the end
vertex is reached), but will correctly compute shortest paths even for some graphs with negative
edges, and will raise an exception if it discovers that a negative edge has caused it to make a mistake.
*Adapted to altgraph by Istvan Albert, Pennsylvania State University - June, 9 2004*
"""
D = {} # dictionary of final distances
P = {} # dictionary of predecessors
Q = _priorityDictionary() # estimated distances of non-final vertices
Q[start] = 0
for v in Q:
D[v] = Q[v]
if v == end: break
for w in graph.out_nbrs(v):
edge_id = graph.edge_by_node(v,w)
vwLength = D[v] + graph.edge_data(edge_id)
if w in D:
if vwLength < D[w]:
raise GraphError("Dijkstra: found better path to already-final vertex")
elif w not in Q or vwLength < Q[w]:
Q[w] = vwLength
P[w] = v
return (D,P) | [
"def",
"dijkstra",
"(",
"graph",
",",
"start",
",",
"end",
"=",
"None",
")",
":",
"D",
"=",
"{",
"}",
"# dictionary of final distances",
"P",
"=",
"{",
"}",
"# dictionary of predecessors",
"Q",
"=",
"_priorityDictionary",
"(",
")",
"# estimated distances of non-... | Dijkstra's algorithm for shortest paths
`David Eppstein, UC Irvine, 4 April 2002 <http://www.ics.uci.edu/~eppstein/161/python/>`_
`Python Cookbook Recipe <http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/119466>`_
Find shortest paths from the start node to all nodes nearer than or equal to the end node.
Dijkstra's algorithm is only guaranteed to work correctly when all edge lengths are positive.
This code does not verify this property for all edges (only the edges examined until the end
vertex is reached), but will correctly compute shortest paths even for some graphs with negative
edges, and will raise an exception if it discovers that a negative edge has caused it to make a mistake.
*Adapted to altgraph by Istvan Albert, Pennsylvania State University - June, 9 2004* | [
"Dijkstra",
"s",
"algorithm",
"for",
"shortest",
"paths"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/GraphAlgo.py#L7-L44 | train | 32,162 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/GraphAlgo.py | _priorityDictionary.smallest | def smallest(self):
'''
Find smallest item after removing deleted items from front of heap.
'''
if len(self) == 0:
raise IndexError, "smallest of empty priorityDictionary"
heap = self.__heap
while heap[0][1] not in self or self[heap[0][1]] != heap[0][0]:
lastItem = heap.pop()
insertionPoint = 0
while 1:
smallChild = 2*insertionPoint+1
if smallChild+1 < len(heap) and heap[smallChild] > heap[smallChild+1] :
smallChild += 1
if smallChild >= len(heap) or lastItem <= heap[smallChild]:
heap[insertionPoint] = lastItem
break
heap[insertionPoint] = heap[smallChild]
insertionPoint = smallChild
return heap[0][1] | python | def smallest(self):
'''
Find smallest item after removing deleted items from front of heap.
'''
if len(self) == 0:
raise IndexError, "smallest of empty priorityDictionary"
heap = self.__heap
while heap[0][1] not in self or self[heap[0][1]] != heap[0][0]:
lastItem = heap.pop()
insertionPoint = 0
while 1:
smallChild = 2*insertionPoint+1
if smallChild+1 < len(heap) and heap[smallChild] > heap[smallChild+1] :
smallChild += 1
if smallChild >= len(heap) or lastItem <= heap[smallChild]:
heap[insertionPoint] = lastItem
break
heap[insertionPoint] = heap[smallChild]
insertionPoint = smallChild
return heap[0][1] | [
"def",
"smallest",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
")",
"==",
"0",
":",
"raise",
"IndexError",
",",
"\"smallest of empty priorityDictionary\"",
"heap",
"=",
"self",
".",
"__heap",
"while",
"heap",
"[",
"0",
"]",
"[",
"1",
"]",
"not",
"... | Find smallest item after removing deleted items from front of heap. | [
"Find",
"smallest",
"item",
"after",
"removing",
"deleted",
"items",
"from",
"front",
"of",
"heap",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/GraphAlgo.py#L90-L109 | train | 32,163 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/configure.py | _write_textfile | def _write_textfile(filename, text):
"""
Write `text` into file `filename`. If the target directory does
not exist, create it.
"""
dirname = os.path.dirname(filename)
if not os.path.exists(dirname):
os.makedirs(dirname)
outf = open(filename, 'w')
outf.write(text)
outf.close() | python | def _write_textfile(filename, text):
"""
Write `text` into file `filename`. If the target directory does
not exist, create it.
"""
dirname = os.path.dirname(filename)
if not os.path.exists(dirname):
os.makedirs(dirname)
outf = open(filename, 'w')
outf.write(text)
outf.close() | [
"def",
"_write_textfile",
"(",
"filename",
",",
"text",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dirname",
")",
":",
"os",
".",
"makedirs",
"(",
"dirname",... | Write `text` into file `filename`. If the target directory does
not exist, create it. | [
"Write",
"text",
"into",
"file",
"filename",
".",
"If",
"the",
"target",
"directory",
"does",
"not",
"exist",
"create",
"it",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/configure.py#L43-L53 | train | 32,164 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/configure.py | __add_options | def __add_options(parser):
"""
Add the `Configure` options to a option-parser instance or a
option group.
"""
parser.add_option('--upx-dir', default=None,
help='Directory containing UPX.')
parser.add_option('-C', '--configfile',
default=DEFAULT_CONFIGFILE,
dest='configfilename',
help='Name of generated configfile (default: %default)') | python | def __add_options(parser):
"""
Add the `Configure` options to a option-parser instance or a
option group.
"""
parser.add_option('--upx-dir', default=None,
help='Directory containing UPX.')
parser.add_option('-C', '--configfile',
default=DEFAULT_CONFIGFILE,
dest='configfilename',
help='Name of generated configfile (default: %default)') | [
"def",
"__add_options",
"(",
"parser",
")",
":",
"parser",
".",
"add_option",
"(",
"'--upx-dir'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"'Directory containing UPX.'",
")",
"parser",
".",
"add_option",
"(",
"'-C'",
",",
"'--configfile'",
",",
"default"... | Add the `Configure` options to a option-parser instance or a
option group. | [
"Add",
"the",
"Configure",
"options",
"to",
"a",
"option",
"-",
"parser",
"instance",
"or",
"a",
"option",
"group",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/configure.py#L328-L338 | train | 32,165 |
bwhite/hadoopy | hadoopy/_hdfs.py | abspath | def abspath(path):
"""Return the absolute path to a file and canonicalize it
Path is returned without a trailing slash and without redundant slashes.
Caches the user's home directory.
:param path: A string for the path. This should not have any wildcards.
:returns: Absolute path to the file
:raises IOError: If unsuccessful
"""
global _USER_HOME_DIR
# FIXME(brandyn): User's home directory must exist
# FIXME(brandyn): Requires something to be in home dir
if path[0] == '/':
return os.path.abspath(path)
if _USER_HOME_DIR is None:
try:
_USER_HOME_DIR = _get_home_dir()
except IOError, e:
if not exists('.'):
raise IOError("Home directory doesn't exist")
raise e
return os.path.abspath(os.path.join(_USER_HOME_DIR, path)) | python | def abspath(path):
"""Return the absolute path to a file and canonicalize it
Path is returned without a trailing slash and without redundant slashes.
Caches the user's home directory.
:param path: A string for the path. This should not have any wildcards.
:returns: Absolute path to the file
:raises IOError: If unsuccessful
"""
global _USER_HOME_DIR
# FIXME(brandyn): User's home directory must exist
# FIXME(brandyn): Requires something to be in home dir
if path[0] == '/':
return os.path.abspath(path)
if _USER_HOME_DIR is None:
try:
_USER_HOME_DIR = _get_home_dir()
except IOError, e:
if not exists('.'):
raise IOError("Home directory doesn't exist")
raise e
return os.path.abspath(os.path.join(_USER_HOME_DIR, path)) | [
"def",
"abspath",
"(",
"path",
")",
":",
"global",
"_USER_HOME_DIR",
"# FIXME(brandyn): User's home directory must exist",
"# FIXME(brandyn): Requires something to be in home dir",
"if",
"path",
"[",
"0",
"]",
"==",
"'/'",
":",
"return",
"os",
".",
"path",
".",
"abspath... | Return the absolute path to a file and canonicalize it
Path is returned without a trailing slash and without redundant slashes.
Caches the user's home directory.
:param path: A string for the path. This should not have any wildcards.
:returns: Absolute path to the file
:raises IOError: If unsuccessful | [
"Return",
"the",
"absolute",
"path",
"to",
"a",
"file",
"and",
"canonicalize",
"it"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_hdfs.py#L113-L135 | train | 32,166 |
bwhite/hadoopy | hadoopy/_hdfs.py | cp | def cp(hdfs_src, hdfs_dst):
"""Copy a file
:param hdfs_src: Source (str)
:param hdfs_dst: Destination (str)
:raises: IOError: If unsuccessful
"""
cmd = "hadoop fs -cp %s %s" % (hdfs_src, hdfs_dst)
rcode, stdout, stderr = _checked_hadoop_fs_command(cmd) | python | def cp(hdfs_src, hdfs_dst):
"""Copy a file
:param hdfs_src: Source (str)
:param hdfs_dst: Destination (str)
:raises: IOError: If unsuccessful
"""
cmd = "hadoop fs -cp %s %s" % (hdfs_src, hdfs_dst)
rcode, stdout, stderr = _checked_hadoop_fs_command(cmd) | [
"def",
"cp",
"(",
"hdfs_src",
",",
"hdfs_dst",
")",
":",
"cmd",
"=",
"\"hadoop fs -cp %s %s\"",
"%",
"(",
"hdfs_src",
",",
"hdfs_dst",
")",
"rcode",
",",
"stdout",
",",
"stderr",
"=",
"_checked_hadoop_fs_command",
"(",
"cmd",
")"
] | Copy a file
:param hdfs_src: Source (str)
:param hdfs_dst: Destination (str)
:raises: IOError: If unsuccessful | [
"Copy",
"a",
"file"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_hdfs.py#L148-L156 | train | 32,167 |
bwhite/hadoopy | hadoopy/_hdfs.py | stat | def stat(path, format):
"""Call stat on file
:param path: HDFS Path
:param format: Stat format
:returns: Stat output
:raises: IOError: If unsuccessful
"""
cmd = "hadoop fs -stat %s %s" % (format, path)
rcode, stdout, stderr = _checked_hadoop_fs_command(cmd)
return stdout.rstrip() | python | def stat(path, format):
"""Call stat on file
:param path: HDFS Path
:param format: Stat format
:returns: Stat output
:raises: IOError: If unsuccessful
"""
cmd = "hadoop fs -stat %s %s" % (format, path)
rcode, stdout, stderr = _checked_hadoop_fs_command(cmd)
return stdout.rstrip() | [
"def",
"stat",
"(",
"path",
",",
"format",
")",
":",
"cmd",
"=",
"\"hadoop fs -stat %s %s\"",
"%",
"(",
"format",
",",
"path",
")",
"rcode",
",",
"stdout",
",",
"stderr",
"=",
"_checked_hadoop_fs_command",
"(",
"cmd",
")",
"return",
"stdout",
".",
"rstrip"... | Call stat on file
:param path: HDFS Path
:param format: Stat format
:returns: Stat output
:raises: IOError: If unsuccessful | [
"Call",
"stat",
"on",
"file"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_hdfs.py#L159-L169 | train | 32,168 |
bwhite/hadoopy | hadoopy/_hdfs.py | mv | def mv(hdfs_src, hdfs_dst):
"""Move a file on hdfs
:param hdfs_src: Source (str)
:param hdfs_dst: Destination (str)
:raises: IOError: If unsuccessful
"""
cmd = "hadoop fs -mv %s %s" % (hdfs_src, hdfs_dst)
rcode, stdout, stderr = _checked_hadoop_fs_command(cmd) | python | def mv(hdfs_src, hdfs_dst):
"""Move a file on hdfs
:param hdfs_src: Source (str)
:param hdfs_dst: Destination (str)
:raises: IOError: If unsuccessful
"""
cmd = "hadoop fs -mv %s %s" % (hdfs_src, hdfs_dst)
rcode, stdout, stderr = _checked_hadoop_fs_command(cmd) | [
"def",
"mv",
"(",
"hdfs_src",
",",
"hdfs_dst",
")",
":",
"cmd",
"=",
"\"hadoop fs -mv %s %s\"",
"%",
"(",
"hdfs_src",
",",
"hdfs_dst",
")",
"rcode",
",",
"stdout",
",",
"stderr",
"=",
"_checked_hadoop_fs_command",
"(",
"cmd",
")"
] | Move a file on hdfs
:param hdfs_src: Source (str)
:param hdfs_dst: Destination (str)
:raises: IOError: If unsuccessful | [
"Move",
"a",
"file",
"on",
"hdfs"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_hdfs.py#L182-L190 | train | 32,169 |
bwhite/hadoopy | hadoopy/_hdfs.py | put | def put(local_path, hdfs_path):
"""Put a file on hdfs
:param local_path: Source (str)
:param hdfs_path: Destination (str)
:raises: IOError: If unsuccessful
"""
cmd = "hadoop fs -put %s %s" % (local_path, hdfs_path)
rcode, stdout, stderr = _checked_hadoop_fs_command(cmd) | python | def put(local_path, hdfs_path):
"""Put a file on hdfs
:param local_path: Source (str)
:param hdfs_path: Destination (str)
:raises: IOError: If unsuccessful
"""
cmd = "hadoop fs -put %s %s" % (local_path, hdfs_path)
rcode, stdout, stderr = _checked_hadoop_fs_command(cmd) | [
"def",
"put",
"(",
"local_path",
",",
"hdfs_path",
")",
":",
"cmd",
"=",
"\"hadoop fs -put %s %s\"",
"%",
"(",
"local_path",
",",
"hdfs_path",
")",
"rcode",
",",
"stdout",
",",
"stderr",
"=",
"_checked_hadoop_fs_command",
"(",
"cmd",
")"
] | Put a file on hdfs
:param local_path: Source (str)
:param hdfs_path: Destination (str)
:raises: IOError: If unsuccessful | [
"Put",
"a",
"file",
"on",
"hdfs"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_hdfs.py#L193-L201 | train | 32,170 |
bwhite/hadoopy | hadoopy/_hdfs.py | get | def get(hdfs_path, local_path):
"""Get a file from hdfs
:param hdfs_path: Destination (str)
:param local_path: Source (str)
:raises: IOError: If unsuccessful
"""
cmd = "hadoop fs -get %s %s" % (hdfs_path, local_path)
rcode, stdout, stderr = _checked_hadoop_fs_command(cmd) | python | def get(hdfs_path, local_path):
"""Get a file from hdfs
:param hdfs_path: Destination (str)
:param local_path: Source (str)
:raises: IOError: If unsuccessful
"""
cmd = "hadoop fs -get %s %s" % (hdfs_path, local_path)
rcode, stdout, stderr = _checked_hadoop_fs_command(cmd) | [
"def",
"get",
"(",
"hdfs_path",
",",
"local_path",
")",
":",
"cmd",
"=",
"\"hadoop fs -get %s %s\"",
"%",
"(",
"hdfs_path",
",",
"local_path",
")",
"rcode",
",",
"stdout",
",",
"stderr",
"=",
"_checked_hadoop_fs_command",
"(",
"cmd",
")"
] | Get a file from hdfs
:param hdfs_path: Destination (str)
:param local_path: Source (str)
:raises: IOError: If unsuccessful | [
"Get",
"a",
"file",
"from",
"hdfs"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_hdfs.py#L204-L212 | train | 32,171 |
bwhite/hadoopy | hadoopy/_hdfs.py | ls | def ls(path):
"""List files on HDFS.
:param path: A string (potentially with wildcards).
:rtype: A list of strings representing HDFS paths.
:raises: IOError: An error occurred listing the directory (e.g., not available).
"""
rcode, stdout, stderr = _checked_hadoop_fs_command('hadoop fs -ls %s' % path)
found_line = lambda x: re.search('Found [0-9]+ items$', x)
out = [x.split(' ')[-1] for x in stdout.split('\n')
if x and not found_line(x)]
return out | python | def ls(path):
"""List files on HDFS.
:param path: A string (potentially with wildcards).
:rtype: A list of strings representing HDFS paths.
:raises: IOError: An error occurred listing the directory (e.g., not available).
"""
rcode, stdout, stderr = _checked_hadoop_fs_command('hadoop fs -ls %s' % path)
found_line = lambda x: re.search('Found [0-9]+ items$', x)
out = [x.split(' ')[-1] for x in stdout.split('\n')
if x and not found_line(x)]
return out | [
"def",
"ls",
"(",
"path",
")",
":",
"rcode",
",",
"stdout",
",",
"stderr",
"=",
"_checked_hadoop_fs_command",
"(",
"'hadoop fs -ls %s'",
"%",
"path",
")",
"found_line",
"=",
"lambda",
"x",
":",
"re",
".",
"search",
"(",
"'Found [0-9]+ items$'",
",",
"x",
"... | List files on HDFS.
:param path: A string (potentially with wildcards).
:rtype: A list of strings representing HDFS paths.
:raises: IOError: An error occurred listing the directory (e.g., not available). | [
"List",
"files",
"on",
"HDFS",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_hdfs.py#L215-L226 | train | 32,172 |
bwhite/hadoopy | hadoopy/_hdfs.py | writetb | def writetb(path, kvs, java_mem_mb=256):
"""Write typedbytes sequence file to HDFS given an iterator of KeyValue pairs
:param path: HDFS path (string)
:param kvs: Iterator of (key, value)
:param java_mem_mb: Integer of java heap size in MB (default 256)
:raises: IOError: An error occurred while saving the data.
"""
read_fd, write_fd = os.pipe()
read_fp = os.fdopen(read_fd, 'r')
hstreaming = _find_hstreaming()
cmd = 'hadoop jar %s loadtb %s' % (hstreaming, path)
p = _hadoop_fs_command(cmd, stdin=read_fp, java_mem_mb=java_mem_mb)
read_fp.close()
with hadoopy.TypedBytesFile(write_fd=write_fd) as tb_fp:
for kv in kvs:
if p.poll() is not None:
raise IOError('writetb: Hadoop process quit while we were sending it data. Hadoop output below...\nstdout\n%s\nstderr\n%s' % p.communicate())
tb_fp.write(kv)
tb_fp.flush()
p.wait()
if p.returncode is not 0:
raise IOError('writetb: Hadoop process returned [%d]. Hadoop output below...\nstderr\n%s' % (p.returncode, p.stderr.read())) | python | def writetb(path, kvs, java_mem_mb=256):
"""Write typedbytes sequence file to HDFS given an iterator of KeyValue pairs
:param path: HDFS path (string)
:param kvs: Iterator of (key, value)
:param java_mem_mb: Integer of java heap size in MB (default 256)
:raises: IOError: An error occurred while saving the data.
"""
read_fd, write_fd = os.pipe()
read_fp = os.fdopen(read_fd, 'r')
hstreaming = _find_hstreaming()
cmd = 'hadoop jar %s loadtb %s' % (hstreaming, path)
p = _hadoop_fs_command(cmd, stdin=read_fp, java_mem_mb=java_mem_mb)
read_fp.close()
with hadoopy.TypedBytesFile(write_fd=write_fd) as tb_fp:
for kv in kvs:
if p.poll() is not None:
raise IOError('writetb: Hadoop process quit while we were sending it data. Hadoop output below...\nstdout\n%s\nstderr\n%s' % p.communicate())
tb_fp.write(kv)
tb_fp.flush()
p.wait()
if p.returncode is not 0:
raise IOError('writetb: Hadoop process returned [%d]. Hadoop output below...\nstderr\n%s' % (p.returncode, p.stderr.read())) | [
"def",
"writetb",
"(",
"path",
",",
"kvs",
",",
"java_mem_mb",
"=",
"256",
")",
":",
"read_fd",
",",
"write_fd",
"=",
"os",
".",
"pipe",
"(",
")",
"read_fp",
"=",
"os",
".",
"fdopen",
"(",
"read_fd",
",",
"'r'",
")",
"hstreaming",
"=",
"_find_hstream... | Write typedbytes sequence file to HDFS given an iterator of KeyValue pairs
:param path: HDFS path (string)
:param kvs: Iterator of (key, value)
:param java_mem_mb: Integer of java heap size in MB (default 256)
:raises: IOError: An error occurred while saving the data. | [
"Write",
"typedbytes",
"sequence",
"file",
"to",
"HDFS",
"given",
"an",
"iterator",
"of",
"KeyValue",
"pairs"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_hdfs.py#L229-L251 | train | 32,173 |
bwhite/hadoopy | hadoopy/_hdfs.py | writetb_parts | def writetb_parts(path, kvs, num_per_file, **kw):
"""Write typedbytes sequence files to HDFS given an iterator of KeyValue pairs
This is useful when a task is CPU bound and wish to break up its inputs
into pieces smaller than the HDFS block size. This causes Hadoop to launch
one Map task per file. As such, you can consider this a way of forcing
a minimum number of map tasks.
:param path: HDFS path (string)
:param kvs: Iterator of (key, value)
:param num_per_file: Max # of kv pairs per file.
:param java_mem_mb: Integer of java heap size in MB (default 256)
:raises: IOError: An error occurred while saving the data.
"""
out = []
part_num = 0
def _flush(out, part_num):
hadoopy.writetb('%s/part-%.5d' % (path, part_num), out, **kw)
return [], part_num + 1
for kv in kvs:
out.append(kv)
if len(out) >= num_per_file:
out, part_num = _flush(out, part_num)
if out:
out, part_num = _flush(out, part_num) | python | def writetb_parts(path, kvs, num_per_file, **kw):
"""Write typedbytes sequence files to HDFS given an iterator of KeyValue pairs
This is useful when a task is CPU bound and wish to break up its inputs
into pieces smaller than the HDFS block size. This causes Hadoop to launch
one Map task per file. As such, you can consider this a way of forcing
a minimum number of map tasks.
:param path: HDFS path (string)
:param kvs: Iterator of (key, value)
:param num_per_file: Max # of kv pairs per file.
:param java_mem_mb: Integer of java heap size in MB (default 256)
:raises: IOError: An error occurred while saving the data.
"""
out = []
part_num = 0
def _flush(out, part_num):
hadoopy.writetb('%s/part-%.5d' % (path, part_num), out, **kw)
return [], part_num + 1
for kv in kvs:
out.append(kv)
if len(out) >= num_per_file:
out, part_num = _flush(out, part_num)
if out:
out, part_num = _flush(out, part_num) | [
"def",
"writetb_parts",
"(",
"path",
",",
"kvs",
",",
"num_per_file",
",",
"*",
"*",
"kw",
")",
":",
"out",
"=",
"[",
"]",
"part_num",
"=",
"0",
"def",
"_flush",
"(",
"out",
",",
"part_num",
")",
":",
"hadoopy",
".",
"writetb",
"(",
"'%s/part-%.5d'",... | Write typedbytes sequence files to HDFS given an iterator of KeyValue pairs
This is useful when a task is CPU bound and wish to break up its inputs
into pieces smaller than the HDFS block size. This causes Hadoop to launch
one Map task per file. As such, you can consider this a way of forcing
a minimum number of map tasks.
:param path: HDFS path (string)
:param kvs: Iterator of (key, value)
:param num_per_file: Max # of kv pairs per file.
:param java_mem_mb: Integer of java heap size in MB (default 256)
:raises: IOError: An error occurred while saving the data. | [
"Write",
"typedbytes",
"sequence",
"files",
"to",
"HDFS",
"given",
"an",
"iterator",
"of",
"KeyValue",
"pairs"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_hdfs.py#L254-L279 | train | 32,174 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.add_node | def add_node(self, node, node_data=None):
"""
Adds a new node to the graph. Arbitrary data can be attached to the
node via the node_data parameter. Adding the same node twice will be
silently ignored.
The node must be a hashable value.
"""
#
# the nodes will contain tuples that will store incoming edges,
# outgoing edges and data
#
# index 0 -> incoming edges
# index 1 -> outgoing edges
if node in self.hidden_nodes:
# Node is present, but hidden
return
if node not in self.nodes:
self.nodes[node] = ([], [], node_data) | python | def add_node(self, node, node_data=None):
"""
Adds a new node to the graph. Arbitrary data can be attached to the
node via the node_data parameter. Adding the same node twice will be
silently ignored.
The node must be a hashable value.
"""
#
# the nodes will contain tuples that will store incoming edges,
# outgoing edges and data
#
# index 0 -> incoming edges
# index 1 -> outgoing edges
if node in self.hidden_nodes:
# Node is present, but hidden
return
if node not in self.nodes:
self.nodes[node] = ([], [], node_data) | [
"def",
"add_node",
"(",
"self",
",",
"node",
",",
"node_data",
"=",
"None",
")",
":",
"#",
"# the nodes will contain tuples that will store incoming edges,",
"# outgoing edges and data",
"#",
"# index 0 -> incoming edges",
"# index 1 -> outgoing edges",
"if",
"node",
"in",
... | Adds a new node to the graph. Arbitrary data can be attached to the
node via the node_data parameter. Adding the same node twice will be
silently ignored.
The node must be a hashable value. | [
"Adds",
"a",
"new",
"node",
"to",
"the",
"graph",
".",
"Arbitrary",
"data",
"can",
"be",
"attached",
"to",
"the",
"node",
"via",
"the",
"node_data",
"parameter",
".",
"Adding",
"the",
"same",
"node",
"twice",
"will",
"be",
"silently",
"ignored",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L64-L84 | train | 32,175 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.add_edge | def add_edge(self, head_id, tail_id, edge_data=1, create_nodes=True):
"""
Adds a directed edge going from head_id to tail_id.
Arbitrary data can be attached to the edge via edge_data.
It may create the nodes if adding edges between nonexisting ones.
:param head_id: head node
:param tail_id: tail node
:param edge_data: (optional) data attached to the edge
:param create_nodes: (optional) creates the head_id or tail_id node in case they did not exist
"""
# shorcut
edge = self.next_edge
# add nodes if on automatic node creation
if create_nodes:
self.add_node(head_id)
self.add_node(tail_id)
# update the corresponding incoming and outgoing lists in the nodes
# index 0 -> incoming edges
# index 1 -> outgoing edges
try:
self.nodes[tail_id][0].append(edge)
self.nodes[head_id][1].append(edge)
except KeyError:
raise GraphError('Invalid nodes %s -> %s' % (head_id, tail_id))
# store edge information
self.edges[edge] = (head_id, tail_id, edge_data)
self.next_edge += 1 | python | def add_edge(self, head_id, tail_id, edge_data=1, create_nodes=True):
"""
Adds a directed edge going from head_id to tail_id.
Arbitrary data can be attached to the edge via edge_data.
It may create the nodes if adding edges between nonexisting ones.
:param head_id: head node
:param tail_id: tail node
:param edge_data: (optional) data attached to the edge
:param create_nodes: (optional) creates the head_id or tail_id node in case they did not exist
"""
# shorcut
edge = self.next_edge
# add nodes if on automatic node creation
if create_nodes:
self.add_node(head_id)
self.add_node(tail_id)
# update the corresponding incoming and outgoing lists in the nodes
# index 0 -> incoming edges
# index 1 -> outgoing edges
try:
self.nodes[tail_id][0].append(edge)
self.nodes[head_id][1].append(edge)
except KeyError:
raise GraphError('Invalid nodes %s -> %s' % (head_id, tail_id))
# store edge information
self.edges[edge] = (head_id, tail_id, edge_data)
self.next_edge += 1 | [
"def",
"add_edge",
"(",
"self",
",",
"head_id",
",",
"tail_id",
",",
"edge_data",
"=",
"1",
",",
"create_nodes",
"=",
"True",
")",
":",
"# shorcut",
"edge",
"=",
"self",
".",
"next_edge",
"# add nodes if on automatic node creation",
"if",
"create_nodes",
":",
... | Adds a directed edge going from head_id to tail_id.
Arbitrary data can be attached to the edge via edge_data.
It may create the nodes if adding edges between nonexisting ones.
:param head_id: head node
:param tail_id: tail node
:param edge_data: (optional) data attached to the edge
:param create_nodes: (optional) creates the head_id or tail_id node in case they did not exist | [
"Adds",
"a",
"directed",
"edge",
"going",
"from",
"head_id",
"to",
"tail_id",
".",
"Arbitrary",
"data",
"can",
"be",
"attached",
"to",
"the",
"edge",
"via",
"edge_data",
".",
"It",
"may",
"create",
"the",
"nodes",
"if",
"adding",
"edges",
"between",
"nonex... | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L86-L119 | train | 32,176 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.hide_edge | def hide_edge(self, edge):
"""
Hides an edge from the graph. The edge may be unhidden at some later
time.
"""
try:
head_id, tail_id, edge_data = self.hidden_edges[edge] = self.edges[edge]
self.nodes[tail_id][0].remove(edge)
self.nodes[head_id][1].remove(edge)
del self.edges[edge]
except KeyError:
raise GraphError('Invalid edge %s' % edge) | python | def hide_edge(self, edge):
"""
Hides an edge from the graph. The edge may be unhidden at some later
time.
"""
try:
head_id, tail_id, edge_data = self.hidden_edges[edge] = self.edges[edge]
self.nodes[tail_id][0].remove(edge)
self.nodes[head_id][1].remove(edge)
del self.edges[edge]
except KeyError:
raise GraphError('Invalid edge %s' % edge) | [
"def",
"hide_edge",
"(",
"self",
",",
"edge",
")",
":",
"try",
":",
"head_id",
",",
"tail_id",
",",
"edge_data",
"=",
"self",
".",
"hidden_edges",
"[",
"edge",
"]",
"=",
"self",
".",
"edges",
"[",
"edge",
"]",
"self",
".",
"nodes",
"[",
"tail_id",
... | Hides an edge from the graph. The edge may be unhidden at some later
time. | [
"Hides",
"an",
"edge",
"from",
"the",
"graph",
".",
"The",
"edge",
"may",
"be",
"unhidden",
"at",
"some",
"later",
"time",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L121-L132 | train | 32,177 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.hide_node | def hide_node(self, node):
"""
Hides a node from the graph. The incoming and outgoing edges of the
node will also be hidden. The node may be unhidden at some later time.
"""
try:
all_edges = self.all_edges(node)
self.hidden_nodes[node] = (self.nodes[node], all_edges)
for edge in all_edges:
self.hide_edge(edge)
del self.nodes[node]
except KeyError:
raise GraphError('Invalid node %s' % node) | python | def hide_node(self, node):
"""
Hides a node from the graph. The incoming and outgoing edges of the
node will also be hidden. The node may be unhidden at some later time.
"""
try:
all_edges = self.all_edges(node)
self.hidden_nodes[node] = (self.nodes[node], all_edges)
for edge in all_edges:
self.hide_edge(edge)
del self.nodes[node]
except KeyError:
raise GraphError('Invalid node %s' % node) | [
"def",
"hide_node",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"all_edges",
"=",
"self",
".",
"all_edges",
"(",
"node",
")",
"self",
".",
"hidden_nodes",
"[",
"node",
"]",
"=",
"(",
"self",
".",
"nodes",
"[",
"node",
"]",
",",
"all_edges",
")"... | Hides a node from the graph. The incoming and outgoing edges of the
node will also be hidden. The node may be unhidden at some later time. | [
"Hides",
"a",
"node",
"from",
"the",
"graph",
".",
"The",
"incoming",
"and",
"outgoing",
"edges",
"of",
"the",
"node",
"will",
"also",
"be",
"hidden",
".",
"The",
"node",
"may",
"be",
"unhidden",
"at",
"some",
"later",
"time",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L134-L146 | train | 32,178 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.restore_node | def restore_node(self, node):
"""
Restores a previously hidden node back into the graph and restores
all of its incoming and outgoing edges.
"""
try:
self.nodes[node], all_edges = self.hidden_nodes[node]
for edge in all_edges:
self.restore_edge(edge)
del self.hidden_nodes[node]
except KeyError:
raise GraphError('Invalid node %s' % node) | python | def restore_node(self, node):
"""
Restores a previously hidden node back into the graph and restores
all of its incoming and outgoing edges.
"""
try:
self.nodes[node], all_edges = self.hidden_nodes[node]
for edge in all_edges:
self.restore_edge(edge)
del self.hidden_nodes[node]
except KeyError:
raise GraphError('Invalid node %s' % node) | [
"def",
"restore_node",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"self",
".",
"nodes",
"[",
"node",
"]",
",",
"all_edges",
"=",
"self",
".",
"hidden_nodes",
"[",
"node",
"]",
"for",
"edge",
"in",
"all_edges",
":",
"self",
".",
"restore_edge",
"... | Restores a previously hidden node back into the graph and restores
all of its incoming and outgoing edges. | [
"Restores",
"a",
"previously",
"hidden",
"node",
"back",
"into",
"the",
"graph",
"and",
"restores",
"all",
"of",
"its",
"incoming",
"and",
"outgoing",
"edges",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L148-L159 | train | 32,179 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.restore_edge | def restore_edge(self, edge):
"""
Restores a previously hidden edge back into the graph.
"""
try:
head_id, tail_id, data = self.hidden_edges[edge]
self.nodes[tail_id][0].append(edge)
self.nodes[head_id][1].append(edge)
self.edges[edge] = head_id, tail_id, data
del self.hidden_edges[edge]
except KeyError:
raise GraphError('Invalid edge %s' % edge) | python | def restore_edge(self, edge):
"""
Restores a previously hidden edge back into the graph.
"""
try:
head_id, tail_id, data = self.hidden_edges[edge]
self.nodes[tail_id][0].append(edge)
self.nodes[head_id][1].append(edge)
self.edges[edge] = head_id, tail_id, data
del self.hidden_edges[edge]
except KeyError:
raise GraphError('Invalid edge %s' % edge) | [
"def",
"restore_edge",
"(",
"self",
",",
"edge",
")",
":",
"try",
":",
"head_id",
",",
"tail_id",
",",
"data",
"=",
"self",
".",
"hidden_edges",
"[",
"edge",
"]",
"self",
".",
"nodes",
"[",
"tail_id",
"]",
"[",
"0",
"]",
".",
"append",
"(",
"edge",... | Restores a previously hidden edge back into the graph. | [
"Restores",
"a",
"previously",
"hidden",
"edge",
"back",
"into",
"the",
"graph",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L161-L172 | train | 32,180 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.restore_all_edges | def restore_all_edges(self):
"""
Restores all hidden edges.
"""
for edge in self.hidden_edges.keys():
try:
self.restore_edge(edge)
except GraphError:
pass | python | def restore_all_edges(self):
"""
Restores all hidden edges.
"""
for edge in self.hidden_edges.keys():
try:
self.restore_edge(edge)
except GraphError:
pass | [
"def",
"restore_all_edges",
"(",
"self",
")",
":",
"for",
"edge",
"in",
"self",
".",
"hidden_edges",
".",
"keys",
"(",
")",
":",
"try",
":",
"self",
".",
"restore_edge",
"(",
"edge",
")",
"except",
"GraphError",
":",
"pass"
] | Restores all hidden edges. | [
"Restores",
"all",
"hidden",
"edges",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L174-L182 | train | 32,181 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.describe_node | def describe_node(self, node):
"""
return node, node data, outgoing edges, incoming edges for node
"""
incoming, outgoing, data = self.nodes[node]
return node, data, outgoing, incoming | python | def describe_node(self, node):
"""
return node, node data, outgoing edges, incoming edges for node
"""
incoming, outgoing, data = self.nodes[node]
return node, data, outgoing, incoming | [
"def",
"describe_node",
"(",
"self",
",",
"node",
")",
":",
"incoming",
",",
"outgoing",
",",
"data",
"=",
"self",
".",
"nodes",
"[",
"node",
"]",
"return",
"node",
",",
"data",
",",
"outgoing",
",",
"incoming"
] | return node, node data, outgoing edges, incoming edges for node | [
"return",
"node",
"node",
"data",
"outgoing",
"edges",
"incoming",
"edges",
"for",
"node"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L272-L277 | train | 32,182 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.describe_edge | def describe_edge(self, edge):
"""
return edge, edge data, head, tail for edge
"""
head, tail, data = self.edges[edge]
return edge, data, head, tail | python | def describe_edge(self, edge):
"""
return edge, edge data, head, tail for edge
"""
head, tail, data = self.edges[edge]
return edge, data, head, tail | [
"def",
"describe_edge",
"(",
"self",
",",
"edge",
")",
":",
"head",
",",
"tail",
",",
"data",
"=",
"self",
".",
"edges",
"[",
"edge",
"]",
"return",
"edge",
",",
"data",
",",
"head",
",",
"tail"
] | return edge, edge data, head, tail for edge | [
"return",
"edge",
"edge",
"data",
"head",
"tail",
"for",
"edge"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L279-L284 | train | 32,183 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.out_nbrs | def out_nbrs(self, node):
"""
List of nodes connected by outgoing edges
"""
l = map(self.tail, self.out_edges(node))
#l.sort()
return l | python | def out_nbrs(self, node):
"""
List of nodes connected by outgoing edges
"""
l = map(self.tail, self.out_edges(node))
#l.sort()
return l | [
"def",
"out_nbrs",
"(",
"self",
",",
"node",
")",
":",
"l",
"=",
"map",
"(",
"self",
".",
"tail",
",",
"self",
".",
"out_edges",
"(",
"node",
")",
")",
"#l.sort()",
"return",
"l"
] | List of nodes connected by outgoing edges | [
"List",
"of",
"nodes",
"connected",
"by",
"outgoing",
"edges"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L310-L316 | train | 32,184 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.inc_nbrs | def inc_nbrs(self, node):
"""
List of nodes connected by incoming edges
"""
l = map(self.head, self.inc_edges(node))
#l.sort()
return l | python | def inc_nbrs(self, node):
"""
List of nodes connected by incoming edges
"""
l = map(self.head, self.inc_edges(node))
#l.sort()
return l | [
"def",
"inc_nbrs",
"(",
"self",
",",
"node",
")",
":",
"l",
"=",
"map",
"(",
"self",
".",
"head",
",",
"self",
".",
"inc_edges",
"(",
"node",
")",
")",
"#l.sort()",
"return",
"l"
] | List of nodes connected by incoming edges | [
"List",
"of",
"nodes",
"connected",
"by",
"incoming",
"edges"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L318-L324 | train | 32,185 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.all_nbrs | def all_nbrs(self, node):
"""
List of nodes connected by incoming and outgoing edges
"""
l = dict.fromkeys( self.inc_nbrs(node) + self.out_nbrs(node) )
return list(l) | python | def all_nbrs(self, node):
"""
List of nodes connected by incoming and outgoing edges
"""
l = dict.fromkeys( self.inc_nbrs(node) + self.out_nbrs(node) )
return list(l) | [
"def",
"all_nbrs",
"(",
"self",
",",
"node",
")",
":",
"l",
"=",
"dict",
".",
"fromkeys",
"(",
"self",
".",
"inc_nbrs",
"(",
"node",
")",
"+",
"self",
".",
"out_nbrs",
"(",
"node",
")",
")",
"return",
"list",
"(",
"l",
")"
] | List of nodes connected by incoming and outgoing edges | [
"List",
"of",
"nodes",
"connected",
"by",
"incoming",
"and",
"outgoing",
"edges"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L326-L331 | train | 32,186 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.out_edges | def out_edges(self, node):
"""
Returns a list of the outgoing edges
"""
try:
return list(self.nodes[node][1])
except KeyError:
raise GraphError('Invalid node %s' % node)
return None | python | def out_edges(self, node):
"""
Returns a list of the outgoing edges
"""
try:
return list(self.nodes[node][1])
except KeyError:
raise GraphError('Invalid node %s' % node)
return None | [
"def",
"out_edges",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"return",
"list",
"(",
"self",
".",
"nodes",
"[",
"node",
"]",
"[",
"1",
"]",
")",
"except",
"KeyError",
":",
"raise",
"GraphError",
"(",
"'Invalid node %s'",
"%",
"node",
")",
"retu... | Returns a list of the outgoing edges | [
"Returns",
"a",
"list",
"of",
"the",
"outgoing",
"edges"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L333-L342 | train | 32,187 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.inc_edges | def inc_edges(self, node):
"""
Returns a list of the incoming edges
"""
try:
return list(self.nodes[node][0])
except KeyError:
raise GraphError('Invalid node %s' % node)
return None | python | def inc_edges(self, node):
"""
Returns a list of the incoming edges
"""
try:
return list(self.nodes[node][0])
except KeyError:
raise GraphError('Invalid node %s' % node)
return None | [
"def",
"inc_edges",
"(",
"self",
",",
"node",
")",
":",
"try",
":",
"return",
"list",
"(",
"self",
".",
"nodes",
"[",
"node",
"]",
"[",
"0",
"]",
")",
"except",
"KeyError",
":",
"raise",
"GraphError",
"(",
"'Invalid node %s'",
"%",
"node",
")",
"retu... | Returns a list of the incoming edges | [
"Returns",
"a",
"list",
"of",
"the",
"incoming",
"edges"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L344-L353 | train | 32,188 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.all_edges | def all_edges(self, node):
"""
Returns a list of incoming and outging edges.
"""
return set(self.inc_edges(node) + self.out_edges(node)) | python | def all_edges(self, node):
"""
Returns a list of incoming and outging edges.
"""
return set(self.inc_edges(node) + self.out_edges(node)) | [
"def",
"all_edges",
"(",
"self",
",",
"node",
")",
":",
"return",
"set",
"(",
"self",
".",
"inc_edges",
"(",
"node",
")",
"+",
"self",
".",
"out_edges",
"(",
"node",
")",
")"
] | Returns a list of incoming and outging edges. | [
"Returns",
"a",
"list",
"of",
"incoming",
"and",
"outging",
"edges",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L355-L359 | train | 32,189 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph._topo_sort | def _topo_sort(self, forward=True):
"""
Topological sort.
Returns a list of nodes where the successors (based on outgoing and
incoming edges selected by the forward parameter) of any given node
appear in the sequence after that node.
"""
topo_list = []
queue = deque()
indeg = {}
# select the operation that will be performed
if forward:
get_edges = self.out_edges
get_degree = self.inc_degree
get_next = self.tail
else:
get_edges = self.inc_edges
get_degree = self.out_degree
get_next = self.head
for node in self.node_list():
degree = get_degree(node)
if degree:
indeg[node] = degree
else:
queue.append(node)
while queue:
curr_node = queue.popleft()
topo_list.append(curr_node)
for edge in get_edges(curr_node):
tail_id = get_next(edge)
if tail_id in indeg:
indeg[tail_id] -= 1
if indeg[tail_id] == 0:
queue.append(tail_id)
if len(topo_list) == len(self.node_list()):
valid = True
else:
# the graph has cycles, invalid topological sort
valid = False
return (valid, topo_list) | python | def _topo_sort(self, forward=True):
"""
Topological sort.
Returns a list of nodes where the successors (based on outgoing and
incoming edges selected by the forward parameter) of any given node
appear in the sequence after that node.
"""
topo_list = []
queue = deque()
indeg = {}
# select the operation that will be performed
if forward:
get_edges = self.out_edges
get_degree = self.inc_degree
get_next = self.tail
else:
get_edges = self.inc_edges
get_degree = self.out_degree
get_next = self.head
for node in self.node_list():
degree = get_degree(node)
if degree:
indeg[node] = degree
else:
queue.append(node)
while queue:
curr_node = queue.popleft()
topo_list.append(curr_node)
for edge in get_edges(curr_node):
tail_id = get_next(edge)
if tail_id in indeg:
indeg[tail_id] -= 1
if indeg[tail_id] == 0:
queue.append(tail_id)
if len(topo_list) == len(self.node_list()):
valid = True
else:
# the graph has cycles, invalid topological sort
valid = False
return (valid, topo_list) | [
"def",
"_topo_sort",
"(",
"self",
",",
"forward",
"=",
"True",
")",
":",
"topo_list",
"=",
"[",
"]",
"queue",
"=",
"deque",
"(",
")",
"indeg",
"=",
"{",
"}",
"# select the operation that will be performed",
"if",
"forward",
":",
"get_edges",
"=",
"self",
"... | Topological sort.
Returns a list of nodes where the successors (based on outgoing and
incoming edges selected by the forward parameter) of any given node
appear in the sequence after that node. | [
"Topological",
"sort",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L379-L424 | train | 32,190 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph._bfs_subgraph | def _bfs_subgraph(self, start_id, forward=True):
"""
Private method creates a subgraph in a bfs order.
The forward parameter specifies whether it is a forward or backward
traversal.
"""
if forward:
get_bfs = self.forw_bfs
get_nbrs = self.out_nbrs
else:
get_bfs = self.back_bfs
get_nbrs = self.inc_nbrs
g = Graph()
bfs_list = get_bfs(start_id)
for node in bfs_list:
g.add_node(node)
for node in bfs_list:
for nbr_id in get_nbrs(node):
g.add_edge(node, nbr_id)
return g | python | def _bfs_subgraph(self, start_id, forward=True):
"""
Private method creates a subgraph in a bfs order.
The forward parameter specifies whether it is a forward or backward
traversal.
"""
if forward:
get_bfs = self.forw_bfs
get_nbrs = self.out_nbrs
else:
get_bfs = self.back_bfs
get_nbrs = self.inc_nbrs
g = Graph()
bfs_list = get_bfs(start_id)
for node in bfs_list:
g.add_node(node)
for node in bfs_list:
for nbr_id in get_nbrs(node):
g.add_edge(node, nbr_id)
return g | [
"def",
"_bfs_subgraph",
"(",
"self",
",",
"start_id",
",",
"forward",
"=",
"True",
")",
":",
"if",
"forward",
":",
"get_bfs",
"=",
"self",
".",
"forw_bfs",
"get_nbrs",
"=",
"self",
".",
"out_nbrs",
"else",
":",
"get_bfs",
"=",
"self",
".",
"back_bfs",
... | Private method creates a subgraph in a bfs order.
The forward parameter specifies whether it is a forward or backward
traversal. | [
"Private",
"method",
"creates",
"a",
"subgraph",
"in",
"a",
"bfs",
"order",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L444-L467 | train | 32,191 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.iterdfs | def iterdfs(self, start, end=None, forward=True):
"""
Collecting nodes in some depth first traversal.
The forward parameter specifies whether it is a forward or backward
traversal.
"""
visited, stack = set([start]), deque([start])
if forward:
get_edges = self.out_edges
get_next = self.tail
else:
get_edges = self.inc_edges
get_next = self.head
while stack:
curr_node = stack.pop()
yield curr_node
if curr_node == end:
break
for edge in sorted(get_edges(curr_node)):
tail = get_next(edge)
if tail not in visited:
visited.add(tail)
stack.append(tail) | python | def iterdfs(self, start, end=None, forward=True):
"""
Collecting nodes in some depth first traversal.
The forward parameter specifies whether it is a forward or backward
traversal.
"""
visited, stack = set([start]), deque([start])
if forward:
get_edges = self.out_edges
get_next = self.tail
else:
get_edges = self.inc_edges
get_next = self.head
while stack:
curr_node = stack.pop()
yield curr_node
if curr_node == end:
break
for edge in sorted(get_edges(curr_node)):
tail = get_next(edge)
if tail not in visited:
visited.add(tail)
stack.append(tail) | [
"def",
"iterdfs",
"(",
"self",
",",
"start",
",",
"end",
"=",
"None",
",",
"forward",
"=",
"True",
")",
":",
"visited",
",",
"stack",
"=",
"set",
"(",
"[",
"start",
"]",
")",
",",
"deque",
"(",
"[",
"start",
"]",
")",
"if",
"forward",
":",
"get... | Collecting nodes in some depth first traversal.
The forward parameter specifies whether it is a forward or backward
traversal. | [
"Collecting",
"nodes",
"in",
"some",
"depth",
"first",
"traversal",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L483-L508 | train | 32,192 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph._iterbfs | def _iterbfs(self, start, end=None, forward=True):
"""
The forward parameter specifies whether it is a forward or backward
traversal. Returns a list of tuples where the first value is the hop
value the second value is the node id.
"""
queue, visited = deque([(start, 0)]), set([start])
# the direction of the bfs depends on the edges that are sampled
if forward:
get_edges = self.out_edges
get_next = self.tail
else:
get_edges = self.inc_edges
get_next = self.head
while queue:
curr_node, curr_step = queue.popleft()
yield (curr_node, curr_step)
if curr_node == end:
break
for edge in get_edges(curr_node):
tail = get_next(edge)
if tail not in visited:
visited.add(tail)
queue.append((tail, curr_step + 1)) | python | def _iterbfs(self, start, end=None, forward=True):
"""
The forward parameter specifies whether it is a forward or backward
traversal. Returns a list of tuples where the first value is the hop
value the second value is the node id.
"""
queue, visited = deque([(start, 0)]), set([start])
# the direction of the bfs depends on the edges that are sampled
if forward:
get_edges = self.out_edges
get_next = self.tail
else:
get_edges = self.inc_edges
get_next = self.head
while queue:
curr_node, curr_step = queue.popleft()
yield (curr_node, curr_step)
if curr_node == end:
break
for edge in get_edges(curr_node):
tail = get_next(edge)
if tail not in visited:
visited.add(tail)
queue.append((tail, curr_step + 1)) | [
"def",
"_iterbfs",
"(",
"self",
",",
"start",
",",
"end",
"=",
"None",
",",
"forward",
"=",
"True",
")",
":",
"queue",
",",
"visited",
"=",
"deque",
"(",
"[",
"(",
"start",
",",
"0",
")",
"]",
")",
",",
"set",
"(",
"[",
"start",
"]",
")",
"# ... | The forward parameter specifies whether it is a forward or backward
traversal. Returns a list of tuples where the first value is the hop
value the second value is the node id. | [
"The",
"forward",
"parameter",
"specifies",
"whether",
"it",
"is",
"a",
"forward",
"or",
"backward",
"traversal",
".",
"Returns",
"a",
"list",
"of",
"tuples",
"where",
"the",
"first",
"value",
"is",
"the",
"hop",
"value",
"the",
"second",
"value",
"is",
"t... | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L543-L568 | train | 32,193 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.forw_bfs | def forw_bfs(self, start, end=None):
"""
Returns a list of nodes in some forward BFS order.
Starting from the start node the breadth first search proceeds along
outgoing edges.
"""
return [node for node, step in self._iterbfs(start, end, forward=True)] | python | def forw_bfs(self, start, end=None):
"""
Returns a list of nodes in some forward BFS order.
Starting from the start node the breadth first search proceeds along
outgoing edges.
"""
return [node for node, step in self._iterbfs(start, end, forward=True)] | [
"def",
"forw_bfs",
"(",
"self",
",",
"start",
",",
"end",
"=",
"None",
")",
":",
"return",
"[",
"node",
"for",
"node",
",",
"step",
"in",
"self",
".",
"_iterbfs",
"(",
"start",
",",
"end",
",",
"forward",
"=",
"True",
")",
"]"
] | Returns a list of nodes in some forward BFS order.
Starting from the start node the breadth first search proceeds along
outgoing edges. | [
"Returns",
"a",
"list",
"of",
"nodes",
"in",
"some",
"forward",
"BFS",
"order",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L571-L578 | train | 32,194 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.back_bfs | def back_bfs(self, start, end=None):
"""
Returns a list of nodes in some backward BFS order.
Starting from the start node the breadth first search proceeds along
incoming edges.
"""
return [node for node, step in self._iterbfs(start, end, forward=False)] | python | def back_bfs(self, start, end=None):
"""
Returns a list of nodes in some backward BFS order.
Starting from the start node the breadth first search proceeds along
incoming edges.
"""
return [node for node, step in self._iterbfs(start, end, forward=False)] | [
"def",
"back_bfs",
"(",
"self",
",",
"start",
",",
"end",
"=",
"None",
")",
":",
"return",
"[",
"node",
"for",
"node",
",",
"step",
"in",
"self",
".",
"_iterbfs",
"(",
"start",
",",
"end",
",",
"forward",
"=",
"False",
")",
"]"
] | Returns a list of nodes in some backward BFS order.
Starting from the start node the breadth first search proceeds along
incoming edges. | [
"Returns",
"a",
"list",
"of",
"nodes",
"in",
"some",
"backward",
"BFS",
"order",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L580-L587 | train | 32,195 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.forw_dfs | def forw_dfs(self, start, end=None):
"""
Returns a list of nodes in some forward DFS order.
Starting with the start node the depth first search proceeds along
outgoing edges.
"""
return list(self.iterdfs(start, end, forward=True)) | python | def forw_dfs(self, start, end=None):
"""
Returns a list of nodes in some forward DFS order.
Starting with the start node the depth first search proceeds along
outgoing edges.
"""
return list(self.iterdfs(start, end, forward=True)) | [
"def",
"forw_dfs",
"(",
"self",
",",
"start",
",",
"end",
"=",
"None",
")",
":",
"return",
"list",
"(",
"self",
".",
"iterdfs",
"(",
"start",
",",
"end",
",",
"forward",
"=",
"True",
")",
")"
] | Returns a list of nodes in some forward DFS order.
Starting with the start node the depth first search proceeds along
outgoing edges. | [
"Returns",
"a",
"list",
"of",
"nodes",
"in",
"some",
"forward",
"DFS",
"order",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L589-L596 | train | 32,196 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.back_dfs | def back_dfs(self, start, end=None):
"""
Returns a list of nodes in some backward DFS order.
Starting from the start node the depth first search proceeds along
incoming edges.
"""
return list(self.iterdfs(start, end, forward=False)) | python | def back_dfs(self, start, end=None):
"""
Returns a list of nodes in some backward DFS order.
Starting from the start node the depth first search proceeds along
incoming edges.
"""
return list(self.iterdfs(start, end, forward=False)) | [
"def",
"back_dfs",
"(",
"self",
",",
"start",
",",
"end",
"=",
"None",
")",
":",
"return",
"list",
"(",
"self",
".",
"iterdfs",
"(",
"start",
",",
"end",
",",
"forward",
"=",
"False",
")",
")"
] | Returns a list of nodes in some backward DFS order.
Starting from the start node the depth first search proceeds along
incoming edges. | [
"Returns",
"a",
"list",
"of",
"nodes",
"in",
"some",
"backward",
"DFS",
"order",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L598-L605 | train | 32,197 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.clust_coef | def clust_coef(self, node):
"""
Computes and returns the local clustering coefficient of node. The
local cluster coefficient is proportion of the actual number of edges between
neighbours of node and the maximum number of edges between those neighbours.
See <http://en.wikipedia.org/wiki/Clustering_coefficient#Local_clustering_coefficient>
for a formal definition.
"""
num = 0
nbr_set = set(self.out_nbrs(node))
if node in nbr_set:
nbr_set.remove(node) # loop defense
for nbr in nbr_set:
sec_set = set(self.out_nbrs(nbr))
if nbr in sec_set:
sec_set.remove(nbr) # loop defense
num += len(nbr_set & sec_set)
nbr_num = len(nbr_set)
if nbr_num:
clust_coef = float(num) / (nbr_num * (nbr_num - 1))
else:
clust_coef = 0.0
return clust_coef | python | def clust_coef(self, node):
"""
Computes and returns the local clustering coefficient of node. The
local cluster coefficient is proportion of the actual number of edges between
neighbours of node and the maximum number of edges between those neighbours.
See <http://en.wikipedia.org/wiki/Clustering_coefficient#Local_clustering_coefficient>
for a formal definition.
"""
num = 0
nbr_set = set(self.out_nbrs(node))
if node in nbr_set:
nbr_set.remove(node) # loop defense
for nbr in nbr_set:
sec_set = set(self.out_nbrs(nbr))
if nbr in sec_set:
sec_set.remove(nbr) # loop defense
num += len(nbr_set & sec_set)
nbr_num = len(nbr_set)
if nbr_num:
clust_coef = float(num) / (nbr_num * (nbr_num - 1))
else:
clust_coef = 0.0
return clust_coef | [
"def",
"clust_coef",
"(",
"self",
",",
"node",
")",
":",
"num",
"=",
"0",
"nbr_set",
"=",
"set",
"(",
"self",
".",
"out_nbrs",
"(",
"node",
")",
")",
"if",
"node",
"in",
"nbr_set",
":",
"nbr_set",
".",
"remove",
"(",
"node",
")",
"# loop defense",
... | Computes and returns the local clustering coefficient of node. The
local cluster coefficient is proportion of the actual number of edges between
neighbours of node and the maximum number of edges between those neighbours.
See <http://en.wikipedia.org/wiki/Clustering_coefficient#Local_clustering_coefficient>
for a formal definition. | [
"Computes",
"and",
"returns",
"the",
"local",
"clustering",
"coefficient",
"of",
"node",
".",
"The",
"local",
"cluster",
"coefficient",
"is",
"proportion",
"of",
"the",
"actual",
"number",
"of",
"edges",
"between",
"neighbours",
"of",
"node",
"and",
"the",
"ma... | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L619-L645 | train | 32,198 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py | Graph.get_hops | def get_hops(self, start, end=None, forward=True):
"""
Computes the hop distance to all nodes centered around a specified node.
First order neighbours are at hop 1, their neigbours are at hop 2 etc.
Uses :py:meth:`forw_bfs` or :py:meth:`back_bfs` depending on the value of the forward
parameter. If the distance between all neighbouring nodes is 1 the hop
number corresponds to the shortest distance between the nodes.
:param start: the starting node
:param end: ending node (optional). When not specified will search the whole graph.
:param forward: directionality parameter (optional). If C{True} (default) it uses L{forw_bfs} otherwise L{back_bfs}.
:return: returns a list of tuples where each tuple contains the node and the hop.
Typical usage::
>>> print graph.get_hops(1, 8)
>>> [(1, 0), (2, 1), (3, 1), (4, 2), (5, 3), (7, 4), (8, 5)]
# node 1 is at 0 hops
# node 2 is at 1 hop
# ...
# node 8 is at 5 hops
"""
if forward:
return list(self._iterbfs(start=start, end=end, forward=True))
else:
return list(self._iterbfs(start=start, end=end, forward=False)) | python | def get_hops(self, start, end=None, forward=True):
"""
Computes the hop distance to all nodes centered around a specified node.
First order neighbours are at hop 1, their neigbours are at hop 2 etc.
Uses :py:meth:`forw_bfs` or :py:meth:`back_bfs` depending on the value of the forward
parameter. If the distance between all neighbouring nodes is 1 the hop
number corresponds to the shortest distance between the nodes.
:param start: the starting node
:param end: ending node (optional). When not specified will search the whole graph.
:param forward: directionality parameter (optional). If C{True} (default) it uses L{forw_bfs} otherwise L{back_bfs}.
:return: returns a list of tuples where each tuple contains the node and the hop.
Typical usage::
>>> print graph.get_hops(1, 8)
>>> [(1, 0), (2, 1), (3, 1), (4, 2), (5, 3), (7, 4), (8, 5)]
# node 1 is at 0 hops
# node 2 is at 1 hop
# ...
# node 8 is at 5 hops
"""
if forward:
return list(self._iterbfs(start=start, end=end, forward=True))
else:
return list(self._iterbfs(start=start, end=end, forward=False)) | [
"def",
"get_hops",
"(",
"self",
",",
"start",
",",
"end",
"=",
"None",
",",
"forward",
"=",
"True",
")",
":",
"if",
"forward",
":",
"return",
"list",
"(",
"self",
".",
"_iterbfs",
"(",
"start",
"=",
"start",
",",
"end",
"=",
"end",
",",
"forward",
... | Computes the hop distance to all nodes centered around a specified node.
First order neighbours are at hop 1, their neigbours are at hop 2 etc.
Uses :py:meth:`forw_bfs` or :py:meth:`back_bfs` depending on the value of the forward
parameter. If the distance between all neighbouring nodes is 1 the hop
number corresponds to the shortest distance between the nodes.
:param start: the starting node
:param end: ending node (optional). When not specified will search the whole graph.
:param forward: directionality parameter (optional). If C{True} (default) it uses L{forw_bfs} otherwise L{back_bfs}.
:return: returns a list of tuples where each tuple contains the node and the hop.
Typical usage::
>>> print graph.get_hops(1, 8)
>>> [(1, 0), (2, 1), (3, 1), (4, 2), (5, 3), (7, 4), (8, 5)]
# node 1 is at 0 hops
# node 2 is at 1 hop
# ...
# node 8 is at 5 hops | [
"Computes",
"the",
"hop",
"distance",
"to",
"all",
"nodes",
"centered",
"around",
"a",
"specified",
"node",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Graph.py#L647-L673 | train | 32,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.