_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q248100 | task_list | train | def task_list(task_array):
"""Return a task list.
The task_array should be 2-dimensional; the first item should be the task
text, and the second the boolean completion state.
>>> task_list([["Be born", True], ["Be dead", False]])
| python | {
"resource": ""
} |
q248101 | table | train | def table(big_array):
"""Return a formatted table, generated from arrays representing columns.
The function requires a 2-dimensional array, where each array is a column
of the table. This will be used to generate a formatted table in string
format. The number of items in each columns does not need to be... | python | {
"resource": ""
} |
q248102 | compare | train | def compare(sig1, sig2):
"""
Computes the match score between two fuzzy hash signatures.
Returns a value from zero to 100 indicating the match score of the
two signatures. A match score of zero indicates the signatures
did not match.
:param Bytes|String sig1: First fuzzy hash signature
:pa... | python | {
"resource": ""
} |
q248103 | hash | train | def hash(buf, encoding="utf-8"):
"""
Compute the fuzzy hash of a buffer
:param String|Bytes buf: The data to be fuzzy hashed
:return: The fuzzy hash
:rtype: String
:raises InternalError: If lib returns an internal error
:raises TypeError: If buf is not String or Bytes
"""
if isins... | python | {
"resource": ""
} |
q248104 | hash_from_file | train | def hash_from_file(filename):
"""
Compute the fuzzy hash of a file.
Opens, reads, and hashes the contents of the file 'filename'
:param String|Bytes filename: The name of the file to be hashed
:return: The fuzzy hash of the file
:rtype: String
:raises IOError: If Python is unable to read t... | python | {
"resource": ""
} |
q248105 | Hash.digest | train | def digest(self, elimseq=False, notrunc=False):
"""
Obtain the fuzzy hash.
This operation does not change the state at all. It reports the hash
for the concatenation of the data previously fed using update().
:return: The fuzzy hash
:rtype: String
:raises Intern... | python | {
"resource": ""
} |
q248106 | IconFont.load_css | train | def load_css(self):
"""
Creates a dict of all icons available in CSS file, and finds out
what's their common prefix.
:returns sorted icons dict, common icon prefix
"""
icons = dict()
common_prefix = None
parser = tinycss.make_parser('page3')
style... | python | {
"resource": ""
} |
q248107 | IconFont.export_icon | train | def export_icon(self, icon, size, color='black', scale='auto',
filename=None, export_dir='exported'):
"""
Exports given icon with provided parameters.
If the desired icon size is less than 150x150 pixels, we will first
create a 150x150 pixels image and then scale it ... | python | {
"resource": ""
} |
q248108 | basic_distance | train | def basic_distance(trig_pin, echo_pin, celsius=20):
'''Return an unformatted distance in cm's as read directly from
RPi.GPIO.'''
speed_of_sound = 331.3 * math.sqrt(1+(celsius / 273.15))
GPIO.setup(trig_pin, GPIO.OUT)
GPIO.setup(echo_pin, GPIO.IN)
GPIO.output(trig_pin, GPIO.LOW)
time.sleep(0... | python | {
"resource": ""
} |
q248109 | Measurement.raw_distance | train | def raw_distance(self, sample_size=11, sample_wait=0.1):
'''Return an error corrected unrounded distance, in cm, of an object
adjusted for temperature in Celcius. The distance calculated
is the median value of a sample of `sample_size` readings.
Speed of readings is a result ... | python | {
"resource": ""
} |
q248110 | main | train | def main():
'''Calculate the depth of a liquid in centimeters using a HCSR04 sensor
and a Raspberry Pi'''
trig_pin = 17
echo_pin = 27
# Default values
# unit = 'metric'
# temperature = 20
# round_to = 1
hole_depth = 80 # centimeters
# Create a distance reading with the hc... | python | {
"resource": ""
} |
q248111 | main | train | def main():
'''Calculate the distance of an object in centimeters using a HCSR04 sensor
and a Raspberry Pi. This script allows for a quicker reading by
decreasing the number of samples and forcing the readings to be
taken at quicker intervals.'''
trig_pin = 17
echo_pin = 27
# Cre... | python | {
"resource": ""
} |
q248112 | main | train | def main():
'''Main function to run the sensor with passed arguments'''
trig, echo, speed, samples = get_args()
print('trig pin = gpio {}'.format(trig))
print('echo pin = gpio {}'.format(echo))
print('speed = {}'.format(speed))
print('samples = {}'.format(samples))
| python | {
"resource": ""
} |
q248113 | main | train | def main():
'''Calculate the depth of a liquid in inches using a HCSR04 sensor
and a Raspberry Pi'''
trig_pin = 17
echo_pin = 27
hole_depth = 31.5 # inches
# Default values
# unit = 'metric'
# temperature = 20
# round_to = 1
# Create a distance reading with the hcsr04 sens... | python | {
"resource": ""
} |
q248114 | main | train | def main():
'''Calculate the distance of an object in inches using a HCSR04 sensor
and a Raspberry Pi'''
trig_pin = 17
echo_pin = 27
# Default values
# unit = 'metric'
# temperature = 20
# round_to = 1
# Create a distance reading with the hcsr04 sensor module
# and overide ... | python | {
"resource": ""
} |
q248115 | LED.read | train | def read(self):
"""Read the brightness of the LED.
Returns:
int: Current brightness.
Raises:
LEDError: if an I/O or OS error occurs.
"""
# Read value
try:
| python | {
"resource": ""
} |
q248116 | LED.write | train | def write(self, brightness):
"""Set the brightness of the LED to `brightness`.
`brightness` can be a boolean for on/off, or integer value for a
specific brightness.
Args:
brightness (bool, int): Brightness value to set.
Raises:
LEDError: if an I/O or OS... | python | {
"resource": ""
} |
q248117 | LED.close | train | def close(self):
"""Close the sysfs LED.
Raises:
LEDError: if an I/O or OS error occurs.
"""
if self._fd is None:
return
try:
| python | {
"resource": ""
} |
q248118 | I2C.transfer | train | def transfer(self, address, messages):
"""Transfer `messages` to the specified I2C `address`. Modifies the
`messages` array with the results of any read transactions.
Args:
address (int): I2C address.
messages (list): list of I2C.Message messages.
Raises:
... | python | {
"resource": ""
} |
q248119 | Serial.read | train | def read(self, length, timeout=None):
"""Read up to `length` number of bytes from the serial port with an
optional timeout.
`timeout` can be positive for a timeout in seconds, 0 for a
non-blocking read, or negative or None for a blocking read that will
block until `length` numbe... | python | {
"resource": ""
} |
q248120 | Serial.write | train | def write(self, data):
"""Write `data` to the serial port and return the number of bytes
written.
Args:
data (bytes, bytearray, list): a byte array or list of 8-bit integers to write.
Returns:
int: number of bytes written.
Raises:
SerialErro... | python | {
"resource": ""
} |
q248121 | Serial.poll | train | def poll(self, timeout=None):
"""Poll for data available for reading from the serial port.
`timeout` can be positive for a timeout in seconds, 0 for a
non-blocking poll, or negative or None for a blocking poll. Default is
a blocking poll.
Args: | python | {
"resource": ""
} |
q248122 | Serial.flush | train | def flush(self):
"""Flush the write buffer of the serial port, blocking until all bytes
are written.
Raises:
SerialError: if an I/O or OS error occurs.
"""
try:
| python | {
"resource": ""
} |
q248123 | Serial.input_waiting | train | def input_waiting(self):
"""Query the number of bytes waiting to be read from the serial port.
Returns:
int: number of bytes waiting to be read.
Raises:
SerialError: if an I/O or | python | {
"resource": ""
} |
q248124 | Serial.output_waiting | train | def output_waiting(self):
"""Query the number of bytes waiting to be written to the serial port.
Returns:
int: number of bytes waiting to be written.
Raises:
SerialError: if an I/O or | python | {
"resource": ""
} |
q248125 | GPIO.read | train | def read(self):
"""Read the state of the GPIO.
Returns:
bool: ``True`` for high state, ``False`` for low state.
Raises:
GPIOError: if an I/O or OS error occurs.
"""
# Read value
try:
buf = os.read(self._fd, 2)
except OSError ... | python | {
"resource": ""
} |
q248126 | GPIO.write | train | def write(self, value):
"""Set the state of the GPIO to `value`.
Args:
value (bool): ``True`` for high state, ``False`` for low state.
Raises:
GPIOError: if an I/O or OS error occurs.
TypeError: if `value` type is not bool.
"""
if not isinst... | python | {
"resource": ""
} |
q248127 | GPIO.poll | train | def poll(self, timeout=None):
"""Poll a GPIO for the edge event configured with the .edge property.
`timeout` can be a positive number for a timeout in seconds, 0 for a
non-blocking poll, or negative or None for a blocking poll. Defaults to
blocking poll.
Args:
time... | python | {
"resource": ""
} |
q248128 | MMIO.read32 | train | def read32(self, offset):
"""Read 32-bits from the specified `offset` in bytes, relative to the
base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
Returns:
int: 32-bit value read.
Raises:
... | python | {
"resource": ""
} |
q248129 | MMIO.read | train | def read(self, offset, length):
"""Read a string of bytes from the specified `offset` in bytes,
relative to the base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
length (int): number of bytes to read.
... | python | {
"resource": ""
} |
q248130 | MMIO.write8 | train | def write8(self, offset, value):
"""Write 8-bits to the specified `offset` in bytes, relative to the
base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
value (int, long): 8-bit value to write.
Raises:... | python | {
"resource": ""
} |
q248131 | MMIO.write | train | def write(self, offset, data):
"""Write a string of bytes to the specified `offset` in bytes, relative
to the base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
data (bytes, bytearray, list): a byte array or l... | python | {
"resource": ""
} |
q248132 | MMIO.close | train | def close(self):
"""Unmap the MMIO object's mapped physical memory."""
if self.mapping is None:
return | python | {
"resource": ""
} |
q248133 | MMIO.pointer | train | def pointer(self):
"""Get a ctypes void pointer to the memory mapped region.
:type: ctypes.c_void_p
"""
| python | {
"resource": ""
} |
q248134 | SPI.transfer | train | def transfer(self, data):
"""Shift out `data` and return shifted in data.
Args:
data (bytes, bytearray, list): a byte array or list of 8-bit integers to shift out.
Returns:
bytes, bytearray, list: data shifted in.
Raises:
SPIError: if an I/O or OS e... | python | {
"resource": ""
} |
q248135 | ensure_session_key | train | def ensure_session_key(request):
"""
Given a request return a session key that will be used. There may already
be a session key associated, but if there is not, we force the session to
create itself and persist between requests for the client behind the given
request.
"""
key = request.sessi... | python | {
"resource": ""
} |
q248136 | add_proxy_auth | train | def add_proxy_auth(possible_proxy_url, proxy_auth):
"""
Add a username and password to a proxy URL, if the input value is a proxy URL.
:param str possible_proxy_url: Proxy URL or ``DIRECT``.
:param requests.auth.HTTPProxyAuth proxy_auth: Proxy authentication info.
:returns: Proxy URL with auth info... | python | {
"resource": ""
} |
q248137 | ProxyResolver.get_proxies | train | def get_proxies(self, url):
"""
Get the proxies that are applicable to a given URL, according to the PAC file.
:param str url: The URL for which to find appropriate proxies.
:return: All the proxies that apply to the given URL.
Can be empty, which means to abort the request.... | python | {
"resource": ""
} |
q248138 | ProxyResolver.get_proxy | train | def get_proxy(self, url):
"""
Get a proxy to use for a given URL, excluding any banned ones.
:param str url: The URL for which to find an appropriate proxy.
:return: A proxy to use for the URL,
or the string 'DIRECT', which means a proxy is not to be used.
Can be... | python | {
"resource": ""
} |
q248139 | ProxyResolver.get_proxy_for_requests | train | def get_proxy_for_requests(self, url):
"""
Get proxy configuration for a given URL, in a form ready to use with the Requests library.
:param str url: The URL for which to obtain proxy configuration.
:returns: Proxy configuration in a form recognized by Requests, for use with the ``proxi... | python | {
"resource": ""
} |
q248140 | isInNet | train | def isInNet(host, pattern, mask):
"""
Pattern and mask specification is done the same way as for SOCKS configuration.
:param str host: a DNS hostname, or IP address.
If a hostname is passed, it will be resolved into an IP address by this function.
:param str pattern: an IP address pattern in th... | python | {
"resource": ""
} |
q248141 | SSHFS._get_ssh_config | train | def _get_ssh_config(config_path='~/.ssh/config'):
"""Extract the configuration located at ``config_path``.
Returns:
paramiko.SSHConfig: the configuration instance.
"""
ssh_config = paramiko.SSHConfig()
try:
| python | {
"resource": ""
} |
q248142 | SSHFS.openbin | train | def openbin(self, path, mode='r', buffering=-1, **options): # noqa: D102
"""Open a binary file-like object.
Arguments:
path (str): A path on the filesystem.
mode (str): Mode to open the file (must be a valid, non-text mode).
Since this method only opens binary f... | python | {
"resource": ""
} |
q248143 | SSHFS.platform | train | def platform(self):
"""The platform the server is running on.
Returns:
str: the platform of the remote server, as in `sys.platform`.
"""
uname_sys = self._exec_command("uname -s")
sysinfo = self._exec_command("sysinfo")
if uname_sys is not None:
i... | python | {
"resource": ""
} |
q248144 | SSHFS.locale | train | def locale(self):
"""The locale the server is running on.
Returns:
str: the locale of the remote server if detected, or `None`.
| python | {
"resource": ""
} |
q248145 | SSHFS._exec_command | train | def _exec_command(self, cmd):
"""Run a command on the remote SSH server.
Returns:
bytes: the output of the command, if it didn't fail
None: if the error pipe of the command was not empty
"""
| python | {
"resource": ""
} |
q248146 | SSHFS._make_info | train | def _make_info(self, name, stat_result, namespaces):
"""Create an `Info` object from a stat result.
"""
info = {
'basic': {
'name': name,
'is_dir': stat.S_ISDIR(stat_result.st_mode)
}
}
if | python | {
"resource": ""
} |
q248147 | LDAPAttribute.value | train | def value(self):
'''Return single value or list of values from the attribute.
If FORCE_ATTRIBUTE_VALUE_AS_LIST is True, always return a
list with values.
'''
| python | {
"resource": ""
} |
q248148 | LDAPAttribute.append | train | def append(self, value):
'''Add another value to the attribute'''
if self.__dict__['values']:
| python | {
"resource": ""
} |
q248149 | LDAPConn.authenticate | train | def authenticate(self,
username,
password,
attribute=None,
base_dn=None,
search_filter=None,
search_scope=SUBTREE):
'''Attempts to bind a user to the LDAP server.
Args:
... | python | {
"resource": ""
} |
q248150 | BaseQuery.get | train | def get(self, ldap_dn):
'''Return an LDAP entry by DN
Args:
ldap_dn (str): LDAP DN
'''
| python | {
"resource": ""
} |
q248151 | BaseQuery.filter | train | def filter(self, *query_filter):
'''Set the query filter to perform the query with
Args:
| python | {
"resource": ""
} |
q248152 | BaseQuery.all | train | def all(self, components_in_and=True):
'''Return all of the results of a | python | {
"resource": ""
} |
q248153 | set_monitor | train | def set_monitor(module):
""" Defines the monitor method on the module. """
def monitor(name, tensor,
track_data=True,
track_grad=True):
"""
Register the tensor under the name given (now a string)
and track it based on the track_data and track_grad argument... | python | {
"resource": ""
} |
q248154 | set_monitoring | train | def set_monitoring(module):
""" Defines the monitoring method on the module. """
def monitoring(is_monitoring,
track_data=None,
track_grad=None,
track_update=None,
track_update_ratio=None):
"""
Turn monitoring on or off.... | python | {
"resource": ""
} |
q248155 | grad_hook | train | def grad_hook(module, name, writer, bins):
""" Factory for grad_hook closures """
def hook(grad):
writer.add_histogram('{}/grad'.format(name.replace('.','/')),
| python | {
"resource": ""
} |
q248156 | remove_grad_hooks | train | def remove_grad_hooks(module, input):
""" Remove gradient hooks to all of the parameters and monitored vars """
for hook in list(module.param_hooks.keys()):
module.param_hooks[hook].remove()
module.param_hooks.pop(hook) | python | {
"resource": ""
} |
q248157 | get_monitor_forward_and_backward | train | def get_monitor_forward_and_backward(summary_writer, bins):
""" Get the method for monitoring the forward values of the network """
def monitor_forward_and_backward(module, input, output):
"""
Iterate over the module parameters and monitor their forward values.
Then iterate over all of t... | python | {
"resource": ""
} |
q248158 | commit | train | def commit(experiment_name, time):
"""
Try to commit repo exactly as it is when starting the experiment for reproducibility.
"""
try:
sh.git.commit('-a',
m='"auto commit tracked files for new experiment: {} on {}"'.format(experiment_name, time),
allow_empty=True
| python | {
"resource": ""
} |
q248159 | Firewall.json | train | def json(self):
"""
Output the security rules as a json string.
Return:
str
"""
return json.dumps(self.dict_rules,
| python | {
"resource": ""
} |
q248160 | Firewall.rules | train | def rules(self):
"""
Returns a sorted list of firewall rules.
Returns:
list
"""
list_of_rules = []
for main_row in self.dict_rules:
if 'rules' in main_row:
for rule_row in main_row['rules']:
if 'grants' in rule... | python | {
"resource": ""
} |
q248161 | Firewall.csv | train | def csv(self):
"""
Returns the security rules as a CSV.
CSV format:
- id
- name
- description
- rules_direction
- rules_ip_protocol
- rules_from_port
- rules_to_port
- rules_grants_group_id
- rules_grants_name
- rul... | python | {
"resource": ""
} |
q248162 | Firewall._get_rules_from_aws | train | def _get_rules_from_aws(self):
"""
Load the EC2 security rules off AWS into a list of dict.
Returns:
list
"""
list_of_rules = list()
if self.profile:
boto3.setup_default_session(profile_name=self.profile)
if self.region:
ec2 ... | python | {
"resource": ""
} |
q248163 | getattr_sdk | train | def getattr_sdk(attr, name):
"""
Filter SDK attributes
Args:
attr(attribute): Attribute as returned by :func:`getattr`.
name(str): Attribute name.
Returns:
`attr` if passed.
"""
| python | {
"resource": ""
} |
q248164 | setup_sdk_logging | train | def setup_sdk_logging(logfile=None, loglevel=logging.INFO):
"""
Setup a NullHandler to the root logger. If ``logfile`` is passed,
additionally add a FileHandler in ``loglevel`` level.
Args:
logfile(str): A path to setup a log file.
loglevel(int): :mod:`logging` log level.
Returns:
... | python | {
"resource": ""
} |
q248165 | get_ssh_client | train | def get_ssh_client(
ip_addr,
ssh_key=None,
host_name=None,
ssh_tries=None,
propagate_fail=True,
username='root',
password='123456',
):
"""
Get a connected SSH client
Args:
ip_addr(str): IP address of the endpoint
ssh_key(str or list of str): Path to a file which
... | python | {
"resource": ""
} |
q248166 | sysprep | train | def sysprep(disk, distro, loader=None, backend='direct', **kwargs):
"""
Run virt-sysprep on the ``disk``, commands are built from the distro
specific template and arguments passed in ``kwargs``. If no template is
available it will default to ``sysprep-base.j2``.
Args:
disk(str): path to dis... | python | {
"resource": ""
} |
q248167 | get_domain_template | train | def get_domain_template(distro, libvirt_ver, **kwargs):
"""
Get a rendered Jinja2 domain template
Args:
distro(str): domain distro
libvirt_ver(int): libvirt version
kwargs(dict): args for template render
Returns:
str: rendered template
"""
env = Environment(
... | python | {
"resource": ""
} |
q248168 | dict_to_xml | train | def dict_to_xml(spec, full_document=False):
"""
Convert dict to XML
Args:
spec(dict): dict to convert
full_document(bool): whether to | python | {
"resource": ""
} |
q248169 | guestfs_conn_ro | train | def guestfs_conn_ro(disk):
"""
Open a GuestFS handle and add `disk` in read only mode.
Args:
disk(disk path): Path to the disk.
Yields:
guestfs.GuestFS: Open GuestFS handle
Raises:
:exc:`GuestFSError`: On any guestfs operation failure
"""
disk_path = os.path.expan... | python | {
"resource": ""
} |
q248170 | guestfs_conn_mount_ro | train | def guestfs_conn_mount_ro(disk_path, disk_root, retries=5, wait=1):
"""
Open a GuestFS handle with `disk_path` and try mounting the root
filesystem. `disk_root` is a hint where it should be looked and will
only be used if GuestFS will not be able to deduce it independently.
Note that mounting a liv... | python | {
"resource": ""
} |
q248171 | find_rootfs | train | def find_rootfs(conn, disk_root):
"""
Find the image's device root filesystem, and return its path.
1. Use :func:`guestfs.GuestFS.inspect_os` method. If it returns more than
one root filesystem or None, try:
2. Find an exact match of `disk_root` from
:func:`guestfs.GuestFS.list_filesyst... | python | {
"resource": ""
} |
q248172 | extract_paths | train | def extract_paths(disk_path, disk_root, paths, ignore_nopath):
"""
Extract paths from a disk using guestfs
Args:
disk_path(str): path to the disk
disk_root(str): root partition
paths(list of tuples): files to extract in
`[(src1, dst1), (src2, dst2)...]` format, if ``srcN... | python | {
"resource": ""
} |
q248173 | cli_plugin_add_argument | train | def cli_plugin_add_argument(*args, **kwargs):
"""
Decorator generator that adds an argument to the cli plugin based on the
decorated function
Args:
*args: Any args to be passed to
:func:`argparse.ArgumentParser.add_argument`
*kwargs: Any keyword args to be passed to
... | python | {
"resource": ""
} |
q248174 | cli_plugin_add_help | train | def cli_plugin_add_help(help):
"""
Decorator generator that adds the cli help to the cli plugin based on the
decorated function
Args:
help (str): help string for the cli plugin
Returns:
function: Decorator that builds or extends the cliplugin for the
decorated function,... | python | {
"resource": ""
} |
q248175 | LocalLibvirtVMProvider._get_domain | train | def _get_domain(self):
"""
Return the object representation of this provider VM.
Returns:
libvirt.virDomain: Libvirt domain object
Raises:
:exc:`~lago.plugins.vm.LagoFailedToGetVMStateError:
If the VM exist, but the query returned an error.
... | python | {
"resource": ""
} |
q248176 | LocalLibvirtVMProvider.raw_state | train | def raw_state(self):
"""
Return the state of the domain in Libvirt's terms
Retruns:
tuple of ints: The state and its reason
Raises:
:exc:`~lago.plugins.vm.LagoVMDoesNotExistError`:
If the VM of this provider doesn't exist.
:exc:`~lago... | python | {
"resource": ""
} |
q248177 | LocalLibvirtVMProvider.state | train | def state(self):
"""
Return a small description of the current status of the domain
Returns:
str: small description of the domain status, 'down' if it's not
found at all.
"""
try:
return libvirt_utils.Domain.resolve_state(self.raw_state())
| python | {
"resource": ""
} |
q248178 | LocalLibvirtVMProvider.extract_paths | train | def extract_paths(self, paths, ignore_nopath):
"""
Extract the given paths from the domain
Attempt to extract all files defined in ``paths`` with the method
defined in :func:`~lago.plugins.vm.VMProviderPlugin.extract_paths`,
if it fails, and `guestfs` is available it will try ex... | python | {
"resource": ""
} |
q248179 | LocalLibvirtVMProvider.extract_paths_dead | train | def extract_paths_dead(self, paths, ignore_nopath):
"""
Extract the given paths from the domain using guestfs.
Using guestfs can have side-effects and should be used as a second
option, mainly when SSH is not available.
Args:
paths(list of str): paths to extract
... | python | {
"resource": ""
} |
q248180 | LocalLibvirtVMProvider.export_disks | train | def export_disks(
self,
standalone,
dst_dir,
compress,
collect_only=False,
with_threads=True,
*args,
**kwargs
):
"""
Export all the disks of self.
Args:
standalone (bool): if true, merge the base images and the laye... | python | {
"resource": ""
} |
q248181 | LocalLibvirtVMProvider.interactive_console | train | def interactive_console(self):
"""
Opens an interactive console
Returns:
lago.utils.CommandStatus: result of the virsh command execution
"""
if not self.running():
| python | {
"resource": ""
} |
q248182 | init | train | def init(config, workdir=None, logfile=None, loglevel=logging.INFO, **kwargs):
"""
Initialize the Lago environment
Args:
config(str): Path to LagoInitFile
workdir(str): Path to initalize the workdir, defaults to "$PWD/.lago"
**kwargs(dict): Pass arguments to :func:`~lago.cmd.do_init... | python | {
"resource": ""
} |
q248183 | load_env | train | def load_env(workdir, logfile=None, loglevel=logging.INFO):
"""
Load an existing Lago environment
Args:
workdir(str): Path to the workdir directory, as created by
:func:`~lago.sdk.init` or created by the CLI.
logfile(str): A Path to setup a log file.
loglevel(int): :mod:`log... | python | {
"resource": ""
} |
q248184 | SDK.ansible_inventory | train | def ansible_inventory(
self,
keys=['vm-type', 'groups', 'vm-provider'],
):
"""
Get an Ansible inventory as a string, ``keys`` should be list on which
to group the hosts by. You can use any key defined in LagoInitFile.
Examples of possible `keys`:
`keys=[... | python | {
"resource": ""
} |
q248185 | DiskExportManager.calc_sha | train | def calc_sha(self, checksum):
"""
Calculate the checksum of the new exported disk, write it to
a file, and update this managers 'exported_metadata'.
Args:
checksum(str): The type of the checksum
"""
with LogTask('Calculating {}'.format(checksum)):
| python | {
"resource": ""
} |
q248186 | DiskExportManager.compress | train | def compress(self):
"""
Compress the new exported image,
Block size was taken from virt-builder page
"""
if not self.do_compress:
return
| python | {
"resource": ""
} |
q248187 | TemplateExportManager.rebase | train | def rebase(self):
"""
Change the backing-file entry of the exported disk.
Please refer to 'qemu-img rebase' manual for more info.
"""
if self.standalone:
rebase_msg = 'Merging layered image with base'
else:
rebase_msg = 'Rebase'
with LogTa... | python | {
"resource": ""
} |
q248188 | FileExportManager.export | train | def export(self):
"""
See DiskExportManager.export
"""
with LogTask('Exporting disk {} to {}'.format(self.name, self.dst)):
with utils.RollbackContext() as rollback:
rollback.prependDefer(
shutil.rmtree, self.dst, ignore_errors=True
... | python | {
"resource": ""
} |
q248189 | Build.normalize_build_spec | train | def normalize_build_spec(self, build_spec):
"""
Convert a build spec into a list of Command tuples.
After running this command, self.build_cmds should hold all
the commands that should be run on the disk in self.disk_path.
Args:
build_spec (dict): The buildspec part ... | python | {
"resource": ""
} |
q248190 | Build.get_cmd_handler | train | def get_cmd_handler(self, cmd):
"""
Return an handler for cmd.
The handler and the command should have the same name.
See class description for more info about handlers.
Args:
cmd (str): The name of the command
Returns:
callable: which handles cm... | python | {
"resource": ""
} |
q248191 | Build.build | train | def build(self):
"""
Run all the commands in self.build_cmds
Raises:
lago.build.BuildException: If a command returned a non-zero code
"""
if not self.build_cmds:
LOGGER.debug('No build commands were found, skipping build step')
with LogTask('Buil... | python | {
"resource": ""
} |
q248192 | FileSystemTemplateProvider.download_image | train | def download_image(self, handle, dest):
"""
Copies over the handl to the destination
Args:
handle (str): path to copy over
dest (str): path to copy to
| python | {
"resource": ""
} |
q248193 | HttpTemplateProvider.download_image | train | def download_image(self, handle, dest):
"""
Downloads the image from the http server
Args:
handle (str): url from the `self.baseurl` to the remote template
dest (str): Path to store the downloaded url to, must be a file
path
Returns:
... | python | {
"resource": ""
} |
q248194 | TemplateRepository.get_by_name | train | def get_by_name(self, name):
"""
Retrieve a template by it's name
Args:
name (str): Name of the template to retrieve
Raises:
LagoMissingTemplateError: if no template is found
"""
try:
spec = self._dom.get('templates', {})[name]
... | python | {
"resource": ""
} |
q248195 | TemplateVersion.get_hash | train | def get_hash(self):
"""
Returns the associated hash for this template version
Returns:
str: Hash for this version
"""
if self._hash is None:
| python | {
"resource": ""
} |
q248196 | TemplateVersion.get_metadata | train | def get_metadata(self):
"""
Returns the associated metadata info for this template version
Returns:
dict: Metadata for this version
"""
if self._metadata is | python | {
"resource": ""
} |
q248197 | TemplateStore.get_path | train | def get_path(self, temp_ver):
"""
Get the path of the given version in this store
Args:
temp_ver TemplateVersion: version to look for
Returns:
str: The path to the template version inside the store
Raises:
RuntimeError: if the template is no... | python | {
"resource": ""
} |
q248198 | TemplateStore.download | train | def download(self, temp_ver, store_metadata=True):
"""
Retrieve the given template version
Args:
temp_ver (TemplateVersion): template version to retrieve
store_metadata (bool): If set to ``False``, will not refresh the
local metadata with the retrieved on... | python | {
"resource": ""
} |
q248199 | TemplateStore.get_stored_metadata | train | def get_stored_metadata(self, temp_ver):
"""
Retrieves the metadata for the given template version from the store
Args:
temp_ver (TemplateVersion): template version to retrieve the
metadata for
Returns:
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.