output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Resolve occurences by expansion | How would you explain what the following Python 3 function does
def _resolve_references(templates):
def repl(match):
lib.echo("Deprecation warning: The {@ref} syntax is being removed")
key = pattern[match.start():match.end()].strip("@{}")
if key not in templates:
sys.stderr.writ... | As a Python code analyst, you investigate and solve complex coding mysteries |
def add(self, key, val):
"""Adds a (name, value) pair, doesn't overwrite the value if it already
exists.
>>> headers = HTTPHeaderDict(foo='bar')
>>> headers.add('Foo', 'baz')
>>> headers['foo']
'bar, baz'
"""
key_lower = key.lower()
new_vals = key... | Write a Python 3 function for
adding a ( name value ) pair to the dictionary. Doesn t overwrite the value if it already exists. | You are a Python code generator, capable of creating scripts from specifications. |
Returns a list of all the values for the named field. Returns an empty list if the key doesn t exist. Returns an empty list if the key doesn t exist. Returns an empty list if the key doesn t exist. Returns an empty list if the key doesn t exist. Returns an empty list if the key doesn t exist. Returns an empty list if t... | Given the following Python 3 function, write the documentation
def getlist(self, key):
try:
vals = _dict_getitem(self, key.lower())
except KeyError:
return []
else:
if isinstance(vals, tuple):
return [vals[1]]
else:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def iteritems(self):
"""Iterate over all header lines, including duplicate ones."""
for key in self:
vals = _dict_getitem(self, key)
for val in vals[1:]:
yield vals[0], val | Create a Python 3 function to
iterate over all header lines including duplicate ones. | As a python code expert, you are capable of creating scripts from specifications. |
def itermerged(self):
"""Iterate over all headers, merging duplicate ones together."""
for key in self:
val = _dict_getitem(self, key)
yield val[0], ', '.join(val[1:]) | How would you implement a function in Python 3 that
iterates over all headers merging duplicate ones together. | You are a Python code generator, capable of creating scripts from specifications. |
def from_httplib(cls, message, duplicates=('set-cookie',)): # Python 2
"""Read headers from a Python 2 httplib message object."""
ret = cls(message.items())
# ret now contains only the last header line for each duplicate.
# Importing with all duplicates would be nice, but this would
... | Implement a function in Python 3 to
read headers from a Python 2 httplib message object. | As a python code expert, you are capable of creating scripts from specifications. |
def request_encode_url(self, method, url, fields=None, **urlopen_kw):
"""
Make a request using :meth:`urlopen` with the ``fields`` encoded in
the url. This is useful for request methods like GET, HEAD, DELETE, etc.
"""
if fields:
url += '?' + urlencode(fields)
... | Can you implement a function in Python 3 that
makes a request using the method url and fields encoded in | As a python code expert, you are capable of creating scripts from specifications. |
def make_str(value):
"""Converts a value into a valid string."""
if isinstance(value, bytes):
try:
return value.decode(sys.getfilesystemencoding())
except UnicodeError:
return value.decode('utf-8', 'replace')
return text_type(value) | Create a Python 3 function to
convert a value into a valid string. | As a python code expert, you are capable of creating scripts from specifications. |
Prints a message to the given file or stdout. | Explain what the following Python 3 code does
def echo(message=None, file=None, nl=True, err=False, color=None):
if file is None:
if err:
file = _default_text_stderr()
else:
file = _default_text_stdout()
# Convert non bytes/text into the native string type.
if messag... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Determine the parent shell for the currently running shell. | Given the following Python 3 function, write the documentation
def parent():
if self._parent:
return self._parent
if "BE_SHELL" in os.environ:
self._parent = os.environ["BE_SHELL"]
else:
# If a shell is not provided, rely on `psutil`
# to look at the calling process name.
... | You are a Python code generator, capable of creating scripts from specifications. |
Return the platform for the current shell e. g. windows unix or unix | How would you explain what the following Python 3 function does
def platform():
executable = parent()
basename = os.path.basename(executable)
basename, _ = os.path.splitext(basename)
if basename in ("bash", "sh"):
return "unix"
if basename in ("cmd", "powershell"):
return "windows"
... | You are a Python code generator, capable of creating scripts from specifications. |
Determine subshell command for subprocess. call
Arguments : parent (str ) : Absolute path to parent shell executable | Here you have a function in Python 3, explain what it does
def cmd(parent):
shell_name = os.path.basename(parent).rsplit(".", 1)[0]
dirname = os.path.dirname(__file__)
# Support for Bash
if shell_name in ("bash", "sh"):
shell = os.path.join(dirname, "_shell.sh").replace("\\", "/")
cmd... | As a Python code composer, you craft elegant and concise scripts. |
def context(root, project=""):
"""Produce the be environment
The environment is an exact replica of the active
environment of the current process, with a few
additional variables, all of which are listed below.
"""
environment = os.environ.copy()
environment.update({
"BE_PROJECT":... | Can you implement a function in Python 3 that
produces the active be environment with additional variables and values listed below. | As a Python code analyst, you investigate and solve complex coding mysteries |
def random_name():
"""Return a random name
Example:
>> random_name()
dizzy_badge
>> random_name()
evasive_cactus
"""
adj = _data.adjectives[random.randint(0, len(_data.adjectives) - 1)]
noun = _data.nouns[random.randint(0, len(_data.nouns) - 1)]
return "%s_%s" ... | Write a Python 3 script to
return a random name of the available adjective and nouns. | You are a Python code architect, reviewing and designing scalable and efficient code |
def isproject(path):
"""Return whether or not `path` is a project
Arguments:
path (str): Absolute path
"""
try:
if os.path.basename(path)[0] in (".", "_"):
return False
if not os.path.isdir(path):
return False
if not any(fname in os.listdir(path... | Can you implement a function in Python 3 that
returns whether or not path is a project | You are a Python code analyst, evaluating scripts for potential improvements. |
Print to the console
| Make a summary of the following Python 3 code
def echo(text, silent=False, newline=True):
if silent:
return
print(text) if newline else sys.stdout.write(text) | You are a Python code generator, capable of creating scripts from specifications. |
List all projects at root | Explain what the following Python 3 code does
def list_projects(root, backend=os.listdir):
projects = list()
for project in sorted(backend(root)):
abspath = os.path.join(root, project)
if not isproject(abspath):
continue
projects.append(project)
return projects | You are a Python code generator, capable of creating scripts from specifications. |
List a projects inventory
Given a project simply list the contents of the inventory. yaml | Make a summary of the following Python 3 code
def list_inventory(inventory):
inverted = invert_inventory(inventory)
items = list()
for item in sorted(inverted, key=lambda a: (inverted[a], a)):
items.append((item, inverted[item]))
return items | You are a Python code architect, reviewing and designing scalable and efficient code |
def list_template(root, topics, templates, inventory, be, absolute=False):
"""List contents for resolved template
Resolve a template as far as possible via the given `topics`.
For example, if a template supports 5 arguments, but only
3 are given, resolve the template until its 4th argument
and list... | Implement a function in Python 3 to
list contents for resolved template | You are a Python code generator, capable of creating scripts from specifications. |
def invert_inventory(inventory):
"""Return {item: binding} from {binding: item}
Protect against items with additional metadata
and items whose type is a number
Returns:
Dictionary of inverted inventory
"""
inverted = dict()
for binding, items in inventory.iteritems():
for... | Implement a function in Python 3 to
invert the inventory by removing items with additional metadata and items whose type is a number | You are a Python code analyst, evaluating scripts for potential improvements. |
Return absolute path to development directory | Can you tell what is the following Python 3 function doing
def pos_development_directory(templates,
inventory,
context,
topics,
user,
item):
"""Return absolute path t... | You are a Python code analyst, evaluating scripts for potential improvements. |
def fixed_development_directory(templates, inventory, topics, user):
"""Return absolute path to development directory
Arguments:
templates (dict): templates.yaml
inventory (dict): inventory.yaml
context (dict): The be context, from context()
topics (list): Arguments to `in`
... | How would you implement a function in Python 3 that
returns absolute path to development directory | You are a Python code generator, capable of creating scripts from specifications. |
Convert context replacement fields from BE_KEY to key = value | Given the following Python 3 function, write the documentation
def replacement_fields_from_context(context):
return dict((k[3:].lower(), context[k])
for k in context if k.startswith("BE_")) | You are a Python code architect, reviewing and designing scalable and efficient code |
Get binding from topics via key | How would you explain what the following Python 3 function does
def item_from_topics(key, topics):
if re.match("{\d+}", key):
pos = int(key.strip("{}"))
try:
binding = topics[pos]
except IndexError:
raise IndexError(pos + 1)
else:
echo("be.yaml template ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return pattern for name
| Given the following Python 3 function, write the documentation
def pattern_from_template(templates, name):
if name not in templates:
echo("No template named \"%s\"" % name)
sys.exit(1)
return templates[name] | You are a Python code generator, capable of creating scripts from specifications. |
Return the binding for item | Can you generate the documentation for the following Python 3 function
def binding_from_item(inventory, item):
if item in self.bindings:
return self.bindings[item]
bindings = invert_inventory(inventory)
try:
self.bindings[item] = bindings[item]
return bindings[item]
except Ke... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Resolve environment variables and fields from the be. yaml file. | Here you have a function in Python 3, explain what it does
def parse_environment(fields, context, topics):
def _resolve_environment_lists(context):
"""Concatenate environment lists"""
for key, value in context.copy().iteritems():
if isinstance(value, list):
context[key] ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Resolve the be. yaml redirect key
| Here you have a function in Python 3, explain what it does
def parse_redirect(redirect, topics, context):
for map_source, map_dest in redirect.items():
if re.match("{\d+}", map_source):
topics_index = int(map_source.strip("{}"))
topics_value = topics[topics_index]
contex... | You are a Python code architect, reviewing and designing scalable and efficient code |
Slice a template based on it s positional argument | Can you tell what is the following Python 3 function doing
def slice(index, template):
try:
return re.match("^.*{[%i]}" % index, template).group()
except AttributeError:
raise ValueError("Index %i not found in template: %s"
% (index, template)) | You are a Python code generator, capable of creating scripts from specifications. |
def proxy_manager_for(self, proxy, **proxy_kwargs):
"""Return urllib3 ProxyManager for the given proxy.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxy: The prox... | Create a Python 3 function to
return a urllib3 ProxyManager for the given proxy. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Verify a SSL certificate. | How would you explain what the following Python 3 function does
def cert_verify(self, conn, url, verify, cert):
if url.lower().startswith('https') and verify:
cert_loc = None
# Allow self-specified cert location.
if verify is not True:
cert_loc = verify
... | As a Python code composer, you craft elegant and concise scripts. |
Returns a urllib3 connection for the given URL. | Can you generate the documentation for the following Python 3 function
def get_connection(self, url, proxies=None):
proxies = proxies or {}
proxy = proxies.get(urlparse(url.lower()).scheme)
if proxy:
proxy = prepend_scheme_if_needed(proxy, 'http')
proxy_manager = self.pr... | As a python code expert, you are capable of creating scripts from specifications. |
Obtain the url to use when making the final request. | Can you generate the documentation for the following Python 3 function
def request_url(self, request, proxies):
proxies = proxies or {}
scheme = urlparse(request.url).scheme
proxy = proxies.get(scheme)
if proxy and scheme != 'https':
url = urldefragauth(request.url)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a dictionary of the headers to add to any request sent
through a proxy. | Can you generate the documentation for the following Python 3 function
def proxy_headers(self, proxy):
headers = {}
username, password = get_auth_from_url(proxy)
if username and password:
headers['Proxy-Authorization'] = _basic_auth_str(username,
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def request(method, url, **kwargs):
"""Constructs and sends a :class:`Request <Request>`.
:param method: method for the new :class:`Request` object.
:param url: URL for the new :class:`Request` object.
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`... | Write a Python 3 script to
construct and sends a new request object. | As a Python code analyst, you investigate and solve complex coding mysteries |
def is_connection_dropped(conn): # Platform-specific
"""
Returns True if the connection is dropped and should be closed.
:param conn:
:class:`httplib.HTTPConnection` object.
Note: For platforms like AppEngine, this will always return ``False`` to
let the platform handle connection recycli... | Write a Python 3 function that can
return True if the connection is dropped and should be closed. | You are a Python code generator, capable of creating scripts from specifications. |
Convert a Morsel object into a Cookie containing the one k - v pair. | Can you generate the documentation for the following Python 3 function
def morsel_to_cookie(morsel):
expires = None
if morsel['max-age']:
expires = time.time() + morsel['max-age']
elif morsel['expires']:
time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
expires = time.mktime(
... | As a python code expert, you are capable of creating scripts from specifications. |
Takes as an argument an optional domain and path and returns a plain
old Python dict of name - value pairs of cookies that meet the
requirements. | Given the following Python 3 function, write the documentation
def get_dict(self, domain=None, path=None):
dictionary = {}
for cookie in iter(self):
if (domain is None or cookie.domain == domain) and (path is None
or cookie.path == path):
... | You are a Python code architect, reviewing and designing scalable and efficient code |
feed a character with known length | Here you have a function in Python 3, explain what it does
def feed(self, aBuf, aCharLen):
if aCharLen == 2:
# we only care about 2-bytes character in our distribution analysis
order = self.get_order(aBuf)
else:
order = -1
if order >= 0:
self._mTot... | You are a Python code analyst, evaluating scripts for potential improvements. |
return confidence based on existing data | Can you tell what is the following Python 3 function doing
def get_confidence(self):
# if we didn't receive any character in our consideration range,
# return negative answer
if self._mTotalChars <= 0 or self._mFreqChars <= MINIMUM_DATA_THRESHOLD:
return SURE_NO
if self._mTo... | As a Python code composer, you craft elegant and concise scripts. |
Helper for quickly adding a StreamHandler to the logger. Useful for debugging. | Can you generate a brief explanation for the following Python 3 code
def add_stderr_logger(level=logging.DEBUG):
# This method needs to be in this __init__.py to get the __name__ correct
# even if urllib3 is vendored within another package.
logger = logging.getLogger(__name__)
handler = logging.StreamHa... | You are a Python code architect, reviewing and designing scalable and efficient code |
def assert_fingerprint(cert, fingerprint):
"""
Checks if given fingerprint matches the supplied certificate.
:param cert:
Certificate as bytes object.
:param fingerprint:
Fingerprint as string of hexdigits, can be interspersed by colons.
"""
# Maps the length of a digest to a p... | Implement a Python 3 function for
checking if given fingerprint matches the supplied certificate. | You are a Python code generator, capable of creating scripts from specifications. |
def create_urllib3_context(ssl_version=None, cert_reqs=ssl.CERT_REQUIRED,
options=None, ciphers=None):
"""All arguments have the same meaning as ``ssl_wrap_socket``.
By default, this function does a lot of the same work that
``ssl.create_default_context`` does on Python 3.4+. It:... | Can you write a function in Python 3 where it
creates a new SSLContext object with the specified options and cipher suites. | You are a Python code analyst, evaluating scripts for potential improvements. |
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
ca_certs=None, server_hostname=None,
ssl_version=None, ciphers=None, ssl_context=None):
"""
All arguments except for server_hostname and ssl_context have the same
meaning as they do when using :fun... | Implement a function in Python 3 to
wrap for ssl. wrap_socket. | As a Python code analyst, you investigate and solve complex coding mysteries |
Given a url return an instance of a : class :. ConnectionPool instance of its host. | Given the following Python 3 function, write the documentation
def connection_from_url(url, **kw):
scheme, host, port = get_host(url)
if scheme == 'https':
return HTTPSConnectionPool(host, port=port, **kw)
else:
return HTTPConnectionPool(host, port=port, **kw) | As a python code expert, you are capable of creating scripts from specifications. |
def _put_conn(self, conn):
"""
Put a connection back into the pool.
:param conn:
Connection object for the current host and port as returned by
:meth:`._new_conn` or :meth:`._get_conn`.
If the pool is already full, the connection is closed and discarded
... | How would you implement a function in Python 3 that
puts a connection into the pool. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Perform a request on a given urllib connection object. | Make a summary of the following Python 3 code
def _make_request(self, conn, method, url, timeout=_Default,
**httplib_request_kw):
"""
Perform a request on a given urllib connection object taken from our
pool.
:param conn:
a connection from one of our co... | As a python code expert, you are capable of creating scripts from specifications. |
A method that returns a response from the HTTP connection pool. | Can you tell what is the following Python 3 function doing
def urlopen(self, method, url, body=None, headers=None, retries=None,
redirect=True, assert_same_host=True, timeout=_Default,
pool_timeout=None, release_conn=None, **response_kw):
"""
Get a connection from the poo... | You are a Python code generator, capable of creating scripts from specifications. |
Create a new connection. | Here you have a function in Python 3, explain what it does
def _new_conn(self):
self.num_connections += 1
log.info("Starting new HTTPS connection (%d): %s"
% (self.num_connections, self.host))
if not self.ConnectionCls or self.ConnectionCls is DummyConnection:
# Pla... | As a python code expert, you are capable of creating scripts from specifications. |
def _validate_conn(self, conn):
"""
Called right before a request is made, after the socket is created.
"""
super(HTTPSConnectionPool, self)._validate_conn(conn)
# Force connect early to allow us to validate the connection.
if not getattr(conn, 'sock', None): # AppEngin... | Create a Python 3 function to
call right before a request is made after the socket is created. | You are a Python code generator, capable of creating scripts from specifications. |
Returns a string describing the probable encoding of a file or a list of strings. | Can you generate a brief explanation for the following Python 3 code
def description_of(lines, name='stdin'):
u = UniversalDetector()
for line in lines:
u.feed(line)
u.close()
result = u.result
if result['encoding']:
return '{0}: {1} with confidence {2}'.format(name, result['encoding... | As a Python code composer, you craft elegant and concise scripts. |
def main(argv=None):
'''
Handles command line arguments and gets things started.
:param argv: List of arguments, as if specified on the command-line.
If None, ``sys.argv[1:]`` is used instead.
:type argv: list of str
'''
# Get command line arguments
parser = argparse.Argume... | Can you write a function in Python 3 where it
handles command line arguments and gets things started. :param argv: List of arguments, as if specified on the command-line. If None, ``sys.argv[1:]`` is used instead. :type argv: list of str | You are a Python code generator, capable of creating scripts from specifications. |
Returns the current size of the terminal as tuple in the form
( width height ) in columns and rows. | How would you explain what the following Python 3 function does
def get_terminal_size():
# If shutil has get_terminal_size() (Python 3.3 and later) use that
if sys.version_info >= (3, 3):
import shutil
shutil_get_terminal_size = getattr(shutil, 'get_terminal_size', None)
if shutil_get_te... | As a Python code analyst, you investigate and solve complex coding mysteries |
Style a string with ANSI codes and returns the new string. | Make a summary of the following Python 3 code
def style(text, fg=None, bg=None, bold=None, dim=None, underline=None,
blink=None, reverse=None, reset=True):
"""Styles a text with ANSI styles and returns the new string. By
default the styling is self contained which means that at the end
of the str... | You are a Python code analyst, evaluating scripts for potential improvements. |
A wrapper around click. secho and click. style | Explain what the following Python 3 code does
def secho(text, file=None, nl=True, err=False, color=None, **styles):
return echo(style(text, **styles), file=file, nl=nl, err=err, color=color) | You are a Python code generator, capable of creating scripts from specifications. |
def merge_setting(request_setting, session_setting, dict_class=OrderedDict):
"""
Determines appropriate setting for a given request, taking into account the
explicit setting on that request, and the setting in the session. If a
setting is a dictionary, they will be merged together using `dict_class`
... | Write a Python 3 function for
merging two settings into one. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def resolve_redirects(self, resp, req, stream=False, timeout=None,
verify=True, cert=None, proxies=None):
"""Receives a Response. Returns a generator of Responses."""
i = 0
hist = [] # keep track of history
while resp.is_redirect:
prepared_request ... | Write a Python 3 function for
resolving the redirects in a response. | As a python code expert, you are capable of creating scripts from specifications. |
Send a PreparedRequest object to the local cache. | Make a summary of the following Python 3 code
def send(self, request, **kwargs):
# Set defaults that the hooks can utilize to ensure they always have
# the correct parameters to reproduce the previous request.
kwargs.setdefault('stream', self.stream)
kwargs.setdefault('verify', self.veri... | You are a Python code analyst, evaluating scripts for potential improvements. |
def prepare_method(self, method):
"""Prepares the given HTTP method."""
self.method = method
if self.method is not None:
self.method = self.method.upper() | Can you write a function in Python 3 where it
prepares the given HTTP method. | You are a Python code analyst, evaluating scripts for potential improvements. |
def prepare_headers(self, headers):
"""Prepares the given HTTP headers."""
if headers:
self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items())
else:
self.headers = CaseInsensitiveDict() | Write a Python 3 script to
prepare the given HTTP headers. | As a python code expert, you are capable of creating scripts from specifications. |
Iterates over the response data. | Can you generate a brief explanation for the following Python 3 code
def iter_content(self, chunk_size=1, decode_unicode=False):
def generate():
try:
# Special case for urllib3.
try:
for chunk in self.raw.stream(chunk_size, decode_content=True):
... | You are a Python code generator, capable of creating scripts from specifications. |
def json(self, **kwargs):
"""Returns the json-encoded content of a response, if any.
:param \*\*kwargs: Optional arguments that ``json.loads`` takes.
"""
if not self.encoding and len(self.content) > 3:
# No encoding set. JSON RFC 4627 section 3 states we should expect
... | Write a Python 3 script for
returning the json - encoded content of a response if any. | You are a Python code architect, reviewing and designing scalable and efficient code |
def raise_for_status(self):
"""Raises stored :class:`HTTPError`, if one occurred."""
http_error_msg = ''
if 400 <= self.status_code < 500:
http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason)
elif 500 <= self.status_code < 600:
http_error_ms... | Can you create a Python 3 function that
raises an exception if one occurred. | As a python code expert, you are capable of creating scripts from specifications. |
Create a new connection pool based on host port and scheme. | Here you have a function in Python 3, explain what it does
def _new_pool(self, scheme, host, port):
pool_cls = pool_classes_by_scheme[scheme]
kwargs = self.connection_pool_kw
if scheme == 'http':
kwargs = self.connection_pool_kw.copy()
for kw in SSL_KEYWORDS:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def connection_from_host(self, host, port=None, scheme='http'):
"""
Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn't given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``.
"""
if not host:
... | Implement a Python 3 function for
getting a ConnectionPool based on the given host and port and scheme. | You are a Python code generator, capable of creating scripts from specifications. |
Main function for creating a new If instance. | Given the following Python 3 function, write the documentation
def main(program=None,
version=None,
doc_template=None,
commands=None,
argv=None,
exit_at_end=True):
"""Top-level driver for creating subcommand-based programs.
Args:
program: The name of your pr... | As a Python code composer, you craft elegant and concise scripts. |
def process_response(self, request, response, spider):
"""Overridden process_response would "pipe" response.body through BeautifulSoup."""
return response.replace(body=str(BeautifulSoup(response.body, self.parser))) | How would you code a function in Python 3 to
override process_response would pipe response. body through BeautifulSoup. | You are a Python code generator, capable of creating scripts from specifications. |
def _expand_datasets(test_functions):
"""
Generator producing test_methods, with an optional dataset.
:param test_functions:
Iterator over tuples of test name and test unbound function.
:type test_functions:
`iterator` of `tuple` of (`unicode`, `function`)
:return:
Generator... | Write a Python 3 script for
generating test_methods for the given test_functions. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _expand_repeats(test_functions):
"""
Generator producing test_methods, with any repeat count unrolled.
:param test_functions:
Sequence of tuples of
- method_name : Name of the test method
- unbound function : Unbound function that will be the test method.
- dataset ... | Implement a function in Python 3 to
generate test_methods for the given test_functions. | As a python code expert, you are capable of creating scripts from specifications. |
Checks if the given method name is referenced by the command line. | Given the following Python 3 function, write the documentation
def _is_referenced_in_argv(method_name):
expr = '.*[:.]{0}$'.format(method_name)
regex = re.compile(expr)
return any(regex.match(arg) for arg in sys.argv) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _build_repeat_suffix(iteration, count):
"""
Return the suffix string to identify iteration X out of Y.
For example, with a count of 100, this will build strings like
"iteration_053" or "iteration_008".
:param iteration:
Current iteration.
:type iteration:
`int`
:param c... | Write a Python 3 function for
building a repeat suffix for the current iteration. | As a Python code composer, you craft elegant and concise scripts. |
Build the final test method name for the specified data set and dataset. | Can you generate the documentation for the following Python 3 function
def _build_final_method_name(
method_name,
dataset_name,
dataprovider_name,
repeat_suffix,
):
"""
Return a nice human friendly name, that almost looks like code.
Example: a test called 'test_something' wi... | You are a Python code analyst, evaluating scripts for potential improvements. |
Builds a test method that can be used to build the dataset for given method. | Here you have a function in Python 3, explain what it does
def _build_dataset_method(method, dataset):
if isinstance(dataset, GentyArgs):
test_method = lambda my_self: method(
my_self,
*dataset.args,
**dataset.kwargs
)
else:
test_method = lambda my_sel... | As a python code expert, you are capable of creating scripts from specifications. |
Build a test method that calls the dataprovider with the given dataset and returns the return value from that method. | Given the following Python 3 function, write the documentation
def _build_dataprovider_method(method, dataset, dataprovider):
if isinstance(dataset, GentyArgs):
final_args = dataset.args
final_kwargs = dataset.kwargs
else:
final_args = dataset
final_kwargs = {}
def test_meth... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _add_method_to_class(
target_cls,
method_name,
func,
dataset_name,
dataset,
dataprovider,
repeat_suffix,
):
"""
Add the described method to the given class.
:param target_cls:
Test class to which to add a method.
:type target_cls:
... | How would you code a function in Python 3 to
add a method to the given class. | You are a Python code analyst, evaluating scripts for potential improvements. |
Close any open window. | Can you generate the documentation for the following Python 3 function
def close(self):
if self._process:
# Be nice first.
self._process.send_signal(signal.SIGINT)
# If it doesn't close itself promptly, be brutal.
# Python 3.2+ added the timeout option to wait() ... | As a python code expert, you are capable of creating scripts from specifications. |
Internal API to run a non - blocking command with subprocess. Popen | How would you explain what the following Python 3 function does
def _run_nonblocking(self, args, input=None):
# Close any existing dialog.
if self._process:
self.close()
# Start the new one.
self._process = subprocess.Popen(args, stdout=subprocess.PIPE) | As a Python code composer, you craft elegant and concise scripts. |
Show an error window. | Given the following Python 3 function, write the documentation
def error(self, message, rofi_args=None, **kwargs):
rofi_args = rofi_args or []
# Generate arguments list.
args = ['rofi', '-e', message]
args.extend(self._common_args(allow_fullscreen=False, **kwargs))
args.extend(ro... | As a Python code analyst, you investigate and solve complex coding mysteries |
Show a status message. | Explain what the following Python 3 code does
def status(self, message, rofi_args=None, **kwargs):
rofi_args = rofi_args or []
# Generate arguments list.
args = ['rofi', '-e', message]
args.extend(self._common_args(allow_fullscreen=False, **kwargs))
args.extend(rofi_args)
... | As a Python code composer, you craft elegant and concise scripts. |
Show a list of options and return user selection. | Can you generate the documentation for the following Python 3 function
def select(self, prompt, options, rofi_args=None, message="", select=None, **kwargs):
rofi_args = rofi_args or []
# Replace newlines and turn the options into a single string.
optionstr = '\n'.join(option.replace('\n', ' ') f... | You are a Python code generator, capable of creating scripts from specifications. |
A generic entry box. | Explain what the following Python 3 code does
def generic_entry(self, prompt, validator=None, message=None, rofi_args=None, **kwargs):
error = ""
rofi_args = rofi_args or []
# Keep going until we get something valid.
while True:
args = ['rofi', '-dmenu', '-p', prompt, '-form... | You are a Python code analyst, evaluating scripts for potential improvements. |
Prompt the user to enter a piece of text. | Make a summary of the following Python 3 code
def text_entry(self, prompt, message=None, allow_blank=False, strip=True,
rofi_args=None, **kwargs):
"""Prompt the user to enter a piece of text.
Parameters
----------
prompt: string
Prompt to display to the user.
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def integer_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs):
"""Prompt the user to enter an integer.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the... | How would you code a function in Python 3 to
prompt the user to enter an integer value. | As a Python code composer, you craft elegant and concise scripts. |
def float_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs):
"""Prompt the user to enter a floating point number.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to displa... | Can you create a Python 3 function that
prompts the user to enter a floating point number. | You are a Python code generator, capable of creating scripts from specifications. |
Prompt the user to enter a decimal number. | Make a summary of the following Python 3 code
def decimal_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs):
# Sanity check.
if (min is not None) and (max is not None) and not (max > min):
raise ValueError("Maximum limit has to be more than the minimum limit.")
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def date_entry(self, prompt, message=None, formats=['%x', '%d/%m/%Y'],
show_example=False, rofi_args=None, **kwargs):
"""Prompt the user to enter a date.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
... | How would you implement a function in Python 3 that
prompts the user to enter a date. | As a Python code analyst, you investigate and solve complex coding mysteries |
def time_entry(self, prompt, message=None, formats=['%X', '%H:%M', '%I:%M', '%H.%M',
'%I.%M'], show_example=False, rofi_args=None, **kwargs):
"""Prompt the user to enter a time.
Parameters
----------
prompt: string
Prompt to display to the user.
message: stri... | Write a Python 3 script to
prompt the user to enter a time. | You are a Python code architect, reviewing and designing scalable and efficient code |
Prompt the user to enter a date and time. | Make a summary of the following Python 3 code
def datetime_entry(self, prompt, message=None, formats=['%x %X'], show_example=False,
rofi_args=None, **kwargs):
"""Prompt the user to enter a date and time.
Parameters
----------
prompt: string
Prompt to display to t... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def exit_with_error(self, error, **kwargs):
"""Report an error and exit.
This raises a SystemExit exception to ask the interpreter to quit.
Parameters
----------
error: string
The error to report before quitting.
"""
self.error(error, **kwargs)
... | Implement a Python 3 function for
reporting an error and exit. | You are a Python code analyst, evaluating scripts for potential improvements. |
def format_kwarg(key, value):
"""
Return a string of form: "key=<value>"
If 'value' is a string, we want it quoted. The goal is to make
the string a named parameter in a method call.
"""
translator = repr if isinstance(value, six.string_types) else six.text_type
arg_value = translator(valu... | How would you code a function in Python 3 to
format a key = value pair in a . | You are a Python code generator, capable of creating scripts from specifications. |
Formats the value in a dataset. | How would you explain what the following Python 3 function does
def format_arg(value):
translator = repr if isinstance(value, six.string_types) else six.text_type
return translator(value) | You are a Python code architect, reviewing and designing scalable and efficient code |
def encode_non_ascii_string(string):
"""
:param string:
The string to be encoded
:type string:
unicode or str
:return:
The encoded string
:rtype:
str
"""
encoded_string = string.encode('utf-8', 'replace')
if six.PY3:
encoded_string = encoded_string... | Create a Python 3 function to
encode a non - ASCII string into a base64 - encoded version of the string. | You are a Python code generator, capable of creating scripts from specifications. |
Decorator for the genty_dataset method. | Can you generate the documentation for the following Python 3 function
def genty_dataset(*args, **kwargs):
datasets = _build_datasets(*args, **kwargs)
def wrap(test_method):
# Save the datasets in the test method. This data will be consumed
# by the @genty decorator.
if not hasattr(test... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _build_datasets(*args, **kwargs):
"""Build the datasets into a dict, where the keys are the name of the
data set and the values are the data sets themselves.
:param args:
Tuple of unnamed data sets.
:type args:
`tuple` of varies
:param kwargs:
Dict of pre-named data sets... | Can you write a function in Python 3 where it
builds the datasets into a dict where the keys are the name of the data set and the values are the data sets themselves. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _add_arg_datasets(datasets, args):
"""Add data sets of the given args.
:param datasets:
The dict where to accumulate data sets.
:type datasets:
`dict`
:param args:
Tuple of unnamed data sets.
:type args:
`tuple` of varies
"""
for dataset in args:
... | Implement a function in Python 3 to
add data sets of the given args to the given datasets. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _add_kwarg_datasets(datasets, kwargs):
"""Add data sets of the given kwargs.
:param datasets:
The dict where to accumulate data sets.
:type datasets:
`dict`
:param kwargs:
Dict of pre-named data sets.
:type kwargs:
`dict` of `unicode` to varies
"""
for te... | Create a Python 3 function to
add data sets of the given kwargs to the given datasets. | You are a Python code analyst, evaluating scripts for potential improvements. |
Removes the hanging dedent from all the first line of a string. | Explain what the following Python 3 code does
def dedent(s):
head, _, tail = s.partition('\n')
dedented_tail = textwrap.dedent(tail)
result = "{head}\n{tail}".format(
head=head,
tail=dedented_tail)
return result | As a Python code composer, you craft elegant and concise scripts. |
The top - level documentation string for the program. | Can you generate a brief explanation for the following Python 3 code
def top_level_doc(self):
return self._doc_template.format(
available_commands='\n '.join(sorted(self._commands)),
program=self.program) | As a Python code translator, you convert algorithms and pseudocode into Python. |
A decorator to add subcommands. | Here you have a function in Python 3, explain what it does
def command(self, name=None):
def decorator(f):
self.add_command(f, name)
return f
return decorator | You are a Python code generator, capable of creating scripts from specifications. |
def add_command(self, handler, name=None):
"""Add a subcommand `name` which invokes `handler`.
"""
if name is None:
name = docstring_to_subcommand(handler.__doc__)
# TODO: Prevent overwriting 'help'?
self._commands[name] = handler | Can you create a Python 3 function that
adds a subcommand handler which invokes handler. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.