output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Converts an integer to a sequence of strings and reverse. | Given the following Python 3 function, write the documentation
def strkey(val, chaffify=1, keyspace=string.ascii_letters + string.digits):
chaffify = chaffify or 1
keylen = len(keyspace)
try:
# INT TO STRING
if val < 0:
raise ValueError("Input value must be greater than -1.")
... | As a python code expert, you are capable of creating scripts from specifications. |
Calculates the number of characters in a keyspace given the number of bits of entropy given the keyspace. | Explain what the following Python 3 code does
def chars_in(bits, keyspace):
keyspace = len(keyspace)
if keyspace < 2:
raise ValueError("Keyspace size must be >1")
bits_per_cycle = 512
if bits > bits_per_cycle:
chars = 0
bits_processed = 0
cycles = ceil(bits / bits_per_cyc... | As a Python code analyst, you investigate and solve complex coding mysteries |
Calculates the number of bits of entropy in a given length of a given keyspace. | Can you tell what is the following Python 3 function doing
def bits_in(length, keyspace):
keyspace = len(keyspace)
length_per_cycle = 64
if length > length_per_cycle:
bits = 0
length_processed = 0
cycles = ceil(length / length_per_cycle)
for _ in range(int(cycles)):
... | As a Python code composer, you craft elegant and concise scripts. |
def iter_random_chars(bits,
keyspace=string.ascii_letters + string.digits + '#/.',
rng=None):
""" Yields a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entr... | Write a Python 3 function that can
yield a cryptographically secure random key of desired bits of entropy of the keyspace. | You are a Python code analyst, evaluating scripts for potential improvements. |
def randkey(bits, keyspace=string.ascii_letters + string.digits + '#/.',
rng=None):
""" Returns a cryptographically secure random key of desired @bits of
entropy within @keyspace using :class:random.SystemRandom
@bits: (#int) minimum bits of entropy
@keyspace: (#str) or iterable... | Implement a function in Python 3 to
return a cryptographically secure random key of desired bits of entropy within a keyspace. | As a Python code composer, you craft elegant and concise scripts. |
Returns a cryptographically secure random string of desired size within a keyspace. | Can you generate a brief explanation for the following Python 3 code
def randstr(size, keyspace=string.ascii_letters + string.digits, rng=None):
rng = rng or random.SystemRandom()
return "".join(rng.choice(keyspace) for char in range(int(ceil(size)))) | You are a Python code generator, capable of creating scripts from specifications. |
load a pip requirements file | Can you generate the documentation for the following Python 3 function
def parse_requirements(filename):
lineiter = (line.strip() for line in open(filename))
return (line for line in lineiter if line and not line.startswith("#")) | As a Python code composer, you craft elegant and concise scripts. |
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... | Create a Python 3 function to
round a floating point number x to n significant figures | You are a Python code analyst, evaluating scripts for potential improvements. |
Find ex rounded to n sig - figs and make the floating point x
match the number of decimals. | Here you have a function in Python 3, explain what it does
def round_sig_error(x, ex, n, paren=False):
'''Find ex rounded to n sig-figs and make the floating point x
match the number of decimals. If [paren], the string is
returned as quantity(error) format'''
stex = round_sig(ex,n)
if stex.find('.'... | You are a Python code analyst, evaluating scripts for potential improvements. |
def format_table(cols, errors, n, labels=None, headers=None, latex=False):
'''Format a table such that the errors have n significant
figures. [cols] and [errors] should be a list of 1D arrays
that correspond to data and errors in columns. [n] is the number of
significant figures to keep in the errors.... | Create a Python 3 function to
format a table such that the errors have n significant figures. | You are a Python code architect, reviewing and designing scalable and efficient code |
def round_sig_error2(x, ex1, ex2, n):
'''Find min(ex1,ex2) rounded to n sig-figs and make the floating point x
and max(ex,ex2) match the number of decimals.'''
minerr = min(ex1,ex2)
minstex = round_sig(minerr,n)
if minstex.find('.') < 0:
extra_zeros = len(minstex) - n
sigfigs = len(s... | Can you write a function in Python 3 where it
finds the min max and min error and make the floating point x and max ( ex ex1 ex2 match the number of decimals. | You are a Python code generator, capable of creating scripts from specifications. |
def send_to_azure_multi_threads(instance, data, nb_threads=4, replace=True, types=None, primary_key=(),
sub_commit=False):
"""
data = {
"table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist,
"columns_name" : [first_colum... | Write a Python 3 function that can
send data to all available Azure threads. | You are a Python code architect, reviewing and designing scalable and efficient code |
def send_to_azure(instance, data, thread_number, sub_commit, table_info, nb_threads):
"""
data = {
"table_name" : 'name_of_the_azure_schema' + '.' + 'name_of_the_azure_table' #Must already exist,
"columns_name" : [first_column_name,second_column_name,...,last_column_name],
"rows" : [[... | Can you create a Python 3 function that
sends data to Azure. | As a python code expert, you are capable of creating scripts from specifications. |
Adds the items to the invoice | Given the following Python 3 function, write the documentation
def create(self, items=[], taxes=[], custom_data=[]):
self.add_items(items)
self.add_taxes(taxes)
self.add_custom_data(custom_data)
return self._process('checkout-invoice/create', self._prepare_data) | As a python code expert, you are capable of creating scripts from specifications. |
Returns the status of the invoice | How would you explain what the following Python 3 function does
def confirm(self, token=None):
_token = token if token else self._response.get("token")
return self._process('checkout-invoice/confirm/' + str(_token)) | As a Python code analyst, you investigate and solve complex coding mysteries |
Appends the data to the taxes key in the request object
| Can you tell what is the following Python 3 function doing
def add_taxes(self, taxes):
# 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.taxe... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Adds an item to the list of items in the current transaction | Explain what the following Python 3 code does
def add_item(self, item):
_idx = len(self.items)
self.items.update({"item_" + str(_idx + 1): item}) | You are a Python code analyst, evaluating scripts for potential improvements. |
Formats the data in the current transaction for processing | How would you explain what the following Python 3 function does
def _prepare_data(self):
total_amount = self.total_amount or self.calculate_total_amt()
self._data = {
"invoice": {
"items": self.__encode_items(self.items),
"taxes": self.taxes,
"... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the total amount of items in the current invoice | Explain what the following Python 3 code does
def calculate_total_amt(self, items={}):
_items = items.items() or self.items.items()
return sum(float(x[1].total_price) for x in _items) | As a Python code composer, you craft elegant and concise scripts. |
Encodes the InvoiceItems into a JSON serializable format | Can you generate a brief explanation for the following Python 3 code
def __encode_items(self, items):
xs = [item._asdict() for (_key, item) in items.items()]
return list(map(lambda x: dict(zip(x.keys(), x.values())), xs)) | As a Python code composer, you craft elegant and concise scripts. |
Sets the deployment home for the cons3rt agent run directory. | Given the following Python 3 function, write the documentation
def set_deployment_home(self):
log = logging.getLogger(self.cls_logger + '.set_deployment_home')
try:
self.deployment_home = os.environ['DEPLOYMENT_HOME']
except KeyError:
log.warn('DEPLOYMENT_HOME environment... | As a python code expert, you are capable of creating scripts from specifications. |
def read_deployment_properties(self):
"""Reads the deployment properties file
This method reads the deployment properties file into the
"properties" dictionary object.
:return: None
:raises: DeploymentError
"""
log = logging.getLogger(self.cls_logger + '.read_de... | Write a Python 3 script to
read the deployment properties file into the properties dictionary. | As a python code expert, you are capable of creating scripts from specifications. |
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. If either the property
is not found or if the passed string matches more than one
property, this function will return ... | Write a Python 3 script for
getting the name of a specific property This public method is passed a regular expression and returns the matching property name. If either the property is not found or if the passed string matches more than one property, this function will return None. :param regex: Regular expression to se... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_matching_property_names(self, regex):
"""Returns a list of property names matching the provided
regular expression
:param regex: Regular expression to search on
:return: (list) of property names matching the regex
"""
log = logging.getLogger(self.cls_logger + '.g... | Write a Python 3 script to
return a list of property names matching the provided regular expression | As a Python code composer, you craft elegant and concise scripts. |
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 returns the value of that property. If the property is not
found, None will be returned.
:param property_name (str) The na... | Implement a Python 3 function for
returning the value associated to the passed property_name or None if the property is not found. | You are a Python code analyst, evaluating scripts for potential improvements. |
Set the cons3rt_role_name member for this system | How would you explain what the following Python 3 function does
def set_cons3rt_role_name(self):
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 ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Determines the cons3rt_role_name member for this Linux system and sets the cons3rt_role_name member for this Linux system. | Can you tell what is the following Python 3 function doing
def determine_cons3rt_role_name_linux(self):
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...')
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 returns either the string value if
set or None if it is not set.
:return: None
"""
log = logging.getLogge... | Can you implement a function in Python 3 that
returns the ASSET_DIR environment variable for the the current asset install. | As a Python code composer, you craft elegant and concise scripts. |
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 list of deployment properties containing "isMaster" because
there is exactly one per scenario host, containing the role name
... | Implement a Python 3 function for
populating the list of scenario role names in this deployment and extracts the master role name and the scenario master role name. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Populates a list of network info for each scenario host from the deployment properties
| Can you generate the documentation for the following Python 3 function
def set_scenario_network_info(self):
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_hos... | As a python code expert, you are capable of creating scripts from specifications. |
Sets the deployment name from deployment properties
| Here you have a function in Python 3, explain what it does
def set_deployment_name(self):
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)) | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Can you create a Python 3 function that
sets the deployment ID from deployment properties | You are a Python code analyst, evaluating scripts for potential improvements. |
Sets the deployment run name from deployment properties | Explain what the following Python 3 code does
def set_deployment_run_name(self):
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_na... | As a Python code analyst, you investigate and solve complex coding mysteries |
Sets the deployment run ID from deployment properties | Make a summary of the following Python 3 code
def set_deployment_run_id(self):
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 i... | As a Python code composer, you craft elegant and concise scripts. |
Sets the virtualization realm type from deployment properties
| Explain what the following Python 3 code does
def set_virtualization_realm_type(self):
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 : {... | As a Python code composer, you craft elegant and concise scripts. |
Updates the hosts file depending on the OS and the IP address. | Can you generate a brief explanation for the following Python 3 code
def update_hosts_file(self, ip, entry):
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':
... | You are a Python code generator, capable of creating scripts from specifications. |
Adds hosts file entries for each system in the scenario_hosts file for the specified network_name and domain_name. | Make a summary of the following Python 3 code
def set_scenario_hosts_file(self, network_name='user-net', domain_name=None):
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))... | As a Python code composer, you craft elegant and concise scripts. |
Adds an entry to the hosts file for a scenario host given a role name and network name. | Given the following Python 3 function, write the documentation
def set_hosts_file_entry_for_role(self, role_name, network_name='user-net', fqdn=None, domain_name=None):
log = logging.getLogger(self.cls_logger + '.set_hosts_file_entry_for_role')
# Determine the host file entry portion
if fqdn:
... | As a python code expert, you are capable of creating scripts from specifications. |
def get_ip_on_network(self, network_name):
"""Given a network name, returns the IP address
:param network_name: (str) Name of the network to search for
:return: (str) IP address on the specified network or None
"""
return self.get_scenario_host_ip_on_network(
scenari... | Can you create a Python 3 function that
gives a network name returns the IP address on the specified network or None if no IP address is found. | As a Python code composer, you craft elegant and concise scripts. |
Given a network name returns the IP address on the specified network or None if no matching IP is found. | Can you generate a brief explanation for the following Python 3 code
def get_scenario_host_ip_on_network(self, scenario_role_name, network_name):
log = logging.getLogger(self.cls_logger + '.get_scenario_host_ip_on_network')
# Determine the network info for this host based on role name
cons3rt_n... | As a python code expert, you are capable of creating scripts from specifications. |
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: (str) Name of the network to search for
:return: (str) name of the network interface device or None
"""
log ... | Write a Python 3 function for
giving a cons3rt network name return the network interface name on this Linux system | As a python code expert, you are capable of creating scripts from specifications. |
Returns authenticated User.
:param request: HttpRequest
:param exceptions: Raise (NotAuthenticated) exception. Default is True.
:return: User | Explain what the following Python 3 code does
def require_auth(request: Request, exceptions: bool=True) -> User:
if not request.user or not request.user.is_authenticated:
if exceptions:
raise NotAuthenticated()
return None
return request.user | You are a Python code architect, reviewing and designing scalable and efficient code |
Insert sane defaults rules into the raw and filter tables. | Here you have a function in Python 3, explain what it does
def insertSaneDefaults(self):
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.ins... | You are a Python code architect, reviewing and designing scalable and efficient code |
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 | Create a Python 3 function to
add a DROP policy at the end of the rules. | You are a Python code analyst, evaluating scripts for potential improvements. |
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(... | Implement a function in Python 3 to
create a rules file in iptables - restore format | You are a Python code architect, reviewing and designing scalable and efficient code |
def template(self):
""" Create a rules file in ipset --restore format """
s = Template(self._IPSET_TEMPLATE)
return s.substitute(sets='\n'.join(self.sets),
date=datetime.today()) | Write a Python 3 function that can
return a template that creates a rules file in ipset -- restore format | You are a Python code analyst, evaluating scripts for potential improvements. |
search for a user in LDAP and return its DN and uid | Can you generate the documentation for the following Python 3 function
def getUserByNumber(self, base, uidNumber):
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] | You are a Python code architect, reviewing and designing scalable and efficient code |
def getACLs(self, base, searchstr):
"""
Query LDAP to obtain the network ACLs of a given user,
parse the ACLs, and return the results in a dict of the form
acls[group][cidr] = description
"""
acls = dict()
res = self.query(base, searchstr, ['cn', 'ipHostNumber'])
for dn,attr in res:
cn = attr['cn'... | How would you code a function in Python 3 to
query LDAP to obtain the network ACLs of a given user and return the results in a dict of the form cn = description desc = description cn = cn | You are a Python code analyst, evaluating scripts for potential improvements. |
Splits a comma - separated number sequence into a list of floats. | Here you have a function in Python 3, explain what it does
def splitValues(textStr):
vals = textStr.split(",")
nums = []
for v in vals:
nums.append(float(v))
return nums | As a Python code analyst, you investigate and solve complex coding mysteries |
def expandParameters(*args):
"""Expands parameters (presented as tuples of lists and symbolic names)
so that each is returned in a new list where each contains the same number
of values.
Each `arg` is a tuple containing two items: a list of values and a
symbolic name.
"""
count = 1
for ... | Can you create a Python 3 function that
expands parameters into a new list where each element is a tuple containing two items of lists and symbolic names. | You are a Python code architect, reviewing and designing scalable and efficient code |
def expandValues(inputs, count, name):
"""Returns the input list with the length of `count`. If the
list is [1] and the count is 3. [1,1,1] is returned. The list
must be the count length or 1. Normally called from `expandParameters()`
where `name` is the symbolic name of the input.
"""
if len(in... | Can you implement a function in Python 3 that
returns the input list with the length of count. | You are a Python code generator, capable of creating scripts from specifications. |
def get_geo_ip(ip: str, exceptions: bool=False, timeout: int=10) -> dict:
"""
Returns geo IP info or empty dict if geoip query fails at http://ipstack.com.
requires settings.IPSTACK_TOKEN set as valid access token to the API.
Example replies:
{'country_name': 'United States', 'country_code': 'US', ... | Write a Python 3 script for
getting geo IP info from ipstack. com. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_ip_info(ip: str, exceptions: bool=False, timeout: int=10) -> tuple:
"""
Returns (ip, country_code, host) tuple of the IP address.
:param ip: IP address
:param exceptions: Raise Exception or not
:param timeout: Timeout in seconds. Note that timeout only affects geo IP part, not getting host n... | Create a Python 3 function for
getting the IP information from the given IP address. | You are a Python code analyst, evaluating scripts for potential improvements. |
Determines if this system is running on AWS | Here you have a function in Python 3, explain what it does
def is_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
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Gets the instance ID of this EC2 instance | Can you generate the documentation for the following Python 3 function
def get_instance_id():
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 = metad... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the VPC ID for this EC2 instance based on the MAC address of the primary interface. | Can you tell what is the following Python 3 function doing
def get_vpc_id_from_mac_address():
log = logging.getLogger(mod_logger + '.get_vpc_id')
# Exit if not running on AWS
if not is_aws():
log.info('This machine is not running in AWS, exiting...')
return
# Get the primary interface ... | You are a Python code generator, capable of creating scripts from specifications. |
Returns the AWS Availability Zone ID for this system | Can you generate the documentation for the following Python 3 function
def get_availability_zone():
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
availabilit... | You are a Python code architect, reviewing and designing scalable and efficient code |
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 ... | Write a Python 3 function for
getting the AWS Region ID for this system | As a python code expert, you are capable of creating scripts from specifications. |
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 for the eth0 interface
:raises: AWSMetaDataError
"""
log = logging.getLogger(mod_logger + '.get_primary_mac_address')
log.debug('... | Create a Python 3 function for
determining the MAC address to use for querying the AWSMetaData service for network related queries | As a Python code analyst, you investigate and solve complex coding mysteries |
Set the new value for the attribute separator. | Can you generate the documentation for the following Python 3 function
def attr_sep(self, new_sep: str) -> None:
self._attr_sep = new_sep
self._filters_tree = self._generate_filters_tree() | As a Python code analyst, you investigate and solve complex coding mysteries |
def url_equals(a: str, b: str) -> bool:
"""
Compares two URLs/paths and returns True if they point to same URI.
For example, querystring parameters can be different order but URLs are still equal.
:param a: URL/path
:param b: URL/path
:return: True if URLs/paths are equal
"""
from urllib... | Write a Python 3 script to
compare two URLs and returns True if they point to same URI. | You are a Python code generator, capable of creating scripts from specifications. |
Modifies existing URL by setting or overriding specified query string parameters. | Make a summary of the following Python 3 code
def url_mod(url: str, new_params: dict) -> str:
from urllib.parse import urlparse, parse_qsl, urlunparse, urlencode
res = urlparse(url)
query_params = dict(parse_qsl(res.query))
for k, v in new_params.items():
if v is None:
query_params[s... | As a Python code composer, you craft elegant and concise scripts. |
Parses hostname from URL. | Can you generate a brief explanation for the following Python 3 code
def url_host(url: str) -> str:
from urllib.parse import urlparse
res = urlparse(url)
return res.netloc.split(':')[0] if res.netloc else '' | You are a Python code architect, reviewing and designing scalable and efficient code |
This gives us a dictionary of nominal values from a dictionary of uncertainties | Can you generate the documentation for the following Python 3 function
def ufloatDict_nominal(self, ufloat_dict):
'This gives us a dictionary of nominal values from a dictionary of uncertainties'
return OrderedDict(izip(ufloat_dict.keys(), map(lambda x: x.nominal_value, ufloat_dict.values()))) | As a Python code composer, you craft elegant and concise scripts. |
Build the documentation for the project. | Can you generate the documentation for the following Python 3 function
def docs(recreate, gen_index, run_doctests):
# type: (bool, bool, bool) -> None
""" Build the documentation for the project.
Args:
recreate (bool):
If set to **True**, the build and output directories will be cleared... | You are a Python code architect, reviewing and designing scalable and efficient code |
def gen_ref_docs(gen_index=False):
# type: (int, bool) -> None
""" Generate reference documentation for the project.
This will use **sphinx-refdoc** to generate the source .rst files for the
reference documentation.
Args:
gen_index (bool):
Set it to **True** if you want to gene... | How would you implement a function in Python 3 that
generates reference documentation for the project. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate the ID - NAME map for a given CloudGenix SDK. | Explain what the following Python 3 code does
def generate_id_name_map(sdk, reverse=False):
global_id_name_dict = {}
global_name_id_dict = {}
# system struct
system_list = []
# Global lookup dictionary for sub items
if_id_to_name = {}
global_swi_id = {}
global_ln_id = {}
swi_to_w... | As a Python code analyst, you investigate and solve complex coding mysteries |
Reverse sorts a dictionary by a given key. | Here you have a function in Python 3, explain what it does
def revrank_dict(dict, key=lambda t: t[1], as_tuple=False):
sorted_list = sorted(dict.items(), key=key, reverse=True)
return OrderedDict(sorted_list) if not as_tuple else tuple(sorted_list) | As a Python code analyst, you investigate and solve complex coding mysteries |
Sort a dictionary by a given key optionally returning it as a tuple. | How would you explain what the following Python 3 function does
def rank_dict(dict, key=lambda t: t[1], as_tuple=False):
sorted_list = sorted(dict.items(), key=key)
return OrderedDict(sorted_list) if not as_tuple else tuple(sorted_list) | You are a Python code generator, capable of creating scripts from specifications. |
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 = {'foo': {'bar': {'baz': True}}}
getitem_in(obj, 'foo.bar.baz')
..
|True|
"""
for p... | Write a Python 3 script for
finding a key in a dictionary via a period - delimited string name. | As a Python code analyst, you investigate and solve complex coding mysteries |
Start a new release. | Here you have a function in Python 3, explain what it does
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/<version>` with one new commit (the version bump).
**Example Config**::
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 that's uploaded as the release
(to pypi for example).
**Example Config**::
\b
version_file: 'src/mypkg/__init__.py'
... | Write a Python 3 script for
tagging the current commit with as the current version release. | As a Python code composer, you craft elegant and concise scripts. |
Takes two strings and returns a full name of the specified length. | Can you tell what is the following Python 3 function doing
def format_full_name(first_name: str, last_name: str, max_length: int = 20):
# dont allow commas in limited names
first_name = first_name.replace(',', ' ')
last_name = last_name.replace(',', ' ')
# accept short full names as is
original_ful... | You are a Python code architect, reviewing and designing scalable and efficient code |
Formats timedelta to readable format e. g. 1h30min. | Here you have a function in Python 3, explain what it does
def format_timedelta(dt: timedelta) -> str:
seconds = int(dt.total_seconds())
days, remainder = divmod(seconds, 86400)
hours, remainder = divmod(remainder, 3600)
minutes, seconds = divmod(remainder, 60)
s = ""
if days > 0:
s += s... | You are a Python code analyst, evaluating scripts for potential improvements. |
Formats XML document as human - readable plain text. | Can you tell what is the following Python 3 function doing
def format_xml(xml_str: str, exceptions: bool=False):
try:
import xml.dom.minidom
return xml.dom.minidom.parseString(xml_str).toprettyxml()
except Exception:
if exceptions:
raise
return xml_str | You are a Python code analyst, evaluating scripts for potential improvements. |
def send_mail(form, from_name):
"""
Sends a mail using the configured mail server for Pulsar. See mailgun documentation at
https://documentation.mailgun.com/en/latest/user_manual.html#sending-via-api for specifics.
Args:
form: `dict`. The mail form fields, i.e. 'to', 'from', ...
Returns:... | Can you implement a function in Python 3 that
sends a mail using the configured mailgun API. | You are a Python code analyst, evaluating scripts for potential improvements. |
Determines whether the biosample is part of a ChipseqExperiment or SingleCellSorting experiment and returns the associated model instance. | Can you tell what is the following Python 3 function doing
def get_exp_of_biosample(biosample_rec):
chip_exp_id = biosample_rec.chipseq_experiment_id
ssc_id = biosample_rec.sorting_biosample_single_cell_sorting_id
if chip_exp_id:
return {"type": "chipseq_experiment", "record": models.ChipseqExperime... | As a python code expert, you are capable of creating scripts from specifications. |
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 eliminate line breaks and indentation. Lines will be joined
together by a single space.
:param text: The text string to clean up. It is... | Can you create a Python 3 function that
cleans up a multiple - line potentially multiple - paragraph text string. | As a Python code analyst, you investigate and solve complex coding mysteries |
Decorator used to specify a usage string for the console script
help message. | Can you generate the documentation for the following Python 3 function
def usage(text):
def decorator(func):
adaptor = ScriptAdaptor._get_adaptor(func)
adaptor.usage = text
return func
return decorator | You are a Python code generator, capable of creating scripts from specifications. |
Decorator used to specify an epilog for the console script help
message. | Can you generate the documentation for the following Python 3 function
def epilog(text):
def decorator(func):
adaptor = ScriptAdaptor._get_adaptor(func)
adaptor.epilog = text
return func
return decorator | As a Python code composer, you craft elegant and concise scripts. |
Decorator used to specify the formatter class for the console
script. | Here you have a function in Python 3, explain what it does
def formatter_class(klass):
def decorator(func):
adaptor = ScriptAdaptor._get_adaptor(func)
adaptor.formatter_class = klass
return func
return decorator | You are a Python code architect, reviewing and designing scalable and efficient code |
Decorator used to specify an argument group. | How would you explain what the following Python 3 function does
def argument_group(group, **kwargs):
def decorator(func):
adaptor = ScriptAdaptor._get_adaptor(func)
adaptor._add_group(group, 'group', kwargs)
return func
return decorator | As a Python code composer, you craft elegant and concise scripts. |
Collapse a sub - tree. | Explain what the following Python 3 code does
def _collapse_subtree(self, name, recursive=True):
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)
... | As a python code expert, you are capable of creating scripts from specifications. |
Create intermediate nodes if hierarchy does not exist. | Can you generate the documentation for the following Python 3 function
def _create_intermediate_nodes(self, name):
hierarchy = self._split_node_name(name, self.root_name)
node_tree = [
self.root_name
+ self._node_separator
+ self._node_separator.join(hierarchy[: num +... | You are a Python code generator, capable of creating scripts from specifications. |
def _create_node(self, name, parent, children, data):
"""Create new tree node."""
self._db[name] = {"parent": parent, "children": children, "data": data} | Implement a Python 3 function for
creating a new tree node. | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Write a Python 3 script to
delete subtree private method. | As a Python code analyst, you investigate and solve complex coding mysteries |
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... | Create a Python 3 function for
finding common prefix between two nodes. | You are a Python code analyst, evaluating scripts for potential improvements. |
Print a row of tree. | How would you explain what the following Python 3 function does
def _prt(self, name, lparent, sep, pre1, pre2):
# pylint: disable=R0914
nname = name[lparent + 1 :]
children = self._db[name]["children"]
ncmu = len(children) - 1
plst1 = ncmu * [self._vertical_and_right] + [self._up... | You are a Python code architect, reviewing and designing scalable and efficient code |
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"]
se... | Write a Python 3 script for
renaming a node in the cache. | You are a Python code architect, reviewing and designing scalable and efficient code |
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)
... | Implement a Python 3 function for
validating NodeName pseudo - type. | As a Python code composer, you craft elegant and concise scripts. |
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 (
... | Can you implement a function in Python 3 that
validates NodeWithData pseudo - type. | As a Python code composer, you craft elegant and concise scripts. |
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 as a single tree node
:param name: Root of the sub-tree to collapse
:type name: :ref:`NodeName`
:... | Implement a Python 3 function for
collapsing a sub - tree. | You are a Python code generator, capable of creating scripts from specifications. |
Copy a sub - tree from one node to another. | Given the following Python 3 function, write the documentation
def copy_subtree(self, source_node, dest_node): # noqa: D302
if self._validate_node_name(source_node):
raise RuntimeError("Argument `source_node` is not valid")
if self._validate_node_name(dest_node):
raise RuntimeEr... | As a Python code analyst, you investigate and solve complex coding mysteries |
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`
:raises:
* RuntimeError (Argument \`name\` is not a valid prefix)
* RuntimeError (Argument \`nam... | Can you write a function in Python 3 where it
deletes a prefix from all nodes in the tree. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Delete nodes and their sub - trees from the tree. | Can you generate the documentation for the following Python 3 function
def delete_subtree(self, nodes): # noqa: D302
if self._validate_node_name(nodes):
raise RuntimeError("Argument `nodes` is not valid")
self._delete_subtree(nodes) | You are a Python code architect, reviewing and designing scalable and efficient code |
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 hierarchy node whose sub-trees are to be
flattened
:type name: :ref:`NodeName`
:raises:
... | How would you implement a function in Python 3 that
flattens the hierarchy node that has children and no data are merged with each child node. | As a Python code analyst, you investigate and solve complex coding mysteries |
r Returns the children node names of a node. | How would you explain what the following Python 3 function does
def get_children(self, name):
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
self._node_in_tree(name)
return sorted(self._db[name]["children"]) | You are a Python code generator, capable of creating scripts from specifications. |
r Returns the leaf nodes of the given name. | How would you explain what the following Python 3 function does
def get_leafs(self, name):
if self._validate_node_name(name):
raise RuntimeError("Argument `name` is not valid")
self._node_in_tree(name)
return [node for node in self._get_subtree(name) if self.is_leaf(node)] | As a Python code analyst, you investigate and solve complex coding mysteries |
r Returns the list of children structures of a node. | Here you have a function in Python 3, explain what it does
def get_node_children(self, name):
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"]] | You are a Python code generator, capable of creating scripts from specifications. |
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 :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeErro... | Write a Python 3 function for
getting all node names in a sub - tree. | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.