output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def add_origin_info(self, packet):
"""Add optional Origin headers to message"""
packet.add_header('Origin-Machine-Name', platform.node())
packet.add_header('Origin-Software-Name', 'gntp.py')
packet.add_header('Origin-Software-Version', __version__)
packet.add_header('Origin-Platform-Name', platform.system())
... | Can you create a Python 3 function that
adds optional Origin headers to message | As a python code expert, you are capable of creating scripts from specifications. |
def _send(self, messagetype, packet):
"""Send the GNTP Packet"""
packet.validate()
data = packet.encode()
logger.debug('To : %s:%s <%s>\n%s', self.hostname, self.port, packet.__class__, data)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(self.socketTimeout)
try:
s.connect((self.... | How would you implement a function in Python 3 that
sends the GNTP Packet | As a python code expert, you are capable of creating scripts from specifications. |
Add a new word to the list of words. | Explain what the following Python 3 code does
def add(self, word):
desc = {
"name": "CodeSuccessReslut",
"desc": " http 成功返回结果",
"fields": [{
"name": "code",
"type": "Integer",
"desc": "返回码,200 为正常。"
}, {
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get list of words. | Make a summary of the following Python 3 code
def getList(self):
desc = {
"name": "ListWordfilterReslut",
"desc": "listWordfilter返回结果",
"fields": [{
"name": "code",
"type": "Integer",
"desc": "返回码,200 为正常。"
}, {
... | As a Python code composer, you craft elegant and concise scripts. |
Downloads allele database from IEDB returns local path to XML file. | How would you explain what the following Python 3 function does
def local_path(force_download=False):
return cache.fetch(
filename=ALLELE_XML_FILENAME,
url=ALLELE_XML_URL,
decompress=ALLELE_XML_DECOMPRESS,
force=force_download) | As a python code expert, you are capable of creating scripts from specifications. |
Deletes the local XML file | Can you tell what is the following Python 3 function doing
def delete():
path = cache.local_path(
filename=ALLELE_XML_FILENAME,
url=ALLELE_XML_URL,
decompress=ALLELE_XML_DECOMPRESS)
os.remove(path) | As a Python code analyst, you investigate and solve complex coding mysteries |
Parses the IEDB MhcAlleleName XML file and returns a list of Allele objects containing information about that each allele s HLA
class and source organism. | Can you generate the documentation for the following Python 3 function
def load_alleles():
result = []
path = local_path()
etree = xml.etree.ElementTree.parse(path)
for allele in etree.iterfind("MhcAlleleName"):
name_element = allele.find("DisplayedRestriction")
mhc_class_element = allel... | You are a Python code analyst, evaluating scripts for potential improvements. |
Create a dictionary mapping each unique allele name to a namedtuple
containing information about that alleles class locus species and &c.
| Can you generate the documentation for the following Python 3 function
def load_alleles_dict():
alleles = load_alleles()
result = {}
for allele in alleles:
for name in {allele.name}.union(allele.synonyms):
result[name] = allele
return result | As a python code expert, you are capable of creating scripts from specifications. |
def read_pmbec_coefficients(
key_type='row',
verbose=True,
filename=join(MATRIX_DIR, 'pmbec.mat')):
"""
Parameters
------------
filename : str
Location of PMBEC coefficient matrix
key_type : str
'row' : every key is a single amino acid,
which maps... | Can you implement a function in Python 3 that
reads the PMBEC coefficient matrix from a file. | As a Python code composer, you craft elegant and concise scripts. |
Run commands through an SSH connection. | Can you generate a brief explanation for the following Python 3 code
async def async_run_command(self, command, retry=False):
if not self.is_connected:
await self.async_connect()
try:
result = await asyncio.wait_for(self._client.run(
"%s && %s" % (_PATH_EXPORT_COM... | As a Python code composer, you craft elegant and concise scripts. |
Fetches the client or creates a new one. | Given the following Python 3 function, write the documentation
async def async_connect(self):
kwargs = {
'username': self._username if self._username else None,
'client_keys': [self._ssh_key] if self._ssh_key else None,
'port': self._port,
'password': self._passw... | You are a Python code generator, capable of creating scripts from specifications. |
Run a command through a Telnet connection. | Can you generate the documentation for the following Python 3 function
async def async_run_command(self, command, first_try=True):
await self.async_connect()
try:
with (await self._io_lock):
self._writer.write('{}\n'.format(
"%s && %s" % (
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Connect to the ASUS - WDT Telnet server. | Given the following Python 3 function, write the documentation
async def async_connect(self):
self._reader, self._writer = await asyncio.open_connection(
self._host, self._port)
with (await self._io_lock):
try:
await asyncio.wait_for(self._reader.readuntil(b'logi... | You are a Python code architect, reviewing and designing scalable and efficient code |
async def _parse_lines(lines, regex):
"""Parse the lines using the given regular expression.
If a line can't be parsed it is logged and skipped in the output.
"""
results = []
if inspect.iscoroutinefunction(lines):
lines = await lines
for line in lines:
if line:
matc... | How would you code a function in Python 3 to
parse the lines using the given regular expression. | You are a Python code generator, capable of creating scripts from specifications. |
async def async_get_connected_devices(self):
"""Retrieve data from ASUSWRT.
Calls various commands on the router and returns the superset of all
responses. Some commands will not work on some routers.
"""
devices = {}
dev = await self.async_get_wl()
devices.updat... | Can you write a function in Python 3 where it
retrieves data from ASUSWRT. | You are a Python code generator, capable of creating scripts from specifications. |
async def async_get_bytes_total(self, use_cache=True):
"""Retrieve total bytes (rx an tx) from ASUSWRT."""
now = datetime.utcnow()
if use_cache and self._trans_cache_timer and self._cache_time > \
(now - self._trans_cache_timer).total_seconds():
return self._transfer_... | Write a Python 3 function that can
retrieve total bytes from ASUSWRT. | As a Python code composer, you craft elegant and concise scripts. |
Gets current transfer rates calculated in per second in bytes. | Can you tell what is the following Python 3 function doing
async def async_get_current_transfer_rates(self, use_cache=True):
now = datetime.utcnow()
data = await self.async_get_bytes_total(use_cache)
if self._rx_latest is None or self._tx_latest is None:
self._latest_transfer_check =... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Gets current transfer rates in a human readable format. | Can you tell what is the following Python 3 function doing
async def async_current_transfer_human_readable(
self, use_cache=True):
"""Gets current transfer rates in a human readable format."""
rx, tx = await self.async_get_current_transfer_rates(use_cache)
return "%s/s" % convert_si... | You are a Python code analyst, evaluating scripts for potential improvements. |
Load IEDB T - cell data from a local file. | How would you explain what the following Python 3 function does
def load_dataframe(
mhc_class=None, # 1, 2, or None for neither
hla=None,
exclude_hla=None,
human_only=False,
peptide_length=None,
assay_method=None,
assay_group=None,
only_standard_amino_aci... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def parse_blosum_table(table, coeff_type=int, key_type='row'):
"""
Parse a table of pairwise amino acid coefficient (e.g. BLOSUM50)
"""
lines = table.split("\n")
# drop comments
lines = [line for line in lines if not line.startswith("#")]
# drop CR endline characters
lines = [line.repla... | Can you create a Python 3 function that
parses a BLOSUM table of amino acid coefficients. | As a Python code analyst, you investigate and solve complex coding mysteries |
Prepare a key for a memoization function. | Can you tell what is the following Python 3 function doing
def _prepare_memoization_key(args, kwargs):
key_list = []
for arg in args:
try:
hash(arg)
key_list.append(arg)
except:
key_list.append(repr(arg))
for (k, v) in kwargs.items():
try:
... | As a Python code composer, you craft elegant and concise scripts. |
Load the MHC data from a local file and return a Pandas DataFrame. | Can you tell what is the following Python 3 function doing
def load_dataframe(
mhc_class=None, # 1, 2, or None for neither
hla=None,
exclude_hla=None,
human_only=False,
peptide_length=None,
assay_method=None,
assay_group=None,
only_standard_amino_acids=Tr... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_fieldsets(self, request, obj=None):
"""
Add ownership info fields in fieldset with proper separation.
Author: Himanshu Shankar (https://himanshus.com)
"""
fieldsets = list(super(CreateUpdateAdmin, self).get_fieldsets(
request=request, obj=obj))
# Cre... | Write a Python 3 function that can
return a tuple of fieldsets for the current object. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_readonly_fields(self, request, obj=None):
"""
Makes `created_by`, `create_date` & `update_date` readonly when
editing.
Author: Himanshu Shankar (https://himanshus.com)
"""
# Get read only fields from super
fields = list(super(CreateUpdateAdmin, self).get... | Create a Python 3 function for
returning a tuple of the read only fields for the current object. | You are a Python code generator, capable of creating scripts from specifications. |
This function extracts the authorization string from the request body or the header part of the request. | Given the following Python 3 function, write the documentation
def get_authorization(self, request):
from django.utils.six import text_type
from rest_framework import HTTP_HEADER_ENCODING
auth = request.data.get(self.key, b'') or request.META.get(
self.header_key, b'')
if i... | You are a Python code generator, capable of creating scripts from specifications. |
def main(args=None):
"""Call the CLI interface and wait for the result."""
retcode = 0
try:
ci = CliInterface()
args = ci.parser.parse_args()
result = args.func(args)
if result is not None:
print(result)
retcode = 0
except Exception:
retcode = ... | Write a Python 3 script to
call the CLI interface and wait for the result. | You are a Python code generator, capable of creating scripts from specifications. |
Write the table of contents. | Can you generate a brief explanation for the following Python 3 code
def write_toc(self, args):
# FIXME: Can this logic be moved into the create_parser function?
ordered = False
if args.ordered_list_marker is not None:
list_marker = args.ordered_list_marker
ordered = True... | You are a Python code generator, capable of creating scripts from specifications. |
Create the CLI parser. | Explain what the following Python 3 code does
def create_parser(self):
parser = argparse.ArgumentParser(
description=PROGRAM_DESCRIPTION,
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent(PROGRAM_EPILOG))
parser.add_argument(
'f... | As a python code expert, you are capable of creating scripts from specifications. |
Decorator for monkeypatching functions on modules and classes. | Make a summary of the following Python 3 code
def patch(func=None, obj=None, name=None, avoid_doublewrap=True):
if obj is None:
if isinstance(func, (type, ModuleType)):
obj = func
func = None
elif isinstance(func, (list, tuple)) and all([isinstance(i, (ModuleType, type)) for ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def unpatch(obj, name):
"""
Undo the effects of patch(func, obj, name)
"""
setattr(obj, name, getattr(obj, name).original) | Can you implement a function in Python 3 that
undoes the effects of patch(func, obj, name) | As a python code expert, you are capable of creating scripts from specifications. |
Validates an email address and returns a boolean indicating if the email is valid. | Can you generate the documentation for the following Python 3 function
def validate_email(email):
from django.core.validators import validate_email
from django.core.exceptions import ValidationError
try:
validate_email(email)
return True
except ValidationError:
return False | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_mobile_number(mobile):
"""
Returns a mobile number after removing blanks
Author: Himanshu Shankar (https://himanshus.com)
Parameters
----------
mobile: str
Returns
-------
str
"""
blanks = [' ', '.', ',', '(', ')', '-']
for b in blanks:
mobile = mobile.... | Write a Python 3 script for
returning a mobile number after removing blanks | As a Python code composer, you craft elegant and concise scripts. |
def paginate_data(searched_data, request_data):
"""
Paginates the searched_data as per the request_data
Source: Himanshu Shankar (https://github.com/iamhssingh)
Parameters
----------
searched_data: Serializer.data
It is the data received from queryset. It uses
... | Create a Python 3 function to
paginate the searched_data as per the request_data | You are a Python code generator, capable of creating scripts from specifications. |
def send_message(message: str, subject: str, recip: list, recip_email: list,
html_message: str = None):
"""
Sends message to specified value.
Source: Himanshu Shankar (https://github.com/iamhssingh)
Parameters
----------
message: str
Message that is to be sent to user.
... | Can you create a Python 3 function that
sends a message to specified value. | You are a Python code generator, capable of creating scripts from specifications. |
Checks if user is superuser or object has permission over object | Explain what the following Python 3 code does
def has_object_permission(self, request, view, obj):
return (
request.user.is_superuser or
super(IAWPOrSuperuser, self).has_object_permission(
request=request, view=view, obj=obj
)
) | As a Python code translator, you convert algorithms and pseudocode into Python. |
r Write the string on a single file between a marker and a marker. | Can you tell what is the following Python 3 function doing
def write_string_on_file_between_markers(filename: str, string: str,
marker: str):
r"""Write the table of contents on a single file.
:parameter filename: the file that needs to be read or modified.
:paramete... | As a python code expert, you are capable of creating scripts from specifications. |
r Builds a table of contents of a single file. | Can you tell what is the following Python 3 function doing
def build_toc(filename: str,
ordered: bool = False,
no_links: bool = False,
no_indentation: bool = False,
no_list_coherence: bool = False,
keep_header_levels: int = 3,
parser: s... | You are a Python code analyst, evaluating scripts for potential improvements. |
r Increase the current index for ordered list table of contents. | Can you generate a brief explanation for the following Python 3 code
def increase_index_ordered_list(header_type_count: dict,
header_type_prev: int,
header_type_curr: int,
parser: str = 'github'):
r"""Compute the current... | As a Python code translator, you convert algorithms and pseudocode into Python. |
r Builds a list marker log. | Can you generate the documentation for the following Python 3 function
def build_list_marker_log(parser: str = 'github',
list_marker: str = '.') -> list:
r"""Create a data structure that holds list marker information.
:parameter parser: decides rules on how compute indentations.
... | You are a Python code analyst, evaluating scripts for potential improvements. |
r Compute the number of indentation spaces for the TOC list element. | Can you tell what is the following Python 3 function doing
def compute_toc_line_indentation_spaces(
header_type_curr: int = 1,
header_type_prev: int = 0,
no_of_indentation_spaces_prev: int = 0,
parser: str = 'github',
ordered: bool = False,
list_marker: str = '-',
... | As a python code expert, you are capable of creating scripts from specifications. |
r Builds a single line of the table of contents without indentation. | Given the following Python 3 function, write the documentation
def build_toc_line_without_indentation(header: dict,
ordered: bool = False,
no_links: bool = False,
index: int = 1,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
r Returns a dictionary containing the elements needed to create a TOC line. | Explain what the following Python 3 code does
def get_md_header(header_text_line: str,
header_duplicate_counter: dict,
keep_header_levels: int = 3,
parser: str = 'github',
no_links: bool = False) -> dict:
r"""Build a data structure with the ele... | As a python code expert, you are capable of creating scripts from specifications. |
r Determine if the given line is possibly the opening of a fenced code block. | Can you generate the documentation for the following Python 3 function
def is_opening_code_fence(line: str, parser: str = 'github'):
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker'):
markers = md_parser['github']['code fence']['marker']
marke... | As a Python code translator, you convert algorithms and pseudocode into Python. |
r Creates a list that contains the state of indentations given a header type. | Given the following Python 3 function, write the documentation
def build_indentation_list(parser: str = 'github'):
indentation_list = list()
if (parser == 'github' or parser == 'cmark' or parser == 'gitlab'
or parser == 'commonmarker' or parser == 'redcarpet'):
for i in range(0, md_parser[p... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def is_owner(self, user):
"""
Checks if user is the owner of object
Parameters
----------
user: get_user_model() instance
Returns
-------
bool
Author
------
Himanshu Shankar (https://himanshus.com)
"""
if user.is_... | Write a Python 3 function for
checking if user is the owner of object | As a Python code composer, you craft elegant and concise scripts. |
def run(xml_report_dir, xml_report_filter='TEST-', html_report_path='.',
generate_exec_time_graphs=True, html_report_dir='report.th',
initial_java_heap_size=None, maximum_java_heap_size=None):
""" Use UnitTH to generate a test history report
Args:
xml_report_dir (:obj:`str`... | Write a Python 3 function that can
use UnitTH to generate a test history report of | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get the counter from the data. | Here you have a function in Python 3, explain what it does
def get_counter(data, base):
b0 = data[base]
b1 = data[base + 1]
b2 = data[base + 2]
b3 = data[base + 3]
counter = b3
position = (b1 << 8) + b2
return counter, position | As a Python code composer, you craft elegant and concise scripts. |
Get or delete a resource from a resource. | Make a summary of the following Python 3 code
def get_delete(url, id, method, key=None):
return Util(
url=url + id + "/",
method=method,
key=key,
).json_result() | As a python code expert, you are capable of creating scripts from specifications. |
Get a user by login. | Given the following Python 3 function, write the documentation
def get_user(self, login):
return youtrack.User(self._get("/admin/user/" + urlquote(login.encode('utf8'))), self) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def import_users(self, users):
""" Import users, returns import result (http://confluence.jetbrains.net/display/YTD2/Import+Users)
Example: importUsers([{'login':'vadim', 'fullName':'vadim', 'email':'eee@ss.com', 'jabber':'fff@fff.com'},
{'login':'maxim', 'fullName'... | Write a Python 3 script for
importing users returns import result | As a python code expert, you are capable of creating scripts from specifications. |
def import_links(self, links):
""" Import links, returns import result (http://confluence.jetbrains.net/display/YTD2/Import+Links)
Accepts result of getLinks()
Example: importLinks([{'login':'vadim', 'fullName':'vadim', 'email':'eee@ss.com', 'jabber':'fff@fff.com'},
... | Can you implement a function in Python 3 that
imports links returns import result | As a Python code analyst, you investigate and solve complex coding mysteries |
Imports issues into a JIRA file. | Explain what the following Python 3 code does
def import_issues(self, project_id, assignee_group, issues):
if len(issues) <= 0:
return
bad_fields = ['id', 'projectShortName', 'votes', 'commentsCount',
'historyUpdated', 'updatedByFullName', 'updaterFullName',
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_project(self, project_id):
""" http://confluence.jetbrains.net/display/YTD2/GET+project
"""
return youtrack.Project(self._get("/admin/project/" + urlquote(project_id)), self) | How would you implement a function in Python 3 that
gets a project by ID | You are a Python code architect, reviewing and designing scalable and efficient code |
def create_subsystems(self, project_id, subsystems):
""" Accepts result of getSubsystems()
"""
for s in subsystems:
self.create_subsystem(project_id, s) | Create a Python 3 function to
create a new subsystem for the given project. | As a Python code analyst, you investigate and solve complex coding mysteries |
Creates the versions of the items in the list of versions. | Explain what the following Python 3 code does
def create_versions(self, project_id, versions):
for v in versions:
self.create_version(project_id, v) | As a Python code analyst, you investigate and solve complex coding mysteries |
def run_cmd(call, cmd, *, echo=True, **kwargs):
"""Run a command and echo it first"""
if echo:
print('$> ' + ' '.join(map(pipes.quote, cmd)))
return call(cmd, **kwargs) | Implement a Python 3 function for
running a command and echo it first | As a Python code composer, you craft elegant and concise scripts. |
def git_remote(git_repo):
"""Return the URL for remote git repository.
Depending on the system setup it returns ssh or https remote.
"""
github_token = os.getenv(GITHUB_TOKEN_KEY)
if github_token:
return 'https://{0}@github.com/{1}'.format(
github_token, git_repo)
return 'gi... | Write a Python 3 function that can
return the URL for remote git repository. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get docker build args dict rendering any templated args. | Can you tell what is the following Python 3 function doing
def render_build_args(options, ns):
build_args = options.get('buildArgs', {})
for key, value in build_args.items():
build_args[key] = value.format(**ns)
return build_args | You are a Python code analyst, evaluating scripts for potential improvements. |
Build an image in the cluster | Can you generate a brief explanation for the following Python 3 code
def build_image(image_path, image_name, build_args=None, dockerfile_path=None):
cmd = ['docker', 'build', '-t', image_name, image_path]
if dockerfile_path:
cmd.extend(['-f', dockerfile_path])
for k, v in (build_args or {}).items()... | You are a Python code generator, capable of creating scripts from specifications. |
Returns whether an image needs pushing on the registry | Given the following Python 3 function, write the documentation
def image_needs_pushing(image):
d = docker_client()
try:
d.images.get_registry_data(image)
except docker.errors.APIError:
# image not found on registry, needs pushing
return True
else:
return False | As a Python code composer, you craft elegant and concise scripts. |
Returns whether an image needs building | Can you generate a brief explanation for the following Python 3 code
def image_needs_building(image):
d = docker_client()
# first, check for locally built image
try:
d.images.get(image)
except docker.errors.ImageNotFound:
# image not found, check registry
pass
else:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def build_images(prefix, images, tag=None, commit_range=None, push=False, chart_version=None):
"""Build a collection of docker images
Args:
prefix (str): the prefix to add to images
images (dict): dict of image-specs from chartpress.yml
tag (str):
Specific tag to use instead of the last mod... | Write a Python 3 function that can
build a collection of docker images with the given prefix. | As a Python code analyst, you investigate and solve complex coding mysteries |
Build the values. yaml file for the given name and modifications. | How would you explain what the following Python 3 function does
def build_values(name, values_mods):
values_file = os.path.join(name, 'values.yaml')
with open(values_file) as f:
values = yaml.load(f)
for key, value in values_mods.items():
parts = key.split('.')
mod_obj = values
... | As a Python code composer, you craft elegant and concise scripts. |
Build a new chart with specified version or last - modified commit in path list. | Given the following Python 3 function, write the documentation
def build_chart(name, version=None, paths=None):
chart_file = os.path.join(name, 'Chart.yaml')
with open(chart_file) as f:
chart = yaml.load(f)
if version is None:
if paths is None:
paths = ['.']
commit = las... | As a Python code analyst, you investigate and solve complex coding mysteries |
Publish the given list of paths to github pages | Given the following Python 3 function, write the documentation
def publish_pages(name, paths, git_repo, published_repo, extra_message=''):
version = last_modified_commit(*paths)
checkout_dir = '{}-{}'.format(name, version)
check_call([
'git', 'clone', '--no-checkout',
git_remote(git_repo), c... | As a Python code composer, you craft elegant and concise scripts. |
Main function for the chartpress script | Given the following Python 3 function, write the documentation
def main():
argparser = argparse.ArgumentParser(description=__doc__)
argparser.add_argument('--commit-range',
help='Range of commits to consider when building images')
argparser.add_argument('--push', action='store_true',
help='... | You are a Python code architect, reviewing and designing scalable and efficient code |
Creates a custom field prototype and sets default values bundle if needed. | Explain what the following Python 3 code does
def create_custom_field(connection, cf_type, cf_name, auto_attached, value_names=None, bundle_policy="0"):
if (value_names is None) and (not auto_attached or "[" not in cf_type):
_create_custom_field_prototype(connection, cf_type, cf_name, auto_attached)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def process_custom_field(connection, project_id, cf_type, cf_name, value_names=None):
"""
Creates custom field and attaches it to the project. If custom field already exists and has type
cf_type it is attached to the project. If it has another type, LogicException is raised. If project field already
exi... | Can you create a Python 3 function that
processes a custom field. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def add_values_to_bundle_safe(connection, bundle, values):
"""
Adds values to specified bundle. Checks, whether each value already contains in bundle. If yes, it is not added.
Args:
connection: An opened Connection instance.
bundle: Bundle instance to add values in.
values: Values, ... | Can you create a Python 3 function that
adds values to specified bundle. | You are a Python code architect, reviewing and designing scalable and efficient code |
Parses the incoming bytestream as YAML and returns the resulting data. | Explain what the following Python 3 code does
def parse(self, stream, media_type=None, parser_context=None):
assert yaml, 'YAMLParser requires pyyaml to be installed'
parser_context = parser_context or {}
encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
try:
... | As a Python code composer, you craft elegant and concise scripts. |
def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Renders `data` into serialized YAML.
"""
assert yaml, 'YAMLRenderer requires pyyaml to be installed'
if data is None:
return ''
return yaml.dump(
data,
strea... | Create a Python 3 function for
rendering data into serialized YAML. | As a Python code analyst, you investigate and solve complex coding mysteries |
Creates a <Model >Closure model in the same module as the model. | Explain what the following Python 3 code does
def create_closure_model(cls):
meta_vals = {
'unique_together': (("parent", "child"),)
}
if getattr(cls._meta, 'db_table', None):
meta_vals['db_table'] = '%sclosure' % getattr(cls._meta, 'db_table')
model = type('%sClosure' % cls.__name__, (... | As a python code expert, you are capable of creating scripts from specifications. |
Find the top level of the chain we re in. | Can you tell what is the following Python 3 function doing
def _toplevel(cls):
superclasses = (
list(set(ClosureModel.__subclasses__()) &
set(cls._meta.get_parent_list()))
)
return next(iter(superclasses)) if superclasses else cls | As a Python code analyst, you investigate and solve complex coding mysteries |
def rebuildtable(cls):
"""Regenerate the entire closuretree."""
cls._closure_model.objects.all().delete()
cls._closure_model.objects.bulk_create([cls._closure_model(
parent_id=x['pk'],
child_id=x['pk'],
depth=0
) for x in cls.objects.values("pk")])
... | Create a Python 3 function to
regenerate the entire closuretree. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _closure_deletelink(self, oldparentpk):
"""Remove incorrect links from the closure tree."""
self._closure_model.objects.filter(
**{
"parent__%s__child" % self._closure_parentref(): oldparentpk,
"child__%s__parent" % self._closure_childref(): self.pk
... | Write a Python 3 script for
removing incorrect links from the closure tree. | You are a Python code generator, capable of creating scripts from specifications. |
def _closure_createlink(self):
"""Create a link in the closure tree."""
linkparents = self._closure_model.objects.filter(
child__pk=self._closure_parent_pk
).values("parent", "depth")
linkchildren = self._closure_model.objects.filter(
parent__pk=self.pk
).... | Create a Python 3 function for
creating a link in the closure tree. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_ancestors(self, include_self=False, depth=None):
"""Return all the ancestors of this object."""
if self.is_root_node():
if not include_self:
return self._toplevel().objects.none()
else:
# Filter on pk for efficiency.
return ... | Write a Python 3 script for
returning all the ancestors of this object. | As a Python code composer, you craft elegant and concise scripts. |
def get_descendants(self, include_self=False, depth=None):
"""Return all the descendants of this object."""
params = {"%s__parent" % self._closure_childref():self.pk}
if depth is not None:
params["%s__depth__lte" % self._closure_childref()] = depth
descendants = self._topleve... | Write a Python 3 script to
return all the descendants of this object. | You are a Python code generator, capable of creating scripts from specifications. |
def get_children(self):
"""Return all the children of this object."""
if hasattr(self, '_cached_children'):
children = self._toplevel().objects.filter(
pk__in=[n.pk for n in self._cached_children]
)
children._result_cache = self._cached_children
... | Write a Python 3 function that can
return all the children of this object. | As a Python code composer, you craft elegant and concise scripts. |
def get_root(self):
"""Return the furthest ancestor of this node."""
if self.is_root_node():
return self
return self.get_ancestors().order_by(
"-%s__depth" % self._closure_parentref()
)[0] | How would you implement a function in Python 3 that
returns the furthest ancestor of this node. | As a python code expert, you are capable of creating scripts from specifications. |
def is_descendant_of(self, other, include_self=False):
"""Is this node a descendant of `other`?"""
if other.pk == self.pk:
return include_self
return self._closure_model.objects.filter(
parent=other,
child=self
).exclude(pk=self.pk).exists() | Can you create a Python 3 function that
is this node a descendant of other? | You are a Python code analyst, evaluating scripts for potential improvements. |
Is this node an ancestor of other? | Can you generate a brief explanation for the following Python 3 code
def is_ancestor_of(self, other, include_self=False):
return other.is_descendant_of(self, include_self=include_self) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Quantize a number to a number of digits. | Make a summary of the following Python 3 code
def quantize(number, digits=0, q=builtins.round):
base, fraction = split(digits)
# quantization beyond an order of magnitude results in a variable amount
# of decimal digits depending on the lowest common multiple,
# e.g. floor(1.2341234, 1.25) = 1.225 but ... | You are a Python code generator, capable of creating scripts from specifications. |
A method that accepts a list argument but internally deal only
with a single item of that list. | Can you tell what is the following Python 3 function doing
def vectorize(fn):
@functools.wraps(fn)
def vectorized_function(values, *vargs, **kwargs):
return [fn(value, *vargs, **kwargs) for value in values]
return vectorized_function | You are a Python code architect, reviewing and designing scalable and efficient code |
def engineering(value, precision=3, prefix=False, prefixes=SI):
""" Convert a number to engineering notation. """
display = decimal.Context(prec=precision)
value = decimal.Decimal(value).normalize(context=display)
string = value.to_eng_string()
if prefix:
prefixes = {e(exponent): prefix fo... | Create a Python 3 function for
converting a number to engineering notation. | As a Python code composer, you craft elegant and concise scripts. |
def business(values, precision=3, prefix=True, prefixes=SI, statistic=median, default=''):
"""
Convert a list of numbers to the engineering notation appropriate to a
reference point like the minimum, the median or the mean --
think of it as "business notation".
Any number will have at most the amou... | Write a Python 3 script for
converting a list of numbers to the business notation appropriate to the reference point. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def chunked(iterator, chunksize):
"""
Yields items from 'iterator' in chunks of size 'chunksize'.
>>> list(chunked([1, 2, 3, 4, 5], chunksize=2))
[(1, 2), (3, 4), (5,)]
"""
chunk = []
for idx, item in enumerate(iterator, 1):
chunk.append(item)
if idx % chunksize == 0:
... | Write a Python 3 script for
yielding items from iterator in chunks of size chunksize. | You are a Python code generator, capable of creating scripts from specifications. |
Check if process can accept TCP connections. | Given the following Python 3 function, write the documentation
def pre_start_check(self):
try:
sock = socket.socket()
sock.connect((self.host, self.port))
return True
except (socket.error, socket.timeout):
return False
finally:
# close ... | As a Python code composer, you craft elegant and concise scripts. |
Check if defined URL returns expected status to a HEAD request. | Can you generate the documentation for the following Python 3 function
def after_start_check(self):
try:
conn = HTTPConnection(self.host, self.port)
conn.request('HEAD', self.url.path)
status = str(conn.getresponse().status)
if status == self.status or self.stat... | You are a Python code analyst, evaluating scripts for potential improvements. |
def start(self):
"""
Start process.
:returns: itself
:rtype: OutputExecutor
.. note::
Process will be considered started, when defined banner will appear
in process output.
"""
super(OutputExecutor, self).start()
# get a polling... | How would you code a function in Python 3 to
start the output process. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _wait_for_output(self):
"""
Check if output matches banner.
.. warning::
Waiting for I/O completion. It does not work on Windows. Sorry.
"""
# Here we should get an empty list or list with a tuple [(fd, event)]
# When we get list with a tuple we can use r... | Can you write a function in Python 3 where it
checks if output matches banner. | As a Python code analyst, you investigate and solve complex coding mysteries |
def construct_mail(recipients=None, context=None, template_base='emailit/email', subject=None, message=None, site=None,
subject_templates=None, body_templates=None, html_templates=None, from_email=None, language=None,
**kwargs):
"""
usage:
construct_mail(['my@email.com'... | Can you create a Python 3 function that
constructs a new email object | As a python code expert, you are capable of creating scripts from specifications. |
On python exit kill all processes that are running. | Can you tell what is the following Python 3 function doing
def cleanup_subprocesses():
# pylint: disable=redefined-outer-name, reimported
# atexit functions tends to loose global imports sometimes so reimport
# everything what is needed again here:
import os
import errno
from mirakuru.base_env i... | As a Python code composer, you craft elegant and concise scripts. |
def start(self):
"""
Start defined process.
After process gets started, timeout countdown begins as well.
:returns: itself
:rtype: SimpleExecutor
.. note::
We want to open ``stdin``, ``stdout`` and ``stderr`` as text
streams in universal newline... | Create a Python 3 function for
starting the countdown process. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _clear_process(self):
"""
Close stdin/stdout of subprocess.
It is required because of ResourceWarning in Python 3.
"""
if self.process:
if self.process.stdin:
self.process.stdin.close()
if self.process.stdout:
self.proc... | Create a Python 3 function to
clear the process object. | As a python code expert, you are capable of creating scripts from specifications. |
Kill all processes that have started and have left. | Can you generate a brief explanation for the following Python 3 code
def _kill_all_kids(self, sig):
pids = processes_with_env(ENV_UUID, self._uuid)
for pid in pids:
log.debug("Killing process %d ...", pid)
try:
os.kill(pid, sig)
except OSError as err:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Kill the process if running. | How would you explain what the following Python 3 function does
def kill(self, wait=True, sig=None):
if sig is None:
sig = self._sig_kill
if self.running():
os.killpg(self.process.pid, sig)
if wait:
self.process.wait()
self._kill_all_kids(sig)... | You are a Python code analyst, evaluating scripts for potential improvements. |
def wait_for(self, wait_for):
"""
Wait for callback to return True.
Simply returns if wait_for condition has been met,
raises TimeoutExpired otherwise and kills the process.
:param callback wait_for: callback to call
:raises: mirakuru.exceptions.TimeoutExpired
:... | How would you implement a function in Python 3 that
waits for a callback to return True. | As a Python code analyst, you investigate and solve complex coding mysteries |
Start executor with additional checks. | Can you tell what is the following Python 3 function doing
def start(self):
if self.pre_start_check():
# Some other executor (or process) is running with same config:
raise AlreadyRunning(self)
super(Executor, self).start()
self.wait_for(self.check_subprocess)
r... | As a Python code analyst, you investigate and solve complex coding mysteries |
def check_subprocess(self):
"""
Make sure the process didn't exit with an error and run the checks.
:rtype: bool
:return: the actual check status
:raise ProcessExitedWithError: when the main process exits with
an error
"""
exit_code = self.process.pol... | Implement a Python 3 function for
checking the status of the main process and run the checks. | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.