output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def example_yaml(cls, skip=()):
"""
Generate an example yaml string for a Serializable subclass.
If traits have been tagged with an `example` value, then we use that
value. Otherwise we fall back the default_value for the instance.
"""
return cls.example_instance(skip=s... | Can you write a function in Python 3 where it
generates an example yaml string for a Serializable subclass. | As a python code expert, you are capable of creating scripts from specifications. |
def write_example_yaml(cls, dest, skip=()):
"""
Write a file containing an example yaml string for a Serializable
subclass.
"""
# Make sure we can make an instance before we open a file.
inst = cls.example_instance(skip=skip)
with open(dest, 'w') as f:
... | Create a Python 3 function to
write a file containing an example yaml string for a Serializable subclass. | You are a Python code architect, reviewing and designing scalable and efficient code |
Construct from base64 - encoded JSON. | Can you generate a brief explanation for the following Python 3 code
def to_base64(self, skip=()):
return base64.b64encode(
ensure_bytes(
self.to_json(skip=skip),
encoding='utf-8',
)
) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def to_environ(self, environ, skip=()):
"""
Serialize and write self to environ[self._envvar].
Parameters
----------
environ : dict-like
Dict-like object (e.g. os.environ) into which to write ``self``.
"""
environ[ensure_unicode(type(self).__name__)] ... | Implement a function in Python 3 to
serialize and write self into environ. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_one(self, object_id):
"""
Retrieve an object by its object_id
:param object_id: the objects id.
:return: the requested object
:raises: :class: NoResultFound when the object could not be found
"""
return self.session.query(self.cls).filter_by(id=object_id)... | How would you code a function in Python 3 to
retrieve an object by its object_id | You are a Python code analyst, evaluating scripts for potential improvements. |
Retrieve an object by its object_id | Can you tell what is the following Python 3 function doing
def get_one_for_update(self, object_id):
return self.session.query(self.cls).with_for_update().filter_by(id=object_id).one() | As a python code expert, you are capable of creating scripts from specifications. |
Retrieve an object by its object_id and class. | Given the following Python 3 function, write the documentation
def get(self, object_id, cls=None):
cls = self.cls if cls is None else cls
return self.session.query(cls).get(object_id) | You are a Python code architect, reviewing and designing scalable and efficient code |
Retrieve an object by its object_id and select for update on the row level lock. | Here you have a function in Python 3, explain what it does
def get_for_update(self, object_id, cls=None):
cls = self.cls if cls is None else cls
return self.session.query(cls).with_for_update().get(object_id) | As a Python code analyst, you investigate and solve complex coding mysteries |
def delete(self, object_id):
"""
Delete an object by its id
:param object_id: the objects id.
:return: the deleted object
:raises: :class: NoResultFound when the object could not be found
"""
obj = self.session.query(self.cls).filter_by(id=object_id).one()
... | How would you implement a function in Python 3 that
deletes an object by its id. | As a python code expert, you are capable of creating scripts from specifications. |
def save(self, obj):
"""
save an object
:param obj: the object
:return: the saved object
"""
if obj not in self.session:
self.session.add(obj)
else:
obj = self.session.merge(obj)
self.session.flush()
self.session.refresh(ob... | Create a Python 3 function for
saving an object to the session | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_sibling(self, feed_id, sibling_type):
"""
get a previous/next sibling from a feed
:param feed_id: id of the feed
:param sibling_type: sibling type ('previous', 'next')
:return: the sibling
"""
if sibling_type == 'previous':
query = self.session... | Write a Python 3 function for
getting a previous or next sibling from a feed | As a Python code analyst, you investigate and solve complex coding mysteries |
def save_object(self, obj):
"""
Save an object to the db
:param obj: the object to save
:return: the saved object
"""
self.session.add(obj)
self.session.flush()
return obj | Can you implement a function in Python 3 that
saves an object to the db | As a Python code analyst, you investigate and solve complex coding mysteries |
Retrieves the atom feed from the feed archive. | How would you explain what the following Python 3 function does
def get_from_archive(self, feed_id):
file_path = self.feed_repository + '/' + str(feed_id) + '.xml'
if not os.path.isfile(file_path):
raise FeedArchiveNotFound()
with open(file_path, 'r') as rec_file:
return ... | As a Python code analyst, you investigate and solve complex coding mysteries |
Get a specific feed entry by ID | Can you generate a brief explanation for the following Python 3 code
def get_atom_feed_entry(self, feedentry_id):
return self.session.query(self.feedentry_model).filter(
self.feedentry_model.id == feedentry_id
).one() | As a Python code composer, you craft elegant and concise scripts. |
def archive_feed(self, feed_id, feed):
"""
Archive a feed
:param feed_id: the feed id of the feed to archive
:param feed: the feed to archive
"""
with open(self.feed_repository + '/' + str(feed_id) + '.xml', 'w') as rec_file:
rec_file.write(feed.atom_str(prett... | Write a Python 3 script for
archiving a feed :param feed_id: the feed id of the feed to archive :param feed: the feed to archive | As a python code expert, you are capable of creating scripts from specifications. |
def add_named_concept_filters(self, named_filter_concepts):
"""
Adds named concept filters
:param named_filter_concepts: dict with named filter concepts which will be mapped as the key as query param and the value as search string
"""
for concept_key, concept_name in named_filte... | Can you write a function in Python 3 where it
adds named concept filters to the internal list of named concept resources. | You are a Python code architect, reviewing and designing scalable and efficient code |
def add_concept_filter(self, concept, concept_name=None):
"""
Add a concept filter
:param concept: concept which will be used as lowercase string in a search term
:param concept_name: name of the place where there will be searched for
"""
if concept in self.query_params.... | Write a Python 3 script to
add a concept filter to the search term | As a Python code translator, you convert algorithms and pseudocode into Python. |
Builds the query string which can be used for a search query | Here you have a function in Python 3, explain what it does
def build(self):
if self.es_version == '1':
if len(self.filters) > 0:
return {
'filtered': {
'query': self.query,
'filter': {
'an... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def parse(cls, request, default_start=0, default_end=9, max_end=50):
'''
Parse the range headers into a range object. When there are no range headers,
check for a page 'pagina' parameter, otherwise use the defaults defaults
:param request: a request object
:param default_start: ... | Implement a function in Python 3 to
parse the range headers into a range object. | As a Python code composer, you craft elegant and concise scripts. |
def set_response_headers(self, request, total_count):
'''
Set the correct range headers on the response
:param request: a request object
:param total_count: the total number of results
'''
response = request.response
response.headerlist.append(('Access-Control-Ex... | Write a Python 3 function that can
set the correct range headers on the response object. | You are a Python code analyst, evaluating scripts for potential improvements. |
Sets the Link headers on the response. | Here you have a function in Python 3, explain what it does
def set_link_headers(self, request, total_count):
response = request.response
if request.headers.get('Range'):
# Don't set the Link headers when custom ranges were used.
return
settings = request.registry.setting... | You are a Python code analyst, evaluating scripts for potential improvements. |
Colander validator that checks whether a given value is a valid Belgian national ID number. | Can you tell what is the following Python 3 function doing
def validator(node, rrn):
'''
Colander validator that checks whether a given value is a valid
Belgian national ID number .
:raises colander.Invalid: If the value is no valid Belgian national ID number.
'''
def _v... | As a python code expert, you are capable of creating scripts from specifications. |
def preparer(value):
'''
Edit a value to a value that can be validated as a
kbo number.
'''
if value is None or value == colander.null:
return colander.null
return value.strip().replace('.', '') | Can you implement a function in Python 3 that
edits a value to a value that can be validated as a kbo number. | As a Python code analyst, you investigate and solve complex coding mysteries |
This function takes a telefoon and returns a dictionary with the values that can be validated as a value. | Given the following Python 3 function, write the documentation
def preparer(telefoon):
'''
Edit a phone value to a value that can be validated as a
phone number.
This takes the incoming value and :
Removes all whitespace ( space, tab , newline , ... ) characters
R... | As a Python code analyst, you investigate and solve complex coding mysteries |
def validator(node, telefoon):
''' A valid international phone number looks like this: + .
It is up to 15 digits long . The country code consists of 1 to 4 digits.
The actual number may even 15 - cells ( country code) figures cover . We're going to keep the phone numbers including a + to indicat... | Write a Python 3 function that can
validate international phone number. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def cvm_unif_inf(statistic):
"""
Calculates the limiting distribution of the Cramer-von Mises statistic.
After the second line of equation 1.3 from the Csorgo and Faraway paper.
"""
args = inf_args / statistic
return (inf_cs * exp(-args) * kv(.25, args)).sum() / statistic ** .5 | Can you implement a function in Python 3 that
calculates the limiting distribution of the Cramer - von Mises statistic. | You are a Python code analyst, evaluating scripts for potential improvements. |
Compute the first term of the small sample count Gotze expansion. | Explain what the following Python 3 code does
def cvm_unif_fix1(statistic):
args = fix1_args / statistic
kvs = kv((.25, .75, 1.25), args[:, :, newaxis])
gs, hs = exp(-args) * tensordot(((1, 1, 0), (2, 3, -1)), kvs, axes=(1, 2))
a = dot((7, 16, 7), fix1_csa * gs).sum() / statistic ** 1.5
b = dot((1, ... | You are a Python code generator, capable of creating scripts from specifications. |
Merge together a sequence of dictionaries. | Explain what the following Python 3 code does
def merge(*ds):
if not ds:
raise ValueError("Must provide at least one dict to merge().")
out = {}
for d in ds:
out.update(d)
return out | As a Python code translator, you convert algorithms and pseudocode into Python. |
def sqlalchemy_validator(node, value, model, session=None, msg='%s is ongeldig'):
"""
Validate a sqlalchemy object or identifier.
Function checks if value is an instance of sqlalchemy model
or an id of one.
:param node: A colander SchemaNode.
:param value: The value to be validated. Is the key o... | Create a Python 3 function to
validate a sqlalchemy object or identifier. | As a Python code analyst, you investigate and solve complex coding mysteries |
def ks_stat(data):
"""
Calculates the Kolmogorov-Smirnov statistic for sorted values from U(0, 1).
"""
samples = len(data)
uniform = arange(0, samples + 1) / samples
d_plus = (uniform[1:] - data).max()
d_minus = (data - uniform[:-1]).max()
return max(d_plus, d_minus) | Implement a Python 3 function for
calculating the Kolmogorov - Smirnov statistic for sorted values from U 0 1. | You are a Python code generator, capable of creating scripts from specifications. |
Calculate the Cramer - von Mises statistic for sorted values from U 0 1. | Can you generate a brief explanation for the following Python 3 code
def cvm_stat(data):
samples2 = 2 * len(data)
minuends = arange(1, samples2, 2) / samples2
return 1 / (6 * samples2) + ((minuends - data) ** 2).sum() | You are a Python code analyst, evaluating scripts for potential improvements. |
def ad_stat(data):
"""
Calculates the Anderson-Darling statistic for sorted values from U(0, 1).
The statistic is not defined if any of the values is exactly 0 or 1. You
will get infinity as a result and a divide-by-zero warning for such values.
The warning can be silenced or raised using numpy.err... | Create a Python 3 function for
calculating the Anderson - Darling statistic for sorted values from U 0 1. | As a python code expert, you are capable of creating scripts from specifications. |
This function calculates the probability that the statistic is less than the given value. | Make a summary of the following Python 3 code
def ks_unif_durbin_matrix(samples, statistic):
# Construct the Durbin matrix.
h, k = modf(samples * statistic)
k = int(k)
h = 1 - h
m = 2 * k + 1
A = tri(m, k=1)
hs = h ** arange(1, m + 1)
A[:, 0] -= hs
A[-1] -= hs[::-1]
if h > .5:
... | As a python code expert, you are capable of creating scripts from specifications. |
Calculates the probability that the statistic is less than the given value. | Make a summary of the following Python 3 code
def ks_unif_durbin_recurrence_rational(samples, statistic):
t = statistic * samples
# Python 3: int()s can be skipped.
ft1 = int(floor(t)) + 1
fmt1 = int(floor(-t)) + 1
fdt1 = int(floor(2 * t)) + 1
qs = [Fraction(i ** i, factorial(i)) for i in range(... | You are a Python code analyst, evaluating scripts for potential improvements. |
def ks_unif_pelz_good(samples, statistic):
"""
Approximates the statistic distribution by a transformed Li-Chien formula.
This ought to be a bit more accurate than using the Kolmogorov limit, but
should only be used with large squared sample count times statistic.
See: doi:10.18637/jss.v039.i11 and... | Create a Python 3 function to
approximate the statistic distribution by a transformed Li-Chien formula. This ought to be a bit more accurate than using the Kolmogorov limit, but should only be used with large squared sample count times statistic. See: doi:10.18637/jss.v039.i11 and http://www.jstor.org/stable/2985019. | You are a Python code generator, capable of creating scripts from specifications. |
Activate the type safety checker. | Can you tell what is the following Python 3 function doing
def activate(self, *, filter_func=None):
'''
Activate the type safety checker. After the call all functions
that need to be checked will be.
'''
if self.active:
raise RuntimeError("Type safety check already a... | As a python code expert, you are capable of creating scripts from specifications. |
def audit(**kwargs):
"""
use this decorator to audit an operation
"""
def wrap(fn):
@functools.wraps(fn)
def advice(parent_object, *args, **kw):
request = parent_object.request
wijziging = request.audit_manager.create_revision()
result = fn(parent_o... | Write a Python 3 script for
using this decorator to audit an operation | As a Python code analyst, you investigate and solve complex coding mysteries |
def audit_with_request(**kwargs):
"""
use this decorator to audit an operation with a request as input variable
"""
def wrap(fn):
@audit(**kwargs)
def operation(parent_object, *args, **kw):
return fn(parent_object.request, *args, **kw)
@functools.wraps(fn)
de... | Can you create a Python 3 function that
uses this decorator to audit an operation with a request as input variable | You are a Python code generator, capable of creating scripts from specifications. |
def example_value(self):
"""
If we're an instance of a Serializable, fall back to its
`example_instance()` method.
"""
from .serializable import Serializable
inst = self._static_example_value()
if inst is tr.Undefined and issubclass(self.klass, Serializable):
... | Can you implement a function in Python 3 that
returns the instance of the class in which this instance is stored. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Copy a file and replace some placeholders with new values. | Can you generate a brief explanation for the following Python 3 code
def copy_and_replace(file_in, file_out, mapping, **kwargs):
'''
Copy a file and replace some placeholders with new values.
'''
separator = '@@'
if 'separator' in kwargs:
separator = kwargs['separator']
file_in = open(fi... | As a Python code analyst, you investigate and solve complex coding mysteries |
def coerce(cls, key, value):
"""
Convert plain list to MutableList.
"""
if not isinstance(value, MutableList):
if isinstance(value, list):
return MutableList(value)
# this call will raise ValueError
return Mutable.coerce(key, value)
... | Can you create a Python 3 function that
converts plain list to MutableList. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def registerWorker(self, name, worker):
"""
Register a new Worker, under the given descriptive name.
Trying to register multiple workers under the same name will raise an Exception.
Parameters
----------
name: string
Name to register the given worker under.
worker: multiprocessing.Process, or a subcl... | Write a Python 3 script to
register a new Worker under the given descriptive name. | As a Python code composer, you craft elegant and concise scripts. |
def getWorker(self, name):
"""
Retrieve the Worker registered under the given name.
If the given name does not exists in the Worker list, an Exception is raised.
Parameters
----------
name: string
Name of the Worker to retrieve
"""
if not name in self.worker_list:
self.logger.error("Worker {0} i... | Write a Python 3 function that can
retrieve the Worker registered under the given name. | As a Python code composer, you craft elegant and concise scripts. |
Unregister the Worker with the given name. | Can you tell what is the following Python 3 function doing
def unregisterWorker(self, name):
if not name in self.worker_list:
self.logger.error("Worker {0} is not registered!".format(name))
raise Exception("Worker {0} is not registered!".format(name))
del self.worker_list[name]
self.logger.debug("Unregiste... | You are a Python code generator, capable of creating scripts from specifications. |
Start all registered Workers. | How would you explain what the following Python 3 function does
def startAll(self):
self.logger.info("Starting all workers...")
for worker in self.getWorkers():
process = self.getWorker(worker)
self.logger.debug("Starting {0}".format(process.name))
process.start()
self.logger.info("Started all workers"... | As a Python code analyst, you investigate and solve complex coding mysteries |
Stop all registered Workers. | Can you tell what is the following Python 3 function doing
def stopAll(self, timeout=10, stop=False):
self.logger.info("Stopping all workers...")
for worker in self.getWorkers():
process = self.getWorker(worker)
self.logger.debug("Stopping {0}".format(process.name))
if process.is_alive():
process.join... | You are a Python code analyst, evaluating scripts for potential improvements. |
get the cached data for a given url | How would you explain what the following Python 3 function does
def get_cached_data(self, url):
key = self.get_key_from_url(url)
with self.conn as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM ensembl WHERE key=? AND genome_build=?",
... | As a python code expert, you are capable of creating scripts from specifications. |
Cache the data retrieved from the given URL and store it in the cache. | Given the following Python 3 function, write the documentation
def cache_url_data(self, url, data, attempt=0):
if attempt > 5:
raise ValueError('too many attempts at writing to the cache')
key = self.get_key_from_url(url)
# don't cache the ensembl version c... | As a Python code composer, you craft elegant and concise scripts. |
This function parses the url into a list of folder locations
and returns it as a string | Explain what the following Python 3 code does
def get_key_from_url(self, url):
key = url.split("/")[3:]
# fix the final bit of the url, none of which uniquely define the data
suffix = key.pop()
suffix = suffix.split(";")[0]
# convert "LONG_ID?feature=tr... | As a python code expert, you are capable of creating scripts from specifications. |
def cast_datetime_filter(value):
"""Cast a datetime filter value.
:param value: string representation of a value that needs to be casted to
a `datetime` object.
"""
if isinstance(value, str):
dtime = parse_datetime(value)
elif isinstance(value, datetime):
dtime = value
... | Implement a Python 3 function for
casting a datetime filter value to a datetime object. | You are a Python code analyst, evaluating scripts for potential improvements. |
Cast and validate filter args. | Given the following Python 3 function, write the documentation
def filter_args_to_dict(filter_dict, accepted_filter_keys=[]):
out_dict = {}
for k, v in filter_dict.items():
# make sure that the filter k is acceptable
# and that there is a value associated with the key
if k not in accepte... | You are a Python code analyst, evaluating scripts for potential improvements. |
Bencodes obj and returns it as a string | How would you explain what the following Python 3 function does
def bencode(obj):
if isinstance(obj, int):
return "i" + str(obj) + "e"
if isinstance(obj, str):
if not obj:
return None
return str(len(obj)) + ":" + obj
if isinstance(obj, list):
res = "l"
f... | As a Python code composer, you craft elegant and concise scripts. |
def bdecode(text):
"""Decodes a bencoded bytearray and returns it as a python object"""
text = text.decode('utf-8')
def bdecode_next(start):
"""bdecode helper function"""
if text[start] == 'i':
end = text.find('e', start)
return int(text[start+1:end], 10), end + 1
... | Implement a function in Python 3 to
decode a bencoded bytearray and returns it as a python object | As a Python code composer, you craft elegant and concise scripts. |
def change_password():
"""
Changes the standard password from neo4j to testing to be able to run the test suite.
"""
basic_auth = '%s:%s' % (DEFAULT_USERNAME, DEFAULT_PASSWORD)
try: # Python 2
auth = base64.encodestring(basic_auth)
except TypeError: # Python 3
auth = base64.enc... | Can you implement a function in Python 3 that
changes the standard password from neo4j to testing to be able to run the test suite. | As a python code expert, you are capable of creating scripts from specifications. |
def get_config_argparse(suppress=None):
"""
Create an ArgumentParser which listens for the following common options:
- --config
- --help
- --quiet
- --verbose
- --version
Arguments
---------
suppress_help: list of strings
Defines what options to suppress from being added to the ArgumentParser. Provide
th... | Can you create a Python 3 function that
creates an ArgumentParser which listens for common options and adds them to the config file. | You are a Python code generator, capable of creating scripts from specifications. |
This method parses the command line arguments and returns a tuple containing parsed variables and unknown variables. | How would you explain what the following Python 3 function does
def get_config_arguments():
logger = logging.getLogger(__name__)
logger.debug("Parsing configuration arguments")
return get_config_argparse(suppress=["help"]).parse_known_args() | As a Python code translator, you convert algorithms and pseudocode into Python. |
This method will take an ArgumentParser and return a ConfigObj compatible configuration file. | Can you generate a brief explanation for the following Python 3 code
def get_default_config_file(argparser, suppress=None, default_override=None):
if not suppress:
suppress = []
if not default_override:
default_override = {}
lines = []
seen_arguments = []
for arg in argparser._actions:
if arg.dest in suppre... | You are a Python code analyst, evaluating scripts for potential improvements. |
Perform the binds on the queue | Can you generate a brief explanation for the following Python 3 code
def _perform_binds(self, binds):
for bind in binds:
self.logger.debug("Binding queue {0} to exchange {1} with key {2}".format(bind['queue'], bind['exchange'], bind['routing_key']))
self.channel.queue_bind(**bind) | You are a Python code architect, reviewing and designing scalable and efficient code |
Unbinds queues from exchanges. | Given the following Python 3 function, write the documentation
def _perform_unbinds(self, binds):
for bind in binds:
self.logger.debug("Unbinding queue {0} from exchange {1} with key {2}".format(bind['queue'], bind['exchange'], bind['routing_key']))
self.channel.queue_unbind(**bind) | As a python code expert, you are capable of creating scripts from specifications. |
Closes the internal connection. | Given the following Python 3 function, write the documentation
def close(self):
self.cancel()
self.logger.debug("Closing AMQP connection")
try:
self.connection.close()
except Exception, eee:
self.logger.warning("Received an error while trying to close AMQP connection: " + str(eee)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Cancels the current consuming action by using the stored consumer_tag. | Explain what the following Python 3 code does
def cancel(self, consumer_tag=None):
if not consumer_tag:
if not hasattr(self, "consumer_tag"):
return
consumer_tag = self.consumer_tag
self.channel.basic_cancel(consumer_tag) | As a python code expert, you are capable of creating scripts from specifications. |
This method is used to start consuming messages from an AMQP queue. | How would you explain what the following Python 3 function does
def consume(self, consumer_callback, exclusive=False, recover=False):
if recover:
self.logger.info("Asking server to requeue all unacknowledged messages")
self.channel.basic_recover(requeue=True)
self.consumer_tag = self.channel.basic_consume(con... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def json_get(parsed_json, key):
"""
Retrieves the key from a parsed_json dictionary, or raises an exception if the
key is not present
"""
if key not in parsed_json:
raise ValueError("JSON does not contain a {} field".format(key))
return parsed_json[key] | Implement a function in Python 3 to
retrieve the key from a parsed_json dictionary | As a Python code composer, you craft elegant and concise scripts. |
def readme(fname):
"""Reads a markdown file and returns the contents formatted as rst"""
md = open(os.path.join(os.path.dirname(__file__), fname)).read()
output = md
try:
import pypandoc
output = pypandoc.convert(md, 'rst', format='md')
except ImportError:
pass
return out... | How would you code a function in Python 3 to
read a markdown file and returns the contents formatted as rst | You are a Python code analyst, evaluating scripts for potential improvements. |
Load a configuration file from multiple locations and merge the results into one. | How would you explain what the following Python 3 function does
def get_config(config_base, custom_file=None, configspec=None):
logger = logging.getLogger(__name__)
logger.debug("Expanding variables")
home = os.path.expanduser("~")
loc = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_config_dir(path, pattern="*.config", configspec=None, allow_errors=False):
"""
Load an entire directory of configuration files, merging them into one.
This function will load multiple configuration files matching the given pattern,
in the given path, and merge them. The found files are first sorted alphabe... | Write a Python 3 script to
load an entire directory of configuration files, merging them into one. This function will load multiple configuration files matching the given pattern, in the given path, and merge them. The found files are first sorted alphabetically, and then loaded and merged. A good practice is to use Co... | You are a Python code analyst, evaluating scripts for potential improvements. |
Check to see if self has been resolved yet invoke then. | Make a summary of the following Python 3 code
def _try_then(self):
if self._cached is not None and self._callback is not None:
self._callback(*self._cached[0], **self._cached[1]) | You are a Python code architect, reviewing and designing scalable and efficient code |
Wrapper for opening an IO object to a local file or URL. | Here you have a function in Python 3, explain what it does
def open(path_or_url):
is_url = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain...
r'localhost|' # localhost...
r'\d{1,3... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Determine if the value is a primitive | Given the following Python 3 function, write the documentation
def _is_primitive(thing):
primitive = (int, str, bool, float)
return isinstance(thing, primitive) | You are a Python code architect, reviewing and designing scalable and efficient code |
Guess the type of the parameter based off the default value if unknown use text | Can you generate the documentation for the following Python 3 function
def _guess_type(val):
if isinstance(val, bool):
return "choice"
elif isinstance(val, int):
return "number"
elif isinstance(val, float):
return "number"
elif isinstance(val, str):
... | As a python code expert, you are capable of creating scripts from specifications. |
def _params(sig):
"""Read params, values and annotations from the signature"""
params = []
for p in sig.parameters:
param = sig.parameters[p]
optional = param.default != inspect.Signature.empty
default = UIBuilder._safe_default(param.default) if param.default ... | Write a Python 3 script to
read params values and annotations from the signature and return a list of dictionaries. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _import(func):
"""Return the namespace path to the function"""
func_name = func.__name__
# from foo.bar import func // func()
# WARNING: May be broken in IPython, in which case the widget will use a fallback
if func_name in globals():
return func_name
# ... | Can you implement a function in Python 3 that
returns the namespace path to the function | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_logger(name=None, level=logging.NOTSET, handlers=None):
"""
Create a Python logging Logger for the given name. A special case is
when the name is None, as this will represent the root Logger object.
When handlers are specified, the currently configured handlers for this name
are removed, and the specified... | How would you implement a function in Python 3 that
returns a Python logging Logger object for the given name and level. | As a Python code composer, you craft elegant and concise scripts. |
Load the de novo data into a dictionary indexed by HGNC ID. | Make a summary of the following Python 3 code
def load_de_novos(path, exclude_indels=True):
genes = {}
with open(path, "r") as handle:
header = handle.readline().strip().split("\t")
for line in handle:
line = line.rstrip().split("\t")
gene = line[0]
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def registerThread(self, name, thread):
"""
Register a new Thread , under the given descriptive name.
Trying to register multiple threads under the same name will raise an Exception.
Parameters
----------
name: string
Name to register the given thread under.
thread: threading.Thread, or a subclass
... | Can you create a Python 3 function that
registers a new Thread , under the given descriptive name. Trying to register multiple threads under the same name will raise an Exception. Parameters ---------- name: string Name to register the given thread under. thread: threading.Thread, or a subclass Thread object to registe... | As a python code expert, you are capable of creating scripts from specifications. |
Retrieve the Thread registered under the given name. | Here you have a function in Python 3, explain what it does
def getThread(self, name):
if not name in self.thread_list:
self.logger.error("Thread {0} is not registered!".format(name))
raise Exception("Thread {0} is not registered!".format(name))
return self.thread_list[name] | As a python code expert, you are capable of creating scripts from specifications. |
Unregister the Thread with the given name. | Given the following Python 3 function, write the documentation
def unregisterThread(self, name):
if not name in self.thread_list:
self.logger.error("Thread {0} is not registered!".format(name))
raise Exception("Thread {0} is not registered!".format(name))
del self.thread_list[name]
self.logger.debug("Unreg... | You are a Python code architect, reviewing and designing scalable and efficient code |
Start all registered Threads.
Start all registered Threads.
| Can you generate the documentation for the following Python 3 function
def startAll(self):
self.logger.info("Starting all threads...")
for thread in self.getThreads():
thr = self.getThread(thread)
self.logger.debug("Starting {0}".format(thr.name))
thr.start()
self.logger.info("Started all threads") | As a Python code translator, you convert algorithms and pseudocode into Python. |
def stopAll(self, stop=False):
"""
Stop all registered Threads. This is method assumes that the Thread is using
and internal variable called stop to control its main loop. Stopping a Thread
is achieved as follows:
1. The Thread is retrieved.
2. $thread.stop is set to False.
3. The Thread is joined, and w... | Can you implement a function in Python 3 that
stops all registered Threads. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the current UserSettings based on the SITE_ID in the project s settings as context variables
| Explain what the following Python 3 code does
def usersettings(request):
if hasattr(request, 'usersettings'):
usersettings = request.usersettings
else:
from .shortcuts import get_current_usersettings
usersettings = get_current_usersettings()
return {
'usersettings': usersett... | You are a Python code architect, reviewing and designing scalable and efficient code |
def check_ensembl_api_version(self):
""" check the ensembl api version matches a currently working version
This function is included so when the api version changes, we notice the
change, and we can manually check the responses for the new version.
"""
self.atte... | Write a Python 3 script for
checking the ensembl api version matches a currently working version | You are a Python code generator, capable of creating scripts from specifications. |
open url with python libraries and return the response and status code and headers | Explain what the following Python 3 code does
def open_url(self, url, headers):
data = self.cache.get_cached_data(url)
if data is not None:
return data, 200, headers
self.rate_limit_ensembl_requests()
req = request.Request(url, headers=headers)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def ensembl_request(self, ext, headers):
""" obtain sequence via the ensembl REST API
"""
self.attempt += 1
if self.attempt > 5:
raise ValueError("too many attempts, figure out why its failing")
response, status, requested_headers = self.open_url(sel... | Write a Python 3 function for
obtaining sequence via the ensembl REST API | As a python code expert, you are capable of creating scripts from specifications. |
def get_genes_for_hgnc_id(self, hgnc_symbol):
""" obtain the ensembl gene IDs that correspond to a HGNC symbol
"""
headers = {"content-type": "application/json"}
# http://grch37.rest.ensembl.org/xrefs/symbol/homo_sapiens/KMT2A?content-type=application/json
... | Implement a Python 3 function for
getting the ensembl gene IDs that correspond to a HGNC symbol | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function is used to get the previous HGNC symbol from the server. | Can you generate the documentation for the following Python 3 function
def get_previous_symbol(self, hgnc_symbol):
ensembl_server = self.server
gene_names_server = "http://rest.genenames.org"
self.server = gene_names_server
headers = {"accept": "application/json", "cont... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_transcript_ids_for_ensembl_gene_ids(self, gene_ids, hgnc_symbols):
""" fetch the ensembl transcript IDs for a given ensembl gene ID.
Args:
gene_ids: list of Ensembl gene IDs for the gene
hgnc_symbols: list of possible HGNC symbols for gene
"""
... | How would you implement a function in Python 3 that
fetches the ensembl transcript IDs for a given list of ensembl gene IDs | As a Python code composer, you craft elegant and concise scripts. |
def get_genomic_seq_for_transcript(self, transcript_id, expand):
""" obtain the sequence for a transcript from ensembl
"""
headers = {"content-type": "application/json"}
self.attempt = 0
ext = "/sequence/id/{0}?type=genomic;expand_3prime={1};expand_5prime={1}".f... | Can you create a Python 3 function that
gets the genomic sequence for a given transcript | You are a Python code generator, capable of creating scripts from specifications. |
get the sequence for a transcript | How would you explain what the following Python 3 function does
def get_cds_seq_for_transcript(self, transcript_id):
headers = {"content-type": "text/plain"}
self.attempt = 0
ext = "/sequence/id/{}?type=cds".format(transcript_id)
return self.ensembl_request(ext... | As a Python code translator, you convert algorithms and pseudocode into Python. |
get the sequence for a given transcript | Make a summary of the following Python 3 code
def get_protein_seq_for_transcript(self, transcript_id):
headers = {"content-type": "text/plain"}
self.attempt = 0
ext = "/sequence/id/{}?type=protein".format(transcript_id)
return self.ensembl_request(ext, headers) | You are a Python code analyst, evaluating scripts for potential improvements. |
get the genomic sequence for a region | Make a summary of the following Python 3 code
def get_genomic_seq_for_region(self, chrom, start_pos, end_pos):
headers = {"content-type": "text/plain"}
self.attempt = 0
ext = "/sequence/region/human/{}:{}..{}:1".format(chrom, start_pos, end_pos)
return self.ens... | You are a Python code architect, reviewing and designing scalable and efficient code |
obtain the chrom of the sequence for a given transcript | Given the following Python 3 function, write the documentation
def get_chrom_for_transcript(self, transcript_id, hgnc_id):
headers = {"content-type": "application/json"}
self.attempt = 0
ext = "/overlap/id/{}?feature=gene".format(transcript_id)
r = self.ensembl_request... | You are a Python code architect, reviewing and designing scalable and efficient code |
get the range of the exon that overlap a given transcript | Can you tell what is the following Python 3 function doing
def get_exon_ranges_for_transcript(self, transcript_id):
headers = {"content-type": "application/json"}
self.attempt = 0
ext = "/overlap/id/{}?feature=exon".format(transcript_id)
r = self.ensembl_request(ext, he... | You are a Python code analyst, evaluating scripts for potential improvements. |
get the sequence for a given transcript | Make a summary of the following Python 3 code
def get_cds_ranges_for_transcript(self, transcript_id):
headers = {"content-type": "application/json"}
self.attempt = 0
ext = "/overlap/id/{}?feature=cds".format(transcript_id)
r = self.ensembl_request(ext, headers)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
limit ensembl requests to one per 0. 0067 s
| How would you explain what the following Python 3 function does
def rate_limit_ensembl_requests(self):
current_time = time.time()
diff_time = current_time - self.prior_time
# sleep until the current rate limit period is finished
if diff_time < self.rate_limit:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def register(nbtool):
"""
Register the provided NBTool object
"""
global _py_funcs
_lazy_init()
# Save references to the tool's load() and render() functions
load_key = nbtool.origin + '|' + nbtool.id + '|load'
render_key = nbtool.origin + '|' + nbtool.id + '|render'
_py_funcs[load_... | Write a Python 3 function that can
register a NBTool object with the NBToolManager. | You are a Python code generator, capable of creating scripts from specifications. |
Wrapper around SimpleCliTool. Simple. | Can you generate a brief explanation for the following Python 3 code
def call_simple_cli(command, cwd=None, universal_newlines=False, redirect_stderr=False):
return SimpleCliTool()._call_cli(command, cwd, universal_newlines, redirect_stderr) | You are a Python code architect, reviewing and designing scalable and efficient code |
def _call_cli(self, command, cwd=None, universal_newlines=False, redirect_stderr=False):
"""
Executes the given command, internally using Popen. The output of
stdout and stderr are returned as a tuple. The returned tuple looks
like: (stdout, stderr, returncode)
Parameters
----------
command: string
Th... | Can you implement a function in Python 3 that
executes a command in the specified working directory and returns the output of the command. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Handle messages from the front - end. | Make a summary of the following Python 3 code
def _on_msg(self, msg):
data = msg['content']['data']
# If the message is a call invoke, run the function and send
# the results.
if 'callback' in data:
guid = data['callback']
callback = callback_registry[guid]
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def serialize(self, obj):
"""Serialize an object for sending to the front-end."""
if hasattr(obj, '_jsid'):
return {'immutable': False, 'value': obj._jsid}
else:
obj_json = {'immutable': True}
try:
json.dumps(obj)
obj_json['valu... | Write a Python 3 script to
serialize an object for sending to the front - end. | As a Python code composer, you craft elegant and concise scripts. |
Deserialize an object from the front - end. | Can you generate a brief explanation for the following Python 3 code
def deserialize(self, obj):
if obj['immutable']:
return obj['value']
else:
guid = obj['value']
if not guid in object_registry:
instance = JSObject(self, guid)
object_r... | As a Python code composer, you craft elegant and concise scripts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.