output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Load the history from disk to self. history_filename. | How would you explain what the following Python 3 function does
def load_history(self) -> List["IterationRecord"]:
if path.isfile(self.history_filename):
with open(self.history_filename, "r") as f:
try:
dicts = json.load(f)
except json.decoder.JSO... | You are a Python code generator, capable of creating scripts from specifications. |
def _setup_all_outputs(self) -> None:
"""Set up all output methods. Provide them credentials and anything else they need."""
# The way this is gonna work is that we assume an output should be set up iff it has a
# credentials_ directory under our secrets dir.
for key in self.outputs.key... | Create a Python 3 function to
set up all output methods. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _parse_output_records(self, item: IterationRecord) -> Dict[str, Any]:
"""Parse output records into dicts ready for JSON."""
output_records = {}
for key, sub_item in item.output_records.items():
if isinstance(sub_item, dict) or isinstance(sub_item, list):
output_re... | Implement a Python 3 function for
parsing the output records into dicts ready for JSON. | As a Python code composer, you craft elegant and concise scripts. |
def make_dir(fname):
"""
Create the directory of a fully qualified file name if it does not exist.
:param fname: File name
:type fname: string
Equivalent to these Bash shell commands:
.. code-block:: bash
$ fname="${HOME}/mydir/myfile.txt"
$ dir=$(dirname "${fname}")
... | Write a Python 3 function that can
create the directory of a fully qualified file name if it does not exist. | As a python code expert, you are capable of creating scripts from specifications. |
r Normalize a Windows file name to be compatible with Windows. | Can you tell what is the following Python 3 function doing
def normalize_windows_fname(fname, _force=False):
if (platform.system().lower() != "windows") and (not _force): # pragma: no cover
return fname
# Replace unintended escape sequences that could be in
# the file name, like "C:\appdata"
rc... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _homogenize_linesep(line):
"""Enforce line separators to be the right one depending on platform."""
token = str(uuid.uuid4())
line = line.replace(os.linesep, token).replace("\n", "").replace("\r", "")
return line.replace(token, os.linesep) | Can you write a function in Python 3 where it
enforces line separators to be the right one depending on platform. | As a python code expert, you are capable of creating scripts from specifications. |
def _proc_token(spec, mlines):
"""Process line range tokens."""
spec = spec.strip().replace(" ", "")
regexp = re.compile(r".*[^0123456789\-,]+.*")
tokens = spec.split(",")
cond = any([not item for item in tokens])
if ("--" in spec) or ("-," in spec) or (",-" in spec) or cond or regexp.match(spec... | Create a Python 3 function for
processing line range tokens. | As a python code expert, you are capable of creating scripts from specifications. |
r Include a file in the current directory. | How would you explain what the following Python 3 function does
def incfile(fname, fpointer, lrange=None, sdir=None):
# pylint: disable=R0914
# Read file
file_dir = (
sdir
if sdir
else os.environ.get("PKG_DOC_DIR", os.path.abspath(os.path.dirname(__file__)))
)
fname = os.path... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def ste(command, nindent, mdir, fpointer, env=None):
"""
Print STDOUT of a shell command formatted in reStructuredText.
This is a simplified version of :py:func:`pmisc.term_echo`.
:param command: Shell command (relative to **mdir** if **env** is not given)
:type command: string
:param ninden... | Implement a Python 3 function for
printing STDOUT of a shell command formatted in reStructuredText. | As a python code expert, you are capable of creating scripts from specifications. |
Print a shell command formatted in reStructuredText. | Can you generate a brief explanation for the following Python 3 code
def term_echo(command, nindent=0, env=None, fpointer=None, cols=60):
# pylint: disable=R0204
# Set argparse width so that output does not need horizontal scroll
# bar in narrow windows or displays
os.environ["COLUMNS"] = str(cols)
... | As a python code expert, you are capable of creating scripts from specifications. |
def flo(string):
'''Return the string given by param formatted with the callers locals.'''
callers_locals = {}
frame = inspect.currentframe()
try:
outerframe = frame.f_back
callers_locals = outerframe.f_locals
finally:
del frame
return string.format(**callers_locals) | Write a Python 3 script to
return the string given by param formatted with the callers locals. | As a python code expert, you are capable of creating scripts from specifications. |
Color wrapper.
Example:
>>> blue = _wrap_with('34')
>>> print(blue('text'))
\033[34mtext\033[0m | Can you generate a brief explanation for the following Python 3 code
def _wrap_with(color_code):
'''Color wrapper.
Example:
>>> blue = _wrap_with('34')
>>> print(blue('text'))
\033[34mtext\033[0m
'''
def inner(text, bold=False):
'''Inner color function.'''
code =... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def clean(deltox=False):
'''Delete temporary files not under version control.
Args:
deltox: If True, delete virtual environments used by tox
'''
basedir = dirname(__file__)
print(cyan('delete temp files and dirs for packaging'))
local(flo(
'rm -rf '
'{basedir}/.eggs/ ... | Create a Python 3 function to
delete temporary files and directories for packaging and editing. | As a python code expert, you are capable of creating scripts from specifications. |
def pythons():
'''Install latest pythons with pyenv.
The python version will be activated in the projects base dir.
Will skip already installed latest python versions.
'''
if not _pyenv_exists():
print('\npyenv is not installed. You can install it with fabsetup '
'(https://gi... | Write a Python 3 function for
installing latest pythons with pyenv. | You are a Python code architect, reviewing and designing scalable and efficient code |
def tox(args=''):
'''Run tox.
Build package and run unit tests against several pythons.
Args:
args: Optional arguments passed to tox.
Example:
fab tox:'-e py36 -r'
'''
basedir = dirname(__file__)
latest_pythons = _determine_latest_pythons()
# e.g. highest_mino... | Can you implement a function in Python 3 that
runs tox. Build package and run unit tests against several pythons. | You are a Python code analyst, evaluating scripts for potential improvements. |
Build and upload to pypi. | Here you have a function in Python 3, explain what it does
def pypi():
'''Build package and upload to pypi.'''
if query_yes_no('version updated in setup.py?'):
print(cyan('\n## clean-up\n'))
execute(clean)
basedir = dirname(__file__)
latest_pythons = _determine_latest_pythons(... | As a Python code analyst, you investigate and solve complex coding mysteries |
def chk_col_numbers(line_num, num_cols, tax_id_col, id_col, symbol_col):
"""
Check that none of the input column numbers is out of range.
(Instead of defining this function, we could depend on Python's built-in
IndexError exception for this issue, but the IndexError exception wouldn't
include line n... | Write a Python 3 function that can
check that the input column numbers are out of range. | You are a Python code analyst, evaluating scripts for potential improvements. |
Read the gene history file into the database. | Make a summary of the following Python 3 code
def import_gene_history(file_handle, tax_id, tax_id_col, id_col, symbol_col):
# Make sure that tax_id is not "" or " "
if not tax_id or tax_id.isspace():
raise Exception("Input tax_id is blank")
# Make sure that tax_id exists in Organism table in the ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Initialize what requires credentials and secret files. | Make a summary of the following Python 3 code
def cred_init(
self,
*,
secrets_dir: str,
log: Logger,
bot_name: str="",
) -> None:
"""Initialize what requires credentials/secret files."""
super().__init__(secrets_dir=secrets_dir, log=log, bo... | As a python code expert, you are capable of creating scripts from specifications. |
Send a message to the specified toot. | Explain what the following Python 3 code does
def send(
self,
*,
text: str,
) -> List[OutputRecord]:
"""
Send mastodon message.
:param text: text to send in post.
:returns: list of output records,
each corresponding to either a single ... | As a Python code composer, you craft elegant and concise scripts. |
def send_with_media(
self,
*,
text: str,
files: List[str],
captions: List[str]=[],
) -> List[OutputRecord]:
"""
Upload media to mastodon,
and send status and media,
and captions if present.
:param text: post text.
... | Can you implement a function in Python 3 that
uploads media to mastodon and sends status and media to the bot. | You are a Python code generator, capable of creating scripts from specifications. |
Perform a batch reply on the target account. | Can you tell what is the following Python 3 function doing
def perform_batch_reply(
self,
*,
callback: Callable[..., str],
lookback_limit: int,
target_handle: str,
) -> List[OutputRecord]:
"""
Performs batch reply on target account.
... | You are a Python code generator, capable of creating scripts from specifications. |
Handle an error while trying to do something. | Given the following Python 3 function, write the documentation
def handle_error(self, message: str, e: mastodon.MastodonError) -> OutputRecord:
self.lerror(f"Got an error! {e}")
# Handle errors if we know how.
try:
code = e[0]["code"]
if code in self.handled_errors:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _read_header(self):
'''
Little-endian
|... 4 bytes unsigned int ...|... 4 bytes unsigned int ...|
| frames count | dimensions count |
'''
self._fh.seek(0)
buf = self._fh.read(4*2)
fc, dc = struct.unpack("<II", buf)
retur... | Implement a Python 3 function for
reading the header from the log file. | As a python code expert, you are capable of creating scripts from specifications. |
def listen(self, you):
"""
Request a callback for value modification.
Parameters
----------
you : object
An instance having ``__call__`` attribute.
"""
self._listeners.append(you)
self.raw.talk_to(you) | Write a Python 3 script to
add a callback to the list of listeners that will be called when the value modification of a key is received. | You are a Python code generator, capable of creating scripts from specifications. |
Simple utility function to load a term.
| Can you generate the documentation for the following Python 3 function
def _get_term_by_id(self, id):
'''Simple utility function to load a term.
'''
url = (self.url + '/%s.json') % id
r = self.session.get(url)
return r.json() | You are a Python code generator, capable of creating scripts from specifications. |
def get_top_display(self, **kwargs):
'''
Returns all concepts or collections that form the top-level of a display
hierarchy.
As opposed to the :meth:`get_top_concepts`, this method can possibly
return both concepts and collections.
:rtype: Returns a list of concepts and... | Create a Python 3 function to
return all concepts or collections that form the top-level of a display hierarchy. As opposed to the :meth:`get_top_concepts`, this method can possibly return both concepts and collections. :rtype: Returns a list of concepts and collections. For each an id is present and a label. The label... | You are a Python code generator, capable of creating scripts from specifications. |
def get_children_display(self, id, **kwargs):
'''
Return a list of concepts or collections that should be displayed
under this concept or collection.
:param id: A concept or collection id.
:rtype: A list of concepts and collections. For each an
id is present and a la... | Can you write a function in Python 3 where it
returns a list of concepts or collections that should be displayed under this concept or collection. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def translate_genes(id_list=None, from_id=None, to_id=None, organism=None):
"""
Pass a list of identifiers (id_list), the name of the database ('Entrez',
'Symbol', 'Standard name', 'Systematic name' or a loaded crossreference
database) that you wish to translate from, and the name of the database
th... | How would you implement a function in Python 3 that
translates a list of identifiers from one gene to another. | As a Python code analyst, you investigate and solve complex coding mysteries |
def Cross(width=3, color=0):
"""Draws a cross centered in the target area
:param width: width of the lines of the cross in pixels
:type width: int
:param color: color of the lines of the cross
:type color: pygame.Color
"""
return Overlay(Line("h", width, color), Line("v", width, color)) | Implement a function in Python 3 to
draw a cross centered in the target area. | You are a Python code analyst, evaluating scripts for potential improvements. |
def compose(target, root=None):
"""Top level function to create a surface.
:param target: the pygame.Surface to blit on. Or a (width, height) tuple
in which case a new surface will be created
:type target: -
"""
if type(root) == Surface:
raise ValueError("A Surface may not be u... | Write a Python 3 function that can
top level function to create a tuple of nodes. | As a Python code composer, you craft elegant and concise scripts. |
def Font(name=None, source="sys", italic=False, bold=False, size=20):
"""Unifies loading of fonts.
:param name: name of system-font or filepath, if None is passed the default
system-font is loaded
:type name: str
:param source: "sys" for system font, or "file" to load a file
:type source: ... | Can you implement a function in Python 3 that
returns a font object for the current object. | You are a Python code architect, reviewing and designing scalable and efficient code |
Renders a text. Supports multiline text. | Explain what the following Python 3 code does
def Text(text, font, color=pygame.Color(0, 0, 0), antialias=False, align="center"):
assert align in ["center", "left", "right"]
margin_l, margin_r = 1, 1
if align == "left": margin_l = 0
elif align == "right": margin_r = 0
margin = Margin(margin_l, margi... | You are a Python code generator, capable of creating scripts from specifications. |
def from_scale(scale_w, scale_h=None):
"""Creates a padding by the remaining space after scaling the content.
E.g. Padding.from_scale(0.5) would produce Padding(0.25, 0.25, 0.25, 0.25) and
Padding.from_scale(0.5, 1) would produce Padding(0.25, 0.25, 0, 0)
because the content would not b... | Write a Python 3 function for
creating a padding by the remaining space after scaling the content. | You are a Python code analyst, evaluating scripts for potential improvements. |
Gets the list of radicals for a given set of levels. | Make a summary of the following Python 3 code
def radicals(self, levels=None):
url = WANIKANI_BASE.format(self.api_key, 'radicals')
if levels:
url += '/{0}'.format(levels)
data = self.get(url)
for item in data['requested_information']:
yield Radical(item) | As a Python code composer, you craft elegant and concise scripts. |
def kanji(self, levels=None):
"""
:param levels: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
:type levels: str or None
http://ww... | How would you code a function in Python 3 to
return an iterator over all Kanji items. | You are a Python code analyst, evaluating scripts for potential improvements. |
def vocabulary(self, levels=None):
"""
:param levels: An optional argument of declaring a single or
comma-delimited list of levels is available, as seen in the example
as 1. An example of a comma-delimited list of levels is 1,2,5,9.
:type levels: str or None
http... | Can you write a function in Python 3 where it
returns a generator that yields all available or obsolete vocabulary items. | As a python code expert, you are capable of creating scripts from specifications. |
Test if the argument is a string representing a valid hexadecimal digit. | Explain what the following Python 3 code does
def ishex(obj):
return isinstance(obj, str) and (len(obj) == 1) and (obj in string.hexdigits) | As a Python code analyst, you investigate and solve complex coding mysteries |
def isnumber(obj):
"""
Test if the argument is a number (complex, float or integer).
:param obj: Object
:type obj: any
:rtype: boolean
"""
return (
(obj is not None)
and (not isinstance(obj, bool))
and isinstance(obj, (int, float, complex))
) | Write a Python 3 script for
testing if the argument is a number. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Test if the argument is a real number. | Explain what the following Python 3 code does
def isreal(obj):
return (
(obj is not None)
and (not isinstance(obj, bool))
and isinstance(obj, (int, float))
) | You are a Python code analyst, evaluating scripts for potential improvements. |
Create and return an API context object | Given the following Python 3 function, write the documentation
def create_api_context(self, cls):
return self.api_context_schema().load({
"name": cls.name,
"cls": cls,
"inst": [],
"conf": self.conf.get_api_service(cls.name),
"calls": self.conf.get_api_... | As a python code expert, you are capable of creating scripts from specifications. |
def receive(self, data, api_context):
"""Pass an API result down the pipeline"""
self.log.debug(f"Putting data on the pipeline: {data}")
result = {
"api_contexts": self.api_contexts,
"api_context": api_context,
"strategy": dict(), # Shared strategy data
... | Create a Python 3 function to
pass an API result down the pipeline | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the Course this node belongs to | Here you have a function in Python 3, explain what it does
def course(self):
course = self.parent
while course.parent:
course = course.parent
return course | As a Python code composer, you craft elegant and concise scripts. |
Returns the path of this node on Studip. | Make a summary of the following Python 3 code
def path(self):
if self.parent is None:
return self.title
return join(self.parent.path, self.title) | As a Python code composer, you craft elegant and concise scripts. |
get the title of this node | Can you generate a brief explanation for the following Python 3 code
def title(self):
tmp = c.namemap_lookup(self.id) if c.namemap_lookup(self.id) is not None else self._title
return secure_filename(tmp) | As a Python code analyst, you investigate and solve complex coding mysteries |
returns a list of all documents find in subtrees of this node | Explain what the following Python 3 code does
def deep_documents(self):
tree = []
for entry in self.contents:
if isinstance(entry, Document):
tree.append(entry)
else:
tree += entry.deep_documents
return tree | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the title of the course. | Given the following Python 3 function, write the documentation
def title(self):
name = c.namemap_lookup(self.id)
if name is None:
name = self._title + " " + client.get_semester_title(self)
c.namemap_set(self.id, name)
return secure_filename(name) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _get(self, route, stream=False):
"""
run a get request against an url. Returns the response which can optionally be streamed
"""
log.debug("Running GET request against %s" % route)
return r.get(self._url(route), auth=c.auth, stream=stream) | Write a Python 3 function that can
run a get request against a url. Returns the response which can optionally be streamed | As a Python code composer, you craft elegant and concise scripts. |
Returns a list of all contents of a folder. Returns a list of all Documents and Folders in this order. | Can you generate the documentation for the following Python 3 function
def get_contents(self, folder: Folder):
log.debug("Listing Contents of %s/%s" % (folder.course.id, folder.id))
if isinstance(folder, Course):
response = json.loads(self._get('/api/documents/%s/folder' % folder.course.id).... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Download a document to the given path. | Can you generate the documentation for the following Python 3 function
def download_document(self, document: Document, overwrite=True, path=None):
if not path:
path = os.path.join(os.path.expanduser(c["base_path"]), document.path)
if (self.modified(document) and overwrite) or not os.path.exi... | You are a Python code generator, capable of creating scripts from specifications. |
get the semester title of a node | Can you tell what is the following Python 3 function doing
def get_semester_title(self, node: BaseNode):
log.debug("Getting Semester Title for %s" % node.course.id)
return self._get_semester_from_id(node.course.semester) | You are a Python code generator, capable of creating scripts from specifications. |
List all courses in the user s site | Make a summary of the following Python 3 code
def get_courses(self):
log.info("Listing Courses...")
courses = json.loads(self._get('/api/courses').text)["courses"]
courses = [Course.from_response(course) for course in courses]
log.debug("Courses: %s" % [str(entry) for entry in courses])
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _minimize_scalar(
self, desc="Progress", rtol=1.4902e-08, atol=1.4902e-08, verbose=True
):
"""
Minimize a scalar function using Brent's method.
Parameters
----------
verbose : bool
``True`` for verbose output; ``False`` otherwise.
"""
... | Write a Python 3 script for
minimizing a scalar function using Brent s method. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a url - safe base64 - encoded SHA - 256 hash of the string | Can you tell what is the following Python 3 function doing
def digest(self, alg='sha256', b64=True, strip=True):
import base64, hashlib
h = hashlib.new(alg)
h.update(str(self).encode('utf-8'))
if b64 == True:
# this returns a string with a predictable amount of = paddi... | As a Python code analyst, you investigate and solve complex coding mysteries |
def camelify(self):
"""turn a string to CamelCase, omitting non-word characters"""
outstring = self.titleify(allwords=True)
outstring = re.sub(r"&[^;]+;", " ", outstring)
outstring = re.sub(r"\W+", "", outstring)
return String(outstring) | How would you implement a function in Python 3 that
turns a string to CamelCase omitting non - word characters | You are a Python code architect, reviewing and designing scalable and efficient code |
def titleify(self, lang='en', allwords=False, lastword=True):
"""takes a string and makes a title from it"""
if lang in LOWERCASE_WORDS:
lc_words = LOWERCASE_WORDS[lang]
else:
lc_words = []
s = str(self).strip()
l = re.split(r"([_\W]+)", s)
... | Write a Python 3 script to
take a string and makes a title from it | As a Python code composer, you craft elegant and concise scripts. |
return a python identifier from the string | How would you explain what the following Python 3 function does
def identifier(self, camelsplit=False, ascii=True):
return self.nameify(camelsplit=camelsplit, ascii=ascii, sep='_') | As a Python code analyst, you investigate and solve complex coding mysteries |
def nameify(self, camelsplit=False, ascii=True, sep='-'):
"""return an XML name (hyphen-separated by default, initial underscore if non-letter)"""
s = String(str(self)) # immutable
if camelsplit == True:
s = s.camelsplit()
s = s.hyphenify(ascii=ascii).replace('-', sep)
... | Implement a function in Python 3 to
return an XML name ( hyphen - separated by default initial underscore if non - letter | As a Python code analyst, you investigate and solve complex coding mysteries |
Turn non - word characters into single hyphens. | How would you explain what the following Python 3 function does
def hyphenify(self, ascii=False):
s = str(self)
s = re.sub("""['"\u2018\u2019\u201c\u201d]""", '', s) # quotes
s = re.sub(r'(?:\s|%20)+', '-', s) # whitespace
if ascii == True: # ASCII-only
s = s.encode('... | You are a Python code analyst, evaluating scripts for potential improvements. |
Turn a CamelCase string into a string with spaces | How would you explain what the following Python 3 function does
def camelsplit(self):
s = str(self)
for i in range(len(s) - 1, -1, -1):
if i != 0 and (
(s[i].isupper() and s[i - 1].isalnum() and not s[i - 1].isupper())
or (s[i].isnumeric() and s[i - 1].is... | As a Python code composer, you craft elegant and concise scripts. |
def run(self):
"""Executed on startup of application"""
self.api = self.context.get("cls")(self.context)
self.context["inst"].append(self) # Adapters used by strategies
for call, calldata in self.context.get("calls", {}).items():
def loop():
"""Loop on event... | Create a Python 3 function for
running the event scheduler. | You are a Python code architect, reviewing and designing scalable and efficient code |
Executes on each scheduled iteration | How would you explain what the following Python 3 function does
def call(self, callname, arguments=None):
# See if a method override exists
action = getattr(self.api, callname, None)
if action is None:
try:
action = self.api.ENDPOINT_OVERRIDES.get(callname, None)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _generate_request(self, callname, request):
"""Generate a request object for delivery to the API"""
# Retrieve path from API class
schema = self.api.request_schema()
schema.context['callname'] = callname
return schema.dump(request).data.get("payload") | Write a Python 3 script to
generate a request object for delivery to the API | As a Python code analyst, you investigate and solve complex coding mysteries |
Generate a result object for delivery to the context object | Can you tell what is the following Python 3 function doing
def _generate_result(self, callname, result):
# Retrieve path from API class
schema = self.api.result_schema()
schema.context['callname'] = callname
self.callback(schema.load(result), self.context) | You are a Python code analyst, evaluating scripts for potential improvements. |
create a key for index by converting index into base - 26 number using A - Z as the characters. | Given the following Python 3 function, write the documentation
def excel_key(index):
X = lambda n: ~n and X((n // 26)-1) + chr(65 + (n % 26)) or ''
return X(int(index)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def convert_to_crash_data(raw_crash, processed_crash):
"""
Takes a raw crash and a processed crash (these are Socorro-centric
data structures) and converts them to a crash data structure used
by signature generation.
:arg raw_crash: raw crash data from Socorro
:arg processed_crash: processed cr... | Can you implement a function in Python 3 that
converts a raw crash and processed crash to a crash data structure used by signature generation. | You are a Python code architect, reviewing and designing scalable and efficient code |
def drop_bad_characters(text):
"""Takes a text and drops all non-printable and non-ascii characters and
also any whitespace characters that aren't space.
:arg str text: the text to fix
:returns: text with all bad characters dropped
"""
# Strip all non-ascii and non-printable characters
te... | Can you create a Python 3 function that
takes a text and drops all non - printable and non - ASCII characters and also any whitespace characters that aren t space. | You are a Python code analyst, evaluating scripts for potential improvements. |
def parse_source_file(source_file):
"""Parses a source file thing and returns the file name
Example:
>>> parse_file('hg:hg.mozilla.org/releases/mozilla-esr52:js/src/jit/MIR.h:755067c14b06')
'js/src/jit/MIR.h'
:arg str source_file: the source file ("file") from a stack frame
:returns: the fil... | Can you write a function in Python 3 where it
parses a source file thing and returns the file name | You are a Python code analyst, evaluating scripts for potential improvements. |
def _is_exception(exceptions, before_token, after_token, token):
"""Predicate for whether the open token is in an exception context
:arg exceptions: list of strings or None
:arg before_token: the text of the function up to the token delimiter
:arg after_token: the text of the function after the token d... | Can you write a function in Python 3 where it
predicates for whether the open token is in an exception context | You are a Python code analyst, evaluating scripts for potential improvements. |
def collapse(
function,
open_string,
close_string,
replacement='',
exceptions=None,
):
"""Collapses the text between two delimiters in a frame function value
This collapses the text between two delimiters and either removes the text
altogether or replaces it with a replacement string.
... | Implement a Python 3 function for
collapsing the text between two delimiters in a frame function value returning a new frame with the text collapsed. | You are a Python code architect, reviewing and designing scalable and efficient code |
Takes the function value from a frame and drops the prefix and return type of the function value. | Can you generate the documentation for the following Python 3 function
def drop_prefix_and_return_type(function):
DELIMITERS = {
'(': ')',
'{': '}',
'[': ']',
'<': '>',
'`': "'"
}
OPEN = DELIMITERS.keys()
CLOSE = DELIMITERS.values()
# The list of tokens accum... | You are a Python code analyst, evaluating scripts for potential improvements. |
def wait_connected(self, conns=None, timeout=None):
'''Wait for connections to be made and their handshakes to finish
:param conns:
a single or list of (host, port) tuples with the connections that
must be finished before the method will return. defaults to all the
p... | Create a Python 3 function for
waiting for all the connections made and their handshakes to finish. | You are a Python code architect, reviewing and designing scalable and efficient code |
def shutdown(self):
'Close all peer connections and stop listening for new ones'
log.info("shutting down")
for peer in self._dispatcher.peers.values():
peer.go_down(reconnect=False)
if self._listener_coro:
backend.schedule_exception(
errors._... | Write a Python 3 function for
closing all peer connections and stop listening for new ones | As a Python code composer, you craft elegant and concise scripts. |
Set a handler for incoming publish messages. | Can you generate the documentation for the following Python 3 function
def accept_publish(
self, service, mask, value, method, handler=None, schedule=False):
'''Set a handler for incoming publish messages
:param service: the incoming message must have this service
:type service: any... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def unsubscribe_publish(self, service, mask, value):
'''Remove a publish subscription
:param service: the service of the subscription to remove
:type service: anything hash-able
:param mask: the mask of the subscription to remove
:type mask: int
:param value: the value i... | Can you implement a function in Python 3 that
removes a publish subscription from a service. | You are a Python code generator, capable of creating scripts from specifications. |
Send a 1 - way message to all peers. | Make a summary of the following Python 3 code
def publish(self, service, routing_id, method, args=None, kwargs=None,
broadcast=False, udp=False):
'''Send a 1-way message
:param service: the service name (the routing top level)
:type service: anything hash-able
:param int rou... | You are a Python code architect, reviewing and designing scalable and efficient code |
def publish_receiver_count(self, service, routing_id):
'''Get the number of peers that would handle a particular publish
:param service: the service name
:type service: anything hash-able
:param routing_id: the id used for limiting the service handlers
:type routing_id: int
... | Write a Python 3 function for
getting the number of peers that would handle a particular publish | You are a Python code analyst, evaluating scripts for potential improvements. |
Set a handler for incoming RPCs with a routing id and a method. | Can you tell what is the following Python 3 function doing
def accept_rpc(self, service, mask, value, method,
handler=None, schedule=True):
'''Set a handler for incoming RPCs
:param service: the incoming RPC must have this service
:type service: anything hash-able
:param mas... | You are a Python code generator, capable of creating scripts from specifications. |
def unsubscribe_rpc(self, service, mask, value):
'''Remove a rpc subscription
:param service: the service of the subscription to remove
:type service: anything hash-able
:param mask: the mask of the subscription to remove
:type mask: int
:param value: the value in the su... | Write a Python 3 function for
removing a rpc subscription :param service: the service of the subscription to remove :type service: anything hash-able :param mask: the mask of the subscription to remove :type mask: int :param value: the value in the subscription to remove :type value: int :param handler: the handler fun... | As a Python code composer, you craft elegant and concise scripts. |
Send out an RPC request to all peers that are subscribed to the current node. | Make a summary of the following Python 3 code
def send_rpc(self, service, routing_id, method, args=None, kwargs=None,
broadcast=False):
'''Send out an RPC request
:param service: the service name (the routing top level)
:type service: anything hash-able
:param routing_id:
... | As a Python code composer, you craft elegant and concise scripts. |
Send an RPC request and return the corresponding response. | Can you generate the documentation for the following Python 3 function
def rpc(self, service, routing_id, method, args=None, kwargs=None,
timeout=None, broadcast=False):
'''Send an RPC request and return the corresponding response
This will block waiting until the response has been received... | As a Python code composer, you craft elegant and concise scripts. |
def rpc_receiver_count(self, service, routing_id):
'''Get the number of peers that would handle a particular RPC
:param service: the service name
:type service: anything hash-able
:param routing_id:
the id used for narrowing within the service handlers
:type routing_... | Can you implement a function in Python 3 that
gets the number of peers that would handle a particular RPC | You are a Python code analyst, evaluating scripts for potential improvements. |
Start up the hub s server and have it start initiating connections | Make a summary of the following Python 3 code
def start(self):
"Start up the hub's server, and have it start initiating connections"
log.info("starting")
self._listener_coro = backend.greenlet(self._listener)
self._udp_listener_coro = backend.greenlet(self._udp_listener)
backend... | As a python code expert, you are capable of creating scripts from specifications. |
def add_peer(self, peer_addr):
"Build a connection to the Hub at a given ``(host, port)`` address"
peer = connection.Peer(
self._ident, self._dispatcher, peer_addr, backend.Socket())
peer.start()
self._started_peers[peer_addr] = peer | Write a Python 3 function for
building a connection to the Hub at a given ( host port ) address | As a Python code translator, you convert algorithms and pseudocode into Python. |
list of the ( host port ) pairs of all connected peer Hubs | Can you generate the documentation for the following Python 3 function
def peers(self):
"list of the (host, port) pairs of all connected peer Hubs"
return [addr for (addr, peer) in self._dispatcher.peers.items()
if peer.up] | As a Python code analyst, you investigate and solve complex coding mysteries |
This function takes crash data via args and generates a Socorro signature for it. | Can you generate a brief explanation for the following Python 3 code
def main(argv=None):
parser = argparse.ArgumentParser(description=DESCRIPTION, epilog=EPILOG)
parser.add_argument(
'-v', '--verbose', help='increase output verbosity', action='store_true'
)
parser.add_argument(
'--forma... | You are a Python code generator, capable of creating scripts from specifications. |
Send the result to Skinken WS | Can you generate a brief explanation for the following Python 3 code
def send_result(self, return_code, output, service_description='', time_stamp=0, specific_servers=None):
'''
Send result to the Skinken WS
'''
if time_stamp == 0:
time_stamp = int(time.time())
if sp... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Close cache of WS Shinken | Explain what the following Python 3 code does
def close_cache(self):
'''
Close cache of WS Shinken
'''
# Close all WS_Shinken cache files
for server in self.servers:
if self.servers[server]['cache'] == True:
self.servers[server]['file'].close() | You are a Python code analyst, evaluating scripts for potential improvements. |
Create apidoc dir and delete contents if delete is True. | How would you explain what the following Python 3 function does
def prepare_dir(app, directory, delete=False):
logger.info("Preparing output directories for jinjaapidoc.")
if os.path.exists(directory):
if delete:
logger.debug("Deleting dir %s", directory)
shutil.rmtree(directory)... | You are a Python code architect, reviewing and designing scalable and efficient code |
Join package and module with a dot. | Can you generate a brief explanation for the following Python 3 code
def makename(package, module):
# Both package and module can be None/empty.
assert package or module, "Specify either package or module"
if package:
name = package
if module:
name += '.' + module
else:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def write_file(app, name, text, dest, suffix, dryrun, force):
"""Write the output file for module/package <name>.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param name: the file name without file extension
:type name: :class:`str`
:param text: the content of the f... | Write a Python 3 script for
writing the content of a file to a directory. | As a Python code composer, you craft elegant and concise scripts. |
def import_name(app, name):
"""Import the given name and return name, obj, parent, mod_name
:param name: name to import
:type name: str
:returns: the imported object or None
:rtype: object | None
:raises: None
"""
try:
logger.debug('Importing %r', name)
name, obj = autos... | Can you implement a function in Python 3 that
imports the given name and return the name obj parent mod_name | You are a Python code analyst, evaluating scripts for potential improvements. |
Return the members of the given type in the given module. | Can you generate a brief explanation for the following Python 3 code
def get_members(app, mod, typ, include_public=None):
def include_here(x):
"""Return true if the member should be included in mod.
A member will be included if it is declared in this module or package.
If the `jinjaapidoc_i... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _get_submodules(app, module):
"""Get all submodules for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names and boolean whether its a pac... | Can you implement a function in Python 3 that
gets all submodules of the given module | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_submodules(app, module):
"""Get all submodules without packages for the given module/package
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param module: the module to query or module path
:type module: module | str
:returns: list of module names excluding pac... | Can you write a function in Python 3 where it
gets all submodules without packages for the given module | As a python code expert, you are capable of creating scripts from specifications. |
Get all subpackages for the given module | Given the following Python 3 function, write the documentation
def get_subpackages(app, module):
submodules = _get_submodules(app, module)
return [name for name, ispkg in submodules if ispkg] | You are a Python code generator, capable of creating scripts from specifications. |
Return a dict with variables for template rendering | Can you tell what is the following Python 3 function doing
def get_context(app, package, module, fullname):
var = {'package': package,
'module': module,
'fullname': fullname}
logger.debug('Creating context for: package %s, module %s, fullname %s', package, module, fullname)
obj = impor... | As a Python code analyst, you investigate and solve complex coding mysteries |
def create_module_file(app, env, package, module, dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphinx`
:param env: the jinja environment for the templates
:type env: :class:`jinja2.Environment`
:... | Create a Python 3 function for
creating the text of the file and write it to dest. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create the text of the file and write it to dest. | Given the following Python 3 function, write the documentation
def create_package_file(app, env, root_package, sub_package, private,
dest, suffix, dryrun, force):
"""Build the text of the file and write the file.
:param app: the sphinx app
:type app: :class:`sphinx.application.Sphin... | You are a Python code analyst, evaluating scripts for potential improvements. |
Check if we should skip this module. | Can you generate a brief explanation for the following Python 3 code
def shall_skip(app, module, private):
logger.debug('Testing if %s should be skipped.', module)
# skip if it has a "private" name and this is selected
if module != '__init__.py' and module.startswith('_') and \
not private:
l... | As a python code expert, you are capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.