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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
CyberReboot/vent | vent/api/tools.py | Tools._start_remaining_containers | def _start_remaining_containers(self, containers_remaining, tool_d):
"""
Select remaining containers that didn't have priorities to start
"""
s_containers = []
f_containers = []
for container in containers_remaining:
s_containers, f_containers = self._start_container(container,
tool_d,
s_containers,
f_containers)
return (s_containers, f_containers) | python | def _start_remaining_containers(self, containers_remaining, tool_d):
"""
Select remaining containers that didn't have priorities to start
"""
s_containers = []
f_containers = []
for container in containers_remaining:
s_containers, f_containers = self._start_container(container,
tool_d,
s_containers,
f_containers)
return (s_containers, f_containers) | [
"def",
"_start_remaining_containers",
"(",
"self",
",",
"containers_remaining",
",",
"tool_d",
")",
":",
"s_containers",
"=",
"[",
"]",
"f_containers",
"=",
"[",
"]",
"for",
"container",
"in",
"containers_remaining",
":",
"s_containers",
",",
"f_containers",
"=",
... | Select remaining containers that didn't have priorities to start | [
"Select",
"remaining",
"containers",
"that",
"didn",
"t",
"have",
"priorities",
"to",
"start"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/api/tools.py#L685-L696 | train | 32,000 |
CyberReboot/vent | vent/api/tools.py | Tools._start_container | def _start_container(self, container, tool_d, s_containers, f_containers):
""" Start container that was passed in and return status """
# use section to add info to manifest
section = tool_d[container]['section']
del tool_d[container]['section']
manifest = Template(self.manifest)
try:
# try to start an existing container first
c = self.d_client.containers.get(container)
c.start()
s_containers.append(container)
manifest.set_option(section, 'running', 'yes')
self.logger.info('started ' + str(container) +
' with ID: ' + str(c.short_id))
except Exception as err:
s_containers, f_containers = self._run_container(
container, tool_d, section, s_containers, f_containers)
# save changes made to manifest
manifest.write_config()
return s_containers, f_containers | python | def _start_container(self, container, tool_d, s_containers, f_containers):
""" Start container that was passed in and return status """
# use section to add info to manifest
section = tool_d[container]['section']
del tool_d[container]['section']
manifest = Template(self.manifest)
try:
# try to start an existing container first
c = self.d_client.containers.get(container)
c.start()
s_containers.append(container)
manifest.set_option(section, 'running', 'yes')
self.logger.info('started ' + str(container) +
' with ID: ' + str(c.short_id))
except Exception as err:
s_containers, f_containers = self._run_container(
container, tool_d, section, s_containers, f_containers)
# save changes made to manifest
manifest.write_config()
return s_containers, f_containers | [
"def",
"_start_container",
"(",
"self",
",",
"container",
",",
"tool_d",
",",
"s_containers",
",",
"f_containers",
")",
":",
"# use section to add info to manifest",
"section",
"=",
"tool_d",
"[",
"container",
"]",
"[",
"'section'",
"]",
"del",
"tool_d",
"[",
"c... | Start container that was passed in and return status | [
"Start",
"container",
"that",
"was",
"passed",
"in",
"and",
"return",
"status"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/api/tools.py#L698-L718 | train | 32,001 |
CyberReboot/vent | vent/api/tools.py | Tools.repo_commits | def repo_commits(self, repo):
""" Get the commit IDs for all of the branches of a repository """
commits = []
try:
status = self.path_dirs.apply_path(repo)
# switch to directory where repo will be cloned to
if status[0]:
cwd = status[1]
else:
self.logger.error('apply_path failed. Exiting repo_commits with'
' status: ' + str(status))
return status
status = self.repo_branches(repo)
if status[0]:
branches = status[1]
for branch in branches:
try:
branch_output = check_output(shlex
.split('git rev-list origin/' +
branch),
stderr=STDOUT,
close_fds=True).decode('utf-8')
branch_output = branch_output.split('\n')[:-1]
branch_output += ['HEAD']
commits.append((branch, branch_output))
except Exception as e: # pragma: no cover
self.logger.error('repo_commits failed with error: ' +
str(e) + ' on branch: ' +
str(branch))
status = (False, e)
return status
else:
self.logger.error('repo_branches failed. Exiting repo_commits'
' with status: ' + str(status))
return status
chdir(cwd)
status = (True, commits)
except Exception as e: # pragma: no cover
self.logger.error('repo_commits failed with error: ' + str(e))
status = (False, e)
return status | python | def repo_commits(self, repo):
""" Get the commit IDs for all of the branches of a repository """
commits = []
try:
status = self.path_dirs.apply_path(repo)
# switch to directory where repo will be cloned to
if status[0]:
cwd = status[1]
else:
self.logger.error('apply_path failed. Exiting repo_commits with'
' status: ' + str(status))
return status
status = self.repo_branches(repo)
if status[0]:
branches = status[1]
for branch in branches:
try:
branch_output = check_output(shlex
.split('git rev-list origin/' +
branch),
stderr=STDOUT,
close_fds=True).decode('utf-8')
branch_output = branch_output.split('\n')[:-1]
branch_output += ['HEAD']
commits.append((branch, branch_output))
except Exception as e: # pragma: no cover
self.logger.error('repo_commits failed with error: ' +
str(e) + ' on branch: ' +
str(branch))
status = (False, e)
return status
else:
self.logger.error('repo_branches failed. Exiting repo_commits'
' with status: ' + str(status))
return status
chdir(cwd)
status = (True, commits)
except Exception as e: # pragma: no cover
self.logger.error('repo_commits failed with error: ' + str(e))
status = (False, e)
return status | [
"def",
"repo_commits",
"(",
"self",
",",
"repo",
")",
":",
"commits",
"=",
"[",
"]",
"try",
":",
"status",
"=",
"self",
".",
"path_dirs",
".",
"apply_path",
"(",
"repo",
")",
"# switch to directory where repo will be cloned to",
"if",
"status",
"[",
"0",
"]"... | Get the commit IDs for all of the branches of a repository | [
"Get",
"the",
"commit",
"IDs",
"for",
"all",
"of",
"the",
"branches",
"of",
"a",
"repository"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/api/tools.py#L858-L901 | train | 32,002 |
CyberReboot/vent | vent/api/tools.py | Tools.repo_branches | def repo_branches(self, repo):
""" Get the branches of a repository """
branches = []
try:
# switch to directory where repo will be cloned to
status = self.path_dirs.apply_path(repo)
if status[0]:
cwd = status[1]
else:
self.logger.error('apply_path failed. Exiting repo_branches'
' with status ' + str(status))
return status
branch_output = check_output(shlex.split('git branch -a'),
stderr=STDOUT,
close_fds=True)
branch_output = branch_output.split(b'\n')
for branch in branch_output:
br = branch.strip()
if br.startswith(b'*'):
br = br[2:]
if b'/' in br:
branches.append(br.rsplit(b'/', 1)[1].decode('utf-8'))
elif br:
branches.append(br.decode('utf-8'))
branches = list(set(branches))
for branch in branches:
try:
check_output(shlex.split('git checkout ' + branch),
stderr=STDOUT,
close_fds=True)
except Exception as e: # pragma: no cover
self.logger.error('repo_branches failed with error: ' +
str(e) + ' on branch: ' + str(branch))
status = (False, e)
return status
chdir(cwd)
status = (True, branches)
except Exception as e: # pragma: no cover
self.logger.error('repo_branches failed with error: ' + str(e))
status = (False, e)
return status | python | def repo_branches(self, repo):
""" Get the branches of a repository """
branches = []
try:
# switch to directory where repo will be cloned to
status = self.path_dirs.apply_path(repo)
if status[0]:
cwd = status[1]
else:
self.logger.error('apply_path failed. Exiting repo_branches'
' with status ' + str(status))
return status
branch_output = check_output(shlex.split('git branch -a'),
stderr=STDOUT,
close_fds=True)
branch_output = branch_output.split(b'\n')
for branch in branch_output:
br = branch.strip()
if br.startswith(b'*'):
br = br[2:]
if b'/' in br:
branches.append(br.rsplit(b'/', 1)[1].decode('utf-8'))
elif br:
branches.append(br.decode('utf-8'))
branches = list(set(branches))
for branch in branches:
try:
check_output(shlex.split('git checkout ' + branch),
stderr=STDOUT,
close_fds=True)
except Exception as e: # pragma: no cover
self.logger.error('repo_branches failed with error: ' +
str(e) + ' on branch: ' + str(branch))
status = (False, e)
return status
chdir(cwd)
status = (True, branches)
except Exception as e: # pragma: no cover
self.logger.error('repo_branches failed with error: ' + str(e))
status = (False, e)
return status | [
"def",
"repo_branches",
"(",
"self",
",",
"repo",
")",
":",
"branches",
"=",
"[",
"]",
"try",
":",
"# switch to directory where repo will be cloned to",
"status",
"=",
"self",
".",
"path_dirs",
".",
"apply_path",
"(",
"repo",
")",
"if",
"status",
"[",
"0",
"... | Get the branches of a repository | [
"Get",
"the",
"branches",
"of",
"a",
"repository"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/api/tools.py#L903-L947 | train | 32,003 |
CyberReboot/vent | vent/api/tools.py | Tools.repo_tools | def repo_tools(self, repo, branch, version):
""" Get available tools for a repository branch at a version """
try:
tools = []
status = self.path_dirs.apply_path(repo)
# switch to directory where repo will be cloned to
if status[0]:
cwd = status[1]
else:
self.logger.error('apply_path failed. Exiting repo_tools with'
' status: ' + str(status))
return status
# TODO commenting out for now, should use update_repo
#status = self.p_helper.checkout(branch=branch, version=version)
status = (True, None)
if status[0]:
path, _, _ = self.path_dirs.get_path(repo)
tools = AvailableTools(path, version=version)
else:
self.logger.error('checkout failed. Exiting repo_tools with'
' status: ' + str(status))
return status
chdir(cwd)
status = (True, tools)
except Exception as e: # pragma: no cover
self.logger.error('repo_tools failed with error: ' + str(e))
status = (False, e)
return status | python | def repo_tools(self, repo, branch, version):
""" Get available tools for a repository branch at a version """
try:
tools = []
status = self.path_dirs.apply_path(repo)
# switch to directory where repo will be cloned to
if status[0]:
cwd = status[1]
else:
self.logger.error('apply_path failed. Exiting repo_tools with'
' status: ' + str(status))
return status
# TODO commenting out for now, should use update_repo
#status = self.p_helper.checkout(branch=branch, version=version)
status = (True, None)
if status[0]:
path, _, _ = self.path_dirs.get_path(repo)
tools = AvailableTools(path, version=version)
else:
self.logger.error('checkout failed. Exiting repo_tools with'
' status: ' + str(status))
return status
chdir(cwd)
status = (True, tools)
except Exception as e: # pragma: no cover
self.logger.error('repo_tools failed with error: ' + str(e))
status = (False, e)
return status | [
"def",
"repo_tools",
"(",
"self",
",",
"repo",
",",
"branch",
",",
"version",
")",
":",
"try",
":",
"tools",
"=",
"[",
"]",
"status",
"=",
"self",
".",
"path_dirs",
".",
"apply_path",
"(",
"repo",
")",
"# switch to directory where repo will be cloned to",
"i... | Get available tools for a repository branch at a version | [
"Get",
"available",
"tools",
"for",
"a",
"repository",
"branch",
"at",
"a",
"version"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/api/tools.py#L949-L980 | train | 32,004 |
CyberReboot/vent | vent/menus/help.py | HelpForm.change_forms | def change_forms(self, *args, **keywords):
"""
Checks which form is currently displayed and toggles to the other one
"""
# Returns to previous Form in history if there is a previous Form
try:
self.parentApp.switchFormPrevious()
except Exception as e: # pragma: no cover
self.parentApp.switchForm('MAIN') | python | def change_forms(self, *args, **keywords):
"""
Checks which form is currently displayed and toggles to the other one
"""
# Returns to previous Form in history if there is a previous Form
try:
self.parentApp.switchFormPrevious()
except Exception as e: # pragma: no cover
self.parentApp.switchForm('MAIN') | [
"def",
"change_forms",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"keywords",
")",
":",
"# Returns to previous Form in history if there is a previous Form",
"try",
":",
"self",
".",
"parentApp",
".",
"switchFormPrevious",
"(",
")",
"except",
"Exception",
"as",
... | Checks which form is currently displayed and toggles to the other one | [
"Checks",
"which",
"form",
"is",
"currently",
"displayed",
"and",
"toggles",
"to",
"the",
"other",
"one"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/help.py#L145-L153 | train | 32,005 |
LettError/MutatorMath | setup.py | capture_logger | def capture_logger(name):
""" Context manager to capture a logger output with a StringIO stream.
"""
import logging
logger = logging.getLogger(name)
try:
import StringIO
stream = StringIO.StringIO()
except ImportError:
from io import StringIO
stream = StringIO()
handler = logging.StreamHandler(stream)
logger.addHandler(handler)
try:
yield stream
finally:
logger.removeHandler(handler) | python | def capture_logger(name):
""" Context manager to capture a logger output with a StringIO stream.
"""
import logging
logger = logging.getLogger(name)
try:
import StringIO
stream = StringIO.StringIO()
except ImportError:
from io import StringIO
stream = StringIO()
handler = logging.StreamHandler(stream)
logger.addHandler(handler)
try:
yield stream
finally:
logger.removeHandler(handler) | [
"def",
"capture_logger",
"(",
"name",
")",
":",
"import",
"logging",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"try",
":",
"import",
"StringIO",
"stream",
"=",
"StringIO",
".",
"StringIO",
"(",
")",
"except",
"ImportError",
":",
"from",... | Context manager to capture a logger output with a StringIO stream. | [
"Context",
"manager",
"to",
"capture",
"a",
"logger",
"output",
"with",
"a",
"StringIO",
"stream",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/setup.py#L10-L27 | train | 32,006 |
LettError/MutatorMath | Lib/mutatorMath/objects/mutator.py | Mutator.setNeutral | def setNeutral(self, aMathObject, deltaName="origin"):
"""Set the neutral object."""
self._neutral = aMathObject
self.addDelta(Location(), aMathObject-aMathObject, deltaName, punch=False, axisOnly=True) | python | def setNeutral(self, aMathObject, deltaName="origin"):
"""Set the neutral object."""
self._neutral = aMathObject
self.addDelta(Location(), aMathObject-aMathObject, deltaName, punch=False, axisOnly=True) | [
"def",
"setNeutral",
"(",
"self",
",",
"aMathObject",
",",
"deltaName",
"=",
"\"origin\"",
")",
":",
"self",
".",
"_neutral",
"=",
"aMathObject",
"self",
".",
"addDelta",
"(",
"Location",
"(",
")",
",",
"aMathObject",
"-",
"aMathObject",
",",
"deltaName",
... | Set the neutral object. | [
"Set",
"the",
"neutral",
"object",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/objects/mutator.py#L98-L101 | train | 32,007 |
LettError/MutatorMath | Lib/mutatorMath/objects/mutator.py | Mutator.getAxisNames | def getAxisNames(self):
"""
Collect a set of axis names from all deltas.
"""
s = {}
for l, x in self.items():
s.update(dict.fromkeys([k for k, v in l], None))
return set(s.keys()) | python | def getAxisNames(self):
"""
Collect a set of axis names from all deltas.
"""
s = {}
for l, x in self.items():
s.update(dict.fromkeys([k for k, v in l], None))
return set(s.keys()) | [
"def",
"getAxisNames",
"(",
"self",
")",
":",
"s",
"=",
"{",
"}",
"for",
"l",
",",
"x",
"in",
"self",
".",
"items",
"(",
")",
":",
"s",
".",
"update",
"(",
"dict",
".",
"fromkeys",
"(",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"l",
"]",
",",
... | Collect a set of axis names from all deltas. | [
"Collect",
"a",
"set",
"of",
"axis",
"names",
"from",
"all",
"deltas",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/objects/mutator.py#L130-L137 | train | 32,008 |
LettError/MutatorMath | Lib/mutatorMath/objects/mutator.py | Mutator._collectAxisPoints | def _collectAxisPoints(self):
"""
Return a dictionary with all on-axis locations.
"""
for l, (value, deltaName) in self.items():
location = Location(l)
name = location.isOnAxis()
if name is not None and name is not False:
if name not in self._axes:
self._axes[name] = []
if l not in self._axes[name]:
self._axes[name].append(l)
return self._axes | python | def _collectAxisPoints(self):
"""
Return a dictionary with all on-axis locations.
"""
for l, (value, deltaName) in self.items():
location = Location(l)
name = location.isOnAxis()
if name is not None and name is not False:
if name not in self._axes:
self._axes[name] = []
if l not in self._axes[name]:
self._axes[name].append(l)
return self._axes | [
"def",
"_collectAxisPoints",
"(",
"self",
")",
":",
"for",
"l",
",",
"(",
"value",
",",
"deltaName",
")",
"in",
"self",
".",
"items",
"(",
")",
":",
"location",
"=",
"Location",
"(",
"l",
")",
"name",
"=",
"location",
".",
"isOnAxis",
"(",
")",
"if... | Return a dictionary with all on-axis locations. | [
"Return",
"a",
"dictionary",
"with",
"all",
"on",
"-",
"axis",
"locations",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/objects/mutator.py#L139-L151 | train | 32,009 |
LettError/MutatorMath | Lib/mutatorMath/objects/mutator.py | Mutator._collectOffAxisPoints | def _collectOffAxisPoints(self):
"""
Return a dictionary with all off-axis locations.
"""
offAxis = {}
for l, (value, deltaName) in self.items():
location = Location(l)
name = location.isOnAxis()
if name is None or name is False:
offAxis[l] = 1
return list(offAxis.keys()) | python | def _collectOffAxisPoints(self):
"""
Return a dictionary with all off-axis locations.
"""
offAxis = {}
for l, (value, deltaName) in self.items():
location = Location(l)
name = location.isOnAxis()
if name is None or name is False:
offAxis[l] = 1
return list(offAxis.keys()) | [
"def",
"_collectOffAxisPoints",
"(",
"self",
")",
":",
"offAxis",
"=",
"{",
"}",
"for",
"l",
",",
"(",
"value",
",",
"deltaName",
")",
"in",
"self",
".",
"items",
"(",
")",
":",
"location",
"=",
"Location",
"(",
"l",
")",
"name",
"=",
"location",
"... | Return a dictionary with all off-axis locations. | [
"Return",
"a",
"dictionary",
"with",
"all",
"off",
"-",
"axis",
"locations",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/objects/mutator.py#L153-L163 | train | 32,010 |
LettError/MutatorMath | Lib/mutatorMath/objects/mutator.py | Mutator.collectLocations | def collectLocations(self):
"""
Return a dictionary with all objects.
"""
pts = []
for l, (value, deltaName) in self.items():
pts.append(Location(l))
return pts | python | def collectLocations(self):
"""
Return a dictionary with all objects.
"""
pts = []
for l, (value, deltaName) in self.items():
pts.append(Location(l))
return pts | [
"def",
"collectLocations",
"(",
"self",
")",
":",
"pts",
"=",
"[",
"]",
"for",
"l",
",",
"(",
"value",
",",
"deltaName",
")",
"in",
"self",
".",
"items",
"(",
")",
":",
"pts",
".",
"append",
"(",
"Location",
"(",
"l",
")",
")",
"return",
"pts"
] | Return a dictionary with all objects. | [
"Return",
"a",
"dictionary",
"with",
"all",
"objects",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/objects/mutator.py#L166-L173 | train | 32,011 |
LettError/MutatorMath | Lib/mutatorMath/objects/mutator.py | Mutator._allLocations | def _allLocations(self):
"""
Return a list of all locations of all objects.
"""
l = []
for locationTuple in self.keys():
l.append(Location(locationTuple))
return l | python | def _allLocations(self):
"""
Return a list of all locations of all objects.
"""
l = []
for locationTuple in self.keys():
l.append(Location(locationTuple))
return l | [
"def",
"_allLocations",
"(",
"self",
")",
":",
"l",
"=",
"[",
"]",
"for",
"locationTuple",
"in",
"self",
".",
"keys",
"(",
")",
":",
"l",
".",
"append",
"(",
"Location",
"(",
"locationTuple",
")",
")",
"return",
"l"
] | Return a list of all locations of all objects. | [
"Return",
"a",
"list",
"of",
"all",
"locations",
"of",
"all",
"objects",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/objects/mutator.py#L175-L182 | train | 32,012 |
LettError/MutatorMath | Lib/mutatorMath/objects/mutator.py | Mutator._accumulateFactors | def _accumulateFactors(self, aLocation, deltaLocation, limits, axisOnly):
"""
Calculate the factors of deltaLocation towards aLocation,
"""
relative = []
deltaAxis = deltaLocation.isOnAxis()
if deltaAxis is None:
relative.append(1)
elif deltaAxis:
deltasOnSameAxis = self._axes.get(deltaAxis, [])
d = ((deltaAxis, 0),)
if d not in deltasOnSameAxis:
deltasOnSameAxis.append(d)
if len(deltasOnSameAxis) == 1:
relative.append(aLocation[deltaAxis] * deltaLocation[deltaAxis])
else:
factor = self._calcOnAxisFactor(aLocation, deltaAxis, deltasOnSameAxis, deltaLocation)
relative.append(factor)
elif not axisOnly:
factor = self._calcOffAxisFactor(aLocation, deltaLocation, limits)
relative.append(factor)
if not relative:
return 0
f = None
for v in relative:
if f is None: f = v
else:
f *= v
return f | python | def _accumulateFactors(self, aLocation, deltaLocation, limits, axisOnly):
"""
Calculate the factors of deltaLocation towards aLocation,
"""
relative = []
deltaAxis = deltaLocation.isOnAxis()
if deltaAxis is None:
relative.append(1)
elif deltaAxis:
deltasOnSameAxis = self._axes.get(deltaAxis, [])
d = ((deltaAxis, 0),)
if d not in deltasOnSameAxis:
deltasOnSameAxis.append(d)
if len(deltasOnSameAxis) == 1:
relative.append(aLocation[deltaAxis] * deltaLocation[deltaAxis])
else:
factor = self._calcOnAxisFactor(aLocation, deltaAxis, deltasOnSameAxis, deltaLocation)
relative.append(factor)
elif not axisOnly:
factor = self._calcOffAxisFactor(aLocation, deltaLocation, limits)
relative.append(factor)
if not relative:
return 0
f = None
for v in relative:
if f is None: f = v
else:
f *= v
return f | [
"def",
"_accumulateFactors",
"(",
"self",
",",
"aLocation",
",",
"deltaLocation",
",",
"limits",
",",
"axisOnly",
")",
":",
"relative",
"=",
"[",
"]",
"deltaAxis",
"=",
"deltaLocation",
".",
"isOnAxis",
"(",
")",
"if",
"deltaAxis",
"is",
"None",
":",
"rela... | Calculate the factors of deltaLocation towards aLocation, | [
"Calculate",
"the",
"factors",
"of",
"deltaLocation",
"towards",
"aLocation"
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/objects/mutator.py#L249-L277 | train | 32,013 |
LettError/MutatorMath | Lib/mutatorMath/objects/mutator.py | Mutator._calcOnAxisFactor | def _calcOnAxisFactor(self, aLocation, deltaAxis, deltasOnSameAxis, deltaLocation):
"""
Calculate the on-axis factors.
"""
if deltaAxis == "origin":
f = 0
v = 0
else:
f = aLocation[deltaAxis]
v = deltaLocation[deltaAxis]
i = []
iv = {}
for value in deltasOnSameAxis:
iv[Location(value)[deltaAxis]]=1
i = sorted(iv.keys())
r = 0
B, M, A = [], [], []
mA, mB, mM = None, None, None
for value in i:
if value < f: B.append(value)
elif value > f: A.append(value)
else: M.append(value)
if len(B) > 0:
mB = max(B)
B.sort()
if len(A) > 0:
mA = min(A)
A.sort()
if len(M) > 0:
mM = min(M)
M.sort()
if mM is not None:
if ((f-_EPSILON < v) and (f+_EPSILON > v)) or f==v: r = 1
else: r = 0
elif mB is not None and mA is not None:
if v < mB or v > mA: r = 0
else:
if v == mA:
r = float(f-mB)/(mA-mB)
else:
r = float(f-mA)/(mB-mA)
elif mB is None and mA is not None:
if v==A[1]:
r = float(f-A[0])/(A[1]-A[0])
elif v == A[0]:
r = float(f-A[1])/(A[0]-A[1])
else:
r = 0
elif mB is not None and mA is None:
if v == B[-2]:
r = float(f-B[-1])/(B[-2]-B[-1])
elif v == mB:
r = float(f-B[-2])/(B[-1]-B[-2])
else:
r = 0
return r | python | def _calcOnAxisFactor(self, aLocation, deltaAxis, deltasOnSameAxis, deltaLocation):
"""
Calculate the on-axis factors.
"""
if deltaAxis == "origin":
f = 0
v = 0
else:
f = aLocation[deltaAxis]
v = deltaLocation[deltaAxis]
i = []
iv = {}
for value in deltasOnSameAxis:
iv[Location(value)[deltaAxis]]=1
i = sorted(iv.keys())
r = 0
B, M, A = [], [], []
mA, mB, mM = None, None, None
for value in i:
if value < f: B.append(value)
elif value > f: A.append(value)
else: M.append(value)
if len(B) > 0:
mB = max(B)
B.sort()
if len(A) > 0:
mA = min(A)
A.sort()
if len(M) > 0:
mM = min(M)
M.sort()
if mM is not None:
if ((f-_EPSILON < v) and (f+_EPSILON > v)) or f==v: r = 1
else: r = 0
elif mB is not None and mA is not None:
if v < mB or v > mA: r = 0
else:
if v == mA:
r = float(f-mB)/(mA-mB)
else:
r = float(f-mA)/(mB-mA)
elif mB is None and mA is not None:
if v==A[1]:
r = float(f-A[0])/(A[1]-A[0])
elif v == A[0]:
r = float(f-A[1])/(A[0]-A[1])
else:
r = 0
elif mB is not None and mA is None:
if v == B[-2]:
r = float(f-B[-1])/(B[-2]-B[-1])
elif v == mB:
r = float(f-B[-2])/(B[-1]-B[-2])
else:
r = 0
return r | [
"def",
"_calcOnAxisFactor",
"(",
"self",
",",
"aLocation",
",",
"deltaAxis",
",",
"deltasOnSameAxis",
",",
"deltaLocation",
")",
":",
"if",
"deltaAxis",
"==",
"\"origin\"",
":",
"f",
"=",
"0",
"v",
"=",
"0",
"else",
":",
"f",
"=",
"aLocation",
"[",
"delt... | Calculate the on-axis factors. | [
"Calculate",
"the",
"on",
"-",
"axis",
"factors",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/objects/mutator.py#L279-L334 | train | 32,014 |
LettError/MutatorMath | Lib/mutatorMath/objects/mutator.py | Mutator._calcOffAxisFactor | def _calcOffAxisFactor(self, aLocation, deltaLocation, limits):
"""
Calculate the off-axis factors.
"""
relative = []
for dim in limits.keys():
f = aLocation[dim]
v = deltaLocation[dim]
mB, M, mA = limits[dim]
r = 0
if mA is not None and v > mA:
relative.append(0)
continue
elif mB is not None and v < mB:
relative.append(0)
continue
if f < v-_EPSILON:
if mB is None:
if M is not None and mA is not None:
if v == M:
r = (float(max(f,mA)-min(f, mA))/float(max(M,mA)-min(M, mA)))
else:
r = -(float(max(f,mA)-min(f, mA))/float(max(M,mA)-min(M, mA)) -1)
else: r = 0
elif mA is None: r = 0
else: r = float(f-mB)/(mA-mB)
elif f > v+_EPSILON:
if mB is None: r = 0
elif mA is None:
if M is not None and mB is not None:
if v == M:
r = (float(max(f,mB)-min(f, mB))/(max(mB, M)-min(mB, M)))
else:
r = -(float(max(f,mB)-min(f, mB))/(max(mB, M)-min(mB, M)) - 1)
else: r = 0
else: r = float(mA-f)/(mA-mB)
else: r = 1
relative.append(r)
f = 1
for i in relative:
f *= i
return f | python | def _calcOffAxisFactor(self, aLocation, deltaLocation, limits):
"""
Calculate the off-axis factors.
"""
relative = []
for dim in limits.keys():
f = aLocation[dim]
v = deltaLocation[dim]
mB, M, mA = limits[dim]
r = 0
if mA is not None and v > mA:
relative.append(0)
continue
elif mB is not None and v < mB:
relative.append(0)
continue
if f < v-_EPSILON:
if mB is None:
if M is not None and mA is not None:
if v == M:
r = (float(max(f,mA)-min(f, mA))/float(max(M,mA)-min(M, mA)))
else:
r = -(float(max(f,mA)-min(f, mA))/float(max(M,mA)-min(M, mA)) -1)
else: r = 0
elif mA is None: r = 0
else: r = float(f-mB)/(mA-mB)
elif f > v+_EPSILON:
if mB is None: r = 0
elif mA is None:
if M is not None and mB is not None:
if v == M:
r = (float(max(f,mB)-min(f, mB))/(max(mB, M)-min(mB, M)))
else:
r = -(float(max(f,mB)-min(f, mB))/(max(mB, M)-min(mB, M)) - 1)
else: r = 0
else: r = float(mA-f)/(mA-mB)
else: r = 1
relative.append(r)
f = 1
for i in relative:
f *= i
return f | [
"def",
"_calcOffAxisFactor",
"(",
"self",
",",
"aLocation",
",",
"deltaLocation",
",",
"limits",
")",
":",
"relative",
"=",
"[",
"]",
"for",
"dim",
"in",
"limits",
".",
"keys",
"(",
")",
":",
"f",
"=",
"aLocation",
"[",
"dim",
"]",
"v",
"=",
"deltaLo... | Calculate the off-axis factors. | [
"Calculate",
"the",
"off",
"-",
"axis",
"factors",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/objects/mutator.py#L336-L377 | train | 32,015 |
LettError/MutatorMath | Lib/mutatorMath/objects/location.py | biasFromLocations | def biasFromLocations(locs, preferOrigin=True):
"""
Find the vector that translates the whole system to the origin.
"""
dims = {}
locs.sort()
for l in locs:
for d in l.keys():
if not d in dims:
dims[d] = []
v = l[d]
if type(v)==tuple:
dims[d].append(v[0])
dims[d].append(v[1])
else:
dims[d].append(v)
candidate = Location()
for k in dims.keys():
dims[k].sort()
v = mostCommon(dims[k])
if dims[k].count(v) > 1:
# add the dimension with two or more hits
candidate[k] = mostCommon(dims[k])
matches = []
# 1. do we have an exact match?
for l in locs:
if candidate == l:
return l
# 2. find a location that matches candidate (but has more dimensions)
for l in locs:
ok = True
for k, v in candidate.items():
if l.get(k)!=v:
ok = False
break
if ok:
if not l in matches:
matches.append(l)
matches.sort()
if len(matches)>0:
if preferOrigin:
for c in matches:
if c.isOrigin():
return c
return matches[0]
# 3. no matches. Find the best from the available locations
results = {}
for bias in locs:
rel = []
for l in locs:
rel.append((l - bias).isOnAxis())
c = rel.count(False)
if not c in results:
results[c] = []
results[c].append(bias)
if results:
candidates = results[min(results.keys())]
if preferOrigin:
for c in candidates:
if c.isOrigin():
return c
candidates.sort()
return candidates[0]
return Location() | python | def biasFromLocations(locs, preferOrigin=True):
"""
Find the vector that translates the whole system to the origin.
"""
dims = {}
locs.sort()
for l in locs:
for d in l.keys():
if not d in dims:
dims[d] = []
v = l[d]
if type(v)==tuple:
dims[d].append(v[0])
dims[d].append(v[1])
else:
dims[d].append(v)
candidate = Location()
for k in dims.keys():
dims[k].sort()
v = mostCommon(dims[k])
if dims[k].count(v) > 1:
# add the dimension with two or more hits
candidate[k] = mostCommon(dims[k])
matches = []
# 1. do we have an exact match?
for l in locs:
if candidate == l:
return l
# 2. find a location that matches candidate (but has more dimensions)
for l in locs:
ok = True
for k, v in candidate.items():
if l.get(k)!=v:
ok = False
break
if ok:
if not l in matches:
matches.append(l)
matches.sort()
if len(matches)>0:
if preferOrigin:
for c in matches:
if c.isOrigin():
return c
return matches[0]
# 3. no matches. Find the best from the available locations
results = {}
for bias in locs:
rel = []
for l in locs:
rel.append((l - bias).isOnAxis())
c = rel.count(False)
if not c in results:
results[c] = []
results[c].append(bias)
if results:
candidates = results[min(results.keys())]
if preferOrigin:
for c in candidates:
if c.isOrigin():
return c
candidates.sort()
return candidates[0]
return Location() | [
"def",
"biasFromLocations",
"(",
"locs",
",",
"preferOrigin",
"=",
"True",
")",
":",
"dims",
"=",
"{",
"}",
"locs",
".",
"sort",
"(",
")",
"for",
"l",
"in",
"locs",
":",
"for",
"d",
"in",
"l",
".",
"keys",
"(",
")",
":",
"if",
"not",
"d",
"in",... | Find the vector that translates the whole system to the origin. | [
"Find",
"the",
"vector",
"that",
"translates",
"the",
"whole",
"system",
"to",
"the",
"origin",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/objects/location.py#L647-L710 | train | 32,016 |
LettError/MutatorMath | Lib/mutatorMath/objects/location.py | Location.getType | def getType(self, short=False):
"""Return a string describing the type of the location, i.e. origin, on axis, off axis etc.
::
>>> l = Location()
>>> l.getType()
'origin'
>>> l = Location(pop=1)
>>> l.getType()
'on-axis, pop'
>>> l = Location(pop=1, snap=1)
>>> l.getType()
'off-axis, pop snap'
>>> l = Location(pop=(1,2))
>>> l.getType()
'on-axis, pop, split'
"""
if self.isOrigin():
return "origin"
t = []
onAxis = self.isOnAxis()
if onAxis is False:
if short:
t.append("off-axis")
else:
t.append("off-axis, "+ " ".join(self.getActiveAxes()))
else:
if short:
t.append("on-axis")
else:
t.append("on-axis, %s"%onAxis)
if self.isAmbivalent():
t.append("split")
return ', '.join(t) | python | def getType(self, short=False):
"""Return a string describing the type of the location, i.e. origin, on axis, off axis etc.
::
>>> l = Location()
>>> l.getType()
'origin'
>>> l = Location(pop=1)
>>> l.getType()
'on-axis, pop'
>>> l = Location(pop=1, snap=1)
>>> l.getType()
'off-axis, pop snap'
>>> l = Location(pop=(1,2))
>>> l.getType()
'on-axis, pop, split'
"""
if self.isOrigin():
return "origin"
t = []
onAxis = self.isOnAxis()
if onAxis is False:
if short:
t.append("off-axis")
else:
t.append("off-axis, "+ " ".join(self.getActiveAxes()))
else:
if short:
t.append("on-axis")
else:
t.append("on-axis, %s"%onAxis)
if self.isAmbivalent():
t.append("split")
return ', '.join(t) | [
"def",
"getType",
"(",
"self",
",",
"short",
"=",
"False",
")",
":",
"if",
"self",
".",
"isOrigin",
"(",
")",
":",
"return",
"\"origin\"",
"t",
"=",
"[",
"]",
"onAxis",
"=",
"self",
".",
"isOnAxis",
"(",
")",
"if",
"onAxis",
"is",
"False",
":",
"... | Return a string describing the type of the location, i.e. origin, on axis, off axis etc.
::
>>> l = Location()
>>> l.getType()
'origin'
>>> l = Location(pop=1)
>>> l.getType()
'on-axis, pop'
>>> l = Location(pop=1, snap=1)
>>> l.getType()
'off-axis, pop snap'
>>> l = Location(pop=(1,2))
>>> l.getType()
'on-axis, pop, split' | [
"Return",
"a",
"string",
"describing",
"the",
"type",
"of",
"the",
"location",
"i",
".",
"e",
".",
"origin",
"on",
"axis",
"off",
"axis",
"etc",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/objects/location.py#L156-L190 | train | 32,017 |
LettError/MutatorMath | Lib/mutatorMath/objects/location.py | Location.distance | def distance(self, other=None):
"""Return the geometric distance to the other location.
If no object is provided, this will calculate the distance to the origin.
::
>>> l = Location(pop=100)
>>> m = Location(pop=200)
>>> l.distance(m)
100.0
>>> l = Location()
>>> m = Location(pop=200)
>>> l.distance(m)
200.0
>>> l = Location(pop=3, snap=5)
>>> m = Location(pop=7, snap=8)
>>> l.distance(m)
5.0
"""
t = 0
if other is None:
other = self.__class__()
for axisName in set(self.keys()) | set(other.keys()):
t += (other.get(axisName,0)-self.get(axisName,0))**2
return math.sqrt(t) | python | def distance(self, other=None):
"""Return the geometric distance to the other location.
If no object is provided, this will calculate the distance to the origin.
::
>>> l = Location(pop=100)
>>> m = Location(pop=200)
>>> l.distance(m)
100.0
>>> l = Location()
>>> m = Location(pop=200)
>>> l.distance(m)
200.0
>>> l = Location(pop=3, snap=5)
>>> m = Location(pop=7, snap=8)
>>> l.distance(m)
5.0
"""
t = 0
if other is None:
other = self.__class__()
for axisName in set(self.keys()) | set(other.keys()):
t += (other.get(axisName,0)-self.get(axisName,0))**2
return math.sqrt(t) | [
"def",
"distance",
"(",
"self",
",",
"other",
"=",
"None",
")",
":",
"t",
"=",
"0",
"if",
"other",
"is",
"None",
":",
"other",
"=",
"self",
".",
"__class__",
"(",
")",
"for",
"axisName",
"in",
"set",
"(",
"self",
".",
"keys",
"(",
")",
")",
"|"... | Return the geometric distance to the other location.
If no object is provided, this will calculate the distance to the origin.
::
>>> l = Location(pop=100)
>>> m = Location(pop=200)
>>> l.distance(m)
100.0
>>> l = Location()
>>> m = Location(pop=200)
>>> l.distance(m)
200.0
>>> l = Location(pop=3, snap=5)
>>> m = Location(pop=7, snap=8)
>>> l.distance(m)
5.0 | [
"Return",
"the",
"geometric",
"distance",
"to",
"the",
"other",
"location",
".",
"If",
"no",
"object",
"is",
"provided",
"this",
"will",
"calculate",
"the",
"distance",
"to",
"the",
"origin",
"."
] | 10318fc4e7c9cee9df6130826829baea3054a42b | https://github.com/LettError/MutatorMath/blob/10318fc4e7c9cee9df6130826829baea3054a42b/Lib/mutatorMath/objects/location.py#L461-L485 | train | 32,018 |
CyberReboot/vent | vent/extras/rmq_es_connector/rmq_es_connector.py | RmqEs.connections | def connections(self, wait):
"""
wait for connections to both rabbitmq and elasticsearch to be made
before binding a routing key to a channel and sending messages to
elasticsearch
"""
while wait:
try:
params = pika.ConnectionParameters(host=self.rmq_host,
port=self.rmq_port)
connection = pika.BlockingConnection(params)
self.channel = connection.channel()
self.channel.exchange_declare(exchange='topic_recs',
exchange_type='topic')
result = self.channel.queue_declare()
self.queue_name = result.method.queue
self.es_conn = Elasticsearch([{'host': self.es_host,
'port': self.es_port}])
wait = False
print('connected to rabbitmq and elasticsearch...')
except Exception as e: # pragma: no cover
print(str(e))
print('waiting for connection to rabbitmq...' + str(e))
time.sleep(2)
wait = True | python | def connections(self, wait):
"""
wait for connections to both rabbitmq and elasticsearch to be made
before binding a routing key to a channel and sending messages to
elasticsearch
"""
while wait:
try:
params = pika.ConnectionParameters(host=self.rmq_host,
port=self.rmq_port)
connection = pika.BlockingConnection(params)
self.channel = connection.channel()
self.channel.exchange_declare(exchange='topic_recs',
exchange_type='topic')
result = self.channel.queue_declare()
self.queue_name = result.method.queue
self.es_conn = Elasticsearch([{'host': self.es_host,
'port': self.es_port}])
wait = False
print('connected to rabbitmq and elasticsearch...')
except Exception as e: # pragma: no cover
print(str(e))
print('waiting for connection to rabbitmq...' + str(e))
time.sleep(2)
wait = True | [
"def",
"connections",
"(",
"self",
",",
"wait",
")",
":",
"while",
"wait",
":",
"try",
":",
"params",
"=",
"pika",
".",
"ConnectionParameters",
"(",
"host",
"=",
"self",
".",
"rmq_host",
",",
"port",
"=",
"self",
".",
"rmq_port",
")",
"connection",
"="... | wait for connections to both rabbitmq and elasticsearch to be made
before binding a routing key to a channel and sending messages to
elasticsearch | [
"wait",
"for",
"connections",
"to",
"both",
"rabbitmq",
"and",
"elasticsearch",
"to",
"be",
"made",
"before",
"binding",
"a",
"routing",
"key",
"to",
"a",
"channel",
"and",
"sending",
"messages",
"to",
"elasticsearch"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/extras/rmq_es_connector/rmq_es_connector.py#L33-L58 | train | 32,019 |
CyberReboot/vent | vent/extras/rmq_es_connector/rmq_es_connector.py | RmqEs.callback | def callback(self, ch, method, properties, body):
"""
callback triggered on rabiitmq message received and sends it to
an elasticsearch index
"""
index = method.routing_key.split('.')[1]
index = index.replace('/', '-')
failed = False
body = str(body)
try:
doc = json.loads(body)
except Exception as e: # pragma: no cover
try:
body = body.strip().replace('"', '\"')
body = '{"log":"' + body + '"}'
doc = json.loads(body)
except Exception as e: # pragma: no cover
failed = True
if not failed:
try:
self.es_conn.index(index=index,
doc_type=method.routing_key.split('.')[1],
id=method.routing_key + '.' +
str(uuid.uuid4()),
body=doc)
except Exception as e: # pragma: no cover
print('Failed to send document to elasticsearch because: ' + str(e)) | python | def callback(self, ch, method, properties, body):
"""
callback triggered on rabiitmq message received and sends it to
an elasticsearch index
"""
index = method.routing_key.split('.')[1]
index = index.replace('/', '-')
failed = False
body = str(body)
try:
doc = json.loads(body)
except Exception as e: # pragma: no cover
try:
body = body.strip().replace('"', '\"')
body = '{"log":"' + body + '"}'
doc = json.loads(body)
except Exception as e: # pragma: no cover
failed = True
if not failed:
try:
self.es_conn.index(index=index,
doc_type=method.routing_key.split('.')[1],
id=method.routing_key + '.' +
str(uuid.uuid4()),
body=doc)
except Exception as e: # pragma: no cover
print('Failed to send document to elasticsearch because: ' + str(e)) | [
"def",
"callback",
"(",
"self",
",",
"ch",
",",
"method",
",",
"properties",
",",
"body",
")",
":",
"index",
"=",
"method",
".",
"routing_key",
".",
"split",
"(",
"'.'",
")",
"[",
"1",
"]",
"index",
"=",
"index",
".",
"replace",
"(",
"'/'",
",",
... | callback triggered on rabiitmq message received and sends it to
an elasticsearch index | [
"callback",
"triggered",
"on",
"rabiitmq",
"message",
"received",
"and",
"sends",
"it",
"to",
"an",
"elasticsearch",
"index"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/extras/rmq_es_connector/rmq_es_connector.py#L60-L87 | train | 32,020 |
CyberReboot/vent | vent/extras/rmq_es_connector/rmq_es_connector.py | RmqEs.start | def start(self):
""" start the channel listener and start consuming messages """
self.connections(True)
binding_keys = sys.argv[1:]
if not binding_keys:
print(sys.stderr,
'Usage: {0!s} [binding_key]...'.format(sys.argv[0]))
sys.exit(0)
for binding_key in binding_keys:
self.channel.queue_bind(exchange='topic_recs',
queue=self.queue_name,
routing_key=binding_key) | python | def start(self):
""" start the channel listener and start consuming messages """
self.connections(True)
binding_keys = sys.argv[1:]
if not binding_keys:
print(sys.stderr,
'Usage: {0!s} [binding_key]...'.format(sys.argv[0]))
sys.exit(0)
for binding_key in binding_keys:
self.channel.queue_bind(exchange='topic_recs',
queue=self.queue_name,
routing_key=binding_key) | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"connections",
"(",
"True",
")",
"binding_keys",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"]",
"if",
"not",
"binding_keys",
":",
"print",
"(",
"sys",
".",
"stderr",
",",
"'Usage: {0!s} [binding_key]...'"... | start the channel listener and start consuming messages | [
"start",
"the",
"channel",
"listener",
"and",
"start",
"consuming",
"messages"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/extras/rmq_es_connector/rmq_es_connector.py#L89-L102 | train | 32,021 |
CyberReboot/vent | vent/extras/rmq_es_connector/rmq_es_connector.py | RmqEs.consume | def consume(self): # pragma: no cover
""" start consuming rabbitmq messages """
print(' [*] Waiting for logs. To exit press CTRL+C')
self.channel.basic_consume(self.queue_name, self.callback)
self.channel.start_consuming() | python | def consume(self): # pragma: no cover
""" start consuming rabbitmq messages """
print(' [*] Waiting for logs. To exit press CTRL+C')
self.channel.basic_consume(self.queue_name, self.callback)
self.channel.start_consuming() | [
"def",
"consume",
"(",
"self",
")",
":",
"# pragma: no cover",
"print",
"(",
"' [*] Waiting for logs. To exit press CTRL+C'",
")",
"self",
".",
"channel",
".",
"basic_consume",
"(",
"self",
".",
"queue_name",
",",
"self",
".",
"callback",
")",
"self",
".",
"chan... | start consuming rabbitmq messages | [
"start",
"consuming",
"rabbitmq",
"messages"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/extras/rmq_es_connector/rmq_es_connector.py#L104-L108 | train | 32,022 |
CyberReboot/vent | vent/api/system.py | System.backup | def backup(self):
"""
Saves the configuration information of the current running vent
instance to be used for restoring at a later time
"""
status = (True, None)
# initialize all needed variables (names for backup files, etc.)
backup_name = ('.vent-backup-' + '-'.join(Timestamp().split(' ')))
backup_dir = join(expanduser('~'), backup_name)
backup_manifest = join(backup_dir, 'backup_manifest.cfg')
backup_vcfg = join(backup_dir, 'backup_vcfg.cfg')
manifest = self.manifest
# create new backup directory
try:
mkdir(backup_dir)
except Exception as e: # pragma: no cover
self.logger.error(str(e))
return (False, str(e))
# create new files in backup directory
try:
# backup manifest
with open(backup_manifest, 'w') as bmanifest:
with open(manifest, 'r') as manifest_file:
bmanifest.write(manifest_file.read())
# backup vent.cfg
with open(backup_vcfg, 'w') as bvcfg:
with open(self.vent_config, 'r') as vcfg_file:
bvcfg.write(vcfg_file.read())
self.logger.info('Backup information written to ' + backup_dir)
status = (True, backup_dir)
except Exception as e: # pragma: no cover
self.logger.error("Couldn't backup vent: " + str(e))
status = (False, str(e))
# TODO #266
return status | python | def backup(self):
"""
Saves the configuration information of the current running vent
instance to be used for restoring at a later time
"""
status = (True, None)
# initialize all needed variables (names for backup files, etc.)
backup_name = ('.vent-backup-' + '-'.join(Timestamp().split(' ')))
backup_dir = join(expanduser('~'), backup_name)
backup_manifest = join(backup_dir, 'backup_manifest.cfg')
backup_vcfg = join(backup_dir, 'backup_vcfg.cfg')
manifest = self.manifest
# create new backup directory
try:
mkdir(backup_dir)
except Exception as e: # pragma: no cover
self.logger.error(str(e))
return (False, str(e))
# create new files in backup directory
try:
# backup manifest
with open(backup_manifest, 'w') as bmanifest:
with open(manifest, 'r') as manifest_file:
bmanifest.write(manifest_file.read())
# backup vent.cfg
with open(backup_vcfg, 'w') as bvcfg:
with open(self.vent_config, 'r') as vcfg_file:
bvcfg.write(vcfg_file.read())
self.logger.info('Backup information written to ' + backup_dir)
status = (True, backup_dir)
except Exception as e: # pragma: no cover
self.logger.error("Couldn't backup vent: " + str(e))
status = (False, str(e))
# TODO #266
return status | [
"def",
"backup",
"(",
"self",
")",
":",
"status",
"=",
"(",
"True",
",",
"None",
")",
"# initialize all needed variables (names for backup files, etc.)",
"backup_name",
"=",
"(",
"'.vent-backup-'",
"+",
"'-'",
".",
"join",
"(",
"Timestamp",
"(",
")",
".",
"split... | Saves the configuration information of the current running vent
instance to be used for restoring at a later time | [
"Saves",
"the",
"configuration",
"information",
"of",
"the",
"current",
"running",
"vent",
"instance",
"to",
"be",
"used",
"for",
"restoring",
"at",
"a",
"later",
"time"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/api/system.py#L132-L167 | train | 32,023 |
CyberReboot/vent | vent/api/system.py | System.reset | def reset(self):
""" Factory reset all of Vent's user data, containers, and images """
status = (True, None)
error_message = ''
# remove containers
try:
c_list = set(self.d_client.containers.list(
filters={'label': 'vent'}, all=True))
for c in c_list:
c.remove(force=True)
except Exception as e: # pragma: no cover
error_message += 'Error removing Vent containers: ' + str(e) + '\n'
# remove images
try:
i_list = set(self.d_client.images.list(filters={'label': 'vent'},
all=True))
for i in i_list:
# delete tagged images only because they are the parents for
# the untagged images. Remove the parents and the children get
# removed automatically
if i.attrs['RepoTags']:
self.d_client.images.remove(image=i.id, force=True)
except Exception as e: # pragma: no cover
error_message += 'Error deleting Vent images: ' + str(e) + '\n'
# remove .vent folder
try:
cwd = getcwd()
if cwd.startswith(join(expanduser('~'), '.vent')):
chdir(expanduser('~'))
shutil.rmtree(join(expanduser('~'), '.vent'))
except Exception as e: # pragma: no cover
error_message += 'Error deleting Vent data: ' + str(e) + '\n'
if error_message:
status = (False, error_message)
return status | python | def reset(self):
""" Factory reset all of Vent's user data, containers, and images """
status = (True, None)
error_message = ''
# remove containers
try:
c_list = set(self.d_client.containers.list(
filters={'label': 'vent'}, all=True))
for c in c_list:
c.remove(force=True)
except Exception as e: # pragma: no cover
error_message += 'Error removing Vent containers: ' + str(e) + '\n'
# remove images
try:
i_list = set(self.d_client.images.list(filters={'label': 'vent'},
all=True))
for i in i_list:
# delete tagged images only because they are the parents for
# the untagged images. Remove the parents and the children get
# removed automatically
if i.attrs['RepoTags']:
self.d_client.images.remove(image=i.id, force=True)
except Exception as e: # pragma: no cover
error_message += 'Error deleting Vent images: ' + str(e) + '\n'
# remove .vent folder
try:
cwd = getcwd()
if cwd.startswith(join(expanduser('~'), '.vent')):
chdir(expanduser('~'))
shutil.rmtree(join(expanduser('~'), '.vent'))
except Exception as e: # pragma: no cover
error_message += 'Error deleting Vent data: ' + str(e) + '\n'
if error_message:
status = (False, error_message)
return status | [
"def",
"reset",
"(",
"self",
")",
":",
"status",
"=",
"(",
"True",
",",
"None",
")",
"error_message",
"=",
"''",
"# remove containers",
"try",
":",
"c_list",
"=",
"set",
"(",
"self",
".",
"d_client",
".",
"containers",
".",
"list",
"(",
"filters",
"=",... | Factory reset all of Vent's user data, containers, and images | [
"Factory",
"reset",
"all",
"of",
"Vent",
"s",
"user",
"data",
"containers",
"and",
"images"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/api/system.py#L189-L228 | train | 32,024 |
CyberReboot/vent | vent/api/system.py | System.get_configure | def get_configure(self,
repo=None,
name=None,
groups=None,
main_cfg=False):
"""
Get the vent.template settings for a given tool by looking at the
plugin_manifest
"""
constraints = locals()
del constraints['main_cfg']
status = (True, None)
template_dict = {}
return_str = ''
if main_cfg:
vent_cfg = Template(self.vent_config)
for section in vent_cfg.sections()[1]:
template_dict[section] = {}
for vals in vent_cfg.section(section)[1]:
template_dict[section][vals[0]] = vals[1]
else:
# all possible vent.template options stored in plugin_manifest
options = ['info', 'service', 'settings', 'docker', 'gpu']
tools = Template(System().manifest).constrain_opts(
constraints, options)[0]
if tools:
# should only be one tool
tool = list(tools.keys())[0]
# load all vent.template options into dict
for section in tools[tool]:
template_dict[section] = json.loads(tools[tool][section])
else:
status = (False, "Couldn't get vent.template information")
if status[0]:
# display all those options as they would in the file
for section in template_dict:
return_str += '[' + section + ']\n'
# ensure instances shows up in configuration
for option in template_dict[section]:
if option.startswith('#'):
return_str += option + '\n'
else:
return_str += option + ' = '
return_str += template_dict[section][option] + '\n'
return_str += '\n'
# only one newline at end of file
status = (True, return_str[:-1])
return status | python | def get_configure(self,
repo=None,
name=None,
groups=None,
main_cfg=False):
"""
Get the vent.template settings for a given tool by looking at the
plugin_manifest
"""
constraints = locals()
del constraints['main_cfg']
status = (True, None)
template_dict = {}
return_str = ''
if main_cfg:
vent_cfg = Template(self.vent_config)
for section in vent_cfg.sections()[1]:
template_dict[section] = {}
for vals in vent_cfg.section(section)[1]:
template_dict[section][vals[0]] = vals[1]
else:
# all possible vent.template options stored in plugin_manifest
options = ['info', 'service', 'settings', 'docker', 'gpu']
tools = Template(System().manifest).constrain_opts(
constraints, options)[0]
if tools:
# should only be one tool
tool = list(tools.keys())[0]
# load all vent.template options into dict
for section in tools[tool]:
template_dict[section] = json.loads(tools[tool][section])
else:
status = (False, "Couldn't get vent.template information")
if status[0]:
# display all those options as they would in the file
for section in template_dict:
return_str += '[' + section + ']\n'
# ensure instances shows up in configuration
for option in template_dict[section]:
if option.startswith('#'):
return_str += option + '\n'
else:
return_str += option + ' = '
return_str += template_dict[section][option] + '\n'
return_str += '\n'
# only one newline at end of file
status = (True, return_str[:-1])
return status | [
"def",
"get_configure",
"(",
"self",
",",
"repo",
"=",
"None",
",",
"name",
"=",
"None",
",",
"groups",
"=",
"None",
",",
"main_cfg",
"=",
"False",
")",
":",
"constraints",
"=",
"locals",
"(",
")",
"del",
"constraints",
"[",
"'main_cfg'",
"]",
"status"... | Get the vent.template settings for a given tool by looking at the
plugin_manifest | [
"Get",
"the",
"vent",
".",
"template",
"settings",
"for",
"a",
"given",
"tool",
"by",
"looking",
"at",
"the",
"plugin_manifest"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/api/system.py#L405-L452 | train | 32,025 |
CyberReboot/vent | vent/menus/add_options.py | AddOptionsForm.repo_values | def repo_values(self):
"""
Set the appropriate repo dir and get the branches and commits of it
"""
branches = []
commits = {}
m_helper = Tools()
status = m_helper.repo_branches(self.parentApp.repo_value['repo'])
# branches and commits must both be retrieved successfully
if status[0]:
branches = status[1]
status = m_helper.repo_commits(self.parentApp.repo_value['repo'])
if status[0]:
r_commits = status[1]
for commit in r_commits:
commits[commit[0]] = commit[1]
else:
# if commits failed, return commit errors
return status
else:
# if branch failed, return branch errors
return status
# if everything is good, return branches with commits
return branches, commits | python | def repo_values(self):
"""
Set the appropriate repo dir and get the branches and commits of it
"""
branches = []
commits = {}
m_helper = Tools()
status = m_helper.repo_branches(self.parentApp.repo_value['repo'])
# branches and commits must both be retrieved successfully
if status[0]:
branches = status[1]
status = m_helper.repo_commits(self.parentApp.repo_value['repo'])
if status[0]:
r_commits = status[1]
for commit in r_commits:
commits[commit[0]] = commit[1]
else:
# if commits failed, return commit errors
return status
else:
# if branch failed, return branch errors
return status
# if everything is good, return branches with commits
return branches, commits | [
"def",
"repo_values",
"(",
"self",
")",
":",
"branches",
"=",
"[",
"]",
"commits",
"=",
"{",
"}",
"m_helper",
"=",
"Tools",
"(",
")",
"status",
"=",
"m_helper",
".",
"repo_branches",
"(",
"self",
".",
"parentApp",
".",
"repo_value",
"[",
"'repo'",
"]",... | Set the appropriate repo dir and get the branches and commits of it | [
"Set",
"the",
"appropriate",
"repo",
"dir",
"and",
"get",
"the",
"branches",
"and",
"commits",
"of",
"it"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/add_options.py#L16-L39 | train | 32,026 |
CyberReboot/vent | vent/menus/add_options.py | AddOptionsForm.on_ok | def on_ok(self):
"""
Take the branch, commit, and build selection and add them as plugins
"""
self.parentApp.repo_value['versions'] = {}
self.parentApp.repo_value['build'] = {}
for branch in self.branch_cb:
if self.branch_cb[branch].value:
# process checkboxes
self.parentApp.repo_value['versions'][branch] = self.commit_tc[branch].values[self.commit_tc[branch].value]
self.parentApp.repo_value['build'][branch] = True
if self.error:
self.quit()
self.parentApp.addForm('CHOOSETOOLS',
ChooseToolsForm,
name='Choose tools to add for new plugin'
'\t\t\t\t\t\t^Q to quit',
color='CONTROL')
self.parentApp.change_form('CHOOSETOOLS') | python | def on_ok(self):
"""
Take the branch, commit, and build selection and add them as plugins
"""
self.parentApp.repo_value['versions'] = {}
self.parentApp.repo_value['build'] = {}
for branch in self.branch_cb:
if self.branch_cb[branch].value:
# process checkboxes
self.parentApp.repo_value['versions'][branch] = self.commit_tc[branch].values[self.commit_tc[branch].value]
self.parentApp.repo_value['build'][branch] = True
if self.error:
self.quit()
self.parentApp.addForm('CHOOSETOOLS',
ChooseToolsForm,
name='Choose tools to add for new plugin'
'\t\t\t\t\t\t^Q to quit',
color='CONTROL')
self.parentApp.change_form('CHOOSETOOLS') | [
"def",
"on_ok",
"(",
"self",
")",
":",
"self",
".",
"parentApp",
".",
"repo_value",
"[",
"'versions'",
"]",
"=",
"{",
"}",
"self",
".",
"parentApp",
".",
"repo_value",
"[",
"'build'",
"]",
"=",
"{",
"}",
"for",
"branch",
"in",
"self",
".",
"branch_cb... | Take the branch, commit, and build selection and add them as plugins | [
"Take",
"the",
"branch",
"commit",
"and",
"build",
"selection",
"and",
"add",
"them",
"as",
"plugins"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/add_options.py#L79-L97 | train | 32,027 |
CyberReboot/vent | vent/menus/add.py | AddForm.create | def create(self):
""" Create widgets for AddForm """
self.add_handlers({'^T': self.quit, '^Q': self.quit})
self.add(npyscreen.Textfield,
value='Add a plugin from a Git repository or an image from a '
'Docker registry.',
editable=False,
color='STANDOUT')
self.add(npyscreen.Textfield,
value='For Git repositories, you can optionally specify a '
'username and password',
editable=False,
color='STANDOUT')
self.add(npyscreen.Textfield,
value='for private repositories.',
editable=False,
color='STANDOUT')
self.add(npyscreen.Textfield,
value='For Docker images, specify a name for referencing the '
'image that is being',
editable=False,
color='STANDOUT')
self.add(npyscreen.Textfield,
value='added and optionally override the tag and/or the '
'registry and specify',
editable=False,
color='STANDOUT')
self.add(npyscreen.Textfield,
value='comma-separated groups this image should belong to.',
editable=False,
color='STANDOUT')
self.nextrely += 1
self.repo = self.add(npyscreen.TitleText,
name='Repository',
value=self.default_repo)
self.user = self.add(npyscreen.TitleText, name='Username')
self.pw = self.add(npyscreen.TitlePassword, name='Password')
self.nextrely += 1
self.add(npyscreen.TitleText,
name='OR',
editable=False,
labelColor='STANDOUT')
self.nextrely += 1
self.image = self.add(npyscreen.TitleText, name='Image')
self.link_name = self.add(npyscreen.TitleText,
name='Name')
self.tag = self.add(npyscreen.TitleText, name='Tag', value='latest')
self.registry = self.add(npyscreen.TitleText,
name='Registry',
value='docker.io')
self.groups = self.add(npyscreen.TitleText, name='Groups')
self.repo.when_value_edited() | python | def create(self):
""" Create widgets for AddForm """
self.add_handlers({'^T': self.quit, '^Q': self.quit})
self.add(npyscreen.Textfield,
value='Add a plugin from a Git repository or an image from a '
'Docker registry.',
editable=False,
color='STANDOUT')
self.add(npyscreen.Textfield,
value='For Git repositories, you can optionally specify a '
'username and password',
editable=False,
color='STANDOUT')
self.add(npyscreen.Textfield,
value='for private repositories.',
editable=False,
color='STANDOUT')
self.add(npyscreen.Textfield,
value='For Docker images, specify a name for referencing the '
'image that is being',
editable=False,
color='STANDOUT')
self.add(npyscreen.Textfield,
value='added and optionally override the tag and/or the '
'registry and specify',
editable=False,
color='STANDOUT')
self.add(npyscreen.Textfield,
value='comma-separated groups this image should belong to.',
editable=False,
color='STANDOUT')
self.nextrely += 1
self.repo = self.add(npyscreen.TitleText,
name='Repository',
value=self.default_repo)
self.user = self.add(npyscreen.TitleText, name='Username')
self.pw = self.add(npyscreen.TitlePassword, name='Password')
self.nextrely += 1
self.add(npyscreen.TitleText,
name='OR',
editable=False,
labelColor='STANDOUT')
self.nextrely += 1
self.image = self.add(npyscreen.TitleText, name='Image')
self.link_name = self.add(npyscreen.TitleText,
name='Name')
self.tag = self.add(npyscreen.TitleText, name='Tag', value='latest')
self.registry = self.add(npyscreen.TitleText,
name='Registry',
value='docker.io')
self.groups = self.add(npyscreen.TitleText, name='Groups')
self.repo.when_value_edited() | [
"def",
"create",
"(",
"self",
")",
":",
"self",
".",
"add_handlers",
"(",
"{",
"'^T'",
":",
"self",
".",
"quit",
",",
"'^Q'",
":",
"self",
".",
"quit",
"}",
")",
"self",
".",
"add",
"(",
"npyscreen",
".",
"Textfield",
",",
"value",
"=",
"'Add a plu... | Create widgets for AddForm | [
"Create",
"widgets",
"for",
"AddForm"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/add.py#L18-L69 | train | 32,028 |
CyberReboot/vent | vent/menus/add.py | AddForm.on_ok | def on_ok(self):
""" Add the repository """
def popup(thr, add_type, title):
"""
Start the thread and display a popup of the plugin being cloned
until the thread is finished
"""
thr.start()
tool_str = 'Cloning repository...'
if add_type == 'image':
tool_str = 'Pulling image...'
npyscreen.notify_wait(tool_str, title=title)
while thr.is_alive():
time.sleep(1)
return
if self.image.value and self.link_name.value:
api_action = Tools()
api_image = Image(System().manifest)
api_system = System()
thr = threading.Thread(target=api_image.add, args=(),
kwargs={'image': self.image.value,
'link_name': self.link_name.value,
'tag': self.tag.value,
'registry': self.registry.value,
'groups': self.groups.value})
popup(thr, 'image', 'Please wait, adding image...')
npyscreen.notify_confirm('Done adding image.', title='Added image')
editor_args = {'tool_name': self.image.value,
'version': self.tag.value,
'get_configure': api_system.get_configure,
'save_configure': api_system.save_configure,
'restart_tools': api_system.restart_tools,
'start_tools': api_action.start,
'from_registry': True,
'just_downloaded': True,
'link_name': self.link_name.value,
'groups': self.groups.value}
self.parentApp.addForm('CONFIGUREIMAGE', EditorForm,
name='Specify vent.template settings for '
'image pulled (optional)', **editor_args)
self.parentApp.change_form('CONFIGUREIMAGE')
elif self.image.value:
npyscreen.notify_confirm('A name needs to be supplied for '
'the image being added!',
title='Specify a name for the image',
form_color='CAUTION')
elif self.repo.value:
self.parentApp.repo_value['repo'] = self.repo.value.lower()
api_repo = Repository(System().manifest)
api_repo.repo = self.repo.value.lower()
thr = threading.Thread(target=api_repo._clone, args=(),
kwargs={'user': self.user.value,
'pw': self.pw.value})
popup(thr, 'repository', 'Please wait, adding repository...')
self.parentApp.addForm('ADDOPTIONS',
AddOptionsForm,
name='Set options for new plugin'
'\t\t\t\t\t\t^Q to quit',
color='CONTROL')
self.parentApp.change_form('ADDOPTIONS')
else:
npyscreen.notify_confirm('Either a repository or an image '
'name must be specified!',
title='Specify plugin to add',
form_color='CAUTION')
return | python | def on_ok(self):
""" Add the repository """
def popup(thr, add_type, title):
"""
Start the thread and display a popup of the plugin being cloned
until the thread is finished
"""
thr.start()
tool_str = 'Cloning repository...'
if add_type == 'image':
tool_str = 'Pulling image...'
npyscreen.notify_wait(tool_str, title=title)
while thr.is_alive():
time.sleep(1)
return
if self.image.value and self.link_name.value:
api_action = Tools()
api_image = Image(System().manifest)
api_system = System()
thr = threading.Thread(target=api_image.add, args=(),
kwargs={'image': self.image.value,
'link_name': self.link_name.value,
'tag': self.tag.value,
'registry': self.registry.value,
'groups': self.groups.value})
popup(thr, 'image', 'Please wait, adding image...')
npyscreen.notify_confirm('Done adding image.', title='Added image')
editor_args = {'tool_name': self.image.value,
'version': self.tag.value,
'get_configure': api_system.get_configure,
'save_configure': api_system.save_configure,
'restart_tools': api_system.restart_tools,
'start_tools': api_action.start,
'from_registry': True,
'just_downloaded': True,
'link_name': self.link_name.value,
'groups': self.groups.value}
self.parentApp.addForm('CONFIGUREIMAGE', EditorForm,
name='Specify vent.template settings for '
'image pulled (optional)', **editor_args)
self.parentApp.change_form('CONFIGUREIMAGE')
elif self.image.value:
npyscreen.notify_confirm('A name needs to be supplied for '
'the image being added!',
title='Specify a name for the image',
form_color='CAUTION')
elif self.repo.value:
self.parentApp.repo_value['repo'] = self.repo.value.lower()
api_repo = Repository(System().manifest)
api_repo.repo = self.repo.value.lower()
thr = threading.Thread(target=api_repo._clone, args=(),
kwargs={'user': self.user.value,
'pw': self.pw.value})
popup(thr, 'repository', 'Please wait, adding repository...')
self.parentApp.addForm('ADDOPTIONS',
AddOptionsForm,
name='Set options for new plugin'
'\t\t\t\t\t\t^Q to quit',
color='CONTROL')
self.parentApp.change_form('ADDOPTIONS')
else:
npyscreen.notify_confirm('Either a repository or an image '
'name must be specified!',
title='Specify plugin to add',
form_color='CAUTION')
return | [
"def",
"on_ok",
"(",
"self",
")",
":",
"def",
"popup",
"(",
"thr",
",",
"add_type",
",",
"title",
")",
":",
"\"\"\"\n Start the thread and display a popup of the plugin being cloned\n until the thread is finished\n \"\"\"",
"thr",
".",
"start",
... | Add the repository | [
"Add",
"the",
"repository"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/add.py#L75-L141 | train | 32,029 |
CyberReboot/vent | vent/menus/tools.py | ToolForm.toggle_view | def toggle_view(self, *args, **kwargs):
""" Toggles the view between different groups """
group_to_display = self.views.popleft()
self.cur_view.value = group_to_display
for repo in self.tools_tc:
for tool in self.tools_tc[repo]:
t_groups = self.manifest.option(tool, 'groups')[1]
if group_to_display not in t_groups and \
group_to_display != 'all groups':
self.tools_tc[repo][tool].value = False
self.tools_tc[repo][tool].hidden = True
else:
self.tools_tc[repo][tool].value = True
self.tools_tc[repo][tool].hidden = False
# redraw elements
self.display()
# add view back to queue
self.views.append(group_to_display) | python | def toggle_view(self, *args, **kwargs):
""" Toggles the view between different groups """
group_to_display = self.views.popleft()
self.cur_view.value = group_to_display
for repo in self.tools_tc:
for tool in self.tools_tc[repo]:
t_groups = self.manifest.option(tool, 'groups')[1]
if group_to_display not in t_groups and \
group_to_display != 'all groups':
self.tools_tc[repo][tool].value = False
self.tools_tc[repo][tool].hidden = True
else:
self.tools_tc[repo][tool].value = True
self.tools_tc[repo][tool].hidden = False
# redraw elements
self.display()
# add view back to queue
self.views.append(group_to_display) | [
"def",
"toggle_view",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"group_to_display",
"=",
"self",
".",
"views",
".",
"popleft",
"(",
")",
"self",
".",
"cur_view",
".",
"value",
"=",
"group_to_display",
"for",
"repo",
"in",
"self"... | Toggles the view between different groups | [
"Toggles",
"the",
"view",
"between",
"different",
"groups"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/tools.py#L63-L80 | train | 32,030 |
CyberReboot/vent | vent/helpers/templates.py | Template.options | def options(self, section):
""" Returns a list of options for a section """
if self.config.has_section(section):
return (True, self.config.options(section))
return (False, 'Section: ' + section + ' does not exist') | python | def options(self, section):
""" Returns a list of options for a section """
if self.config.has_section(section):
return (True, self.config.options(section))
return (False, 'Section: ' + section + ' does not exist') | [
"def",
"options",
"(",
"self",
",",
"section",
")",
":",
"if",
"self",
".",
"config",
".",
"has_section",
"(",
"section",
")",
":",
"return",
"(",
"True",
",",
"self",
".",
"config",
".",
"options",
"(",
"section",
")",
")",
"return",
"(",
"False",
... | Returns a list of options for a section | [
"Returns",
"a",
"list",
"of",
"options",
"for",
"a",
"section"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/templates.py#L30-L34 | train | 32,031 |
CyberReboot/vent | vent/helpers/templates.py | Template.option | def option(self, section, option):
""" Returns the value of the option """
if self.config.has_section(section):
if self.config.has_option(section, option):
return (True, self.config.get(section, option))
return (False, 'Option: ' + option + ' does not exist')
return (False, 'Section: ' + section + ' does not exist') | python | def option(self, section, option):
""" Returns the value of the option """
if self.config.has_section(section):
if self.config.has_option(section, option):
return (True, self.config.get(section, option))
return (False, 'Option: ' + option + ' does not exist')
return (False, 'Section: ' + section + ' does not exist') | [
"def",
"option",
"(",
"self",
",",
"section",
",",
"option",
")",
":",
"if",
"self",
".",
"config",
".",
"has_section",
"(",
"section",
")",
":",
"if",
"self",
".",
"config",
".",
"has_option",
"(",
"section",
",",
"option",
")",
":",
"return",
"(",
... | Returns the value of the option | [
"Returns",
"the",
"value",
"of",
"the",
"option"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/templates.py#L37-L43 | train | 32,032 |
CyberReboot/vent | vent/helpers/templates.py | Template.add_section | def add_section(self, section):
"""
If section exists, returns log,
otherwise adds section and returns list of sections.
"""
# check if section already exists
if not self.config.has_section(section):
self.config.add_section(section)
# return updated sections
return (True, self.config.sections())
return (False, 'Section: ' + section + ' already exists') | python | def add_section(self, section):
"""
If section exists, returns log,
otherwise adds section and returns list of sections.
"""
# check if section already exists
if not self.config.has_section(section):
self.config.add_section(section)
# return updated sections
return (True, self.config.sections())
return (False, 'Section: ' + section + ' already exists') | [
"def",
"add_section",
"(",
"self",
",",
"section",
")",
":",
"# check if section already exists",
"if",
"not",
"self",
".",
"config",
".",
"has_section",
"(",
"section",
")",
":",
"self",
".",
"config",
".",
"add_section",
"(",
"section",
")",
"# return update... | If section exists, returns log,
otherwise adds section and returns list of sections. | [
"If",
"section",
"exists",
"returns",
"log",
"otherwise",
"adds",
"section",
"and",
"returns",
"list",
"of",
"sections",
"."
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/templates.py#L46-L56 | train | 32,033 |
CyberReboot/vent | vent/helpers/templates.py | Template.add_option | def add_option(self, section, option, value=None):
"""
Creates an option for a section. If the section does
not exist, it will create the section.
"""
# check if section exists; create if not
if not self.config.has_section(section):
message = self.add_section(section)
if not message[0]:
return message
if not self.config.has_option(section, option):
if value:
self.config.set(section, option, value)
else:
self.config.set(section, option)
return(True, self.config.options(section))
return(False, 'Option: {} already exists @ {}'.format(option, section)) | python | def add_option(self, section, option, value=None):
"""
Creates an option for a section. If the section does
not exist, it will create the section.
"""
# check if section exists; create if not
if not self.config.has_section(section):
message = self.add_section(section)
if not message[0]:
return message
if not self.config.has_option(section, option):
if value:
self.config.set(section, option, value)
else:
self.config.set(section, option)
return(True, self.config.options(section))
return(False, 'Option: {} already exists @ {}'.format(option, section)) | [
"def",
"add_option",
"(",
"self",
",",
"section",
",",
"option",
",",
"value",
"=",
"None",
")",
":",
"# check if section exists; create if not",
"if",
"not",
"self",
".",
"config",
".",
"has_section",
"(",
"section",
")",
":",
"message",
"=",
"self",
".",
... | Creates an option for a section. If the section does
not exist, it will create the section. | [
"Creates",
"an",
"option",
"for",
"a",
"section",
".",
"If",
"the",
"section",
"does",
"not",
"exist",
"it",
"will",
"create",
"the",
"section",
"."
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/templates.py#L59-L76 | train | 32,034 |
CyberReboot/vent | vent/helpers/templates.py | Template.del_section | def del_section(self, section):
""" Deletes a section if it exists """
if self.config.has_section(section):
self.config.remove_section(section)
return (True, self.config.sections())
return (False, 'Section: ' + section + ' does not exist') | python | def del_section(self, section):
""" Deletes a section if it exists """
if self.config.has_section(section):
self.config.remove_section(section)
return (True, self.config.sections())
return (False, 'Section: ' + section + ' does not exist') | [
"def",
"del_section",
"(",
"self",
",",
"section",
")",
":",
"if",
"self",
".",
"config",
".",
"has_section",
"(",
"section",
")",
":",
"self",
".",
"config",
".",
"remove_section",
"(",
"section",
")",
"return",
"(",
"True",
",",
"self",
".",
"config"... | Deletes a section if it exists | [
"Deletes",
"a",
"section",
"if",
"it",
"exists"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/templates.py#L79-L84 | train | 32,035 |
CyberReboot/vent | vent/helpers/templates.py | Template.del_option | def del_option(self, section, option):
""" Deletes an option if the section and option exist """
if self.config.has_section(section):
if self.config.has_option(section, option):
self.config.remove_option(section, option)
return (True, self.config.options(section))
return (False, 'Option: ' + option + ' does not exist')
return (False, 'Section: ' + section + ' does not exist') | python | def del_option(self, section, option):
""" Deletes an option if the section and option exist """
if self.config.has_section(section):
if self.config.has_option(section, option):
self.config.remove_option(section, option)
return (True, self.config.options(section))
return (False, 'Option: ' + option + ' does not exist')
return (False, 'Section: ' + section + ' does not exist') | [
"def",
"del_option",
"(",
"self",
",",
"section",
",",
"option",
")",
":",
"if",
"self",
".",
"config",
".",
"has_section",
"(",
"section",
")",
":",
"if",
"self",
".",
"config",
".",
"has_option",
"(",
"section",
",",
"option",
")",
":",
"self",
"."... | Deletes an option if the section and option exist | [
"Deletes",
"an",
"option",
"if",
"the",
"section",
"and",
"option",
"exist"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/templates.py#L87-L94 | train | 32,036 |
CyberReboot/vent | vent/helpers/templates.py | Template.set_option | def set_option(self, section, option, value):
"""
Sets an option to a value in the given section. Option is created if it
does not already exist
"""
if self.config.has_section(section):
self.config.set(section, option, value)
return (True, self.config.options(section))
return (False, 'Section: ' + section + ' does not exist') | python | def set_option(self, section, option, value):
"""
Sets an option to a value in the given section. Option is created if it
does not already exist
"""
if self.config.has_section(section):
self.config.set(section, option, value)
return (True, self.config.options(section))
return (False, 'Section: ' + section + ' does not exist') | [
"def",
"set_option",
"(",
"self",
",",
"section",
",",
"option",
",",
"value",
")",
":",
"if",
"self",
".",
"config",
".",
"has_section",
"(",
"section",
")",
":",
"self",
".",
"config",
".",
"set",
"(",
"section",
",",
"option",
",",
"value",
")",
... | Sets an option to a value in the given section. Option is created if it
does not already exist | [
"Sets",
"an",
"option",
"to",
"a",
"value",
"in",
"the",
"given",
"section",
".",
"Option",
"is",
"created",
"if",
"it",
"does",
"not",
"already",
"exist"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/templates.py#L97-L105 | train | 32,037 |
CyberReboot/vent | vent/helpers/templates.py | Template.constrain_opts | def constrain_opts(self, constraint_dict, options):
""" Return result of constraints and options against a template """
constraints = {}
for constraint in constraint_dict:
if constraint != 'self':
if (constraint_dict[constraint] or
constraint_dict[constraint] == ''):
constraints[constraint] = constraint_dict[constraint]
results = self.constrained_sections(constraints=constraints,
options=options)
return results, self.template | python | def constrain_opts(self, constraint_dict, options):
""" Return result of constraints and options against a template """
constraints = {}
for constraint in constraint_dict:
if constraint != 'self':
if (constraint_dict[constraint] or
constraint_dict[constraint] == ''):
constraints[constraint] = constraint_dict[constraint]
results = self.constrained_sections(constraints=constraints,
options=options)
return results, self.template | [
"def",
"constrain_opts",
"(",
"self",
",",
"constraint_dict",
",",
"options",
")",
":",
"constraints",
"=",
"{",
"}",
"for",
"constraint",
"in",
"constraint_dict",
":",
"if",
"constraint",
"!=",
"'self'",
":",
"if",
"(",
"constraint_dict",
"[",
"constraint",
... | Return result of constraints and options against a template | [
"Return",
"result",
"of",
"constraints",
"and",
"options",
"against",
"a",
"template"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/templates.py#L147-L157 | train | 32,038 |
CyberReboot/vent | vent/helpers/templates.py | Template.list_tools | def list_tools(self):
"""
Return list of tuples of all tools
"""
tools = []
exists, sections = self.sections()
if exists:
for section in sections:
options = {'section': section,
'built': None,
'version': None,
'repo': None,
'branch': None,
'name': None,
'groups': None,
'image_name': None}
for option in list(options.keys()):
exists, value = self.option(section, option)
if exists:
options[option] = value
if 'core' not in options['groups'] and 'hidden' not in options['groups']:
tools.append(options)
return tools | python | def list_tools(self):
"""
Return list of tuples of all tools
"""
tools = []
exists, sections = self.sections()
if exists:
for section in sections:
options = {'section': section,
'built': None,
'version': None,
'repo': None,
'branch': None,
'name': None,
'groups': None,
'image_name': None}
for option in list(options.keys()):
exists, value = self.option(section, option)
if exists:
options[option] = value
if 'core' not in options['groups'] and 'hidden' not in options['groups']:
tools.append(options)
return tools | [
"def",
"list_tools",
"(",
"self",
")",
":",
"tools",
"=",
"[",
"]",
"exists",
",",
"sections",
"=",
"self",
".",
"sections",
"(",
")",
"if",
"exists",
":",
"for",
"section",
"in",
"sections",
":",
"options",
"=",
"{",
"'section'",
":",
"section",
","... | Return list of tuples of all tools | [
"Return",
"list",
"of",
"tuples",
"of",
"all",
"tools"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/templates.py#L160-L182 | train | 32,039 |
CyberReboot/vent | vent/menus/del_instances.py | InstanceSelect.when_value_edited | def when_value_edited(self, *args, **kargs):
""" Overrided to prevent user from selecting too many instances """
if len(self.value) > self.instance_num:
self.value.pop(-2)
self.display() | python | def when_value_edited(self, *args, **kargs):
""" Overrided to prevent user from selecting too many instances """
if len(self.value) > self.instance_num:
self.value.pop(-2)
self.display() | [
"def",
"when_value_edited",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"len",
"(",
"self",
".",
"value",
")",
">",
"self",
".",
"instance_num",
":",
"self",
".",
"value",
".",
"pop",
"(",
"-",
"2",
")",
"self",
".",
... | Overrided to prevent user from selecting too many instances | [
"Overrided",
"to",
"prevent",
"user",
"from",
"selecting",
"too",
"many",
"instances"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/del_instances.py#L20-L24 | train | 32,040 |
CyberReboot/vent | vent/menus/del_instances.py | InstanceSelect.safe_to_exit | def safe_to_exit(self, *args, **kargs):
"""
Overrided to prevent user from exiting selection until
they have selected the right amount of instances
"""
if len(self.value) == self.instance_num:
return True
return False | python | def safe_to_exit(self, *args, **kargs):
"""
Overrided to prevent user from exiting selection until
they have selected the right amount of instances
"""
if len(self.value) == self.instance_num:
return True
return False | [
"def",
"safe_to_exit",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"len",
"(",
"self",
".",
"value",
")",
"==",
"self",
".",
"instance_num",
":",
"return",
"True",
"return",
"False"
] | Overrided to prevent user from exiting selection until
they have selected the right amount of instances | [
"Overrided",
"to",
"prevent",
"user",
"from",
"exiting",
"selection",
"until",
"they",
"have",
"selected",
"the",
"right",
"amount",
"of",
"instances"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/del_instances.py#L26-L33 | train | 32,041 |
CyberReboot/vent | vent/menus/del_instances.py | DeleteForm.create | def create(self):
""" Creates the necessary display for this form """
self.add_handlers({'^E': self.quit, '^Q': self.quit})
to_delete = self.old_instances - self.new_instances
self.add(npyscreen.Textfield, value='Select which instances to delete'
' (you must select ' + str(to_delete) +
' instance(s) to delete):', editable=False, color='GOOD')
self.del_instances = self.add(InstanceSelect,
values=self.cur_instances,
scroll_exit=True, rely=3,
instance_num=to_delete) | python | def create(self):
""" Creates the necessary display for this form """
self.add_handlers({'^E': self.quit, '^Q': self.quit})
to_delete = self.old_instances - self.new_instances
self.add(npyscreen.Textfield, value='Select which instances to delete'
' (you must select ' + str(to_delete) +
' instance(s) to delete):', editable=False, color='GOOD')
self.del_instances = self.add(InstanceSelect,
values=self.cur_instances,
scroll_exit=True, rely=3,
instance_num=to_delete) | [
"def",
"create",
"(",
"self",
")",
":",
"self",
".",
"add_handlers",
"(",
"{",
"'^E'",
":",
"self",
".",
"quit",
",",
"'^Q'",
":",
"self",
".",
"quit",
"}",
")",
"to_delete",
"=",
"self",
".",
"old_instances",
"-",
"self",
".",
"new_instances",
"self... | Creates the necessary display for this form | [
"Creates",
"the",
"necessary",
"display",
"for",
"this",
"form"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/del_instances.py#L60-L70 | train | 32,042 |
CyberReboot/vent | vent/menus/del_instances.py | DeleteForm.on_ok | def on_ok(self):
""" Delete the instances that the user chose to delete """
npyscreen.notify_wait('Deleting instances given...',
title='In progress')
# keep track of number for shifting instances down for alignment
shift_num = 1
to_update = []
for i, val in enumerate(self.del_instances.values):
# clean all tools for renmaing and relabeling purposes
t = val.split(':')
section = self.display_to_section[val]
prev_running = self.manifest.option(section, 'running')
run = prev_running[0] and prev_running[1] == 'yes'
if i in self.del_instances.value:
if run:
# grab dependencies of tools that linked to previous one
if i == 0:
dependent_tools = [self.manifest.option(
section, 'link_name')[1]]
for dependency in Dependencies(dependent_tools):
self.clean(**dependency)
to_update.append(dependency)
self.clean(name=t[0], branch=t[1], version=t[2])
self.manifest.del_section(section)
else:
try:
# update instances for tools remaining
section = self.display_to_section[val]
settings_dict = json.loads(self.manifest.option
(section, 'settings')[1])
settings_dict['instances'] = self.new_instances
self.manifest.set_option(section, 'settings',
json.dumps(settings_dict))
# check if tool name doesn't need to be shifted because
# it's already correct
identifier = str(shift_num) if shift_num != 1 else ''
new_section = section.rsplit(':', 2)
new_section[0] = re.sub(r'\d+$', identifier,
new_section[0])
new_section = ':'.join(new_section)
if section != new_section:
# clean tool so that we can rename its container and
# labels with new information
self.clean(name=t[0], branch=t[1], version=t[2])
prev_name = self.manifest.option(section, 'name')[1]
new_name = re.split(r'[0-9]', prev_name)[0] + \
identifier
self.manifest.set_option(section, 'name', new_name)
# copy new contents into shifted version
self.manifest.add_section(new_section)
for val_pair in self.manifest.section(section)[1]:
self.manifest.set_option(new_section, val_pair[0],
val_pair[1])
self.manifest.del_section(section)
if run:
to_update.append({'name': new_name,
'branch': t[1],
'version': t[2]})
shift_num += 1
except Exception as e:
npyscreen.notify_confirm('Trouble deleting tools'
' because ' + str(e))
self.manifest.write_config()
tool_d = {}
for tool in to_update:
tool_d.update(self.prep_start(**tool)[1])
if tool_d:
self.start_tools(tool_d)
npyscreen.notify_confirm('Done deleting instances.',
title='Finished')
self.change_screens() | python | def on_ok(self):
""" Delete the instances that the user chose to delete """
npyscreen.notify_wait('Deleting instances given...',
title='In progress')
# keep track of number for shifting instances down for alignment
shift_num = 1
to_update = []
for i, val in enumerate(self.del_instances.values):
# clean all tools for renmaing and relabeling purposes
t = val.split(':')
section = self.display_to_section[val]
prev_running = self.manifest.option(section, 'running')
run = prev_running[0] and prev_running[1] == 'yes'
if i in self.del_instances.value:
if run:
# grab dependencies of tools that linked to previous one
if i == 0:
dependent_tools = [self.manifest.option(
section, 'link_name')[1]]
for dependency in Dependencies(dependent_tools):
self.clean(**dependency)
to_update.append(dependency)
self.clean(name=t[0], branch=t[1], version=t[2])
self.manifest.del_section(section)
else:
try:
# update instances for tools remaining
section = self.display_to_section[val]
settings_dict = json.loads(self.manifest.option
(section, 'settings')[1])
settings_dict['instances'] = self.new_instances
self.manifest.set_option(section, 'settings',
json.dumps(settings_dict))
# check if tool name doesn't need to be shifted because
# it's already correct
identifier = str(shift_num) if shift_num != 1 else ''
new_section = section.rsplit(':', 2)
new_section[0] = re.sub(r'\d+$', identifier,
new_section[0])
new_section = ':'.join(new_section)
if section != new_section:
# clean tool so that we can rename its container and
# labels with new information
self.clean(name=t[0], branch=t[1], version=t[2])
prev_name = self.manifest.option(section, 'name')[1]
new_name = re.split(r'[0-9]', prev_name)[0] + \
identifier
self.manifest.set_option(section, 'name', new_name)
# copy new contents into shifted version
self.manifest.add_section(new_section)
for val_pair in self.manifest.section(section)[1]:
self.manifest.set_option(new_section, val_pair[0],
val_pair[1])
self.manifest.del_section(section)
if run:
to_update.append({'name': new_name,
'branch': t[1],
'version': t[2]})
shift_num += 1
except Exception as e:
npyscreen.notify_confirm('Trouble deleting tools'
' because ' + str(e))
self.manifest.write_config()
tool_d = {}
for tool in to_update:
tool_d.update(self.prep_start(**tool)[1])
if tool_d:
self.start_tools(tool_d)
npyscreen.notify_confirm('Done deleting instances.',
title='Finished')
self.change_screens() | [
"def",
"on_ok",
"(",
"self",
")",
":",
"npyscreen",
".",
"notify_wait",
"(",
"'Deleting instances given...'",
",",
"title",
"=",
"'In progress'",
")",
"# keep track of number for shifting instances down for alignment",
"shift_num",
"=",
"1",
"to_update",
"=",
"[",
"]",
... | Delete the instances that the user chose to delete | [
"Delete",
"the",
"instances",
"that",
"the",
"user",
"chose",
"to",
"delete"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/del_instances.py#L85-L155 | train | 32,043 |
CyberReboot/vent | vent/extras/network_tap/ncontrol/paths.py | DeleteR.on_post | def on_post(self, req, resp):
"""
Send a POST request with a docker container ID and it will be deleted.
Example input: {'id': "12345"}, {'id': ["123", "456"]}
"""
resp.content_type = falcon.MEDIA_TEXT
resp.status = falcon.HTTP_200
# verify user input
payload = {}
if req.content_length:
try:
payload = json.load(req.stream)
except Exception as e: # pragma: no cover
resp.body = "(False, 'malformed payload')"
return
else:
resp.body = "(False, 'malformed payload')"
return
# verify payload has a container ID
if 'id' not in payload:
resp.body = "(False, 'payload missing id')"
return
# connect to docker and stop the given container
c = None
try:
c = docker.from_env()
except Exception as e: # pragma: no cover
resp.body = "(False, 'unable to connect to docker because: " + str(e) + "')"
return
# delete containers chosen from CLI
try:
for container_id in payload['id']:
c.containers.get(container_id).remove()
except Exception as e: # pragma: no cover
resp.body = "(False, 'unable to delete containers because: " + str(e) + "')"
return
resp.body = '(True, ' + str(payload['id']) + ')'
return | python | def on_post(self, req, resp):
"""
Send a POST request with a docker container ID and it will be deleted.
Example input: {'id': "12345"}, {'id': ["123", "456"]}
"""
resp.content_type = falcon.MEDIA_TEXT
resp.status = falcon.HTTP_200
# verify user input
payload = {}
if req.content_length:
try:
payload = json.load(req.stream)
except Exception as e: # pragma: no cover
resp.body = "(False, 'malformed payload')"
return
else:
resp.body = "(False, 'malformed payload')"
return
# verify payload has a container ID
if 'id' not in payload:
resp.body = "(False, 'payload missing id')"
return
# connect to docker and stop the given container
c = None
try:
c = docker.from_env()
except Exception as e: # pragma: no cover
resp.body = "(False, 'unable to connect to docker because: " + str(e) + "')"
return
# delete containers chosen from CLI
try:
for container_id in payload['id']:
c.containers.get(container_id).remove()
except Exception as e: # pragma: no cover
resp.body = "(False, 'unable to delete containers because: " + str(e) + "')"
return
resp.body = '(True, ' + str(payload['id']) + ')'
return | [
"def",
"on_post",
"(",
"self",
",",
"req",
",",
"resp",
")",
":",
"resp",
".",
"content_type",
"=",
"falcon",
".",
"MEDIA_TEXT",
"resp",
".",
"status",
"=",
"falcon",
".",
"HTTP_200",
"# verify user input",
"payload",
"=",
"{",
"}",
"if",
"req",
".",
"... | Send a POST request with a docker container ID and it will be deleted.
Example input: {'id': "12345"}, {'id': ["123", "456"]} | [
"Send",
"a",
"POST",
"request",
"with",
"a",
"docker",
"container",
"ID",
"and",
"it",
"will",
"be",
"deleted",
"."
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/extras/network_tap/ncontrol/paths.py#L97-L140 | train | 32,044 |
CyberReboot/vent | vent/extras/network_tap/ncontrol/paths.py | ListR.on_get | def on_get(self, req, resp):
"""
Send a GET request to get the list of all of the filter containers
"""
resp.content_type = falcon.MEDIA_TEXT
resp.status = falcon.HTTP_200
# connect to docker
try:
containers = docker.from_env()
except Exception as e: # pragma: no cover
resp.body = "(False, 'unable to connect to docker because: " + str(e) + "')"
return
# search for all docker containers and grab ncapture containers
container_list = []
try:
for c in containers.containers.list(all=True):
# TODO: maybe find a way to not have to hard code image name
if c.attrs['Config']['Image'] == \
'cyberreboot/vent-ncapture:master':
# the core container is not what we want
if 'core' not in c.attrs['Config']['Labels']['vent.groups']:
lst = {}
lst['id'] = c.attrs['Id'][:12]
lst['status'] = c.attrs['State']['Status']
lst['args'] = c.attrs['Args']
container_list.append(lst)
except Exception as e: # pragma: no cover
resp.body = "(False, 'Failure because: " + str(e) + "')"
return
resp.body = json.dumps(container_list)
return | python | def on_get(self, req, resp):
"""
Send a GET request to get the list of all of the filter containers
"""
resp.content_type = falcon.MEDIA_TEXT
resp.status = falcon.HTTP_200
# connect to docker
try:
containers = docker.from_env()
except Exception as e: # pragma: no cover
resp.body = "(False, 'unable to connect to docker because: " + str(e) + "')"
return
# search for all docker containers and grab ncapture containers
container_list = []
try:
for c in containers.containers.list(all=True):
# TODO: maybe find a way to not have to hard code image name
if c.attrs['Config']['Image'] == \
'cyberreboot/vent-ncapture:master':
# the core container is not what we want
if 'core' not in c.attrs['Config']['Labels']['vent.groups']:
lst = {}
lst['id'] = c.attrs['Id'][:12]
lst['status'] = c.attrs['State']['Status']
lst['args'] = c.attrs['Args']
container_list.append(lst)
except Exception as e: # pragma: no cover
resp.body = "(False, 'Failure because: " + str(e) + "')"
return
resp.body = json.dumps(container_list)
return | [
"def",
"on_get",
"(",
"self",
",",
"req",
",",
"resp",
")",
":",
"resp",
".",
"content_type",
"=",
"falcon",
".",
"MEDIA_TEXT",
"resp",
".",
"status",
"=",
"falcon",
".",
"HTTP_200",
"# connect to docker",
"try",
":",
"containers",
"=",
"docker",
".",
"f... | Send a GET request to get the list of all of the filter containers | [
"Send",
"a",
"GET",
"request",
"to",
"get",
"the",
"list",
"of",
"all",
"of",
"the",
"filter",
"containers"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/extras/network_tap/ncontrol/paths.py#L160-L193 | train | 32,045 |
CyberReboot/vent | vent/extras/network_tap/ncontrol/paths.py | NICsR.on_get | def on_get(self, req, resp):
"""
Send a GET request to get the list of all available network interfaces
"""
resp.content_type = falcon.MEDIA_TEXT
resp.status = falcon.HTTP_200
# connect to docker
try:
d_client = docker.from_env()
except Exception as e: # pragma: no cover
resp.body = "(False, 'unable to connect to docker because: " + str(e) + "')"
return
# start container to get network interfaces
nics = ''
try:
nics = d_client.containers.run('cyberreboot/gonet',
network_mode='host', remove=True)
resp.body = '(True, ' + str(nics.id) + ')'
except Exception as e: # pragma: no cover
resp.body = "(False, 'Failure because: " + str(e) + "')"
return
return | python | def on_get(self, req, resp):
"""
Send a GET request to get the list of all available network interfaces
"""
resp.content_type = falcon.MEDIA_TEXT
resp.status = falcon.HTTP_200
# connect to docker
try:
d_client = docker.from_env()
except Exception as e: # pragma: no cover
resp.body = "(False, 'unable to connect to docker because: " + str(e) + "')"
return
# start container to get network interfaces
nics = ''
try:
nics = d_client.containers.run('cyberreboot/gonet',
network_mode='host', remove=True)
resp.body = '(True, ' + str(nics.id) + ')'
except Exception as e: # pragma: no cover
resp.body = "(False, 'Failure because: " + str(e) + "')"
return
return | [
"def",
"on_get",
"(",
"self",
",",
"req",
",",
"resp",
")",
":",
"resp",
".",
"content_type",
"=",
"falcon",
".",
"MEDIA_TEXT",
"resp",
".",
"status",
"=",
"falcon",
".",
"HTTP_200",
"# connect to docker",
"try",
":",
"d_client",
"=",
"docker",
".",
"fro... | Send a GET request to get the list of all available network interfaces | [
"Send",
"a",
"GET",
"request",
"to",
"get",
"the",
"list",
"of",
"all",
"available",
"network",
"interfaces"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/extras/network_tap/ncontrol/paths.py#L201-L225 | train | 32,046 |
CyberReboot/vent | vent/menus/tutorials.py | TutorialForm.create | def create(self):
""" Overridden to add handlers and content """
self.add_handlers({'^Q': self.quit})
self.add(npyscreen.TitleText, name=self.title, editable=False)
self.add(npyscreen.MultiLineEdit, editable=False, value=self.text,
max_width=75, slow_scroll=True)
self.m2 = self.add_menu(name='About Vent', shortcut='v')
self.m2.addItem(text='Background', onSelect=self.switch,
arguments=['TUTORIALBACKGROUND'], shortcut='b')
self.m2.addItem(text='Terminology', onSelect=self.switch,
arguments=['TUTORIALTERMINOLOGY'], shortcut='t')
self.m2.addItem(text='Getting Setup', onSelect=self.switch,
arguments=['TUTORIALGETTINGSETUP'], shortcut='s')
self.m3 = self.add_menu(name='Working with Cores', shortcut='c')
self.m3.addItem(text='Starting Cores', onSelect=self.switch,
arguments=['TUTORIALSTARTINGCORES'], shortcut='c')
self.m4 = self.add_menu(name='Working with Plugins', shortcut='p')
self.m4.addItem(text='Adding Plugins', onSelect=self.switch,
arguments=['TUTORIALADDINGPLUGINS'], shortcut='a')
self.m5 = self.add_menu(name='Files', shortcut='f')
self.m5.addItem(text='Adding Files', onSelect=self.switch,
arguments=['TUTORIALADDINGFILES'], shortcut='a')
self.m6 = self.add_menu(name='Help', shortcut='s')
self.m6.addItem(text='Basic Troubleshooting', onSelect=self.switch,
arguments=['TUTORIALTROUBLESHOOTING'], shortcut='t') | python | def create(self):
""" Overridden to add handlers and content """
self.add_handlers({'^Q': self.quit})
self.add(npyscreen.TitleText, name=self.title, editable=False)
self.add(npyscreen.MultiLineEdit, editable=False, value=self.text,
max_width=75, slow_scroll=True)
self.m2 = self.add_menu(name='About Vent', shortcut='v')
self.m2.addItem(text='Background', onSelect=self.switch,
arguments=['TUTORIALBACKGROUND'], shortcut='b')
self.m2.addItem(text='Terminology', onSelect=self.switch,
arguments=['TUTORIALTERMINOLOGY'], shortcut='t')
self.m2.addItem(text='Getting Setup', onSelect=self.switch,
arguments=['TUTORIALGETTINGSETUP'], shortcut='s')
self.m3 = self.add_menu(name='Working with Cores', shortcut='c')
self.m3.addItem(text='Starting Cores', onSelect=self.switch,
arguments=['TUTORIALSTARTINGCORES'], shortcut='c')
self.m4 = self.add_menu(name='Working with Plugins', shortcut='p')
self.m4.addItem(text='Adding Plugins', onSelect=self.switch,
arguments=['TUTORIALADDINGPLUGINS'], shortcut='a')
self.m5 = self.add_menu(name='Files', shortcut='f')
self.m5.addItem(text='Adding Files', onSelect=self.switch,
arguments=['TUTORIALADDINGFILES'], shortcut='a')
self.m6 = self.add_menu(name='Help', shortcut='s')
self.m6.addItem(text='Basic Troubleshooting', onSelect=self.switch,
arguments=['TUTORIALTROUBLESHOOTING'], shortcut='t') | [
"def",
"create",
"(",
"self",
")",
":",
"self",
".",
"add_handlers",
"(",
"{",
"'^Q'",
":",
"self",
".",
"quit",
"}",
")",
"self",
".",
"add",
"(",
"npyscreen",
".",
"TitleText",
",",
"name",
"=",
"self",
".",
"title",
",",
"editable",
"=",
"False"... | Overridden to add handlers and content | [
"Overridden",
"to",
"add",
"handlers",
"and",
"content"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/tutorials.py#L22-L46 | train | 32,047 |
CyberReboot/vent | vent/menus/backup.py | BackupForm.create | def create(self):
""" Add backup files to select from """
self.add_handlers({'^T': self.quit})
self.add(npyscreen.Textfield, value='Pick a version to restore from: ',
editable=False, color='STANDOUT')
self.dir_select = self.add(npyscreen.SelectOne,
values=self.display_vals,
scroll_exit=True, rely=4) | python | def create(self):
""" Add backup files to select from """
self.add_handlers({'^T': self.quit})
self.add(npyscreen.Textfield, value='Pick a version to restore from: ',
editable=False, color='STANDOUT')
self.dir_select = self.add(npyscreen.SelectOne,
values=self.display_vals,
scroll_exit=True, rely=4) | [
"def",
"create",
"(",
"self",
")",
":",
"self",
".",
"add_handlers",
"(",
"{",
"'^T'",
":",
"self",
".",
"quit",
"}",
")",
"self",
".",
"add",
"(",
"npyscreen",
".",
"Textfield",
",",
"value",
"=",
"'Pick a version to restore from: '",
",",
"editable",
"... | Add backup files to select from | [
"Add",
"backup",
"files",
"to",
"select",
"from"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/backup.py#L18-L25 | train | 32,048 |
CyberReboot/vent | vent/menus/backup.py | BackupForm.on_ok | def on_ok(self):
""" Perform restoration on the backup file selected """
if self.dir_select.value:
npyscreen.notify_wait('In the process of restoring',
title='Restoring...')
status = self.restore(self.dirs[self.dir_select.value[0]])
if status[0]:
npyscreen.notify_confirm('Status of restore:\n' +
status[1])
else:
npyscreen.notify_confirm(status[1])
self.quit()
else:
npyscreen.notify_confirm('Choose a version to restore from') | python | def on_ok(self):
""" Perform restoration on the backup file selected """
if self.dir_select.value:
npyscreen.notify_wait('In the process of restoring',
title='Restoring...')
status = self.restore(self.dirs[self.dir_select.value[0]])
if status[0]:
npyscreen.notify_confirm('Status of restore:\n' +
status[1])
else:
npyscreen.notify_confirm(status[1])
self.quit()
else:
npyscreen.notify_confirm('Choose a version to restore from') | [
"def",
"on_ok",
"(",
"self",
")",
":",
"if",
"self",
".",
"dir_select",
".",
"value",
":",
"npyscreen",
".",
"notify_wait",
"(",
"'In the process of restoring'",
",",
"title",
"=",
"'Restoring...'",
")",
"status",
"=",
"self",
".",
"restore",
"(",
"self",
... | Perform restoration on the backup file selected | [
"Perform",
"restoration",
"on",
"the",
"backup",
"file",
"selected"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/backup.py#L30-L43 | train | 32,049 |
CyberReboot/vent | vent/helpers/paths.py | PathDirs.ensure_dir | def ensure_dir(path):
"""
Tries to create directory, if fails, checks if path already exists
"""
try:
makedirs(path)
except OSError as e: # pragma: no cover
if e.errno == errno.EEXIST and isdir(path):
return (True, 'exists')
else:
return (False, e)
return (True, path) | python | def ensure_dir(path):
"""
Tries to create directory, if fails, checks if path already exists
"""
try:
makedirs(path)
except OSError as e: # pragma: no cover
if e.errno == errno.EEXIST and isdir(path):
return (True, 'exists')
else:
return (False, e)
return (True, path) | [
"def",
"ensure_dir",
"(",
"path",
")",
":",
"try",
":",
"makedirs",
"(",
"path",
")",
"except",
"OSError",
"as",
"e",
":",
"# pragma: no cover",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
"and",
"isdir",
"(",
"path",
")",
":",
"return",
"... | Tries to create directory, if fails, checks if path already exists | [
"Tries",
"to",
"create",
"directory",
"if",
"fails",
"checks",
"if",
"path",
"already",
"exists"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/paths.py#L42-L53 | train | 32,050 |
CyberReboot/vent | vent/helpers/paths.py | PathDirs.ensure_file | def ensure_file(path):
""" Checks if file exists, if fails, tries to create file """
try:
exists = isfile(path)
if not exists:
with open(path, 'w+') as fname:
fname.write('initialized')
return (True, path)
return (True, 'exists')
except OSError as e: # pragma: no cover
return (False, e) | python | def ensure_file(path):
""" Checks if file exists, if fails, tries to create file """
try:
exists = isfile(path)
if not exists:
with open(path, 'w+') as fname:
fname.write('initialized')
return (True, path)
return (True, 'exists')
except OSError as e: # pragma: no cover
return (False, e) | [
"def",
"ensure_file",
"(",
"path",
")",
":",
"try",
":",
"exists",
"=",
"isfile",
"(",
"path",
")",
"if",
"not",
"exists",
":",
"with",
"open",
"(",
"path",
",",
"'w+'",
")",
"as",
"fname",
":",
"fname",
".",
"write",
"(",
"'initialized'",
")",
"re... | Checks if file exists, if fails, tries to create file | [
"Checks",
"if",
"file",
"exists",
"if",
"fails",
"tries",
"to",
"create",
"file"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/paths.py#L56-L66 | train | 32,051 |
CyberReboot/vent | vent/helpers/paths.py | PathDirs.host_config | def host_config(self):
""" Ensure the host configuration file exists """
if platform.system() == 'Darwin':
default_file_dir = join(expanduser('~'),
'vent_files')
else:
default_file_dir = '/opt/vent_files'
status = self.ensure_dir(default_file_dir)
if not isfile(self.cfg_file):
config = Template(template=self.cfg_file)
sections = {'main': {'files': default_file_dir},
'network-mapping': {},
'nvidia-docker-plugin': {'port': '3476'}}
for s in sections:
if sections[s]:
for option in sections[s]:
config.add_option(s, option, sections[s][option])
else:
config.add_section(s)
config.write_config()
return status | python | def host_config(self):
""" Ensure the host configuration file exists """
if platform.system() == 'Darwin':
default_file_dir = join(expanduser('~'),
'vent_files')
else:
default_file_dir = '/opt/vent_files'
status = self.ensure_dir(default_file_dir)
if not isfile(self.cfg_file):
config = Template(template=self.cfg_file)
sections = {'main': {'files': default_file_dir},
'network-mapping': {},
'nvidia-docker-plugin': {'port': '3476'}}
for s in sections:
if sections[s]:
for option in sections[s]:
config.add_option(s, option, sections[s][option])
else:
config.add_section(s)
config.write_config()
return status | [
"def",
"host_config",
"(",
"self",
")",
":",
"if",
"platform",
".",
"system",
"(",
")",
"==",
"'Darwin'",
":",
"default_file_dir",
"=",
"join",
"(",
"expanduser",
"(",
"'~'",
")",
",",
"'vent_files'",
")",
"else",
":",
"default_file_dir",
"=",
"'/opt/vent_... | Ensure the host configuration file exists | [
"Ensure",
"the",
"host",
"configuration",
"file",
"exists"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/paths.py#L89-L109 | train | 32,052 |
CyberReboot/vent | vent/helpers/paths.py | PathDirs.apply_path | def apply_path(self, repo):
""" Set path to where the repo is and return original path """
try:
# rewrite repo for consistency
if repo.endswith('.git'):
repo = repo.split('.git')[0]
# get org and repo name and path repo will be cloned to
org, name = repo.split('/')[-2:]
path = join(self.plugins_dir, org, name)
# save current path
cwd = getcwd()
# set to new repo path
self.ensure_dir(path)
chdir(path)
status = (True, cwd, path)
except Exception as e: # pragma: no cover
status = (False, str(e))
return status | python | def apply_path(self, repo):
""" Set path to where the repo is and return original path """
try:
# rewrite repo for consistency
if repo.endswith('.git'):
repo = repo.split('.git')[0]
# get org and repo name and path repo will be cloned to
org, name = repo.split('/')[-2:]
path = join(self.plugins_dir, org, name)
# save current path
cwd = getcwd()
# set to new repo path
self.ensure_dir(path)
chdir(path)
status = (True, cwd, path)
except Exception as e: # pragma: no cover
status = (False, str(e))
return status | [
"def",
"apply_path",
"(",
"self",
",",
"repo",
")",
":",
"try",
":",
"# rewrite repo for consistency",
"if",
"repo",
".",
"endswith",
"(",
"'.git'",
")",
":",
"repo",
"=",
"repo",
".",
"split",
"(",
"'.git'",
")",
"[",
"0",
"]",
"# get org and repo name an... | Set path to where the repo is and return original path | [
"Set",
"path",
"to",
"where",
"the",
"repo",
"is",
"and",
"return",
"original",
"path"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/paths.py#L111-L131 | train | 32,053 |
CyberReboot/vent | vent/helpers/paths.py | PathDirs.get_path | def get_path(self, repo):
""" Return the path for the repo """
if repo.endswith('.git'):
repo = repo.split('.git')[0]
org, name = repo.split('/')[-2:]
path = self.plugins_dir
path = join(path, org, name)
return path, org, name | python | def get_path(self, repo):
""" Return the path for the repo """
if repo.endswith('.git'):
repo = repo.split('.git')[0]
org, name = repo.split('/')[-2:]
path = self.plugins_dir
path = join(path, org, name)
return path, org, name | [
"def",
"get_path",
"(",
"self",
",",
"repo",
")",
":",
"if",
"repo",
".",
"endswith",
"(",
"'.git'",
")",
":",
"repo",
"=",
"repo",
".",
"split",
"(",
"'.git'",
")",
"[",
"0",
"]",
"org",
",",
"name",
"=",
"repo",
".",
"split",
"(",
"'/'",
")",... | Return the path for the repo | [
"Return",
"the",
"path",
"for",
"the",
"repo"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/paths.py#L133-L140 | train | 32,054 |
CyberReboot/vent | vent/helpers/paths.py | PathDirs.override_config | def override_config(self, path):
"""
Will take a yml located in home directory titled '.plugin_config.yml'.
It'll then override, using the yml, the plugin's config file
"""
status = (True, None)
config_override = False
try:
# parse the yml file
c_dict = {}
if exists(self.plugin_config_file):
with open(self.plugin_config_file, 'r') as config_file:
c_dict = yaml.safe_load(config_file.read())
# check for environment variable overrides
check_c_dict = c_dict.copy()
for tool in check_c_dict:
for section in check_c_dict[tool]:
for key in check_c_dict[tool][section]:
if key in environ:
c_dict[tool][section][key] = getenv(key)
# assume the name of the plugin is its directory
plugin_name = path.split('/')[-1]
if plugin_name == '':
plugin_name = path.split('/')[-2]
plugin_config_path = path + '/config/' + plugin_name + '.config'
if exists(plugin_config_path):
plugin_template = Template(plugin_config_path)
plugin_options = c_dict[plugin_name]
for section in plugin_options:
for option in plugin_options[section]:
plugin_template.set_option(section, option,
str(plugin_options[section][option]))
plugin_template.write_config()
config_override = True
except Exception as e: # pragma: no cover
status = (False, str(e))
return status, config_override | python | def override_config(self, path):
"""
Will take a yml located in home directory titled '.plugin_config.yml'.
It'll then override, using the yml, the plugin's config file
"""
status = (True, None)
config_override = False
try:
# parse the yml file
c_dict = {}
if exists(self.plugin_config_file):
with open(self.plugin_config_file, 'r') as config_file:
c_dict = yaml.safe_load(config_file.read())
# check for environment variable overrides
check_c_dict = c_dict.copy()
for tool in check_c_dict:
for section in check_c_dict[tool]:
for key in check_c_dict[tool][section]:
if key in environ:
c_dict[tool][section][key] = getenv(key)
# assume the name of the plugin is its directory
plugin_name = path.split('/')[-1]
if plugin_name == '':
plugin_name = path.split('/')[-2]
plugin_config_path = path + '/config/' + plugin_name + '.config'
if exists(plugin_config_path):
plugin_template = Template(plugin_config_path)
plugin_options = c_dict[plugin_name]
for section in plugin_options:
for option in plugin_options[section]:
plugin_template.set_option(section, option,
str(plugin_options[section][option]))
plugin_template.write_config()
config_override = True
except Exception as e: # pragma: no cover
status = (False, str(e))
return status, config_override | [
"def",
"override_config",
"(",
"self",
",",
"path",
")",
":",
"status",
"=",
"(",
"True",
",",
"None",
")",
"config_override",
"=",
"False",
"try",
":",
"# parse the yml file",
"c_dict",
"=",
"{",
"}",
"if",
"exists",
"(",
"self",
".",
"plugin_config_file"... | Will take a yml located in home directory titled '.plugin_config.yml'.
It'll then override, using the yml, the plugin's config file | [
"Will",
"take",
"a",
"yml",
"located",
"in",
"home",
"directory",
"titled",
".",
"plugin_config",
".",
"yml",
".",
"It",
"ll",
"then",
"override",
"using",
"the",
"yml",
"the",
"plugin",
"s",
"config",
"file"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/paths.py#L142-L183 | train | 32,055 |
CyberReboot/vent | vent/helpers/meta.py | Logs | def Logs(c_type=None, grep_list=None):
""" Generically filter logs stored in log containers """
def get_logs(logs, log_entries):
try:
for log in logs:
if str(container.name) in log_entries:
log_entries[str(container.name)].append(log)
else:
log_entries[str(container.name)] = [log]
except Exception as e: # pragma: no cover
logger.error('Unable to get logs for ' +
str(container.name) +
' because: ' + str(e))
return log_entries
status = (True, None)
log_entries = {}
d_client = docker.from_env()
containers = d_client.containers.list(all=True,
filters={'label': 'vent'})
logger.debug('containers found: ' + str(containers))
comp_c = containers
if c_type:
try:
comp_c = [c for c in containers
if (c_type
in c.attrs['Config']['Labels']['vent.groups'])]
except Exception as e: # pragma: no cover
logger.error('Unable to limit containers by: ' +
str(c_type) + ' because: ' +
str(e))
if grep_list:
for expression in grep_list:
for container in comp_c:
try:
# 'logs' stores each line containing the expression
logs = [log for log in container.logs().split('\n')
if expression in log]
log_entries = get_logs(logs, log_entries)
except Exception as e: # pragma: no cover
logger.info('Unable to get logs for ' +
str(container) +
' because: ' + str(e))
else:
for container in comp_c:
try:
logs = container.logs().split('\n')
log_entries = get_logs(logs, log_entries)
except Exception as e: # pragma: no cover
logger.info('Unabled to get logs for ' +
str(container) +
' because: ' + str(e))
status = (True, log_entries)
return status | python | def Logs(c_type=None, grep_list=None):
""" Generically filter logs stored in log containers """
def get_logs(logs, log_entries):
try:
for log in logs:
if str(container.name) in log_entries:
log_entries[str(container.name)].append(log)
else:
log_entries[str(container.name)] = [log]
except Exception as e: # pragma: no cover
logger.error('Unable to get logs for ' +
str(container.name) +
' because: ' + str(e))
return log_entries
status = (True, None)
log_entries = {}
d_client = docker.from_env()
containers = d_client.containers.list(all=True,
filters={'label': 'vent'})
logger.debug('containers found: ' + str(containers))
comp_c = containers
if c_type:
try:
comp_c = [c for c in containers
if (c_type
in c.attrs['Config']['Labels']['vent.groups'])]
except Exception as e: # pragma: no cover
logger.error('Unable to limit containers by: ' +
str(c_type) + ' because: ' +
str(e))
if grep_list:
for expression in grep_list:
for container in comp_c:
try:
# 'logs' stores each line containing the expression
logs = [log for log in container.logs().split('\n')
if expression in log]
log_entries = get_logs(logs, log_entries)
except Exception as e: # pragma: no cover
logger.info('Unable to get logs for ' +
str(container) +
' because: ' + str(e))
else:
for container in comp_c:
try:
logs = container.logs().split('\n')
log_entries = get_logs(logs, log_entries)
except Exception as e: # pragma: no cover
logger.info('Unabled to get logs for ' +
str(container) +
' because: ' + str(e))
status = (True, log_entries)
return status | [
"def",
"Logs",
"(",
"c_type",
"=",
"None",
",",
"grep_list",
"=",
"None",
")",
":",
"def",
"get_logs",
"(",
"logs",
",",
"log_entries",
")",
":",
"try",
":",
"for",
"log",
"in",
"logs",
":",
"if",
"str",
"(",
"container",
".",
"name",
")",
"in",
... | Generically filter logs stored in log containers | [
"Generically",
"filter",
"logs",
"stored",
"in",
"log",
"containers"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/meta.py#L32-L87 | train | 32,056 |
CyberReboot/vent | vent/helpers/meta.py | Version | def Version():
""" Get Vent version """
version = ''
try:
version = pkg_resources.require('vent')[0].version
if not version.startswith('v'):
version = 'v' + version
except Exception as e: # pragma: no cover
version = 'Error: ' + str(e)
return version | python | def Version():
""" Get Vent version """
version = ''
try:
version = pkg_resources.require('vent')[0].version
if not version.startswith('v'):
version = 'v' + version
except Exception as e: # pragma: no cover
version = 'Error: ' + str(e)
return version | [
"def",
"Version",
"(",
")",
":",
"version",
"=",
"''",
"try",
":",
"version",
"=",
"pkg_resources",
".",
"require",
"(",
"'vent'",
")",
"[",
"0",
"]",
".",
"version",
"if",
"not",
"version",
".",
"startswith",
"(",
"'v'",
")",
":",
"version",
"=",
... | Get Vent version | [
"Get",
"Vent",
"version"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/meta.py#L90-L99 | train | 32,057 |
CyberReboot/vent | vent/helpers/meta.py | Docker | def Docker():
""" Get Docker setup information """
docker_info = {'server': {}, 'env': '', 'type': '', 'os': ''}
# get docker server version
try:
d_client = docker.from_env()
docker_info['server'] = d_client.version()
except Exception as e: # pragma: no cover
logger.error("Can't get docker info " + str(e))
# get operating system
system = System()
docker_info['os'] = system
# check if native or using docker-machine
if 'DOCKER_MACHINE_NAME' in environ:
# using docker-machine
docker_info['env'] = environ['DOCKER_MACHINE_NAME']
docker_info['type'] = 'docker-machine'
elif 'DOCKER_HOST' in environ:
# not native
docker_info['env'] = environ['DOCKER_HOST']
docker_info['type'] = 'remote'
else:
# using "local" server
docker_info['type'] = 'native'
return docker_info | python | def Docker():
""" Get Docker setup information """
docker_info = {'server': {}, 'env': '', 'type': '', 'os': ''}
# get docker server version
try:
d_client = docker.from_env()
docker_info['server'] = d_client.version()
except Exception as e: # pragma: no cover
logger.error("Can't get docker info " + str(e))
# get operating system
system = System()
docker_info['os'] = system
# check if native or using docker-machine
if 'DOCKER_MACHINE_NAME' in environ:
# using docker-machine
docker_info['env'] = environ['DOCKER_MACHINE_NAME']
docker_info['type'] = 'docker-machine'
elif 'DOCKER_HOST' in environ:
# not native
docker_info['env'] = environ['DOCKER_HOST']
docker_info['type'] = 'remote'
else:
# using "local" server
docker_info['type'] = 'native'
return docker_info | [
"def",
"Docker",
"(",
")",
":",
"docker_info",
"=",
"{",
"'server'",
":",
"{",
"}",
",",
"'env'",
":",
"''",
",",
"'type'",
":",
"''",
",",
"'os'",
":",
"''",
"}",
"# get docker server version",
"try",
":",
"d_client",
"=",
"docker",
".",
"from_env",
... | Get Docker setup information | [
"Get",
"Docker",
"setup",
"information"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/meta.py#L107-L134 | train | 32,058 |
CyberReboot/vent | vent/helpers/meta.py | Containers | def Containers(vent=True, running=True, exclude_labels=None):
"""
Get containers that are created, by default limit to vent containers that
are running
"""
containers = []
try:
d_client = docker.from_env()
if vent:
c = d_client.containers.list(all=not running,
filters={'label': 'vent'})
else:
c = d_client.containers.list(all=not running)
for container in c:
include = True
if exclude_labels:
for label in exclude_labels:
if 'vent.groups' in container.labels and label in container.labels['vent.groups']:
include = False
if include:
containers.append((container.name, container.status))
except Exception as e: # pragma: no cover
logger.error('Docker problem ' + str(e))
return containers | python | def Containers(vent=True, running=True, exclude_labels=None):
"""
Get containers that are created, by default limit to vent containers that
are running
"""
containers = []
try:
d_client = docker.from_env()
if vent:
c = d_client.containers.list(all=not running,
filters={'label': 'vent'})
else:
c = d_client.containers.list(all=not running)
for container in c:
include = True
if exclude_labels:
for label in exclude_labels:
if 'vent.groups' in container.labels and label in container.labels['vent.groups']:
include = False
if include:
containers.append((container.name, container.status))
except Exception as e: # pragma: no cover
logger.error('Docker problem ' + str(e))
return containers | [
"def",
"Containers",
"(",
"vent",
"=",
"True",
",",
"running",
"=",
"True",
",",
"exclude_labels",
"=",
"None",
")",
":",
"containers",
"=",
"[",
"]",
"try",
":",
"d_client",
"=",
"docker",
".",
"from_env",
"(",
")",
"if",
"vent",
":",
"c",
"=",
"d... | Get containers that are created, by default limit to vent containers that
are running | [
"Get",
"containers",
"that",
"are",
"created",
"by",
"default",
"limit",
"to",
"vent",
"containers",
"that",
"are",
"running"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/meta.py#L137-L162 | train | 32,059 |
CyberReboot/vent | vent/helpers/meta.py | Cpu | def Cpu():
""" Get number of available CPUs """
cpu = 'Unknown'
try:
cpu = str(multiprocessing.cpu_count())
except Exception as e: # pragma: no cover
logger.error("Can't access CPU count' " + str(e))
return cpu | python | def Cpu():
""" Get number of available CPUs """
cpu = 'Unknown'
try:
cpu = str(multiprocessing.cpu_count())
except Exception as e: # pragma: no cover
logger.error("Can't access CPU count' " + str(e))
return cpu | [
"def",
"Cpu",
"(",
")",
":",
"cpu",
"=",
"'Unknown'",
"try",
":",
"cpu",
"=",
"str",
"(",
"multiprocessing",
".",
"cpu_count",
"(",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"# pragma: no cover",
"logger",
".",
"error",
"(",
"\"Can't access CPU coun... | Get number of available CPUs | [
"Get",
"number",
"of",
"available",
"CPUs"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/meta.py#L165-L173 | train | 32,060 |
CyberReboot/vent | vent/helpers/meta.py | Gpu | def Gpu(pull=False):
""" Check for support of GPUs, and return what's available """
gpu = (False, '')
try:
image = 'nvidia/cuda:8.0-runtime'
image_name, tag = image.split(':')
d_client = docker.from_env()
nvidia_image = d_client.images.list(name=image)
if pull and len(nvidia_image) == 0:
try:
d_client.images.pull(image_name, tag=tag)
nvidia_image = d_client.images.list(name=image)
except Exception as e: # pragma: no cover
logger.error('Something with the GPU went wrong ' + str(e))
if len(nvidia_image) > 0:
cmd = 'nvidia-docker run --rm ' + image + ' nvidia-smi -L'
proc = Popen([cmd],
stdout=PIPE,
stderr=PIPE,
shell=True,
close_fds=True)
gpus = proc.stdout.read()
err = proc.stderr.read()
if gpus:
gpu_str = ''
for line in gpus.strip().split('\n'):
gpu_str += line.split(' (UUID: ')[0] + ', '
gpu = (True, gpu_str[:-2])
else:
if err:
gpu = (False, 'Unknown', str(err))
else:
gpu = (False, 'None')
else:
gpu = (False, 'None')
except Exception as e: # pragma: no cover
gpu = (False, 'Unknown', str(e))
return gpu | python | def Gpu(pull=False):
""" Check for support of GPUs, and return what's available """
gpu = (False, '')
try:
image = 'nvidia/cuda:8.0-runtime'
image_name, tag = image.split(':')
d_client = docker.from_env()
nvidia_image = d_client.images.list(name=image)
if pull and len(nvidia_image) == 0:
try:
d_client.images.pull(image_name, tag=tag)
nvidia_image = d_client.images.list(name=image)
except Exception as e: # pragma: no cover
logger.error('Something with the GPU went wrong ' + str(e))
if len(nvidia_image) > 0:
cmd = 'nvidia-docker run --rm ' + image + ' nvidia-smi -L'
proc = Popen([cmd],
stdout=PIPE,
stderr=PIPE,
shell=True,
close_fds=True)
gpus = proc.stdout.read()
err = proc.stderr.read()
if gpus:
gpu_str = ''
for line in gpus.strip().split('\n'):
gpu_str += line.split(' (UUID: ')[0] + ', '
gpu = (True, gpu_str[:-2])
else:
if err:
gpu = (False, 'Unknown', str(err))
else:
gpu = (False, 'None')
else:
gpu = (False, 'None')
except Exception as e: # pragma: no cover
gpu = (False, 'Unknown', str(e))
return gpu | [
"def",
"Gpu",
"(",
"pull",
"=",
"False",
")",
":",
"gpu",
"=",
"(",
"False",
",",
"''",
")",
"try",
":",
"image",
"=",
"'nvidia/cuda:8.0-runtime'",
"image_name",
",",
"tag",
"=",
"image",
".",
"split",
"(",
"':'",
")",
"d_client",
"=",
"docker",
".",... | Check for support of GPUs, and return what's available | [
"Check",
"for",
"support",
"of",
"GPUs",
"and",
"return",
"what",
"s",
"available"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/meta.py#L176-L216 | train | 32,061 |
CyberReboot/vent | vent/helpers/meta.py | Images | def Images(vent=True):
""" Get images that are build, by default limit to vent images """
images = []
# TODO needs to also check images in the manifest that couldn't have the
# label added
try:
d_client = docker.from_env()
if vent:
i = d_client.images.list(filters={'label': 'vent'})
else:
i = d_client.images.list()
for image in i:
images.append((image.tags[0], image.short_id))
except Exception as e: # pragma: no cover
logger.error('Something with the Images went wrong ' + str(e))
return images | python | def Images(vent=True):
""" Get images that are build, by default limit to vent images """
images = []
# TODO needs to also check images in the manifest that couldn't have the
# label added
try:
d_client = docker.from_env()
if vent:
i = d_client.images.list(filters={'label': 'vent'})
else:
i = d_client.images.list()
for image in i:
images.append((image.tags[0], image.short_id))
except Exception as e: # pragma: no cover
logger.error('Something with the Images went wrong ' + str(e))
return images | [
"def",
"Images",
"(",
"vent",
"=",
"True",
")",
":",
"images",
"=",
"[",
"]",
"# TODO needs to also check images in the manifest that couldn't have the",
"# label added",
"try",
":",
"d_client",
"=",
"docker",
".",
"from_env",
"(",
")",
"if",
"vent",
":",
"i"... | Get images that are build, by default limit to vent images | [
"Get",
"images",
"that",
"are",
"build",
"by",
"default",
"limit",
"to",
"vent",
"images"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/meta.py#L314-L330 | train | 32,062 |
CyberReboot/vent | vent/helpers/meta.py | ManifestTools | def ManifestTools(**kargs):
""" Get tools that exist in the manifest """
path_dirs = PathDirs(**kargs)
manifest = join(path_dirs.meta_dir, 'plugin_manifest.cfg')
template = Template(template=manifest)
tools = template.sections()
return tools[1] | python | def ManifestTools(**kargs):
""" Get tools that exist in the manifest """
path_dirs = PathDirs(**kargs)
manifest = join(path_dirs.meta_dir, 'plugin_manifest.cfg')
template = Template(template=manifest)
tools = template.sections()
return tools[1] | [
"def",
"ManifestTools",
"(",
"*",
"*",
"kargs",
")",
":",
"path_dirs",
"=",
"PathDirs",
"(",
"*",
"*",
"kargs",
")",
"manifest",
"=",
"join",
"(",
"path_dirs",
".",
"meta_dir",
",",
"'plugin_manifest.cfg'",
")",
"template",
"=",
"Template",
"(",
"template"... | Get tools that exist in the manifest | [
"Get",
"tools",
"that",
"exist",
"in",
"the",
"manifest"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/meta.py#L433-L439 | train | 32,063 |
CyberReboot/vent | vent/helpers/meta.py | ToolMatches | def ToolMatches(tools=None, version='HEAD'):
""" Get the tools paths and versions that were specified """
matches = []
if tools:
for tool in tools:
match_version = version
if tool[1] != '':
match_version = tool[1]
match = ''
if tool[0].endswith('/'):
match = tool[0][:-1]
elif tool[0] != '.':
match = tool[0]
if not match.startswith('/') and match != '':
match = '/'+match
matches.append((match, match_version))
return matches | python | def ToolMatches(tools=None, version='HEAD'):
""" Get the tools paths and versions that were specified """
matches = []
if tools:
for tool in tools:
match_version = version
if tool[1] != '':
match_version = tool[1]
match = ''
if tool[0].endswith('/'):
match = tool[0][:-1]
elif tool[0] != '.':
match = tool[0]
if not match.startswith('/') and match != '':
match = '/'+match
matches.append((match, match_version))
return matches | [
"def",
"ToolMatches",
"(",
"tools",
"=",
"None",
",",
"version",
"=",
"'HEAD'",
")",
":",
"matches",
"=",
"[",
"]",
"if",
"tools",
":",
"for",
"tool",
"in",
"tools",
":",
"match_version",
"=",
"version",
"if",
"tool",
"[",
"1",
"]",
"!=",
"''",
":"... | Get the tools paths and versions that were specified | [
"Get",
"the",
"tools",
"paths",
"and",
"versions",
"that",
"were",
"specified"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/meta.py#L519-L535 | train | 32,064 |
CyberReboot/vent | vent/helpers/meta.py | Timestamp | def Timestamp():
""" Get the current datetime in UTC """
timestamp = ''
try:
timestamp = str(datetime.datetime.now())+' UTC'
except Exception as e: # pragma: no cover
logger.error('Could not get current time ' + str(e))
return timestamp | python | def Timestamp():
""" Get the current datetime in UTC """
timestamp = ''
try:
timestamp = str(datetime.datetime.now())+' UTC'
except Exception as e: # pragma: no cover
logger.error('Could not get current time ' + str(e))
return timestamp | [
"def",
"Timestamp",
"(",
")",
":",
"timestamp",
"=",
"''",
"try",
":",
"timestamp",
"=",
"str",
"(",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
")",
"+",
"' UTC'",
"except",
"Exception",
"as",
"e",
":",
"# pragma: no cover",
"logger",
".",
"err... | Get the current datetime in UTC | [
"Get",
"the",
"current",
"datetime",
"in",
"UTC"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/meta.py#L653-L660 | train | 32,065 |
CyberReboot/vent | vent/helpers/meta.py | Uptime | def Uptime():
""" Get the current uptime information """
uptime = ''
try:
uptime = check_output(['uptime'], close_fds=True).decode('utf-8')[1:]
except Exception as e: # pragma: no cover
logger.error('Could not get current uptime ' + str(e))
return uptime | python | def Uptime():
""" Get the current uptime information """
uptime = ''
try:
uptime = check_output(['uptime'], close_fds=True).decode('utf-8')[1:]
except Exception as e: # pragma: no cover
logger.error('Could not get current uptime ' + str(e))
return uptime | [
"def",
"Uptime",
"(",
")",
":",
"uptime",
"=",
"''",
"try",
":",
"uptime",
"=",
"check_output",
"(",
"[",
"'uptime'",
"]",
",",
"close_fds",
"=",
"True",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"[",
"1",
":",
"]",
"except",
"Exception",
"as",
"e",... | Get the current uptime information | [
"Get",
"the",
"current",
"uptime",
"information"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/meta.py#L663-L670 | train | 32,066 |
CyberReboot/vent | vent/helpers/meta.py | DropLocation | def DropLocation():
""" Get the directory that file drop is watching """
template = Template(template=PathDirs().cfg_file)
drop_loc = template.option('main', 'files')[1]
drop_loc = expanduser(drop_loc)
drop_loc = abspath(drop_loc)
return (True, drop_loc) | python | def DropLocation():
""" Get the directory that file drop is watching """
template = Template(template=PathDirs().cfg_file)
drop_loc = template.option('main', 'files')[1]
drop_loc = expanduser(drop_loc)
drop_loc = abspath(drop_loc)
return (True, drop_loc) | [
"def",
"DropLocation",
"(",
")",
":",
"template",
"=",
"Template",
"(",
"template",
"=",
"PathDirs",
"(",
")",
".",
"cfg_file",
")",
"drop_loc",
"=",
"template",
".",
"option",
"(",
"'main'",
",",
"'files'",
")",
"[",
"1",
"]",
"drop_loc",
"=",
"expand... | Get the directory that file drop is watching | [
"Get",
"the",
"directory",
"that",
"file",
"drop",
"is",
"watching"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/meta.py#L673-L679 | train | 32,067 |
CyberReboot/vent | vent/helpers/meta.py | ParsedSections | def ParsedSections(file_val):
"""
Get the sections and options of a file returned as a dictionary
"""
try:
template_dict = {}
cur_section = ''
for val in file_val.split('\n'):
val = val.strip()
if val != '':
section_match = re.match(r'\[.+\]', val)
if section_match:
cur_section = section_match.group()[1:-1]
template_dict[cur_section] = {}
else:
option, value = val.split('=', 1)
option = option.strip()
value = value.strip()
if option.startswith('#'):
template_dict[cur_section][val] = ''
else:
template_dict[cur_section][option] = value
except Exception: # pragma: no cover
template_dict = {}
return template_dict | python | def ParsedSections(file_val):
"""
Get the sections and options of a file returned as a dictionary
"""
try:
template_dict = {}
cur_section = ''
for val in file_val.split('\n'):
val = val.strip()
if val != '':
section_match = re.match(r'\[.+\]', val)
if section_match:
cur_section = section_match.group()[1:-1]
template_dict[cur_section] = {}
else:
option, value = val.split('=', 1)
option = option.strip()
value = value.strip()
if option.startswith('#'):
template_dict[cur_section][val] = ''
else:
template_dict[cur_section][option] = value
except Exception: # pragma: no cover
template_dict = {}
return template_dict | [
"def",
"ParsedSections",
"(",
"file_val",
")",
":",
"try",
":",
"template_dict",
"=",
"{",
"}",
"cur_section",
"=",
"''",
"for",
"val",
"in",
"file_val",
".",
"split",
"(",
"'\\n'",
")",
":",
"val",
"=",
"val",
".",
"strip",
"(",
")",
"if",
"val",
... | Get the sections and options of a file returned as a dictionary | [
"Get",
"the",
"sections",
"and",
"options",
"of",
"a",
"file",
"returned",
"as",
"a",
"dictionary"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/meta.py#L682-L706 | train | 32,068 |
CyberReboot/vent | vent/helpers/meta.py | Dependencies | def Dependencies(tools):
"""
Takes in a list of tools that are being updated and returns any tools that
depend on linking to them
"""
dependencies = []
if tools:
path_dirs = PathDirs()
man = Template(join(path_dirs.meta_dir, 'plugin_manifest.cfg'))
for section in man.sections()[1]:
# don't worry about dealing with tool if it's not running
running = man.option(section, 'running')
if not running[0] or running[1] != 'yes':
continue
t_name = man.option(section, 'name')[1]
t_branch = man.option(section, 'branch')[1]
t_version = man.option(section, 'version')[1]
t_identifier = {'name': t_name,
'branch': t_branch,
'version': t_version}
options = man.options(section)[1]
if 'docker' in options:
d_settings = json.loads(man.option(section,
'docker')[1])
if 'links' in d_settings:
for link in json.loads(d_settings['links']):
if link in tools:
dependencies.append(t_identifier)
return dependencies | python | def Dependencies(tools):
"""
Takes in a list of tools that are being updated and returns any tools that
depend on linking to them
"""
dependencies = []
if tools:
path_dirs = PathDirs()
man = Template(join(path_dirs.meta_dir, 'plugin_manifest.cfg'))
for section in man.sections()[1]:
# don't worry about dealing with tool if it's not running
running = man.option(section, 'running')
if not running[0] or running[1] != 'yes':
continue
t_name = man.option(section, 'name')[1]
t_branch = man.option(section, 'branch')[1]
t_version = man.option(section, 'version')[1]
t_identifier = {'name': t_name,
'branch': t_branch,
'version': t_version}
options = man.options(section)[1]
if 'docker' in options:
d_settings = json.loads(man.option(section,
'docker')[1])
if 'links' in d_settings:
for link in json.loads(d_settings['links']):
if link in tools:
dependencies.append(t_identifier)
return dependencies | [
"def",
"Dependencies",
"(",
"tools",
")",
":",
"dependencies",
"=",
"[",
"]",
"if",
"tools",
":",
"path_dirs",
"=",
"PathDirs",
"(",
")",
"man",
"=",
"Template",
"(",
"join",
"(",
"path_dirs",
".",
"meta_dir",
",",
"'plugin_manifest.cfg'",
")",
")",
"for... | Takes in a list of tools that are being updated and returns any tools that
depend on linking to them | [
"Takes",
"in",
"a",
"list",
"of",
"tools",
"that",
"are",
"being",
"updated",
"and",
"returns",
"any",
"tools",
"that",
"depend",
"on",
"linking",
"to",
"them"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/meta.py#L709-L737 | train | 32,069 |
CyberReboot/vent | vent/menus/choose_tools.py | ChooseToolsForm.repo_tools | def repo_tools(self, branch):
""" Set the appropriate repo dir and get the tools available of it """
tools = []
m_helper = Tools()
repo = self.parentApp.repo_value['repo']
version = self.parentApp.repo_value['versions'][branch]
status = m_helper.repo_tools(repo, branch, version)
if status[0]:
r_tools = status[1]
for tool in r_tools:
tools.append(tool[0])
return tools | python | def repo_tools(self, branch):
""" Set the appropriate repo dir and get the tools available of it """
tools = []
m_helper = Tools()
repo = self.parentApp.repo_value['repo']
version = self.parentApp.repo_value['versions'][branch]
status = m_helper.repo_tools(repo, branch, version)
if status[0]:
r_tools = status[1]
for tool in r_tools:
tools.append(tool[0])
return tools | [
"def",
"repo_tools",
"(",
"self",
",",
"branch",
")",
":",
"tools",
"=",
"[",
"]",
"m_helper",
"=",
"Tools",
"(",
")",
"repo",
"=",
"self",
".",
"parentApp",
".",
"repo_value",
"[",
"'repo'",
"]",
"version",
"=",
"self",
".",
"parentApp",
".",
"repo_... | Set the appropriate repo dir and get the tools available of it | [
"Set",
"the",
"appropriate",
"repo",
"dir",
"and",
"get",
"the",
"tools",
"available",
"of",
"it"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/choose_tools.py#L14-L25 | train | 32,070 |
CyberReboot/vent | vent/menus/choose_tools.py | ChooseToolsForm.create | def create(self):
""" Update with current tools for each branch at the version chosen """
self.add_handlers({'^Q': self.quit})
self.add(npyscreen.TitleText,
name='Select which tools to add from each branch selected:',
editable=False)
self.add(npyscreen.Textfield,
value='NOTE tools you have already installed will be ignored',
color='STANDOUT',
editable=False)
i = 6
for branch in self.parentApp.repo_value['versions']:
self.tools_tc[branch] = {}
self.add(npyscreen.TitleText,
name='Branch: ' + branch,
editable=False,
rely=i,
relx=5,
max_width=25)
tools = self.repo_tools(branch)
i += 1
for tool in tools:
value = True
if tool.startswith('/dev'):
value = False
# tool in base directory
if tool == '' or tool.startswith(':'):
tool = '/' + tool
self.tools_tc[branch][tool] = self.add(npyscreen.CheckBox,
name=tool,
value=value,
relx=10)
i += 1
i += 2 | python | def create(self):
""" Update with current tools for each branch at the version chosen """
self.add_handlers({'^Q': self.quit})
self.add(npyscreen.TitleText,
name='Select which tools to add from each branch selected:',
editable=False)
self.add(npyscreen.Textfield,
value='NOTE tools you have already installed will be ignored',
color='STANDOUT',
editable=False)
i = 6
for branch in self.parentApp.repo_value['versions']:
self.tools_tc[branch] = {}
self.add(npyscreen.TitleText,
name='Branch: ' + branch,
editable=False,
rely=i,
relx=5,
max_width=25)
tools = self.repo_tools(branch)
i += 1
for tool in tools:
value = True
if tool.startswith('/dev'):
value = False
# tool in base directory
if tool == '' or tool.startswith(':'):
tool = '/' + tool
self.tools_tc[branch][tool] = self.add(npyscreen.CheckBox,
name=tool,
value=value,
relx=10)
i += 1
i += 2 | [
"def",
"create",
"(",
"self",
")",
":",
"self",
".",
"add_handlers",
"(",
"{",
"'^Q'",
":",
"self",
".",
"quit",
"}",
")",
"self",
".",
"add",
"(",
"npyscreen",
".",
"TitleText",
",",
"name",
"=",
"'Select which tools to add from each branch selected:'",
","... | Update with current tools for each branch at the version chosen | [
"Update",
"with",
"current",
"tools",
"for",
"each",
"branch",
"at",
"the",
"version",
"chosen"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/choose_tools.py#L27-L61 | train | 32,071 |
CyberReboot/vent | vent/menus/choose_tools.py | ChooseToolsForm.on_ok | def on_ok(self):
"""
Take the tool selections and add them as plugins
"""
def diff(first, second):
"""
Get the elements that exist in the first list and not in the second
"""
second = set(second)
return [item for item in first if item not in second]
def popup(original_tools, branch, thr, title):
"""
Start the thread and display a popup of the tools being added until
the thread is finished
"""
thr.start()
tool_str = 'Adding tools...'
npyscreen.notify_wait(tool_str, title=title)
while thr.is_alive():
tools = diff(ManifestTools(), original_tools)
if tools:
tool_str = ''
for tool in tools:
pre_tool = 'Added: ' + branch + '/' + tool + '\n'
tool_str = pre_tool + tool_str
npyscreen.notify_wait(tool_str, title=title)
time.sleep(1)
return
original_tools = ManifestTools()
for branch in self.tools_tc:
tools = []
for tool in self.tools_tc[branch]:
if self.tools_tc[branch][tool].value:
# get rid of temporary show for multiple tools in same
# directory
if tool == '/':
tools.append(('.', ''))
else:
tools.append((tool, ''))
repo = self.parentApp.repo_value['repo']
version = self.parentApp.repo_value['versions'][branch]
api_action = Tools(version=version, branch=branch)
thr = threading.Thread(target=api_action.new, args=(),
kwargs={'tool_type': 'repo',
'uri': repo,
'tools': tools})
popup(original_tools, branch, thr,
'Please wait, adding tools for the ' + branch + ' branch...')
npyscreen.notify_confirm('Done adding repository: ' +
self.parentApp.repo_value['repo'],
title='Added Repository')
self.quit() | python | def on_ok(self):
"""
Take the tool selections and add them as plugins
"""
def diff(first, second):
"""
Get the elements that exist in the first list and not in the second
"""
second = set(second)
return [item for item in first if item not in second]
def popup(original_tools, branch, thr, title):
"""
Start the thread and display a popup of the tools being added until
the thread is finished
"""
thr.start()
tool_str = 'Adding tools...'
npyscreen.notify_wait(tool_str, title=title)
while thr.is_alive():
tools = diff(ManifestTools(), original_tools)
if tools:
tool_str = ''
for tool in tools:
pre_tool = 'Added: ' + branch + '/' + tool + '\n'
tool_str = pre_tool + tool_str
npyscreen.notify_wait(tool_str, title=title)
time.sleep(1)
return
original_tools = ManifestTools()
for branch in self.tools_tc:
tools = []
for tool in self.tools_tc[branch]:
if self.tools_tc[branch][tool].value:
# get rid of temporary show for multiple tools in same
# directory
if tool == '/':
tools.append(('.', ''))
else:
tools.append((tool, ''))
repo = self.parentApp.repo_value['repo']
version = self.parentApp.repo_value['versions'][branch]
api_action = Tools(version=version, branch=branch)
thr = threading.Thread(target=api_action.new, args=(),
kwargs={'tool_type': 'repo',
'uri': repo,
'tools': tools})
popup(original_tools, branch, thr,
'Please wait, adding tools for the ' + branch + ' branch...')
npyscreen.notify_confirm('Done adding repository: ' +
self.parentApp.repo_value['repo'],
title='Added Repository')
self.quit() | [
"def",
"on_ok",
"(",
"self",
")",
":",
"def",
"diff",
"(",
"first",
",",
"second",
")",
":",
"\"\"\"\n Get the elements that exist in the first list and not in the second\n \"\"\"",
"second",
"=",
"set",
"(",
"second",
")",
"return",
"[",
"item",
... | Take the tool selections and add them as plugins | [
"Take",
"the",
"tool",
"selections",
"and",
"add",
"them",
"as",
"plugins"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/choose_tools.py#L66-L119 | train | 32,072 |
CyberReboot/vent | vent/menus/main.py | MainForm.while_waiting | def while_waiting(self):
""" Update fields periodically if nothing is happening """
# give a little extra time for file descriptors to close
time.sleep(0.1)
self.addfield.value = Timestamp()
self.addfield.display()
self.addfield2.value = Uptime()
self.addfield2.display()
self.addfield3.value = str(len(Containers()))+' running'
if len(Containers()) > 0:
self.addfield3.labelColor = 'GOOD'
else:
self.addfield3.labelColor = 'DEFAULT'
self.addfield3.display()
# if file drop location changes deal with it
logger = Logger(__name__)
if self.file_drop.value != DropLocation()[1]:
logger.info('Starting: file drop restart')
try:
self.file_drop.value = DropLocation()[1]
logger.info('Path given: ' + str(self.file_drop.value))
except Exception as e: # pragma no cover
logger.error('file drop restart failed with error: ' + str(e))
logger.info('Finished: file drop restart')
self.file_drop.display()
return | python | def while_waiting(self):
""" Update fields periodically if nothing is happening """
# give a little extra time for file descriptors to close
time.sleep(0.1)
self.addfield.value = Timestamp()
self.addfield.display()
self.addfield2.value = Uptime()
self.addfield2.display()
self.addfield3.value = str(len(Containers()))+' running'
if len(Containers()) > 0:
self.addfield3.labelColor = 'GOOD'
else:
self.addfield3.labelColor = 'DEFAULT'
self.addfield3.display()
# if file drop location changes deal with it
logger = Logger(__name__)
if self.file_drop.value != DropLocation()[1]:
logger.info('Starting: file drop restart')
try:
self.file_drop.value = DropLocation()[1]
logger.info('Path given: ' + str(self.file_drop.value))
except Exception as e: # pragma no cover
logger.error('file drop restart failed with error: ' + str(e))
logger.info('Finished: file drop restart')
self.file_drop.display()
return | [
"def",
"while_waiting",
"(",
"self",
")",
":",
"# give a little extra time for file descriptors to close",
"time",
".",
"sleep",
"(",
"0.1",
")",
"self",
".",
"addfield",
".",
"value",
"=",
"Timestamp",
"(",
")",
"self",
".",
"addfield",
".",
"display",
"(",
"... | Update fields periodically if nothing is happening | [
"Update",
"fields",
"periodically",
"if",
"nothing",
"is",
"happening"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/main.py#L39-L66 | train | 32,073 |
CyberReboot/vent | vent/menus/main.py | MainForm.add_form | def add_form(self, form, form_name, form_args):
""" Add new form and switch to it """
self.parentApp.addForm(form_name, form, **form_args)
self.parentApp.change_form(form_name)
return | python | def add_form(self, form, form_name, form_args):
""" Add new form and switch to it """
self.parentApp.addForm(form_name, form, **form_args)
self.parentApp.change_form(form_name)
return | [
"def",
"add_form",
"(",
"self",
",",
"form",
",",
"form_name",
",",
"form_args",
")",
":",
"self",
".",
"parentApp",
".",
"addForm",
"(",
"form_name",
",",
"form",
",",
"*",
"*",
"form_args",
")",
"self",
".",
"parentApp",
".",
"change_form",
"(",
"for... | Add new form and switch to it | [
"Add",
"new",
"form",
"and",
"switch",
"to",
"it"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/main.py#L68-L72 | train | 32,074 |
CyberReboot/vent | vent/menus/main.py | MainForm.remove_forms | def remove_forms(self, form_names):
""" Remove all forms supplied """
for form in form_names:
try:
self.parentApp.removeForm(form)
except Exception as e: # pragma: no cover
pass
return | python | def remove_forms(self, form_names):
""" Remove all forms supplied """
for form in form_names:
try:
self.parentApp.removeForm(form)
except Exception as e: # pragma: no cover
pass
return | [
"def",
"remove_forms",
"(",
"self",
",",
"form_names",
")",
":",
"for",
"form",
"in",
"form_names",
":",
"try",
":",
"self",
".",
"parentApp",
".",
"removeForm",
"(",
"form",
")",
"except",
"Exception",
"as",
"e",
":",
"# pragma: no cover",
"pass",
"return... | Remove all forms supplied | [
"Remove",
"all",
"forms",
"supplied"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/main.py#L74-L81 | train | 32,075 |
CyberReboot/vent | vent/menus/main.py | MainForm.perform_action | def perform_action(self, action):
""" Perform actions in the api from the CLI """
form = ToolForm
s_action = form_action = action.split('_')[0]
form_name = s_action.title() + ' tools'
cores = False
a_type = 'containers'
forms = [action.upper() + 'TOOLS']
form_args = {'color': 'CONTROL',
'names': [s_action],
'name': form_name,
'action_dict': {'action_name': s_action,
'present_t': s_action + 'ing ' + a_type,
'past_t': s_action.title() + ' ' + a_type,
'action': form_action,
'type': a_type,
'cores': cores}}
# grammar rules
vowels = ['a', 'e', 'i', 'o', 'u']
# consonant-vowel-consonant ending
# Eg: stop -> stopping
if s_action[-1] not in vowels and \
s_action[-2] in vowels and \
s_action[-3] not in vowels:
form_args['action_dict']['present_t'] = s_action + \
s_action[-1] + 'ing ' + a_type
# word ends with a 'e'
# eg: remove -> removing
if s_action[-1] == 'e':
form_args['action_dict']['present_t'] = s_action[:-1] \
+ 'ing ' + a_type
if s_action == 'configure':
form_args['names'].pop()
form_args['names'].append('get_configure')
form_args['names'].append('save_configure')
form_args['names'].append('restart_tools')
if action == 'add':
form = AddForm
forms = ['ADD', 'ADDOPTIONS', 'CHOOSETOOLS']
form_args['name'] = 'Add plugins'
form_args['name'] += '\t'*6 + '^Q to quit'
elif action == 'inventory':
form = InventoryToolsForm
forms = ['INVENTORY']
form_args = {'color': 'STANDOUT', 'name': 'Inventory of tools'}
elif action == 'services':
form = ServicesForm
forms = ['SERVICES']
form_args = {'color': 'STANDOUT',
'name': 'Plugin Services',
'core': True}
elif action == 'services_external':
form = ServicesForm
forms = ['SERVICES']
form_args = {'color': 'STANDOUT',
'name': 'External Services',
'core': True,
'external': True}
form_args['name'] += '\t'*8 + '^T to toggle main'
if s_action in self.view_togglable:
form_args['name'] += '\t'*8 + '^V to toggle group view'
try:
self.remove_forms(forms)
thr = Thread(target=self.add_form, args=(),
kwargs={'form': form,
'form_name': forms[0],
'form_args': form_args})
thr.start()
while thr.is_alive():
npyscreen.notify('Please wait, loading form...',
title='Loading')
time.sleep(1)
except Exception as e: # pragma: no cover
pass
return | python | def perform_action(self, action):
""" Perform actions in the api from the CLI """
form = ToolForm
s_action = form_action = action.split('_')[0]
form_name = s_action.title() + ' tools'
cores = False
a_type = 'containers'
forms = [action.upper() + 'TOOLS']
form_args = {'color': 'CONTROL',
'names': [s_action],
'name': form_name,
'action_dict': {'action_name': s_action,
'present_t': s_action + 'ing ' + a_type,
'past_t': s_action.title() + ' ' + a_type,
'action': form_action,
'type': a_type,
'cores': cores}}
# grammar rules
vowels = ['a', 'e', 'i', 'o', 'u']
# consonant-vowel-consonant ending
# Eg: stop -> stopping
if s_action[-1] not in vowels and \
s_action[-2] in vowels and \
s_action[-3] not in vowels:
form_args['action_dict']['present_t'] = s_action + \
s_action[-1] + 'ing ' + a_type
# word ends with a 'e'
# eg: remove -> removing
if s_action[-1] == 'e':
form_args['action_dict']['present_t'] = s_action[:-1] \
+ 'ing ' + a_type
if s_action == 'configure':
form_args['names'].pop()
form_args['names'].append('get_configure')
form_args['names'].append('save_configure')
form_args['names'].append('restart_tools')
if action == 'add':
form = AddForm
forms = ['ADD', 'ADDOPTIONS', 'CHOOSETOOLS']
form_args['name'] = 'Add plugins'
form_args['name'] += '\t'*6 + '^Q to quit'
elif action == 'inventory':
form = InventoryToolsForm
forms = ['INVENTORY']
form_args = {'color': 'STANDOUT', 'name': 'Inventory of tools'}
elif action == 'services':
form = ServicesForm
forms = ['SERVICES']
form_args = {'color': 'STANDOUT',
'name': 'Plugin Services',
'core': True}
elif action == 'services_external':
form = ServicesForm
forms = ['SERVICES']
form_args = {'color': 'STANDOUT',
'name': 'External Services',
'core': True,
'external': True}
form_args['name'] += '\t'*8 + '^T to toggle main'
if s_action in self.view_togglable:
form_args['name'] += '\t'*8 + '^V to toggle group view'
try:
self.remove_forms(forms)
thr = Thread(target=self.add_form, args=(),
kwargs={'form': form,
'form_name': forms[0],
'form_args': form_args})
thr.start()
while thr.is_alive():
npyscreen.notify('Please wait, loading form...',
title='Loading')
time.sleep(1)
except Exception as e: # pragma: no cover
pass
return | [
"def",
"perform_action",
"(",
"self",
",",
"action",
")",
":",
"form",
"=",
"ToolForm",
"s_action",
"=",
"form_action",
"=",
"action",
".",
"split",
"(",
"'_'",
")",
"[",
"0",
"]",
"form_name",
"=",
"s_action",
".",
"title",
"(",
")",
"+",
"' tools'",
... | Perform actions in the api from the CLI | [
"Perform",
"actions",
"in",
"the",
"api",
"from",
"the",
"CLI"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/main.py#L83-L160 | train | 32,076 |
CyberReboot/vent | vent/menus/main.py | MainForm.system_commands | def system_commands(self, action):
""" Perform system commands """
if action == 'backup':
status = self.api_action.backup()
if status[0]:
notify_confirm('Vent backup successful')
else:
notify_confirm('Vent backup could not be completed')
elif action == 'start':
status = self.api_action.start()
if status[0]:
notify_confirm('System start complete. '
'Press OK.')
else:
notify_confirm(status[1])
elif action == 'stop':
status = self.api_action.stop()
if status[0]:
notify_confirm('System stop complete. '
'Press OK.')
else:
notify_confirm(status[1])
elif action == 'configure':
# TODO
form_args = {'name': 'Change vent configuration',
'get_configure': self.api_action.get_configure,
'save_configure': self.api_action.save_configure,
'restart_tools': self.api_action.restart_tools,
'vent_cfg': True}
add_kargs = {'form': EditorForm,
'form_name': 'CONFIGUREVENT',
'form_args': form_args}
self.add_form(**add_kargs)
elif action == 'reset':
okay = npyscreen.notify_ok_cancel(
"This factory reset will remove ALL of Vent's user data, "
'containers, and images. Are you sure?',
title='Confirm system command')
if okay:
status = self.api_action.reset()
if status[0]:
notify_confirm('Vent reset complete. '
'Press OK to exit Vent Manager console.')
else:
notify_confirm(status[1])
MainForm.exit()
elif action == 'gpu':
gpu = Gpu(pull=True)
if gpu[0]:
notify_confirm('GPU detection successful. '
'Found: ' + gpu[1])
else:
if gpu[1] == 'Unknown':
notify_confirm('Unable to detect GPUs, try `make gpu` '
'from the vent repository directory. '
'Error: ' + str(gpu[2]))
else:
notify_confirm('No GPUs detected.')
elif action == 'restore':
backup_dir_home = os.path.expanduser('~')
backup_dirs = [f for f in os.listdir(backup_dir_home) if
f.startswith('.vent-backup')]
form_args = {'restore': self.api_action.restore,
'dirs': backup_dirs,
'name': 'Pick a version to restore from' + '\t'*8 +
'^T to toggle main',
'color': 'CONTROL'}
add_kargs = {'form': BackupForm,
'form_name': 'CHOOSEBACKUP',
'form_args': form_args}
self.add_form(**add_kargs)
return | python | def system_commands(self, action):
""" Perform system commands """
if action == 'backup':
status = self.api_action.backup()
if status[0]:
notify_confirm('Vent backup successful')
else:
notify_confirm('Vent backup could not be completed')
elif action == 'start':
status = self.api_action.start()
if status[0]:
notify_confirm('System start complete. '
'Press OK.')
else:
notify_confirm(status[1])
elif action == 'stop':
status = self.api_action.stop()
if status[0]:
notify_confirm('System stop complete. '
'Press OK.')
else:
notify_confirm(status[1])
elif action == 'configure':
# TODO
form_args = {'name': 'Change vent configuration',
'get_configure': self.api_action.get_configure,
'save_configure': self.api_action.save_configure,
'restart_tools': self.api_action.restart_tools,
'vent_cfg': True}
add_kargs = {'form': EditorForm,
'form_name': 'CONFIGUREVENT',
'form_args': form_args}
self.add_form(**add_kargs)
elif action == 'reset':
okay = npyscreen.notify_ok_cancel(
"This factory reset will remove ALL of Vent's user data, "
'containers, and images. Are you sure?',
title='Confirm system command')
if okay:
status = self.api_action.reset()
if status[0]:
notify_confirm('Vent reset complete. '
'Press OK to exit Vent Manager console.')
else:
notify_confirm(status[1])
MainForm.exit()
elif action == 'gpu':
gpu = Gpu(pull=True)
if gpu[0]:
notify_confirm('GPU detection successful. '
'Found: ' + gpu[1])
else:
if gpu[1] == 'Unknown':
notify_confirm('Unable to detect GPUs, try `make gpu` '
'from the vent repository directory. '
'Error: ' + str(gpu[2]))
else:
notify_confirm('No GPUs detected.')
elif action == 'restore':
backup_dir_home = os.path.expanduser('~')
backup_dirs = [f for f in os.listdir(backup_dir_home) if
f.startswith('.vent-backup')]
form_args = {'restore': self.api_action.restore,
'dirs': backup_dirs,
'name': 'Pick a version to restore from' + '\t'*8 +
'^T to toggle main',
'color': 'CONTROL'}
add_kargs = {'form': BackupForm,
'form_name': 'CHOOSEBACKUP',
'form_args': form_args}
self.add_form(**add_kargs)
return | [
"def",
"system_commands",
"(",
"self",
",",
"action",
")",
":",
"if",
"action",
"==",
"'backup'",
":",
"status",
"=",
"self",
".",
"api_action",
".",
"backup",
"(",
")",
"if",
"status",
"[",
"0",
"]",
":",
"notify_confirm",
"(",
"'Vent backup successful'",... | Perform system commands | [
"Perform",
"system",
"commands"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/main.py#L180-L251 | train | 32,077 |
CyberReboot/vent | vent/helpers/logs.py | Logger | def Logger(name, **kargs):
""" Create and return logger """
path_dirs = PathDirs(**kargs)
logging.captureWarnings(True)
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
handler = logging.handlers.WatchedFileHandler(os.path.join(
path_dirs.meta_dir, 'vent.log'))
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s:%(lineno)-4d - '
'%(levelname)s - %(message)s')
handler.setFormatter(formatter)
if not len(logger.handlers):
logger.addHandler(handler)
return logger | python | def Logger(name, **kargs):
""" Create and return logger """
path_dirs = PathDirs(**kargs)
logging.captureWarnings(True)
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
handler = logging.handlers.WatchedFileHandler(os.path.join(
path_dirs.meta_dir, 'vent.log'))
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s:%(lineno)-4d - '
'%(levelname)s - %(message)s')
handler.setFormatter(formatter)
if not len(logger.handlers):
logger.addHandler(handler)
return logger | [
"def",
"Logger",
"(",
"name",
",",
"*",
"*",
"kargs",
")",
":",
"path_dirs",
"=",
"PathDirs",
"(",
"*",
"*",
"kargs",
")",
"logging",
".",
"captureWarnings",
"(",
"True",
")",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"logger",
".... | Create and return logger | [
"Create",
"and",
"return",
"logger"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/helpers/logs.py#L7-L22 | train | 32,078 |
CyberReboot/vent | vent/menus/editor.py | EditorForm.create | def create(self):
""" Create multi-line widget for editing """
# add various pointers to those editing vent_cfg
if self.vent_cfg:
self.add(npyscreen.Textfield,
value='# when configuring external'
' services make sure to do so',
editable=False)
self.add(npyscreen.Textfield,
value='# in the form of Service = {"setting": "value"}',
editable=False)
self.add(npyscreen.Textfield,
value='# make sure to capitalize your service correctly'
' (i.e. Elasticsearch vs. elasticsearch)',
editable=False)
self.add(npyscreen.Textfield,
value='# and make sure to enclose all dict keys and'
' values in double quotes ("")',
editable=False)
self.add(npyscreen.Textfield,
value='',
editable=False)
elif self.instance_cfg:
self.add(npyscreen.Textfield,
value='# these settings will be used'
' to configure the new instances',
editable=False)
self.edit_space = self.add(npyscreen.MultiLineEdit,
value=self.config_val) | python | def create(self):
""" Create multi-line widget for editing """
# add various pointers to those editing vent_cfg
if self.vent_cfg:
self.add(npyscreen.Textfield,
value='# when configuring external'
' services make sure to do so',
editable=False)
self.add(npyscreen.Textfield,
value='# in the form of Service = {"setting": "value"}',
editable=False)
self.add(npyscreen.Textfield,
value='# make sure to capitalize your service correctly'
' (i.e. Elasticsearch vs. elasticsearch)',
editable=False)
self.add(npyscreen.Textfield,
value='# and make sure to enclose all dict keys and'
' values in double quotes ("")',
editable=False)
self.add(npyscreen.Textfield,
value='',
editable=False)
elif self.instance_cfg:
self.add(npyscreen.Textfield,
value='# these settings will be used'
' to configure the new instances',
editable=False)
self.edit_space = self.add(npyscreen.MultiLineEdit,
value=self.config_val) | [
"def",
"create",
"(",
"self",
")",
":",
"# add various pointers to those editing vent_cfg",
"if",
"self",
".",
"vent_cfg",
":",
"self",
".",
"add",
"(",
"npyscreen",
".",
"Textfield",
",",
"value",
"=",
"'# when configuring external'",
"' services make sure to do so'",
... | Create multi-line widget for editing | [
"Create",
"multi",
"-",
"line",
"widget",
"for",
"editing"
] | 9956a09146b11a89a0eabab3bc7ce8906d124885 | https://github.com/CyberReboot/vent/blob/9956a09146b11a89a0eabab3bc7ce8906d124885/vent/menus/editor.py#L85-L113 | train | 32,079 |
JamesRamm/archook | archook/archook.py | locate_arcgis | def locate_arcgis():
'''
Find the path to the ArcGIS Desktop installation.
Keys to check:
HLKM/SOFTWARE/ESRI/ArcGIS 'RealVersion' - will give the version, then we can use
that to go to
HKLM/SOFTWARE/ESRI/DesktopXX.X 'InstallDir'. Where XX.X is the version
We may need to check HKLM/SOFTWARE/Wow6432Node/ESRI instead
'''
try:
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
'SOFTWARE\\Wow6432Node\\ESRI\\ArcGIS', 0)
version = _winreg.QueryValueEx(key, "RealVersion")[0][:4]
key_string = "SOFTWARE\\Wow6432Node\\ESRI\\Desktop{0}".format(version)
desktop_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
key_string, 0)
install_dir = _winreg.QueryValueEx(desktop_key, "InstallDir")[0]
return install_dir
except WindowsError:
raise ImportError("Could not locate the ArcGIS directory on this machine") | python | def locate_arcgis():
'''
Find the path to the ArcGIS Desktop installation.
Keys to check:
HLKM/SOFTWARE/ESRI/ArcGIS 'RealVersion' - will give the version, then we can use
that to go to
HKLM/SOFTWARE/ESRI/DesktopXX.X 'InstallDir'. Where XX.X is the version
We may need to check HKLM/SOFTWARE/Wow6432Node/ESRI instead
'''
try:
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
'SOFTWARE\\Wow6432Node\\ESRI\\ArcGIS', 0)
version = _winreg.QueryValueEx(key, "RealVersion")[0][:4]
key_string = "SOFTWARE\\Wow6432Node\\ESRI\\Desktop{0}".format(version)
desktop_key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,
key_string, 0)
install_dir = _winreg.QueryValueEx(desktop_key, "InstallDir")[0]
return install_dir
except WindowsError:
raise ImportError("Could not locate the ArcGIS directory on this machine") | [
"def",
"locate_arcgis",
"(",
")",
":",
"try",
":",
"key",
"=",
"_winreg",
".",
"OpenKey",
"(",
"_winreg",
".",
"HKEY_LOCAL_MACHINE",
",",
"'SOFTWARE\\\\Wow6432Node\\\\ESRI\\\\ArcGIS'",
",",
"0",
")",
"version",
"=",
"_winreg",
".",
"QueryValueEx",
"(",
"key",
... | Find the path to the ArcGIS Desktop installation.
Keys to check:
HLKM/SOFTWARE/ESRI/ArcGIS 'RealVersion' - will give the version, then we can use
that to go to
HKLM/SOFTWARE/ESRI/DesktopXX.X 'InstallDir'. Where XX.X is the version
We may need to check HKLM/SOFTWARE/Wow6432Node/ESRI instead | [
"Find",
"the",
"path",
"to",
"the",
"ArcGIS",
"Desktop",
"installation",
"."
] | 4cfe26802d9bd9a892f80c5a186e91a2ed142a7e | https://github.com/JamesRamm/archook/blob/4cfe26802d9bd9a892f80c5a186e91a2ed142a7e/archook/archook.py#L12-L37 | train | 32,080 |
roycehaynes/scrapy-rabbitmq | scrapy_rabbitmq/queue.py | SpiderQueue.pop | def pop(self):
"""Pop a request"""
method_frame, header, body = self.server.basic_get(queue=self.key)
if body:
return self._decode_request(body) | python | def pop(self):
"""Pop a request"""
method_frame, header, body = self.server.basic_get(queue=self.key)
if body:
return self._decode_request(body) | [
"def",
"pop",
"(",
"self",
")",
":",
"method_frame",
",",
"header",
",",
"body",
"=",
"self",
".",
"server",
".",
"basic_get",
"(",
"queue",
"=",
"self",
".",
"key",
")",
"if",
"body",
":",
"return",
"self",
".",
"_decode_request",
"(",
"body",
")"
] | Pop a request | [
"Pop",
"a",
"request"
] | 5053b500aff1d6679cc0e3d3e338c2bf74fadc22 | https://github.com/roycehaynes/scrapy-rabbitmq/blob/5053b500aff1d6679cc0e3d3e338c2bf74fadc22/scrapy_rabbitmq/queue.py#L65-L71 | train | 32,081 |
bwhite/hadoopy | hadoopy/_job_cli.py | change_dir | def change_dir():
"""Change the local directory if the HADOOPY_CHDIR environmental variable is provided"""
try:
d = os.environ['HADOOPY_CHDIR']
sys.stderr.write('HADOOPY: Trying to chdir to [%s]\n' % d)
except KeyError:
pass
else:
try:
os.chdir(d)
except OSError:
sys.stderr.write('HADOOPY: Failed to chdir to [%s]\n' % d) | python | def change_dir():
"""Change the local directory if the HADOOPY_CHDIR environmental variable is provided"""
try:
d = os.environ['HADOOPY_CHDIR']
sys.stderr.write('HADOOPY: Trying to chdir to [%s]\n' % d)
except KeyError:
pass
else:
try:
os.chdir(d)
except OSError:
sys.stderr.write('HADOOPY: Failed to chdir to [%s]\n' % d) | [
"def",
"change_dir",
"(",
")",
":",
"try",
":",
"d",
"=",
"os",
".",
"environ",
"[",
"'HADOOPY_CHDIR'",
"]",
"sys",
".",
"stderr",
".",
"write",
"(",
"'HADOOPY: Trying to chdir to [%s]\\n'",
"%",
"d",
")",
"except",
"KeyError",
":",
"pass",
"else",
":",
... | Change the local directory if the HADOOPY_CHDIR environmental variable is provided | [
"Change",
"the",
"local",
"directory",
"if",
"the",
"HADOOPY_CHDIR",
"environmental",
"variable",
"is",
"provided"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_job_cli.py#L54-L65 | train | 32,082 |
bwhite/hadoopy | hadoopy/_job_cli.py | disable_stdout_buffering | def disable_stdout_buffering():
"""This turns off stdout buffering so that outputs are immediately
materialized and log messages show up before the program exits"""
stdout_orig = sys.stdout
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# NOTE(brandyn): This removes the original stdout
return stdout_orig | python | def disable_stdout_buffering():
"""This turns off stdout buffering so that outputs are immediately
materialized and log messages show up before the program exits"""
stdout_orig = sys.stdout
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# NOTE(brandyn): This removes the original stdout
return stdout_orig | [
"def",
"disable_stdout_buffering",
"(",
")",
":",
"stdout_orig",
"=",
"sys",
".",
"stdout",
"sys",
".",
"stdout",
"=",
"os",
".",
"fdopen",
"(",
"sys",
".",
"stdout",
".",
"fileno",
"(",
")",
",",
"'w'",
",",
"0",
")",
"# NOTE(brandyn): This removes the or... | This turns off stdout buffering so that outputs are immediately
materialized and log messages show up before the program exits | [
"This",
"turns",
"off",
"stdout",
"buffering",
"so",
"that",
"outputs",
"are",
"immediately",
"materialized",
"and",
"log",
"messages",
"show",
"up",
"before",
"the",
"program",
"exits"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_job_cli.py#L73-L79 | train | 32,083 |
bwhite/hadoopy | hadoopy/_reporter.py | counter | def counter(group, counter, amount=1, err=None):
"""Output a counter update that is displayed in the Hadoop web interface
Counters are useful for quickly identifying the number of times an error
occurred, current progress, or coarse statistics.
:param group: Counter group
:param counter: Counter name
:param amount: Value to add (default 1)
:param err: Func that outputs a string, if None then sys.stderr.write is used (default None)
"""
if not err:
err = _err
err("reporter:counter:%s,%s,%s\n" % (group, counter, str(amount))) | python | def counter(group, counter, amount=1, err=None):
"""Output a counter update that is displayed in the Hadoop web interface
Counters are useful for quickly identifying the number of times an error
occurred, current progress, or coarse statistics.
:param group: Counter group
:param counter: Counter name
:param amount: Value to add (default 1)
:param err: Func that outputs a string, if None then sys.stderr.write is used (default None)
"""
if not err:
err = _err
err("reporter:counter:%s,%s,%s\n" % (group, counter, str(amount))) | [
"def",
"counter",
"(",
"group",
",",
"counter",
",",
"amount",
"=",
"1",
",",
"err",
"=",
"None",
")",
":",
"if",
"not",
"err",
":",
"err",
"=",
"_err",
"err",
"(",
"\"reporter:counter:%s,%s,%s\\n\"",
"%",
"(",
"group",
",",
"counter",
",",
"str",
"(... | Output a counter update that is displayed in the Hadoop web interface
Counters are useful for quickly identifying the number of times an error
occurred, current progress, or coarse statistics.
:param group: Counter group
:param counter: Counter name
:param amount: Value to add (default 1)
:param err: Func that outputs a string, if None then sys.stderr.write is used (default None) | [
"Output",
"a",
"counter",
"update",
"that",
"is",
"displayed",
"in",
"the",
"Hadoop",
"web",
"interface"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/_reporter.py#L27-L40 | train | 32,084 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/MachO.py | MachOHeader.rewriteInstallNameCommand | def rewriteInstallNameCommand(self, loadcmd):
"""Rewrite the load command of this dylib"""
if self.id_cmd is not None:
self.rewriteDataForCommand(self.id_cmd, loadcmd)
return True
return False | python | def rewriteInstallNameCommand(self, loadcmd):
"""Rewrite the load command of this dylib"""
if self.id_cmd is not None:
self.rewriteDataForCommand(self.id_cmd, loadcmd)
return True
return False | [
"def",
"rewriteInstallNameCommand",
"(",
"self",
",",
"loadcmd",
")",
":",
"if",
"self",
".",
"id_cmd",
"is",
"not",
"None",
":",
"self",
".",
"rewriteDataForCommand",
"(",
"self",
".",
"id_cmd",
",",
"loadcmd",
")",
"return",
"True",
"return",
"False"
] | Rewrite the load command of this dylib | [
"Rewrite",
"the",
"load",
"command",
"of",
"this",
"dylib"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/MachO.py#L259-L264 | train | 32,085 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/MachO.py | MachOHeader.rewriteLoadCommands | def rewriteLoadCommands(self, changefunc):
"""
Rewrite the load commands based upon a change dictionary
"""
data = changefunc(self.parent.filename)
changed = False
if data is not None:
if self.rewriteInstallNameCommand(
data.encode(sys.getfilesystemencoding())):
changed = True
for idx, name, filename in self.walkRelocatables():
data = changefunc(filename)
if data is not None:
if self.rewriteDataForCommand(idx, data.encode(
sys.getfilesystemencoding())):
changed = True
return changed | python | def rewriteLoadCommands(self, changefunc):
"""
Rewrite the load commands based upon a change dictionary
"""
data = changefunc(self.parent.filename)
changed = False
if data is not None:
if self.rewriteInstallNameCommand(
data.encode(sys.getfilesystemencoding())):
changed = True
for idx, name, filename in self.walkRelocatables():
data = changefunc(filename)
if data is not None:
if self.rewriteDataForCommand(idx, data.encode(
sys.getfilesystemencoding())):
changed = True
return changed | [
"def",
"rewriteLoadCommands",
"(",
"self",
",",
"changefunc",
")",
":",
"data",
"=",
"changefunc",
"(",
"self",
".",
"parent",
".",
"filename",
")",
"changed",
"=",
"False",
"if",
"data",
"is",
"not",
"None",
":",
"if",
"self",
".",
"rewriteInstallNameComm... | Rewrite the load commands based upon a change dictionary | [
"Rewrite",
"the",
"load",
"commands",
"based",
"upon",
"a",
"change",
"dictionary"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/MachO.py#L271-L287 | train | 32,086 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/ptypes.py | sizeof | def sizeof(s):
"""
Return the size of an object when packed
"""
if hasattr(s, '_size_'):
return s._size_
elif isinstance(s, bytes):
return len(s)
raise ValueError(s) | python | def sizeof(s):
"""
Return the size of an object when packed
"""
if hasattr(s, '_size_'):
return s._size_
elif isinstance(s, bytes):
return len(s)
raise ValueError(s) | [
"def",
"sizeof",
"(",
"s",
")",
":",
"if",
"hasattr",
"(",
"s",
",",
"'_size_'",
")",
":",
"return",
"s",
".",
"_size_",
"elif",
"isinstance",
"(",
"s",
",",
"bytes",
")",
":",
"return",
"len",
"(",
"s",
")",
"raise",
"ValueError",
"(",
"s",
")"
... | Return the size of an object when packed | [
"Return",
"the",
"size",
"of",
"an",
"object",
"when",
"packed"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/ptypes.py#L39-L49 | train | 32,087 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/ptypes.py | pypackable | def pypackable(name, pytype, format):
"""
Create a "mix-in" class with a python type and a
Packable with the given struct format
"""
size, items = _formatinfo(format)
return type(Packable)(name, (pytype, Packable), {
'_format_': format,
'_size_': size,
'_items_': items,
}) | python | def pypackable(name, pytype, format):
"""
Create a "mix-in" class with a python type and a
Packable with the given struct format
"""
size, items = _formatinfo(format)
return type(Packable)(name, (pytype, Packable), {
'_format_': format,
'_size_': size,
'_items_': items,
}) | [
"def",
"pypackable",
"(",
"name",
",",
"pytype",
",",
"format",
")",
":",
"size",
",",
"items",
"=",
"_formatinfo",
"(",
"format",
")",
"return",
"type",
"(",
"Packable",
")",
"(",
"name",
",",
"(",
"pytype",
",",
"Packable",
")",
",",
"{",
"'_format... | Create a "mix-in" class with a python type and a
Packable with the given struct format | [
"Create",
"a",
"mix",
"-",
"in",
"class",
"with",
"a",
"python",
"type",
"and",
"a",
"Packable",
"with",
"the",
"given",
"struct",
"format"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/ptypes.py#L91-L101 | train | 32,088 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/ptypes.py | _formatinfo | def _formatinfo(format):
"""
Calculate the size and number of items in a struct format.
"""
size = struct.calcsize(format)
return size, len(struct.unpack(format, B('\x00') * size)) | python | def _formatinfo(format):
"""
Calculate the size and number of items in a struct format.
"""
size = struct.calcsize(format)
return size, len(struct.unpack(format, B('\x00') * size)) | [
"def",
"_formatinfo",
"(",
"format",
")",
":",
"size",
"=",
"struct",
".",
"calcsize",
"(",
"format",
")",
"return",
"size",
",",
"len",
"(",
"struct",
".",
"unpack",
"(",
"format",
",",
"B",
"(",
"'\\x00'",
")",
"*",
"size",
")",
")"
] | Calculate the size and number of items in a struct format. | [
"Calculate",
"the",
"size",
"and",
"number",
"of",
"items",
"in",
"a",
"struct",
"format",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/macholib/ptypes.py#L103-L108 | train | 32,089 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/build.py | addSuffixToExtensions | def addSuffixToExtensions(toc):
"""
Returns a new TOC with proper library suffix for EXTENSION items.
"""
new_toc = TOC()
for inm, fnm, typ in toc:
if typ in ('EXTENSION', 'DEPENDENCY'):
binext = os.path.splitext(fnm)[1]
if not os.path.splitext(inm)[1] == binext:
inm = inm + binext
new_toc.append((inm, fnm, typ))
return new_toc | python | def addSuffixToExtensions(toc):
"""
Returns a new TOC with proper library suffix for EXTENSION items.
"""
new_toc = TOC()
for inm, fnm, typ in toc:
if typ in ('EXTENSION', 'DEPENDENCY'):
binext = os.path.splitext(fnm)[1]
if not os.path.splitext(inm)[1] == binext:
inm = inm + binext
new_toc.append((inm, fnm, typ))
return new_toc | [
"def",
"addSuffixToExtensions",
"(",
"toc",
")",
":",
"new_toc",
"=",
"TOC",
"(",
")",
"for",
"inm",
",",
"fnm",
",",
"typ",
"in",
"toc",
":",
"if",
"typ",
"in",
"(",
"'EXTENSION'",
",",
"'DEPENDENCY'",
")",
":",
"binext",
"=",
"os",
".",
"path",
"... | Returns a new TOC with proper library suffix for EXTENSION items. | [
"Returns",
"a",
"new",
"TOC",
"with",
"proper",
"library",
"suffix",
"for",
"EXTENSION",
"items",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/build.py#L155-L166 | train | 32,090 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/build.py | _check_guts_eq | def _check_guts_eq(attr, old, new, last_build):
"""
rebuild is required if values differ
"""
if old != new:
logger.info("building because %s changed", attr)
return True
return False | python | def _check_guts_eq(attr, old, new, last_build):
"""
rebuild is required if values differ
"""
if old != new:
logger.info("building because %s changed", attr)
return True
return False | [
"def",
"_check_guts_eq",
"(",
"attr",
",",
"old",
",",
"new",
",",
"last_build",
")",
":",
"if",
"old",
"!=",
"new",
":",
"logger",
".",
"info",
"(",
"\"building because %s changed\"",
",",
"attr",
")",
"return",
"True",
"return",
"False"
] | rebuild is required if values differ | [
"rebuild",
"is",
"required",
"if",
"values",
"differ"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/build.py#L171-L178 | train | 32,091 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/build.py | _check_guts_toc_mtime | def _check_guts_toc_mtime(attr, old, toc, last_build, pyc=0):
"""
rebuild is required if mtimes of files listed in old toc are newer
than ast_build
if pyc=1, check for .py files, too
"""
for (nm, fnm, typ) in old:
if mtime(fnm) > last_build:
logger.info("building because %s changed", fnm)
return True
elif pyc and mtime(fnm[:-1]) > last_build:
logger.info("building because %s changed", fnm[:-1])
return True
return False | python | def _check_guts_toc_mtime(attr, old, toc, last_build, pyc=0):
"""
rebuild is required if mtimes of files listed in old toc are newer
than ast_build
if pyc=1, check for .py files, too
"""
for (nm, fnm, typ) in old:
if mtime(fnm) > last_build:
logger.info("building because %s changed", fnm)
return True
elif pyc and mtime(fnm[:-1]) > last_build:
logger.info("building because %s changed", fnm[:-1])
return True
return False | [
"def",
"_check_guts_toc_mtime",
"(",
"attr",
",",
"old",
",",
"toc",
",",
"last_build",
",",
"pyc",
"=",
"0",
")",
":",
"for",
"(",
"nm",
",",
"fnm",
",",
"typ",
")",
"in",
"old",
":",
"if",
"mtime",
"(",
"fnm",
")",
">",
"last_build",
":",
"logg... | rebuild is required if mtimes of files listed in old toc are newer
than ast_build
if pyc=1, check for .py files, too | [
"rebuild",
"is",
"required",
"if",
"mtimes",
"of",
"files",
"listed",
"in",
"old",
"toc",
"are",
"newer",
"than",
"ast_build"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/build.py#L181-L195 | train | 32,092 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/build.py | _check_guts_toc | def _check_guts_toc(attr, old, toc, last_build, pyc=0):
"""
rebuild is required if either toc content changed if mtimes of
files listed in old toc are newer than ast_build
if pyc=1, check for .py files, too
"""
return (_check_guts_eq(attr, old, toc, last_build)
or _check_guts_toc_mtime(attr, old, toc, last_build, pyc=pyc)) | python | def _check_guts_toc(attr, old, toc, last_build, pyc=0):
"""
rebuild is required if either toc content changed if mtimes of
files listed in old toc are newer than ast_build
if pyc=1, check for .py files, too
"""
return (_check_guts_eq(attr, old, toc, last_build)
or _check_guts_toc_mtime(attr, old, toc, last_build, pyc=pyc)) | [
"def",
"_check_guts_toc",
"(",
"attr",
",",
"old",
",",
"toc",
",",
"last_build",
",",
"pyc",
"=",
"0",
")",
":",
"return",
"(",
"_check_guts_eq",
"(",
"attr",
",",
"old",
",",
"toc",
",",
"last_build",
")",
"or",
"_check_guts_toc_mtime",
"(",
"attr",
... | rebuild is required if either toc content changed if mtimes of
files listed in old toc are newer than ast_build
if pyc=1, check for .py files, too | [
"rebuild",
"is",
"required",
"if",
"either",
"toc",
"content",
"changed",
"if",
"mtimes",
"of",
"files",
"listed",
"in",
"old",
"toc",
"are",
"newer",
"than",
"ast_build"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/build.py#L198-L206 | train | 32,093 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/build.py | set_dependencies | def set_dependencies(analysis, dependencies, path):
"""
Syncronize the Analysis result with the needed dependencies.
"""
for toc in (analysis.binaries, analysis.datas):
for i, tpl in enumerate(toc):
if not tpl[1] in dependencies.keys():
logger.info("Adding dependency %s located in %s" % (tpl[1], path))
dependencies[tpl[1]] = path
else:
dep_path = get_relative_path(path, dependencies[tpl[1]])
logger.info("Referencing %s to be a dependecy for %s, located in %s" % (tpl[1], path, dep_path))
analysis.dependencies.append((":".join((dep_path, tpl[0])), tpl[1], "DEPENDENCY"))
toc[i] = (None, None, None)
# Clean the list
toc[:] = [tpl for tpl in toc if tpl != (None, None, None)] | python | def set_dependencies(analysis, dependencies, path):
"""
Syncronize the Analysis result with the needed dependencies.
"""
for toc in (analysis.binaries, analysis.datas):
for i, tpl in enumerate(toc):
if not tpl[1] in dependencies.keys():
logger.info("Adding dependency %s located in %s" % (tpl[1], path))
dependencies[tpl[1]] = path
else:
dep_path = get_relative_path(path, dependencies[tpl[1]])
logger.info("Referencing %s to be a dependecy for %s, located in %s" % (tpl[1], path, dep_path))
analysis.dependencies.append((":".join((dep_path, tpl[0])), tpl[1], "DEPENDENCY"))
toc[i] = (None, None, None)
# Clean the list
toc[:] = [tpl for tpl in toc if tpl != (None, None, None)] | [
"def",
"set_dependencies",
"(",
"analysis",
",",
"dependencies",
",",
"path",
")",
":",
"for",
"toc",
"in",
"(",
"analysis",
".",
"binaries",
",",
"analysis",
".",
"datas",
")",
":",
"for",
"i",
",",
"tpl",
"in",
"enumerate",
"(",
"toc",
")",
":",
"i... | Syncronize the Analysis result with the needed dependencies. | [
"Syncronize",
"the",
"Analysis",
"result",
"with",
"the",
"needed",
"dependencies",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/build.py#L1458-L1474 | train | 32,094 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/build.py | Target.get_guts | def get_guts(self, last_build, missing='missing or bad'):
"""
returns None if guts have changed
"""
try:
data = _load_data(self.out)
except:
logger.info("building because %s %s", os.path.basename(self.out), missing)
return None
if len(data) != len(self.GUTS):
logger.info("building because %s is bad", self.outnm)
return None
for i, (attr, func) in enumerate(self.GUTS):
if func is None:
# no check for this value
continue
if func(attr, data[i], getattr(self, attr), last_build):
return None
return data | python | def get_guts(self, last_build, missing='missing or bad'):
"""
returns None if guts have changed
"""
try:
data = _load_data(self.out)
except:
logger.info("building because %s %s", os.path.basename(self.out), missing)
return None
if len(data) != len(self.GUTS):
logger.info("building because %s is bad", self.outnm)
return None
for i, (attr, func) in enumerate(self.GUTS):
if func is None:
# no check for this value
continue
if func(attr, data[i], getattr(self, attr), last_build):
return None
return data | [
"def",
"get_guts",
"(",
"self",
",",
"last_build",
",",
"missing",
"=",
"'missing or bad'",
")",
":",
"try",
":",
"data",
"=",
"_load_data",
"(",
"self",
".",
"out",
")",
"except",
":",
"logger",
".",
"info",
"(",
"\"building because %s %s\"",
",",
"os",
... | returns None if guts have changed | [
"returns",
"None",
"if",
"guts",
"have",
"changed"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/build.py#L301-L320 | train | 32,095 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/build.py | Analysis.fixMissingPythonLib | def fixMissingPythonLib(self, binaries):
"""Add the Python library if missing from the binaries.
Some linux distributions (e.g. debian-based) statically build the
Python executable to the libpython, so bindepend doesn't include
it in its output.
Darwin custom builds could possibly also have non-framework style libraries,
so this method also checks for that variant as well.
"""
if is_aix:
# Shared libs on AIX are archives with shared object members, thus the ".a" suffix.
names = ('libpython%d.%d.a' % sys.version_info[:2],)
elif is_unix:
# Other *nix platforms.
names = ('libpython%d.%d.so' % sys.version_info[:2],)
elif is_darwin:
names = ('Python', 'libpython%d.%d.dylib' % sys.version_info[:2])
else:
return
for (nm, fnm, typ) in binaries:
for name in names:
if typ == 'BINARY' and name in fnm:
# lib found
return
# resume search using the first item in names
name = names[0]
if is_unix:
lib = bindepend.findLibrary(name)
if lib is None:
raise IOError("Python library not found!")
elif is_darwin:
# On MacPython, Analysis.assemble is able to find the libpython with
# no additional help, asking for config['python'] dependencies.
# However, this fails on system python, because the shared library
# is not listed as a dependency of the binary (most probably it's
# opened at runtime using some dlopen trickery).
lib = os.path.join(sys.exec_prefix, 'Python')
if not os.path.exists(lib):
raise IOError("Python library not found!")
binaries.append((os.path.split(lib)[1], lib, 'BINARY')) | python | def fixMissingPythonLib(self, binaries):
"""Add the Python library if missing from the binaries.
Some linux distributions (e.g. debian-based) statically build the
Python executable to the libpython, so bindepend doesn't include
it in its output.
Darwin custom builds could possibly also have non-framework style libraries,
so this method also checks for that variant as well.
"""
if is_aix:
# Shared libs on AIX are archives with shared object members, thus the ".a" suffix.
names = ('libpython%d.%d.a' % sys.version_info[:2],)
elif is_unix:
# Other *nix platforms.
names = ('libpython%d.%d.so' % sys.version_info[:2],)
elif is_darwin:
names = ('Python', 'libpython%d.%d.dylib' % sys.version_info[:2])
else:
return
for (nm, fnm, typ) in binaries:
for name in names:
if typ == 'BINARY' and name in fnm:
# lib found
return
# resume search using the first item in names
name = names[0]
if is_unix:
lib = bindepend.findLibrary(name)
if lib is None:
raise IOError("Python library not found!")
elif is_darwin:
# On MacPython, Analysis.assemble is able to find the libpython with
# no additional help, asking for config['python'] dependencies.
# However, this fails on system python, because the shared library
# is not listed as a dependency of the binary (most probably it's
# opened at runtime using some dlopen trickery).
lib = os.path.join(sys.exec_prefix, 'Python')
if not os.path.exists(lib):
raise IOError("Python library not found!")
binaries.append((os.path.split(lib)[1], lib, 'BINARY')) | [
"def",
"fixMissingPythonLib",
"(",
"self",
",",
"binaries",
")",
":",
"if",
"is_aix",
":",
"# Shared libs on AIX are archives with shared object members, thus the \".a\" suffix.",
"names",
"=",
"(",
"'libpython%d.%d.a'",
"%",
"sys",
".",
"version_info",
"[",
":",
"2",
"... | Add the Python library if missing from the binaries.
Some linux distributions (e.g. debian-based) statically build the
Python executable to the libpython, so bindepend doesn't include
it in its output.
Darwin custom builds could possibly also have non-framework style libraries,
so this method also checks for that variant as well. | [
"Add",
"the",
"Python",
"library",
"if",
"missing",
"from",
"the",
"binaries",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/build.py#L493-L539 | train | 32,096 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/utils/Crypt.py | gen_random_key | def gen_random_key(size=32):
"""
Generate a cryptographically-secure random key. This is done by using
Python 2.4's os.urandom, or PyCrypto.
"""
import os
if hasattr(os, "urandom"): # Python 2.4+
return os.urandom(size)
# Try using PyCrypto if available
try:
from Crypto.Util.randpool import RandomPool
from Crypto.Hash import SHA256
return RandomPool(hash=SHA256).get_bytes(size)
except ImportError:
print >>sys.stderr, "WARNING: The generated key will not be cryptographically-secure key. Consider using Python 2.4+ to generate the key, or install PyCrypto."
# Stupid random generation
import random
L = []
for i in range(size):
L.append(chr(random.randint(0, 255)))
return "".join(L) | python | def gen_random_key(size=32):
"""
Generate a cryptographically-secure random key. This is done by using
Python 2.4's os.urandom, or PyCrypto.
"""
import os
if hasattr(os, "urandom"): # Python 2.4+
return os.urandom(size)
# Try using PyCrypto if available
try:
from Crypto.Util.randpool import RandomPool
from Crypto.Hash import SHA256
return RandomPool(hash=SHA256).get_bytes(size)
except ImportError:
print >>sys.stderr, "WARNING: The generated key will not be cryptographically-secure key. Consider using Python 2.4+ to generate the key, or install PyCrypto."
# Stupid random generation
import random
L = []
for i in range(size):
L.append(chr(random.randint(0, 255)))
return "".join(L) | [
"def",
"gen_random_key",
"(",
"size",
"=",
"32",
")",
":",
"import",
"os",
"if",
"hasattr",
"(",
"os",
",",
"\"urandom\"",
")",
":",
"# Python 2.4+",
"return",
"os",
".",
"urandom",
"(",
"size",
")",
"# Try using PyCrypto if available",
"try",
":",
"from",
... | Generate a cryptographically-secure random key. This is done by using
Python 2.4's os.urandom, or PyCrypto. | [
"Generate",
"a",
"cryptographically",
"-",
"secure",
"random",
"key",
".",
"This",
"is",
"done",
"by",
"using",
"Python",
"2",
".",
"4",
"s",
"os",
".",
"urandom",
"or",
"PyCrypto",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/utils/Crypt.py#L20-L43 | train | 32,097 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Dot.py | Dot.display | def display(self, mode='dot'):
'''
Displays the current graph via dotty
'''
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)
else:
self.save_dot(self.temp_dot)
plot_cmd = "%s %s" % (self.dotty, self.temp_dot)
os.system(plot_cmd) | python | def display(self, mode='dot'):
'''
Displays the current graph via dotty
'''
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)
else:
self.save_dot(self.temp_dot)
plot_cmd = "%s %s" % (self.dotty, self.temp_dot)
os.system(plot_cmd) | [
"def",
"display",
"(",
"self",
",",
"mode",
"=",
"'dot'",
")",
":",
"if",
"mode",
"==",
"'neato'",
":",
"self",
".",
"save_dot",
"(",
"self",
".",
"temp_neo",
")",
"neato_cmd",
"=",
"\"%s -o %s %s\"",
"%",
"(",
"self",
".",
"neato",
",",
"self",
".",... | Displays the current graph via dotty | [
"Displays",
"the",
"current",
"graph",
"via",
"dotty"
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Dot.py#L177-L190 | train | 32,098 |
bwhite/hadoopy | hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Dot.py | Dot.node_style | def node_style(self, node, **kwargs):
'''
Modifies a node style to the dot representation.
'''
if node not in self.edges:
self.edges[node] = {}
self.nodes[node] = kwargs | python | def node_style(self, node, **kwargs):
'''
Modifies a node style to the dot representation.
'''
if node not in self.edges:
self.edges[node] = {}
self.nodes[node] = kwargs | [
"def",
"node_style",
"(",
"self",
",",
"node",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"node",
"not",
"in",
"self",
".",
"edges",
":",
"self",
".",
"edges",
"[",
"node",
"]",
"=",
"{",
"}",
"self",
".",
"nodes",
"[",
"node",
"]",
"=",
"kwargs"... | Modifies a node style to the dot representation. | [
"Modifies",
"a",
"node",
"style",
"to",
"the",
"dot",
"representation",
"."
] | ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6 | https://github.com/bwhite/hadoopy/blob/ff39b4e6d4e6efaf1f571cf0f2c0e0d7ab28c2d6/hadoopy/thirdparty/pyinstaller/PyInstaller/lib/altgraph/Dot.py#L192-L198 | train | 32,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.