output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def assess_differences(image_file1,
image_file2,
levels=None,
version=None,
size_heuristic=False,
guts1=None,
guts2=None):
'''assess_differences will compare two images on each ... | Can you create a Python 3 function that
assesses the differences between two images on each level of returns a dictionary with files that are the same different and an overall score. | You are a Python code generator, capable of creating scripts from specifications. |
Returns True if the member matches a regular expression from a level
. | Here you have a function in Python 3, explain what it does
def include_file(member,file_filter):
'''include_file will look at a path and determine
if it matches a regular expression from a level
'''
member_path = member.name.replace('.','',1)
if len(member_path) == 0:
return False
# Do... | You are a Python code analyst, evaluating scripts for potential improvements. |
assess if a file is root owned meaning root or user / group
id of 0 | Can you generate the documentation for the following Python 3 function
def is_root_owned(member):
'''assess if a file is root owned, meaning "root" or user/group
id of 0'''
if member.uid == 0 or member.gid == 0:
return True
elif member.uname == 'root' or member.gname == 'root':
return T... | As a Python code analyst, you investigate and solve complex coding mysteries |
def assess_content(member,file_filter):
'''Determine if the filter wants the file to be read for content.
In the case of yes, we would then want to add the content to the
hash and not the file object.
'''
member_path = member.name.replace('.','',1)
if len(member_path) == 0:
return False... | Create a Python 3 function to
determine if the filter wants the file to be read for content. | You are a Python code generator, capable of creating scripts from specifications. |
This function returns a custom level for a user based on a regular expression. | How would you explain what the following Python 3 function does
def get_custom_level(regexp=None,description=None,skip_files=None,include_files=None):
'''get_custom_level will generate a custom level for the user,
based on a regular expression. If used outside the context of tarsum, the user
can generate t... | As a python code expert, you are capable of creating scripts from specifications. |
def modify_level(level,field,values,append=True):
'''modify level is intended to add / modify a content type.
Default content type is list, meaning the entry is appended.
If you set append to False, the content will be overwritten
For any other content type, the entry is overwritten.
'''
field =... | Can you implement a function in Python 3 that
modifies level is intended to add or modify a content type. | You are a Python code generator, capable of creating scripts from specifications. |
get_levels returns a dictionary of levels descriptions and regular expressions for files for the user. | Can you tell what is the following Python 3 function doing
def get_levels(version=None):
'''get_levels returns a dictionary of levels (key) and values (dictionaries with
descriptions and regular expressions for files) for the user.
:param version: the version of singularity to use (default is 2.2)
:par... | You are a Python code generator, capable of creating scripts from specifications. |
def make_levels_set(levels):
'''make set efficient will convert all lists of items
in levels to a set to speed up operations'''
for level_key,level_filters in levels.items():
levels[level_key] = make_level_set(level_filters)
return levels | Can you implement a function in Python 3 that
makes set efficient will convert all lists of items in levels to a set | You are a Python code analyst, evaluating scripts for potential improvements. |
def make_level_set(level):
'''make level set will convert one level into
a set'''
new_level = dict()
for key,value in level.items():
if isinstance(value,list):
new_level[key] = set(value)
else:
new_level[key] = value
return new_level | Implement a function in Python 3 to
make level set will convert one level into a set | You are a Python code generator, capable of creating scripts from specifications. |
def extract_guts(image_path,
tar,
file_filter=None,
tag_root=True,
include_sizes=True):
'''extract the file guts from an in memory tarfile. The file is not closed.
This should not be done for large images.
'''
if file_filter is None... | Create a Python 3 function for
extracting the file guts from an in memory tarfile. | You are a Python code generator, capable of creating scripts from specifications. |
def get_memory_tar(image_path):
'''get an in memory tar of an image. Use carefully, not as reliable
as get_image_tar
'''
byte_array = Client.image.export(image_path)
file_object = io.BytesIO(byte_array)
tar = tarfile.open(mode="r|*", fileobj=file_object)
return (file_object,tar) | Write a Python 3 function for
getting an in memory tar of an image | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_image_tar(image_path):
'''get an image tar, either written in memory or to
the file system. file_obj will either be the file object,
or the file itself.
'''
bot.debug('Generate file system tar...')
file_obj = Client.image.export(image_path=image_path)
if file_obj is None:
... | Implement a Python 3 function for
getting an image tar either written in memory or to the file system. | As a Python code composer, you craft elegant and concise scripts. |
delete image tar will close a file object or delete from the file system | Make a summary of the following Python 3 code
def delete_image_tar(file_obj, tar):
'''delete image tar will close a file object (if extracted into
memory) or delete from the file system (if saved to disk)'''
try:
file_obj.close()
except:
tar.close()
if os.path.exists(file_obj):
... | As a Python code analyst, you investigate and solve complex coding mysteries |
extract_content will extract content from an image using cat. | Given the following Python 3 function, write the documentation
def extract_content(image_path, member_name, return_hash=False):
'''extract_content will extract content from an image using cat.
If hash=True, a hash sum is returned instead
'''
if member_name.startswith('./'):
member_name = member_... | You are a Python code architect, reviewing and designing scalable and efficient code |
This function downloads the repository and builds the singularity image from Singularity and creates the singularity image from Singularity. | Explain what the following Python 3 code does
def run_build(build_dir, params, verbose=True):
'''run_build takes a build directory and params dictionary, and does the following:
- downloads repo to a temporary directory
- changes branch or commit, if needed
- creates and bootstraps singularity ima... | As a Python code composer, you craft elegant and concise scripts. |
finish build sends the build and data to a response url | Explain what the following Python 3 code does
def send_build_data(build_dir, data, secret,
response_url=None,clean_up=True):
'''finish build sends the build and data (response) to a response url
:param build_dir: the directory of the build
:response_url: where to send the response. If N... | As a Python code translator, you convert algorithms and pseudocode into Python. |
send build close to the server | Explain what the following Python 3 code does
def send_build_close(params,response_url):
'''send build close sends a final response (post) to the server to bring down
the instance. The following must be included in params:
repo_url, logfile, repo_id, secret, log_file, token
'''
# Finally, package e... | As a Python code analyst, you investigate and solve complex coding mysteries |
remove unicode keys and values from dict encoding in utf8
| Can you generate a brief explanation for the following Python 3 code
def remove_unicode_dict(input_dict):
'''remove unicode keys and values from dict, encoding in utf8
'''
if isinstance(input_dict, collections.Mapping):
return dict(map(remove_unicode_dict, input_dict.iteritems()))
elif isinstanc... | You are a Python code generator, capable of creating scripts from specifications. |
update_dict will update lists in a dictionary. | Can you generate a brief explanation for the following Python 3 code
def update_dict(input_dict,key,value):
'''update_dict will update lists in a dictionary. If the key is not included,
if will add as new list. If it is, it will append.
:param input_dict: the dict to update
:param value: the value to up... | You are a Python code analyst, evaluating scripts for potential improvements. |
get_url will use the requests library to get a url | Make a summary of the following Python 3 code
def get_google_service(service_type=None,version=None):
'''
get_url will use the requests library to get a url
:param service_type: the service to get (default is storage)
:param version: version to use (default is v1)
'''
if service_type == None:
... | You are a Python code generator, capable of creating scripts from specifications. |
upload a file to the specified bucket | Make a summary of the following Python 3 code
def upload_file(storage_service,bucket,bucket_path,file_name,verbose=True):
'''get_folder will return the folder with folder_name, and if create=True,
will create it if not found. If folder is found or created, the metadata is
returned, otherwise None is returne... | As a Python code analyst, you investigate and solve complex coding mysteries |
This function will determine the path to the image file based on a repo url and the trailing path. | Can you generate the documentation for the following Python 3 function
def get_image_path(repo_url, trailing_path):
'''get_image_path will determine an image path based on a repo url, removing
any token, and taking into account urls that end with .git.
:param repo_url: the repo url to parse:
:param trai... | As a Python code composer, you craft elegant and concise scripts. |
This function will generate the Singularity build from a spec_file from a repo_url and then run it. | Can you generate a brief explanation for the following Python 3 code
def run_build(logfile='/tmp/.shub-log'):
'''run_build will generate the Singularity build from a spec_file from a repo_url.
If no arguments are required, the metadata api is queried for the values.
:param build_dir: directory to do the ... | As a Python code composer, you craft elegant and concise scripts. |
get_build_metadata will return metadata about an instance from within it | Make a summary of the following Python 3 code
def get_build_metadata(key):
'''get_build_metadata will return metadata about an instance from within it.
:param key: the key to look up
'''
headers = {"Metadata-Flavor":"Google"}
url = "http://metadata.google.internal/computeMetadata/v1/instance/attribu... | You are a Python code generator, capable of creating scripts from specifications. |
uses get_build_metadata to retrieve corresponding meta data values for a build
| Can you tell what is the following Python 3 function doing
def get_build_params(metadata):
'''get_build_params uses get_build_metadata to retrieve corresponding meta data values for a build
:param metadata: a list, each item a dictionary of metadata, in format:
metadata = [{'key': 'repo_url', 'value': repo_... | You are a Python code analyst, evaluating scripts for potential improvements. |
wrapper around the rsync command. | Explain what the following Python 3 code does
def rsync(*args, **kwargs):
kwargs.setdefault('capture', False)
replacements = dict(
host_string="{user}@{host}".format(
user=env.instance.config.get('user', 'root'),
host=env.instance.config.get(
'host', env.instance.... | You are a Python code architect, reviewing and designing scalable and efficient code |
def bootstrap(**kwargs):
""" Bootstrap an EC2 instance that has been booted into an AMI from http://www.daemonology.net/freebsd-on-ec2/
Note: deprecated, current AMI images are basically pre-bootstrapped, they just need to be configured.
"""
# the user for the image is `ec2-user`, there is no sudo, but ... | Implement a Python 3 function for
bootstrapping an EC2 instance that has been booted into an AMI from http://www. daemonology. net | You are a Python code generator, capable of creating scripts from specifications. |
def bootstrap(**kwargs):
"""Digital Oceans FreeBSD droplets are pretty much already pre-bootstrapped,
including having python2.7 and sudo etc. pre-installed.
the only thing we need to change is to allow root to login (without a password)
enable pf and ensure it is running
"""
bu = BootstrapUtil... | Write a Python 3 script for
bootstrapping the FreeBSD droplet into a new root. | As a python code expert, you are capable of creating scripts from specifications. |
This method will create a bootstrap file for the FreeBSD installation. | How would you explain what the following Python 3 function does
def bootstrap_files(self):
bootstrap_file_yamls = [
abspath(join(self.default_template_path, self.bootstrap_files_yaml)),
abspath(join(self.custom_template_path, self.bootstrap_files_yaml))]
bootstrap_files = dict()
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def devices(self):
""" computes the name of the disk devices that are suitable
installation targets by subtracting CDROM- and USB devices
from the list of total mounts.
"""
install_devices = self.install_devices
if 'bootstrap-system-devices' in env.instance.config:
... | Can you write a function in Python 3 where it
returns the name of the disk devices that are suitable installation targets by subtracting CDROM - and USB devices from the list of total mounts. | As a python code expert, you are capable of creating scripts from specifications. |
def fetch_assets(self):
""" download bootstrap assets to control host.
If present on the control host they will be uploaded to the target host during bootstrapping.
"""
# allow overwrites from the commandline
packages = set(
env.instance.config.get('bootstrap-packages... | How would you code a function in Python 3 to
download bootstrap assets to control host. | As a python code expert, you are capable of creating scripts from specifications. |
def res_to_str(res):
"""
:param res: :class:`requests.Response` object
Parse the given request and generate an informative string from it
"""
if 'Authorization' in res.request.headers:
res.request.headers['Authorization'] = "*****"
return """
####################################
url = %... | Write a Python 3 script to
return a string representation of the given response object. | You are a Python code generator, capable of creating scripts from specifications. |
def parse_resource_definition(resource_name, resource_dct):
"""
Returns all the info extracted from a resource section of the apipie json
:param resource_name: Name of the resource that is defined by the section
:param resrouce_dict: Dictionary as generated by apipie of the resource
definition
... | Create a Python 3 function to
parse a resource definition and return all the info extracted from the resource section of the apipie | You are a Python code analyst, evaluating scripts for potential improvements. |
def parse_resource_from_url(self, url):
"""
Returns the appropriate resource name for the given URL.
:param url: API URL stub, like: '/api/hosts'
:return: Resource name, like 'hosts', or None if not found
"""
# special case for the api root
if url == '/api':
... | Can you implement a function in Python 3 that
parses the resource name from the given URL. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the name of the current object. | Given the following Python 3 function, write the documentation
def _get_name(self):
if self.url.count(':') > 1:
# /api/one/two/:three/four -> two_:three_four
base_name = self.url.split('/', 3)[-1].replace('/', '_')[1:]
# :one_two_three -> two_three
if base_name.st... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generates function for specific method and using specific api | How would you explain what the following Python 3 function does
def generate_func(self, as_global=False):
keywords = []
params_def = []
params_doc = ""
original_names = {}
params = dict(
(param['name'], param)
for param in self.params
)
#... | You are a Python code analyst, evaluating scripts for potential improvements. |
Generate documentation for single parameter of function
| Here you have a function in Python 3, explain what it does
def create_param_doc(cls, param, prefix=None):
desc = cls.exclude_html_reg.sub('', param['description']).strip()
if not desc:
desc = "<no description>"
name = param['name']
if prefix:
name = "%s[%s]" % (pr... | You are a Python code architect, reviewing and designing scalable and efficient code |
This function parses the plugin definition dict for a
plugin and extracts the relevant information. | How would you explain what the following Python 3 function does
def convert_plugin_def(http_method, funcs):
methods = []
if http_method not in ('GET', 'PUT', 'POST', 'DELETE'):
logger.error(
'Plugin load failure, HTTP method %s unsupported.',
http_method,
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Given a repo will return the current version of the current version | Here you have a function in Python 3, explain what it does
def get_current_version(repo_path):
repo = dulwich.repo.Repo(repo_path)
tags = get_tags(repo)
maj_version = 0
feat_version = 0
fix_version = 0
for commit_sha, children in reversed(
get_children_per_first_parent(repo_path).it... | As a Python code analyst, you investigate and solve complex coding mysteries |
Given a repo and optionally a base revision to start from will return a list of authors. | Given the following Python 3 function, write the documentation
def get_authors(repo_path, from_commit):
repo = dulwich.repo.Repo(repo_path)
refs = get_refs(repo)
start_including = False
authors = set()
if from_commit is None:
start_including = True
for commit_sha, children in reversed(... | You are a Python code architect, reviewing and designing scalable and efficient code |
def emit(
self, tup, tup_id=None, stream=None, direct_task=None, need_task_ids=False
):
"""Emit a spout Tuple message.
:param tup: the Tuple to send to Storm, should contain only
JSON-serializable data.
:type tup: list or tuple
:param tup_id: the ID for t... | Write a Python 3 function that can
emit a spout Tuple message. | You are a Python code generator, capable of creating scripts from specifications. |
def ack(self, tup_id):
"""Called when a bolt acknowledges a Tuple in the topology.
:param tup_id: the ID of the Tuple that has been fully acknowledged in
the topology.
:type tup_id: str
"""
self.failed_tuples.pop(tup_id, None)
try:
del ... | Can you implement a function in Python 3 that
calls when a bolt acknowledges a tuple in the topology. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Called when a Tuple fails in the topology. | How would you explain what the following Python 3 function does
def fail(self, tup_id):
saved_args = self.unacked_tuples.get(tup_id)
if saved_args is None:
self.logger.error("Received fail for unknown tuple ID: %r", tup_id)
return
tup, stream, direct_task, need_task_ids =... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Emit a single entry in the unacked_tuples dictionary. | Here you have a function in Python 3, explain what it does
def emit(
self, tup, tup_id=None, stream=None, direct_task=None, need_task_ids=False
):
"""Emit a spout Tuple & add metadata about it to `unacked_tuples`.
In order for this to work, `tup_id` is a required parameter.
See :me... | As a python code expert, you are capable of creating scripts from specifications. |
Handler to drop us into a remote debugger upon receiving SIGUSR1 | Given the following Python 3 function, write the documentation
def remote_pdb_handler(signum, frame):
try:
from remote_pdb import RemotePdb
rdb = RemotePdb(host="127.0.0.1", port=0)
rdb.set_trace(frame=frame)
except ImportError:
log.warning(
"remote_pdb unavailable. ... | As a Python code composer, you craft elegant and concise scripts. |
Emit a record to Storm. | How would you explain what the following Python 3 function does
def emit(self, record):
try:
msg = self.format(record)
level = _STORM_LOG_LEVELS.get(record.levelname.lower(), _STORM_LOG_INFO)
self.serializer.send_message(
{"command": "log", "msg": str(msg), "l... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Setup the component with the given storm_conf and context. | Can you generate a brief explanation for the following Python 3 code
def _setup_component(self, storm_conf, context):
self.topology_name = storm_conf.get("topology.name", "")
self.task_id = context.get("taskid", "")
self.component_name = context.get("componentid")
# If using Storm before... | You are a Python code generator, capable of creating scripts from specifications. |
def read_handshake(self):
"""Read and process an initial handshake message from Storm."""
msg = self.read_message()
pid_dir, _conf, _context = msg["pidDir"], msg["conf"], msg["context"]
# Write a blank PID file out to the pidDir
open(join(pid_dir, str(self.pid)), "w").close()
... | How would you code a function in Python 3 to
read and process an initial handshake message from Storm. | You are a Python code generator, capable of creating scripts from specifications. |
def send_message(self, message):
"""Send a message to Storm via stdout."""
if not isinstance(message, dict):
logger = self.logger if self.logger else log
logger.error(
"%s.%d attempted to send a non dict message to Storm: " "%r",
self.component_nam... | Create a Python 3 function to
send a message to Storm via stdout. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def raise_exception(self, exception, tup=None):
"""Report an exception back to Storm via logging.
:param exception: a Python exception.
:param tup: a :class:`Tuple` object.
"""
if tup:
message = (
"Python {exception_name} raised while processing Tuple... | Create a Python 3 function to
report an exception back to Storm via logging. | You are a Python code analyst, evaluating scripts for potential improvements. |
def log(self, message, level=None):
"""Log a message to Storm optionally providing a logging level.
:param message: the log message to send to Storm.
:type message: str
:param level: the logging level that Storm should use when writing the
``message``. Can be one o... | Write a Python 3 function for
logging a message to Storm optionally providing a logging level. | You are a Python code generator, capable of creating scripts from specifications. |
def emit(
self,
tup,
tup_id=None,
stream=None,
anchors=None,
direct_task=None,
need_task_ids=False,
):
"""Emit a new Tuple to a stream.
:param tup: the Tuple payload to send to Storm, should contain only
JSON-serializable d... | Write a Python 3 function for
emitting a new tuple to a stream. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a TextIOWrapper around the given stream that handles UTF - 8
encoding and decoding. | Can you generate the documentation for the following Python 3 function
def _wrap_stream(stream):
if hasattr(stream, "buffer"):
return io.TextIOWrapper(stream.buffer, encoding="utf-8")
elif hasattr(stream, "readable"):
return io.TextIOWrapper(stream, encoding="utf-8")
# Py... | You are a Python code analyst, evaluating scripts for potential improvements. |
def read_message(self):
"""The Storm multilang protocol consists of JSON messages followed by
a newline and "end\n".
All of Storm's messages (for either bolts or spouts) should be of the
form::
'<command or task_id form prior emit>\\nend\\n'
Command example, an inc... | Can you write a function in Python 3 where it
reads a message from the input stream and returns it as a dict. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def serialize_dict(self, msg_dict):
"""Serialize to JSON a message dictionary."""
serialized = json.dumps(msg_dict, namedtuple_as_object=False)
if PY2:
serialized = serialized.decode("utf-8")
serialized = "{}\nend\n".format(serialized)
return serialized | Write a Python 3 function for
serializing to JSON a message dictionary. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def read_tuple(self):
"""Read a tuple from the pipe to Storm."""
cmd = self.read_command()
source = cmd["comp"]
stream = cmd["stream"]
values = cmd["tuple"]
val_type = self._source_tuple_types[source].get(stream)
return Tuple(
cmd["id"],
so... | Implement a Python 3 function for
reading a tuple from the pipe to Storm. | You are a Python code architect, reviewing and designing scalable and efficient code |
def emit(
self, tup, stream=None, anchors=None, direct_task=None, need_task_ids=False
):
"""Emit a new Tuple to a stream.
:param tup: the Tuple payload to send to Storm, should contain only
JSON-serializable data.
:type tup: :class:`list` or :class:`pystorm.compo... | How would you code a function in Python 3 to
emit a new tuple to Storm. | You are a Python code generator, capable of creating scripts from specifications. |
def ack(self, tup):
"""Indicate that processing of a Tuple has succeeded.
:param tup: the Tuple to acknowledge.
:type tup: :class:`str` or :class:`pystorm.component.Tuple`
"""
tup_id = tup.id if isinstance(tup, Tuple) else tup
self.send_message({"command": "ack", "id": t... | Can you create a Python 3 function that
indicates that processing of a Tuple has succeeded. | You are a Python code generator, capable of creating scripts from specifications. |
def fail(self, tup):
"""Indicate that processing of a Tuple has failed.
:param tup: the Tuple to fail (its ``id`` if ``str``).
:type tup: :class:`str` or :class:`pystorm.component.Tuple`
"""
tup_id = tup.id if isinstance(tup, Tuple) else tup
self.send_message({"command":... | Write a Python 3 function for
indicating that processing of a Tuple has failed. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _handle_run_exception(self, exc):
"""Process an exception encountered while running the ``run()`` loop.
Called right before program exits.
"""
if len(self._current_tups) == 1:
tup = self._current_tups[0]
self.raise_exception(exc, tup)
if self.auto... | Implement a Python 3 function for
handling an exception raised while running the run loop. | As a Python code analyst, you investigate and solve complex coding mysteries |
def emit(self, tup, **kwargs):
"""Modified emit that will not return task IDs after emitting.
See :class:`pystorm.component.Bolt` for more information.
:returns: ``None``.
"""
kwargs["need_task_ids"] = False
return super(BatchingBolt, self).emit(tup, **kwargs) | Can you write a function in Python 3 where it
modifies emit that will not return task IDs after emitting. | As a Python code analyst, you investigate and solve complex coding mysteries |
Increment tick counter and call process_batch for all current Tuples. | Can you generate the documentation for the following Python 3 function
def process_tick(self, tick_tup):
self._tick_counter += 1
# ACK tick Tuple immediately, since it's just responsible for counter
self.ack(tick_tup)
if self._tick_counter > self.ticks_between_batches and self._batches:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def process_batches(self):
"""Iterate through all batches, call process_batch on them, and ack.
Separated out for the rare instances when we want to subclass
BatchingBolt and customize what mechanism causes batches to be
processed.
"""
for key, batch in iteritems(self._b... | Can you implement a function in Python 3 that
iterates through all batches and process them and ack. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Group non - tick Tuples into batches by group_key. | Can you generate a brief explanation for the following Python 3 code
def process(self, tup):
# Append latest Tuple to batches
group_key = self.group_key(tup)
self._batches[group_key].append(tup) | As a Python code composer, you craft elegant and concise scripts. |
Handle an exception raised while running the run loop. | Can you generate the documentation for the following Python 3 function
def _handle_run_exception(self, exc):
self.raise_exception(exc, self._current_tups)
if self.auto_fail:
failed = set()
for key, batch in iteritems(self._batches):
# Only wipe out batches other ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
The inside of _batch_entry s infinite loop. | Make a summary of the following Python 3 code
def _batch_entry_run(self):
time.sleep(self.secs_between_batches)
with self._batch_lock:
self.process_batches() | As a Python code composer, you craft elegant and concise scripts. |
Entry point for the batcher thread. | Can you generate a brief explanation for the following Python 3 code
def _batch_entry(self):
try:
while True:
self._batch_entry_run()
except:
self.exc_info = sys.exc_info()
os.kill(self.pid, signal.SIGUSR1) | You are a Python code generator, capable of creating scripts from specifications. |
This method is called by the BatchingBolt s main thread to process the current Tuples
. | Can you generate a brief explanation for the following Python 3 code
def _run(self):
tup = self.read_tuple()
with self._batch_lock:
self._current_tups = [tup]
if self.is_heartbeat(tup):
self.send_message({"command": "sync"})
elif self.is_tick(tup):
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def send_message(self, msg_dict):
"""Serialize a message dictionary and write it to the output stream."""
with self._writer_lock:
try:
self.output_stream.flush()
self.output_stream.write(self.serialize_dict(msg_dict))
self.output_stream.flush()... | Implement a Python 3 function for
serializing a message dictionary and write it to the output stream. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _void_array_to_list(restuple, _func, _args):
""" Convert the FFI result to Python data structures """
shape = (restuple.e.len, 1)
array_size = np.prod(shape)
mem_size = 8 * array_size
array_str_e = string_at(restuple.e.data, mem_size)
array_str_n = string_at(restuple.n.data, mem_size)
... | Write a Python 3 script for
converting the FFI result to Python data structures. | You are a Python code generator, capable of creating scripts from specifications. |
def load_data_file(filename, encoding='utf-8'):
"""Load a data file and return it as a list of lines.
Parameters:
filename: The name of the file (no directories included).
encoding: The file encoding. Defaults to utf-8.
"""
data = pkgutil.get_data(PACKAGE_NAME, os.path.join(DATA_DIR, f... | Can you create a Python 3 function that
loads a data file and return it as a list of lines. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _load_data():
"""Load the word and character mapping data into a dictionary.
In the data files, each line is formatted like this:
HANZI PINYIN_READING/PINYIN_READING
So, lines need to be split by '\t' and then the Pinyin readings need to be
split by '/'.
"""
data = {}
for na... | Can you create a Python 3 function that
loads the word and character mapping data into a dictionary. | You are a Python code generator, capable of creating scripts from specifications. |
def _hanzi_to_pinyin(hanzi):
"""Return the Pinyin reading for a Chinese word.
If the given string *hanzi* matches a CC-CEDICT word, the return value is
formatted like this: [WORD_READING1, WORD_READING2, ...]
If the given string *hanzi* doesn't match a CC-CEDICT word, the return
value is formatted... | Can you implement a function in Python 3 that
returns the Pinyin reading for a Chinese word. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _enclose_readings(container, readings):
"""Enclose a reading within a container, e.g. '[]'."""
container_start, container_end = tuple(container)
enclosed_readings = '%(container_start)s%(readings)s%(container_end)s' % {
'container_start': container_start, 'container_end': container_end,
... | Can you implement a function in Python 3 that
encloses a reading within a container. | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert a string s Chinese characters to Pinyin readings. | Explain what the following Python 3 code does
def to_pinyin(s, delimiter=' ', all_readings=False, container='[]',
accented=True):
"""Convert a string's Chinese characters to Pinyin readings.
*s* is a string containing Chinese characters. *accented* is a
boolean value indicating whether to ret... | As a python code expert, you are capable of creating scripts from specifications. |
def to_zhuyin(s, delimiter=' ', all_readings=False, container='[]'):
"""Convert a string's Chinese characters to Zhuyin readings.
*s* is a string containing Chinese characters.
*delimiter* is the character used to indicate word boundaries in *s*.
This is used to differentiate between words and charact... | Write a Python 3 function that can
convert a string s Chinese characters to Zhuyin readings. | You are a Python code generator, capable of creating scripts from specifications. |
Convert a string s Chinese characters to IPA. | Can you tell what is the following Python 3 function doing
def to_ipa(s, delimiter=' ', all_readings=False, container='[]'):
numbered_pinyin = to_pinyin(s, delimiter, all_readings, container, False)
ipa = pinyin_to_ipa(numbered_pinyin)
return ipa | As a Python code composer, you craft elegant and concise scripts. |
def _load_data():
"""Load the transcription mapping data into a dictionary."""
lines = dragonmapper.data.load_data_file('transcriptions.csv')
pinyin_map, zhuyin_map, ipa_map = {}, {}, {}
for line in lines:
p, z, i = line.split(',')
pinyin_map[p] = {'Zhuyin': z, 'IPA': i}
zhuyin_m... | Create a Python 3 function for
loading the transcription mapping data into a dictionary. | As a Python code composer, you craft elegant and concise scripts. |
def _numbered_vowel_to_accented(vowel, tone):
"""Convert a numbered Pinyin vowel to an accented Pinyin vowel."""
if isinstance(tone, int):
tone = str(tone)
return _PINYIN_TONES[vowel + tone] | Can you implement a function in Python 3 that
converts a numbered Pinyin vowel to an accented Pinyin vowel. | As a python code expert, you are capable of creating scripts from specifications. |
def _accented_vowel_to_numbered(vowel):
"""Convert an accented Pinyin vowel to a numbered Pinyin vowel."""
for numbered_vowel, accented_vowel in _PINYIN_TONES.items():
if vowel == accented_vowel:
return tuple(numbered_vowel) | Can you write a function in Python 3 where it
converts an accented Pinyin vowel to a numbered Pinyin vowel. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _parse_numbered_syllable(unparsed_syllable):
"""Return the syllable and tone of a numbered Pinyin syllable."""
tone_number = unparsed_syllable[-1]
if not tone_number.isdigit():
syllable, tone = unparsed_syllable, '5'
elif tone_number == '0':
syllable, tone = unparsed_syllable[:-1], '... | Implement a Python 3 function for
returning the syllable and tone of a numbered Pinyin syllable. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the syllable and tone of an accented Pinyin syllable. | Here you have a function in Python 3, explain what it does
def _parse_accented_syllable(unparsed_syllable):
if unparsed_syllable[0] == '\u00B7':
# Special case for middle dot tone mark.
return unparsed_syllable[1:], '5'
for character in unparsed_syllable:
if character in _ACCENTED_VOWELS... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _parse_zhuyin_syllable(unparsed_syllable):
"""Return the syllable and tone of a Zhuyin syllable."""
zhuyin_tone = unparsed_syllable[-1]
if zhuyin_tone in zhon.zhuyin.characters:
syllable, tone = unparsed_syllable, '1'
elif zhuyin_tone in zhon.zhuyin.marks:
for tone_number, tone_mark ... | Create a Python 3 function for
returning the syllable and tone of a Zhuyin syllable. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the syllable and tone of an IPA syllable. | Explain what the following Python 3 code does
def _parse_ipa_syllable(unparsed_syllable):
ipa_tone = re.search('[%(marks)s]+' % {'marks': _IPA_MARKS},
unparsed_syllable)
if not ipa_tone:
syllable, tone = unparsed_syllable, '5'
else:
for tone_number, tone_mark in _IPA... | You are a Python code generator, capable of creating scripts from specifications. |
def _restore_case(s, memory):
"""Restore a lowercase string's characters to their original case."""
cased_s = []
for i, c in enumerate(s):
if i + 1 > len(memory):
break
cased_s.append(c if memory[i] else c.upper())
return ''.join(cased_s) | How would you code a function in Python 3 to
restore a lowercase string s characters to their original case. | You are a Python code generator, capable of creating scripts from specifications. |
def numbered_syllable_to_accented(s):
"""Convert numbered Pinyin syllable *s* to an accented Pinyin syllable.
It implements the following algorithm to determine where to place tone
marks:
1. If the syllable has an 'a', 'e', or 'o' (in that order), put the
tone mark over that vowel.
2. Othe... | Implement a function in Python 3 to
convert a numbered Pinyin syllable to an accented Pinyin syllable. | You are a Python code analyst, evaluating scripts for potential improvements. |
def accented_syllable_to_numbered(s):
"""Convert accented Pinyin syllable *s* to a numbered Pinyin syllable."""
if s[0] == '\u00B7':
lowercase_syllable, case_memory = _lower_case(s[1:])
lowercase_syllable = '\u00B7' + lowercase_syllable
else:
lowercase_syllable, case_memory = _lower_... | Write a Python 3 script to
convert accented Pinyin syllable s to a numbered Pinyin syllable. | As a python code expert, you are capable of creating scripts from specifications. |
def pinyin_syllable_to_zhuyin(s):
"""Convert Pinyin syllable *s* to a Zhuyin syllable."""
pinyin_syllable, tone = _parse_pinyin_syllable(s)
try:
zhuyin_syllable = _PINYIN_MAP[pinyin_syllable.lower()]['Zhuyin']
except KeyError:
raise ValueError('Not a valid syllable: %s' % s)
return z... | How would you code a function in Python 3 to
convert a Pinyin syllable to a Zhuyin syllable. | As a python code expert, you are capable of creating scripts from specifications. |
Convert Pinyin syllable to an IPA syllable. | Given the following Python 3 function, write the documentation
def pinyin_syllable_to_ipa(s):
pinyin_syllable, tone = _parse_pinyin_syllable(s)
try:
ipa_syllable = _PINYIN_MAP[pinyin_syllable.lower()]['IPA']
except KeyError:
raise ValueError('Not a valid syllable: %s' % s)
return ipa_syl... | As a python code expert, you are capable of creating scripts from specifications. |
def _zhuyin_syllable_to_numbered(s):
"""Convert Zhuyin syllable *s* to a numbered Pinyin syllable."""
zhuyin_syllable, tone = _parse_zhuyin_syllable(s)
try:
pinyin_syllable = _ZHUYIN_MAP[zhuyin_syllable]['Pinyin']
except KeyError:
raise ValueError('Not a valid syllable: %s' % s)
retu... | Write a Python 3 script for
converting a Zhuyin syllable to a numbered Pinyin syllable. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _ipa_syllable_to_numbered(s):
"""Convert IPA syllable *s* to a numbered Pinyin syllable."""
ipa_syllable, tone = _parse_ipa_syllable(s)
try:
pinyin_syllable = _IPA_MAP[ipa_syllable]['Pinyin']
except KeyError:
raise ValueError('Not a valid syllable: %s' % s)
return pinyin_syllable... | How would you code a function in Python 3 to
convert an IPA syllable to a numbered Pinyin syllable. | You are a Python code generator, capable of creating scripts from specifications. |
def _convert(s, re_pattern, syllable_function, add_apostrophes=False,
remove_apostrophes=False, separate_syllables=False):
"""Convert a string's syllables to a different transcription system."""
original = s
new = ''
while original:
match = re.search(re_pattern, original, re.IGNOREC... | How would you implement a function in Python 3 that
converts a string s syllables to a different transcription system. | You are a Python code architect, reviewing and designing scalable and efficient code |
Convert all numbered Pinyin syllables in * s * to accented Pinyin. | Can you generate a brief explanation for the following Python 3 code
def numbered_to_accented(s):
return _convert(s, zhon.pinyin.syllable, numbered_syllable_to_accented,
add_apostrophes=True) | You are a Python code architect, reviewing and designing scalable and efficient code |
def pinyin_to_zhuyin(s):
"""Convert all Pinyin syllables in *s* to Zhuyin.
Spaces are added between connected syllables and syllable-separating
apostrophes are removed.
"""
return _convert(s, zhon.pinyin.syllable, pinyin_syllable_to_zhuyin,
remove_apostrophes=True, separate_syl... | Can you write a function in Python 3 where it
converts all Pinyin syllables in s to Zhuyin. | As a Python code analyst, you investigate and solve complex coding mysteries |
def pinyin_to_ipa(s):
"""Convert all Pinyin syllables in *s* to IPA.
Spaces are added between connected syllables and syllable-separating
apostrophes are removed.
"""
return _convert(s, zhon.pinyin.syllable, pinyin_syllable_to_ipa,
remove_apostrophes=True, separate_syllables=Tr... | How would you implement a function in Python 3 that
converts all Pinyin syllables in s to IPA. | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert all Zhuyin syllables in s to Pinyin syllables. | Make a summary of the following Python 3 code
def zhuyin_to_pinyin(s, accented=True):
if accented:
function = _zhuyin_syllable_to_accented
else:
function = _zhuyin_syllable_to_numbered
return _convert(s, zhon.zhuyin.syllable, function) | You are a Python code architect, reviewing and designing scalable and efficient code |
def ipa_to_pinyin(s, accented=True):
"""Convert all IPA syllables in *s* to Pinyin.
If *accented* is ``True``, diacritics are added to the Pinyin syllables. If
it's ``False``, numbers are used to indicate tone.
"""
if accented:
function = _ipa_syllable_to_accented
else:
functio... | How would you implement a function in Python 3 that
converts all IPA syllables in s to Pinyin syllables. | You are a Python code architect, reviewing and designing scalable and efficient code |
def to_pinyin(s, accented=True):
"""Convert *s* to Pinyin.
If *accented* is ``True``, diacritics are added to the Pinyin syllables. If
it's ``False``, numbers are used to indicate tone.
"""
identity = identify(s)
if identity == PINYIN:
if _has_accented_vowels(s):
return s i... | Implement a function in Python 3 to
convert a Chinese transcription string to a Pinyin syllab. | You are a Python code analyst, evaluating scripts for potential improvements. |
def to_zhuyin(s):
"""Convert *s* to Zhuyin."""
identity = identify(s)
if identity == ZHUYIN:
return s
elif identity == PINYIN:
return pinyin_to_zhuyin(s)
elif identity == IPA:
return ipa_to_zhuyin(s)
else:
raise ValueError("String is not a valid Chinese transcript... | Implement a function in Python 3 to
convert string s to Zhuyin. | As a python code expert, you are capable of creating scripts from specifications. |
Convert string s to IPA. | Make a summary of the following Python 3 code
def to_ipa(s):
identity = identify(s)
if identity == IPA:
return s
elif identity == PINYIN:
return pinyin_to_ipa(s)
elif identity == ZHUYIN:
return zhuyin_to_ipa(s)
else:
raise ValueError("String is not a valid Chinese tra... | 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.