text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_hostname(new_hostname, pretty_hostname=None):
"""Sets this hosts hostname This method updates /etc/sysconfig/network and calls the hostname command to se... |
log = logging.getLogger(mod_logger + '.set_hostname')
# Ensure the hostname is a str
if not isinstance(new_hostname, basestring):
msg = 'new_hostname argument must be a string'
raise CommandError(msg)
# Update the network config file
network_file = '/etc/sysconfig/network'
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_ntp_server(server):
"""Sets the NTP server on Linux :param server: (str) NTP server IP or hostname :return: None :raises CommandError """ |
log = logging.getLogger(mod_logger + '.set_ntp_server')
# Ensure the hostname is a str
if not isinstance(server, basestring):
msg = 'server argument must be a string'
log.error(msg)
raise CommandError(msg)
# Ensure the ntp.conf file exists
ntp_conf = '/etc/ntp.conf'
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_ifcfg_file(source_interface, dest_interface):
"""Copies an existing ifcfg network script to another :param source_interface: String (e.g. 1) :param dest... |
log = logging.getLogger(mod_logger + '.copy_ifcfg_file')
# Validate args
if not isinstance(source_interface, basestring):
msg = 'source_interface argument must be a string'
log.error(msg)
raise TypeError(msg)
if not isinstance(dest_interface, basestring):
msg = 'dest_int... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_ifcfg_file(device_index='0'):
"""Removes the ifcfg file at the specified device index and restarts the network service :param device_index: (int) Devi... |
log = logging.getLogger(mod_logger + '.remove_ifcfg_file')
if not isinstance(device_index, basestring):
msg = 'device_index argument must be a string'
log.error(msg)
raise CommandError(msg)
network_script = '/etc/sysconfig/network-scripts/ifcfg-eth{d}'.format(d=device_index)
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_nat_rule(port, source_interface, dest_interface):
"""Adds a NAT rule to iptables :param port: String or int port number :param source_interface: String (... |
log = logging.getLogger(mod_logger + '.add_nat_rule')
# Validate args
if not isinstance(source_interface, basestring):
msg = 'source_interface argument must be a string'
log.error(msg)
raise TypeError(msg)
if not isinstance(dest_interface, basestring):
msg = 'dest_interf... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_iptables(rules_file='/etc/sysconfig/iptables'):
"""Saves iptables rules to the provided rules file :return: None :raises OSError """ |
log = logging.getLogger(mod_logger + '.save_iptables')
# Run iptables-save to get the output
command = ['iptables-save']
log.debug('Running command: iptables-save')
try:
iptables_out = run_command(command, timeout_sec=20)
except CommandError:
_, ex, trace = sys.exc_info()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_remote_host_marker_file(host, file_path):
"""Queries a remote host over SSH to check for existence of a marker file :param host: (str) host to query :p... |
log = logging.getLogger(mod_logger + '.check_remote_host_marker_file')
if not isinstance(host, basestring):
msg = 'host argument must be a string'
log.error(msg)
raise TypeError(msg)
if not isinstance(file_path, basestring):
msg = 'file_path argument must be a string'
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restore_iptables(firewall_rules):
"""Restores and saves firewall rules from the firewall_rules file :param firewall_rules: (str) Full path to the firewall ru... |
log = logging.getLogger(mod_logger + '.restore_iptables')
log.info('Restoring firewall rules from file: {f}'.format(f=firewall_rules))
# Ensure the firewall rules file exists
if not os.path.isfile(firewall_rules):
msg = 'Unable to restore iptables, file not found: {f}'.format(f=firewall_rules)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_systemd():
"""Determines whether this system uses systemd :return: (bool) True if this distro has systemd """ |
os_family = platform.system()
if os_family != 'Linux':
raise OSError('This method is only supported on Linux, found OS: {o}'.format(o=os_family))
linux_distro, linux_version, distro_name = platform.linux_distribution()
# Determine when to use systemd
systemd = False
if 'ubuntu' in linu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def system_reboot(wait_time_sec=20):
"""Reboots the system after a specified wait time. Must be run as root :param wait_time_sec: (int) number of sec to wait bef... |
log = logging.getLogger(mod_logger + '.system_reboot')
try:
wait_time_sec = int(wait_time_sec)
except ValueError:
raise CommandError('wait_time_sec must be an int, or a string convertible to an int')
log.info('Waiting {t} seconds before reboot...'.format(t=str(wait_time_sec)))
tim... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def aes_pad(s, block_size=32, padding='{'):
""" Adds padding to get the correct block sizes for AES encryption @s: #str being AES encrypted or decrypted @block_s... |
return s + (block_size - len(s) % block_size) * padding |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strkey(val, chaffify=1, keyspace=string.ascii_letters + string.digits):
""" Converts integers to a sequence of strings, and reverse. This is not intended to ... |
chaffify = chaffify or 1
keylen = len(keyspace)
try:
# INT TO STRING
if val < 0:
raise ValueError("Input value must be greater than -1.")
# chaffify the value
val = val * chaffify
if val == 0:
return keyspace[0]
# output the new str... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def round_sig(x, n, scien_notation = False):
if x < 0:
x = x * -1
symbol = '-'
else:
symbol = ''
'''round floating point x to n significant figures'''
if type(n) is not types.IntType:
raise TypeError, "n must be an integer"
try:
x = float(x)
exce... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, items=[], taxes=[], custom_data=[]):
"""Adds the items to the invoice Format of 'items': [ InvoiceItem( name="VIP Ticket", quantity= 2, unit_pri... |
self.add_items(items)
self.add_taxes(taxes)
self.add_custom_data(custom_data)
return self._process('checkout-invoice/create', self._prepare_data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def confirm(self, token=None):
"""Returns the status of the invoice STATUSES: pending, completed, cancelled """ |
_token = token if token else self._response.get("token")
return self._process('checkout-invoice/confirm/' + str(_token)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_taxes(self, taxes):
"""Appends the data to the 'taxes' key in the request object 'taxes' should be in format: [("tax_name", "tax_amount")] For example: [... |
# fixme: how to resolve duplicate tax names
_idx = len(self.taxes) # current index to prevent overwriting
for idx, tax in enumerate(taxes):
tax_key = "tax_" + str(idx + _idx)
self.taxes[tax_key] = {"name": tax[0], "amount": tax[1]} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_item(self, item):
"""Updates the list of items in the current transaction""" |
_idx = len(self.items)
self.items.update({"item_" + str(_idx + 1): item}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prepare_data(self):
"""Formats the data in the current transaction for processing""" |
total_amount = self.total_amount or self.calculate_total_amt()
self._data = {
"invoice": {
"items": self.__encode_items(self.items),
"taxes": self.taxes,
"total_amount": total_amount,
"description": self.description,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __encode_items(self, items):
"""Encodes the InvoiceItems into a JSON serializable format items = [('item_1',InvoiceItem(name='VIP Ticket', quantity=2, unit_p... |
xs = [item._asdict() for (_key, item) in items.items()]
return list(map(lambda x: dict(zip(x.keys(), x.values())), xs)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_deployment_home(self):
"""Sets self.deployment_home This method finds and sets deployment home, primarily based on the DEPLOYMENT_HOME environment variab... |
log = logging.getLogger(self.cls_logger + '.set_deployment_home')
try:
self.deployment_home = os.environ['DEPLOYMENT_HOME']
except KeyError:
log.warn('DEPLOYMENT_HOME environment variable is not set, attempting to set it...')
else:
log.info('Found DEP... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_deployment_properties(self):
"""Reads the deployment properties file This method reads the deployment properties file into the "properties" dictionary o... |
log = logging.getLogger(self.cls_logger + '.read_deployment_properties')
# Ensure deployment properties file exists
self.properties_file = os.path.join(self.deployment_home, 'deployment.properties')
if not os.path.isfile(self.properties_file):
msg = 'Deployment properties f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_property(self, regex):
"""Gets the name of a specific property This public method is passed a regular expression and returns the matching property name. ... |
log = logging.getLogger(self.cls_logger + '.get_property')
if not isinstance(regex, basestring):
log.error('regex arg is not a string found type: {t}'.format(t=regex.__class__.__name__))
return None
log.debug('Looking up property based on regex: {r}'.format(r=regex))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_matching_property_names(self, regex):
"""Returns a list of property names matching the provided regular expression :param regex: Regular expression to se... |
log = logging.getLogger(self.cls_logger + '.get_matching_property_names')
prop_list_matched = []
if not isinstance(regex, basestring):
log.warn('regex arg is not a string, found type: {t}'.format(t=regex.__class__.__name__))
return prop_list_matched
log.debug('Fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_value(self, property_name):
"""Returns the value associated to the passed property This public method is passed a specific property as a string and retur... |
log = logging.getLogger(self.cls_logger + '.get_value')
if not isinstance(property_name, basestring):
log.error('property_name arg is not a string, found type: {t}'.format(t=property_name.__class__.__name__))
return None
# Ensure a property with that name exists
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_cons3rt_role_name(self):
"""Set the cons3rt_role_name member for this system :return: None :raises: DeploymentError """ |
log = logging.getLogger(self.cls_logger + '.set_cons3rt_role_name')
try:
self.cons3rt_role_name = os.environ['CONS3RT_ROLE_NAME']
except KeyError:
log.warn('CONS3RT_ROLE_NAME is not set, attempting to determine it from deployment properties...')
if platform.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def determine_cons3rt_role_name_linux(self):
"""Determines the CONS3RT_ROLE_NAME for this Linux system, and Set the cons3rt_role_name member for this system This... |
log = logging.getLogger(self.cls_logger + '.determine_cons3rt_role_name_linux')
# Determine IP addresses for this system
log.info('Determining the IPv4 addresses for this system...')
try:
ip_addresses = get_ip_addresses()
except CommandError:
_, ex, trac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_asset_dir(self):
"""Returns the ASSET_DIR environment variable This method gets the ASSET_DIR environment variable for the current asset install. It retu... |
log = logging.getLogger(self.cls_logger + '.get_asset_dir')
try:
self.asset_dir = os.environ['ASSET_DIR']
except KeyError:
log.warn('Environment variable ASSET_DIR is not set!')
else:
log.info('Found environment variable ASSET_DIR: {a}'.format(a=self.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_scenario_role_names(self):
"""Populates the list of scenario role names in this deployment and populates the scenario_master with the master role Gets a ... |
log = logging.getLogger(self.cls_logger + '.set_scenario_role_names')
is_master_props = self.get_matching_property_names('isMaster')
for is_master_prop in is_master_props:
role_name = is_master_prop.split('.')[-1]
log.info('Adding scenario host: {n}'.format(n=role_name))... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_scenario_network_info(self):
"""Populates a list of network info for each scenario host from deployment properties :return: None """ |
log = logging.getLogger(self.cls_logger + '.set_scenario_network_info')
for scenario_host in self.scenario_role_names:
scenario_host_network_info = {'scenario_role_name': scenario_host}
log.debug('Looking up network info from deployment properties for scenario host: {s}'.format... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_deployment_name(self):
"""Sets the deployment name from deployment properties :return: None """ |
log = logging.getLogger(self.cls_logger + '.set_deployment_name')
self.deployment_name = self.get_value('cons3rt.deployment.name')
log.info('Found deployment name: {n}'.format(n=self.deployment_name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_deployment_id(self):
"""Sets the deployment ID from deployment properties :return: None """ |
log = logging.getLogger(self.cls_logger + '.set_deployment_id')
deployment_id_val = self.get_value('cons3rt.deployment.id')
if not deployment_id_val:
log.debug('Deployment ID not found in deployment properties')
return
try:
deployment_id = int(deploym... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_deployment_run_name(self):
"""Sets the deployment run name from deployment properties :return: None """ |
log = logging.getLogger(self.cls_logger + '.set_deployment_run_name')
self.deployment_run_name = self.get_value('cons3rt.deploymentRun.name')
log.info('Found deployment run name: {n}'.format(n=self.deployment_run_name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_deployment_run_id(self):
"""Sets the deployment run ID from deployment properties :return: None """ |
log = logging.getLogger(self.cls_logger + '.set_deployment_run_id')
deployment_run_id_val = self.get_value('cons3rt.deploymentRun.id')
if not deployment_run_id_val:
log.debug('Deployment run ID not found in deployment properties')
return
try:
deployme... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_virtualization_realm_type(self):
"""Sets the virtualization realm type from deployment properties :return: None """ |
log = logging.getLogger(self.cls_logger + '.set_virtualization_realm_type')
self.virtualization_realm_type = self.get_value('cons3rt.deploymentRun.virtRealm.type')
log.info('Found virtualization realm type : {t}'.format(t=self.virtualization_realm_type)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_hosts_file(self, ip, entry):
"""Updated the hosts file depending on the OS :param ip: (str) IP address to update :param entry: (str) entry to associat... |
log = logging.getLogger(self.cls_logger + '.update_hosts_file')
if get_os() in ['Linux', 'Darwin']:
update_hosts_file_linux(ip=ip, entry=entry)
elif get_os() == 'Windows':
update_hosts_file_windows(ip=ip, entry=entry)
else:
log.warn('OS detected was ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_scenario_hosts_file(self, network_name='user-net', domain_name=None):
"""Adds hosts file entries for each system in the scenario for the specified networ... |
log = logging.getLogger(self.cls_logger + '.set_scenario_hosts_file')
log.info('Scanning scenario hosts to make entries in the hosts file for network: {n}'.format(n=network_name))
for scenario_host in self.scenario_network_info:
if domain_name:
host_file_entry = '{r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_hosts_file_entry_for_role(self, role_name, network_name='user-net', fqdn=None, domain_name=None):
"""Adds an entry to the hosts file for a scenario host ... |
log = logging.getLogger(self.cls_logger + '.set_hosts_file_entry_for_role')
# Determine the host file entry portion
if fqdn:
host_file_entry = fqdn
else:
if domain_name:
host_file_entry = '{r}.{d} {r}'.format(r=role_name, d=domain_name)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_device_for_network_linux(self, network_name):
"""Given a cons3rt network name, return the network interface name on this Linux system :param network_name... |
log = logging.getLogger(self.cls_logger + '.get_device_for_network_linux')
if get_os() not in ['Linux']:
log.warn('Non-linux OS detected, returning...')
return
# Get the IP address for the network name according to cons3rt
ip_address = self.get_ip_on_network(ne... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insertSaneDefaults(self):
""" Add sane defaults rules to the raw and filter tables """ |
self.raw.insert(0, '-A OUTPUT -o lo -j NOTRACK')
self.raw.insert(1, '-A PREROUTING -i lo -j NOTRACK')
self.filters.insert(0, '-A INPUT -i lo -j ACCEPT')
self.filters.insert(1, '-A OUTPUT -o lo -j ACCEPT')
self.filters.insert(2, '-A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT')
self.filters.i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def appendDefaultDrop(self):
""" Add a DROP policy at the end of the rules """ |
self.filters.append('-A INPUT -j DROP')
self.filters.append('-A OUTPUT -j DROP')
self.filters.append('-A FORWARD -j DROP')
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def template(self):
""" Create a rules file in iptables-restore format """ |
s = Template(self._IPTABLES_TEMPLATE)
return s.substitute(filtertable='\n'.join(self.filters),
rawtable='\n'.join(self.raw),
mangletable='\n'.join(self.mangle),
nattable='\n'.join(self.nat),
date=datetime.today()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query(self, base, filterstr, attrlist=None):
""" wrapper to search_s """ |
return self.conn.search_s(base, ldap.SCOPE_SUBTREE, filterstr, attrlist) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getUserByNumber(self, base, uidNumber):
""" search for a user in LDAP and return its DN and uid """ |
res = self.query(base, "uidNumber="+str(uidNumber), ['uid'])
if len(res) > 1:
raise InputError(uidNumber, "Multiple users found. Expecting one.")
return res[0][0], res[0][1]['uid'][0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_aws():
"""Determines if this system is on AWS :return: bool True if this system is running on AWS """ |
log = logging.getLogger(mod_logger + '.is_aws')
log.info('Querying AWS meta data URL: {u}'.format(u=metadata_url))
# Re-try logic for checking the AWS meta data URL
retry_time_sec = 10
max_num_tries = 10
attempt_num = 1
while True:
if attempt_num > max_num_tries:
log.i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_instance_id():
"""Gets the instance ID of this EC2 instance :return: String instance ID or None """ |
log = logging.getLogger(mod_logger + '.get_instance_id')
# Exit if not running on AWS
if not is_aws():
log.info('This machine is not running in AWS, exiting...')
return
instance_id_url = metadata_url + 'instance-id'
try:
response = urllib.urlopen(instance_id_url)
excep... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_availability_zone():
"""Gets the AWS Availability Zone ID for this system :return: (str) Availability Zone ID where this system lives """ |
log = logging.getLogger(mod_logger + '.get_availability_zone')
# Exit if not running on AWS
if not is_aws():
log.info('This machine is not running in AWS, exiting...')
return
availability_zone_url = metadata_url + 'placement/availability-zone'
try:
response = urllib.urlope... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_region():
"""Gets the AWS Region ID for this system :return: (str) AWS Region ID where this system lives """ |
log = logging.getLogger(mod_logger + '.get_region')
# First get the availability zone
availability_zone = get_availability_zone()
if availability_zone is None:
msg = 'Unable to determine the Availability Zone for this system, cannot determine the AWS Region'
log.error(msg)
ret... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_primary_mac_address():
"""Determines the MAC address to use for querying the AWS meta data service for network related queries :return: (str) MAC address... |
log = logging.getLogger(mod_logger + '.get_primary_mac_address')
log.debug('Attempting to determine the MAC address for eth0...')
try:
mac_address = netifaces.ifaddresses('eth0')[netifaces.AF_LINK][0]['addr']
except Exception:
_, ex, trace = sys.exc_info()
msg = '{n}: Unable to ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def attr_sep(self, new_sep: str) -> None: """Set the new value for the attribute separator. When the new value is assigned a new tree is generated. """ |
self._attr_sep = new_sep
self._filters_tree = self._generate_filters_tree() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def docs(recreate, gen_index, run_doctests):
# type: (bool, bool, bool) -> None """ Build the documentation for the project. Args: recreate (bool):
If set to **... |
build_dir = conf.get_path('build_dir', '.build')
docs_dir = conf.get_path('docs.path', 'docs')
refdoc_paths = conf.get('docs.reference', [])
docs_html_dir = conf.get_path('docs.out', os.path.join(docs_dir, 'html'))
docs_tests_dir = conf.get_path('docs.tests_out',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gen_ref_docs(gen_index=False):
# type: (int, bool) -> None """ Generate reference documentation for the project. This will use **sphinx-refdoc** to generate ... |
try:
from refdoc import generate_docs
except ImportError as ex:
msg = ("You need to install sphinx-refdoc if you want to generate "
"code reference docs.")
print(msg, file=sys.stderr)
log.err("Exception: {}".format(ex))
sys.exit(-1)
pretend = context... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getitem_in(obj, name):
""" Finds a key in @obj via a period-delimited string @name. @obj: (#dict) @name: (#str) |.|-separated keys to search @obj in .. obj =... |
for part in name.split('.'):
obj = obj[part]
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(component, exact):
# type: (str) -> None """ Create a new release. It will bump the current version number and create a release branch called `release/... |
from peltak.extra.gitflow import logic
logic.release.start(component, exact) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tag_release(message):
# type: (str, bool) -> None """ Tag the current commit with as the current version release. This should be the same commit as the one t... |
from peltak.extra.gitflow import logic
logic.release.tag(message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def query_file_location(question, default_address):
""" This function asks for a location file address from the command terminal it checks if the file exists bef... |
while True:
if default_address == None:
prompt = '{}:'.format(question, default_address)
else:
prompt = '{} [{}]'.format(question, default_address)
sys.stdout.write(prompt)
input_address = raw_input()
if default_address is not None and input_address... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def worker_allocator(self, async_loop, to_do, **kwargs):
""" Handler starting the asyncio part. """ |
d = kwargs
threading.Thread(
target=self._asyncio_thread, args=(async_loop, to_do, d)
).start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _clean_text(text):
""" Clean up a multiple-line, potentially multiple-paragraph text string. This is used to extract the first paragraph of a string and elim... |
desc = []
for line in (text or '').strip().split('\n'):
# Clean up the line...
line = line.strip()
# We only want the first paragraph
if not line:
break
desc.append(line)
return ' '.join(desc) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prog(text):
""" Decorator used to specify the program name for the console script help message. :param text: The text to use for the program name. """ |
def decorator(func):
adaptor = ScriptAdaptor._get_adaptor(func)
adaptor.prog = text
return func
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def usage(text):
""" Decorator used to specify a usage string for the console script help message. :param text: The text to use for the usage. """ |
def decorator(func):
adaptor = ScriptAdaptor._get_adaptor(func)
adaptor.usage = text
return func
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def description(text):
""" Decorator used to specify a short description of the console script. This can be used to override the default, which is derived from t... |
def decorator(func):
adaptor = ScriptAdaptor._get_adaptor(func)
adaptor.description = text
return func
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def epilog(text):
""" Decorator used to specify an epilog for the console script help message. :param text: The text to use for the epilog. """ |
def decorator(func):
adaptor = ScriptAdaptor._get_adaptor(func)
adaptor.epilog = text
return func
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def formatter_class(klass):
""" Decorator used to specify the formatter class for the console script. :param klass: The formatter class to use. """ |
def decorator(func):
adaptor = ScriptAdaptor._get_adaptor(func)
adaptor.formatter_class = klass
return func
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_subcommands(group):
""" Decorator used to load subcommands from a given ``pkg_resources`` entrypoint group. Each function must be appropriately decorate... |
def decorator(func):
adaptor = ScriptAdaptor._get_adaptor(func)
adaptor._add_extensions(group)
return func
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _collapse_subtree(self, name, recursive=True):
"""Collapse a sub-tree.""" |
oname = name
children = self._db[name]["children"]
data = self._db[name]["data"]
del_list = []
while (len(children) == 1) and (not data):
del_list.append(name)
name = children[0]
children = self._db[name]["children"]
data = self._d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_intermediate_nodes(self, name):
"""Create intermediate nodes if hierarchy does not exist.""" |
hierarchy = self._split_node_name(name, self.root_name)
node_tree = [
self.root_name
+ self._node_separator
+ self._node_separator.join(hierarchy[: num + 1])
for num in range(len(hierarchy))
]
iobj = [
(child[: child.rfind(self... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_node(self, name, parent, children, data):
"""Create new tree node.""" |
self._db[name] = {"parent": parent, "children": children, "data": data} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _delete_subtree(self, nodes):
""" Delete subtree private method. No argument validation and usage of getter/setter private methods is used for speed """ |
nodes = nodes if isinstance(nodes, list) else [nodes]
iobj = [
(self._db[node]["parent"], node)
for node in nodes
if self._node_name_in_tree(node)
]
for parent, node in iobj:
# Delete link to parent (if not root node)
del_list ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_common_prefix(self, node1, node2):
"""Find common prefix between two nodes.""" |
tokens1 = [item.strip() for item in node1.split(self.node_separator)]
tokens2 = [item.strip() for item in node2.split(self.node_separator)]
ret = []
for token1, token2 in zip(tokens1, tokens2):
if token1 == token2:
ret.append(token1)
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _rename_node(self, name, new_name):
""" Rename node private method. No argument validation and usage of getter/setter private methods is used for speed """ |
# Update parent
if not self.is_root(name):
parent = self._db[name]["parent"]
self._db[parent]["children"].remove(name)
self._db[parent]["children"] = sorted(
self._db[parent]["children"] + [new_name]
)
# Update children
iob... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _search_tree(self, name):
"""Search_tree for nodes that contain a specific hierarchy name.""" |
tpl1 = "{sep}{name}{sep}".format(sep=self._node_separator, name=name)
tpl2 = "{sep}{name}".format(sep=self._node_separator, name=name)
tpl3 = "{name}{sep}".format(sep=self._node_separator, name=name)
return sorted(
[
node
for node in self._db
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_node_name(self, var_value):
"""Validate NodeName pseudo-type.""" |
# pylint: disable=R0201
var_values = var_value if isinstance(var_value, list) else [var_value]
for item in var_values:
if (not isinstance(item, str)) or (
isinstance(item, str)
and (
(" " in item)
or any(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_nodes_with_data(self, names):
"""Validate NodeWithData pseudo-type.""" |
names = names if isinstance(names, list) else [names]
if not names:
raise RuntimeError("Argument `nodes` is not valid")
for ndict in names:
if (not isinstance(ndict, dict)) or (
isinstance(ndict, dict) and (set(ndict.keys()) != set(["name", "data"]))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_nodes(self, nodes):
# noqa: D302 r""" Add nodes to tree. :param nodes: Node(s) to add with associated data. If there are several list items in the argume... |
self._validate_nodes_with_data(nodes)
nodes = nodes if isinstance(nodes, list) else [nodes]
# Create root node (if needed)
if not self.root_name:
self._set_root_name(nodes[0]["name"].split(self._node_separator)[0].strip())
self._root_hierarchy_length = len(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def collapse_subtree(self, name, recursive=True):
# noqa: D302 r""" Collapse a sub-tree. Nodes that have a single child and no data are combined with their child... |
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
if not isinstance(recursive, bool):
raise RuntimeError("Argument `recursive` is not valid")
self._node_in_tree(name)
self._collapse_subtree(name, recursive) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy_subtree(self, source_node, dest_node):
# noqa: D302 r""" Copy a sub-tree from one sub-node to another. Data is added if some nodes of the source sub-tre... |
if self._validate_node_name(source_node):
raise RuntimeError("Argument `source_node` is not valid")
if self._validate_node_name(dest_node):
raise RuntimeError("Argument `dest_node` is not valid")
if source_node not in self._db:
raise RuntimeError("Node {0} no... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete_prefix(self, name):
# noqa: D302 r""" Delete hierarchy levels from all nodes in the tree. :param nodes: Prefix to delete :type nodes: :ref:`NodeName` ... |
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
if (not self.root_name.startswith(name)) or (self.root_name == name):
raise RuntimeError("Argument `name` is not a valid prefix")
self._delete_prefix(name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten_subtree(self, name):
# noqa: D302 r""" Flatten sub-tree. Nodes that have children and no data are merged with each child :param name: Ending hierarch... |
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
self._node_in_tree(name)
parent = self._db[name]["parent"]
if (parent) and (not self._db[name]["data"]):
children = self._db[name]["children"]
for child in children:... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_children(self, name):
r""" Get the children node names of a node. :param name: Parent node name :type name: :ref:`NodeName` :rtype: list of :ref:`NodeNam... |
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
self._node_in_tree(name)
return sorted(self._db[name]["children"]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_data(self, name):
r""" Get the data associated with a node. :param name: Node name :type name: :ref:`NodeName` :rtype: any type or list of objects of any... |
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
self._node_in_tree(name)
return self._db[name]["data"] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_node(self, name):
r""" Get a tree node structure. The structure is a dictionary with the following keys: * **parent** (*NodeName*) Parent node name, :cod... |
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
self._node_in_tree(name)
return self._db[name] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_node_children(self, name):
r""" Get the list of children structures of a node. See :py:meth:`ptrie.Trie.get_node` for details about the structure :param ... |
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
self._node_in_tree(name)
return [self._db[child] for child in self._db[name]["children"]] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_node_parent(self, name):
r""" Get the parent structure of a node. See :py:meth:`ptrie.Trie.get_node` for details about the structure :param name: Child n... |
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
self._node_in_tree(name)
return self._db[self._db[name]["parent"]] if not self.is_root(name) else {} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_subtree(self, name):
# noqa: D302 r""" Get all node names in a sub-tree. :param name: Sub-tree root node name :type name: :ref:`NodeName` :rtype: list of... |
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
self._node_in_tree(name)
return self._get_subtree(name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def in_tree(self, name):
r""" Test if a node is in the tree. :param name: Node name to search for :type name: :ref:`NodeName` :rtype: boolean :raises: RuntimeErr... |
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
return name in self._db |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_root(self, name):
# noqa: D302 r""" Make a sub-node the root node of the tree. All nodes not belonging to the sub-tree are deleted :param name: New root... |
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
if (name != self.root_name) and (self._node_in_tree(name)):
for key in [node for node in self.nodes if node.find(name) != 0]:
del self._db[key]
self._db[name]["paren... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rename_node(self, name, new_name):
# noqa: D302 r""" Rename a tree node. It is typical to have a root node name with more than one hierarchy level after usin... |
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
if self._validate_node_name(new_name):
raise RuntimeError("Argument `new_name` is not valid")
self._node_in_tree(name)
if self.in_tree(new_name) and (name != self.root_name):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def search_tree(self, name):
# noqa: D302 r""" Search tree for all nodes with a specific name. :param name: Node name to search for :type name: :ref:`NodeName` :... |
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
return self._search_tree(name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_in_bids(filename, pattern=None, generator=False, upwards=False, wildcard=True, **kwargs):
"""Find nearest file matching some criteria. Parameters filena... |
if upwards and generator:
raise ValueError('You cannot search upwards and have a generator')
if pattern is None:
pattern = _generate_pattern(wildcard, kwargs)
lg.debug(f'Searching {pattern} in {filename}')
if upwards and filename == find_root(filename):
raise FileNotFoundErro... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_xyz(self, list_of_names=None):
"""Get xyz coordinates for these electrodes Parameters list_of_names : list of str list of electrode names to use Returns ... |
if list_of_names is not None:
filter_lambda = lambda x: x['name'] in list_of_names
else:
filter_lambda = None
return self.electrodes.get(filter_lambda=filter_lambda,
map_lambda=lambda e: (float(e['x']),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bootstrap(v):
""" Constructs Monte Carlo simulated data set using the Bootstrap algorithm. Usage: where x is either an array or a list of arrays. If it is a... |
if type(v)==list:
vboot=[] # list of boostrapped arrays
n=v[0].size
iran=scipy.random.randint(0,n,n) # Array of random indexes
for x in v: vboot.append(x[iran])
else: # if v is an array, not a list of arrays
n=v.size
iran=scipy.random.randint(0,n,n) # Array of random indexes
vboot=v[iran]
return vbo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bcesboot_backup(y1,y1err,y2,y2err,cerr,nsim=10000):
""" Does the BCES with bootstrapping. Usage: :param x,y: data :param xerr,yerr: measurement errors affe... |
import fish
# Progress bar initialization
peixe = fish.ProgressFish(total=nsim)
print "Bootstrapping progress:"
"""
My convention for storing the results of the bces code below as
matrixes for processing later are as follow:
simulation\method y|x x|y bisector orthogonal
sim0 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def median(lst):
""" Calcuates the median value in a @lst """ |
#: http://stackoverflow.com/a/24101534
sortedLst = sorted(lst)
lstLen = len(lst)
index = (lstLen - 1) // 2
if (lstLen % 2):
return sortedLst[index]
else:
return (sortedLst[index] + sortedLst[index + 1])/2.0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_whitespace(s):
""" Unsafely attempts to remove HTML whitespace. This is not an HTML parser which is why its considered 'unsafe', but it should work fo... |
ignores = {}
for ignore in html_ignore_whitespace_re.finditer(s):
name = "{}{}{}".format(r"{}", uuid.uuid4(), r"{}")
ignores[name] = ignore.group()
s = s.replace(ignore.group(), name)
s = whitespace_re(r' ', s).strip()
for name, val in ignores.items():
s = s.replace(name... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hashtag_links(uri, s):
""" Turns hashtag-like strings into HTML links @uri: /uri/ root for the hashtag-like @s: the #str string you're looking for |#|hashtag... |
for tag, after in hashtag_re.findall(s):
_uri = '/' + (uri or "").lstrip("/") + quote(tag)
link = '<a href="{}">#{}</a>{}'.format(_uri.lower(), tag, after)
s = s.replace('#' + tag, link)
return s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload(target):
# type: (str) -> None """ Upload the release to a pypi server. TODO: Make sure the git directory is clean before allowing a release. Args: ta... |
log.info("Uploading to pypi server <33>{}".format(target))
with conf.within_proj_dir():
shell.run('python setup.py sdist register -r "{}"'.format(target))
shell.run('python setup.py sdist upload -r "{}"'.format(target)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_text(self, text):
"""Sets the text attribute of the payload :param text: (str) Text of the message :return: None """ |
log = logging.getLogger(self.cls_logger + '.set_text')
if not isinstance(text, basestring):
msg = 'text arg must be a string'
log.error(msg)
raise ValueError(msg)
self.payload['text'] = text
log.debug('Set message text to: {t}'.format(t=text)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_icon(self, icon_url):
"""Sets the icon_url for the message :param icon_url: (str) Icon URL :return: None """ |
log = logging.getLogger(self.cls_logger + '.set_icon')
if not isinstance(icon_url, basestring):
msg = 'icon_url arg must be a string'
log.error(msg)
raise ValueError(msg)
self.payload['icon_url'] = icon_url
log.debug('Set Icon URL to: {u}'.format(u=ic... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_attachment(self, attachment):
"""Adds an attachment to the SlackMessage payload This public method adds a slack message to the attachment list. :param at... |
log = logging.getLogger(self.cls_logger + '.add_attachment')
if not isinstance(attachment, SlackAttachment):
msg = 'attachment must be of type: SlackAttachment'
log.error(msg)
raise ValueError(msg)
self.attachments.append(attachment.attachment)
log.de... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send(self):
"""Sends the Slack message This public method sends the Slack message along with any attachments, then clears the attachments array. :return: Non... |
log = logging.getLogger(self.cls_logger + '.send')
if self.attachments:
self.payload['attachments'] = self.attachments
# Encode payload in JSON
log.debug('Using payload: %s', self.payload)
try:
json_payload = json.JSONEncoder().encode(self.payload)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def send_cons3rt_agent_logs(self):
"""Sends a Slack message with an attachment for each cons3rt agent log :return: """ |
log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs')
log.debug('Searching for log files in directory: {d}'.format(d=self.dep.cons3rt_agent_log_dir))
for item in os.listdir(self.dep.cons3rt_agent_log_dir):
item_path = os.path.join(self.dep.cons3rt_agent_log_dir, ite... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.