output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Return the metatab document for the URL | Can you generate the documentation for the following Python 3 function
def doc(self):
from metapack import MetapackDoc
t = self.get_resource().get_target()
return MetapackDoc(t, package_url=self.package_url) | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a URL to a local copy of a resource suitable for get_generator | Given the following Python 3 function, write the documentation
def resolve_url(self, resource_name):
if self.target_format == 'csv' and self.target_file != DEFAULT_METATAB_FILE:
# For CSV packages, need to get the package and open it to get the resoruce URL, becuase
# they are always ab... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the package URL associated with this metadata | How would you explain what the following Python 3 function does
def package_url(self):
if self.resource_file == DEFAULT_METATAB_FILE or self.target_format in ('txt','ipynb'):
u = self.inner.clone().clear_fragment()
u.path = dirname(self.path) + '/'
u.scheme_extension = 'meta... | As a python code expert, you are capable of creating scripts from specifications. |
def join_resource_name(self, v):
"""Return a MetapackResourceUrl that includes a reference to the resource. Returns a
MetapackResourceUrl, which will have a fragment """
d = self.dict
d['fragment'] = [v, None]
return MetapackResourceUrl(downloader=self._downloader, **d) | Write a Python 3 script to
return a MetapackResourceUrl that includes a reference to the resource. | As a Python code composer, you craft elegant and concise scripts. |
Resolve a resource URL to a local copy of a resource. | Can you generate the documentation for the following Python 3 function
def resolve_url(self, resource_name):
u = parse_app_url(resource_name)
if u.scheme != 'file':
t = u
elif self.target_format == 'csv' and self.target_file != DEFAULT_METATAB_FILE:
# Thre are two form... | As a python code expert, you are capable of creating scripts from specifications. |
def package_url(self):
"""Return the package URL associated with this metadata"""
return MetapackDocumentUrl(str(self.clear_fragment()), downloader=self._downloader).package_url | Create a Python 3 function to
return the package URL associated with this metadata | You are a Python code architect, reviewing and designing scalable and efficient code |
Search a directory of packages which has an index. json file and return the index. json file containing the packages and the index. json file that has an index. json file. | Given the following Python 3 function, write the documentation
def search_json_indexed_directory(directory):
from metapack.index import SearchIndex, search_index_file
idx = SearchIndex(search_index_file())
def _search_function(url):
packages = idx.search(url, format='issued')
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Search for a url by returning the value from the first callback that returns a non - None value | Given the following Python 3 function, write the documentation
def search(self):
for cb in SearchUrl.search_callbacks:
try:
v = cb(self)
if v is not None:
return v
except Exception as e:
raise | As a Python code translator, you convert algorithms and pseudocode into Python. |
Ensure all of the important directories in a source package exist | Can you generate the documentation for the following Python 3 function
def ensure_source_package_dir(nb_path, pkg_name):
pkg_path = join(dirname(nb_path), pkg_name)
makedirs(join(pkg_path,'notebooks'),exist_ok=True)
makedirs(join(pkg_path, 'docs'), exist_ok=True)
return pkg_path | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_metatab_doc(nb_path):
"""Read a notebook and extract the metatab document. Only returns the first document"""
from metatab.generate import CsvDataRowGenerator
from metatab.rowgenerators import TextRowGenerator
from metatab import MetatabDoc
with open(nb_path) as f:
nb = nbformat.re... | Can you implement a function in Python 3 that
reads a notebook and extract the metatab document. Only returns the first document | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_package_dir(nb_path):
"""Return the package directory for a Notebook that has an embeded Metatab doc, *not* for
notebooks that are part of a package """
doc = get_metatab_doc(nb_path)
doc.update_name(force=True, create_term=True)
pkg_name = doc['Root'].get_value('Root.Name')
assert pkg_n... | Write a Python 3 script for
returning the package directory for a Notebook that is part of a package. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def process_schema(doc, resource, df):
"""Add schema entiries to a metatab doc from a dataframe"""
from rowgenerators import SourceError
from requests.exceptions import ConnectionError
from metapack.cli.core import extract_path_name, alt_col_name, type_map
from tableintuit import TypeIntuiter
f... | Implement a Python 3 function for
adding schema entiries to a metatab doc from a dataframe | As a Python code composer, you craft elegant and concise scripts. |
def boot(hostname, boot_port=consts.BOOT_PORT,
scamp_binary=None, sark_struct=None,
boot_delay=0.05, post_boot_delay=2.0,
sv_overrides=dict(), **kwargs):
"""Boot a SpiNNaker machine of the given size.
Parameters
----------
hostname : str
Hostname or IP address of the ... | Create a Python 3 function for
booting a SpiNNaker machine with the given hostname. | You are a Python code analyst, evaluating scripts for potential improvements. |
def boot_packet(sock, cmd, arg1=0, arg2=0, arg3=0, data=b""):
"""Create and transmit a packet to boot the machine.
Parameters
----------
sock : :py:class:`~socket.socket`
Connected socket to use to transmit the packet.
cmd : int
arg1 : int
arg2 : int
arg3 : int
data : :py:cl... | Write a Python 3 function for
creating and transmit a boot packet to the machine. | You are a Python code architect, reviewing and designing scalable and efficient code |
Produce a copy of this datastructure. | Can you tell what is the following Python 3 function doing
def copy(self):
return Machine(
self.width, self.height,
self.chip_resources, self.chip_resource_exceptions,
self.dead_chips, self.dead_links) | As a python code expert, you are capable of creating scripts from specifications. |
Test whether the resources available in this machine description are a subset of those available in another machine description. | Explain what the following Python 3 code does
def issubset(self, other):
return (set(self).issubset(set(other)) and
set(self.iter_links()).issubset(set(other.iter_links())) and
all(set(self[chip]).issubset(other[chip]) and
all(self[chip][r] <= other[chip][r]
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def has_wrap_around_links(self, minimum_working=0.9):
"""Test if a machine has wrap-around connections installed.
Since the Machine object does not explicitly define whether a machine
has wrap-around links they must be tested for directly. This test
performs a "fuzzy" test on the number... | Create a Python 3 function for
testing if a machine has wrap - around links installed. | You are a Python code generator, capable of creating scripts from specifications. |
def write_doc(doc : MetapackDoc, mt_file=None):
"""
Write a Metatab doc to a CSV file, and update the Modified time
:param doc:
:param mt_file:
:return:
"""
from rowgenerators import parse_app_url
if not mt_file:
mt_file = doc.ref
add_giturl(doc)
u = parse_app_url(mt_... | Can you create a Python 3 function that
writes a Metatab doc to a CSV file and update the Modified time | As a Python code translator, you convert algorithms and pseudocode into Python. |
def update_resource_properties(r, orig_columns={}, force=False):
"""Get descriptions and other properties from this, or upstream, packages, and add them to the schema. """
added = []
schema_term = r.schema_term
if not schema_term:
warn("No schema term for ", r.name)
return
rg = r... | Create a Python 3 function for
updating the resource properties in the schema. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return a configuration dict for the current user | Can you generate a brief explanation for the following Python 3 code
def get_config():
from os import environ
from os.path import expanduser
from pathlib import Path
import yaml
def pexp(p):
try:
return Path(p).expanduser()
except AttributeError:
# python 3.4... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Locate the build CSV package which will have distributions if it was generated | Can you tell what is the following Python 3 function doing
def find_csv_packages(m, downloader):
from metapack.package import CsvPackageBuilder
pkg_dir = m.package_root
name = m.doc.get_value('Root.Name')
package_path, cache_path = CsvPackageBuilder.make_package_path(pkg_dir, name)
if package_pat... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get a specific resource from the ContinuousDelivery API. | Can you generate a brief explanation for the following Python 3 code
def get_provisioning_configuration(
self, provisioning_configuration_id, custom_headers=None, raw=False, **operation_config):
"""GetContinuousDeploymentOperation.
:param provisioning_configuration_id:
:type provisi... | As a Python code analyst, you investigate and solve complex coding mysteries |
Serialize EmailMessages to be passed as task argument. | Here you have a function in Python 3, explain what it does
def serialize_email_messages(messages: List[EmailMessage]):
return [
base64.b64encode(zlib.compress(pickle.dumps(m, protocol=4))).decode()
for m in messages
] | You are a Python code analyst, evaluating scripts for potential improvements. |
Deserialize EmailMessages passed as task argument. | Given the following Python 3 function, write the documentation
def deserialize_email_messages(messages: List[str]):
return [
pickle.loads(zlib.decompress(base64.b64decode(m)))
for m in messages
] | As a Python code analyst, you investigate and solve complex coding mysteries |
def _estimate_count(self):
""" Update the count number using the estimation of the unset ratio """
if self.estimate_z == 0:
self.estimate_z = (1.0 / self.nbr_bits)
self.estimate_z = min(self.estimate_z, 0.999999)
self.count = int(-(self.nbr_bits / self.nbr_slices) * np.log(1 ... | How would you implement a function in Python 3 that
updates the count number using the estimation of the unset ratio | As a Python code composer, you craft elegant and concise scripts. |
Decrement cell value if not zero
This maintenance process need to execute each self. compute_refresh_time | How would you explain what the following Python 3 function does
def expiration_maintenance(self):
if self.cellarray[self.refresh_head] != 0:
self.cellarray[self.refresh_head] -= 1
self.refresh_head = (self.refresh_head + 1) % self.nbr_bits | As a python code expert, you are capable of creating scripts from specifications. |
def batched_expiration_maintenance_dev(self, elapsed_time):
""" Batched version of expiration_maintenance() """
num_iterations = self.num_batched_maintenance(elapsed_time)
for i in range(num_iterations):
self.expiration_maintenance() | Can you create a Python 3 function that
batches version of expiration maintenance dev | You are a Python code architect, reviewing and designing scalable and efficient code |
def batched_expiration_maintenance(self, elapsed_time):
""" Batched version of expiration_maintenance()
Cython version
"""
num_iterations = self.num_batched_maintenance(elapsed_time)
self.refresh_head, nonzero = maintenance(self.cellarray, self.nbr_bits, num_iterations, self.... | How would you implement a function in Python 3 that
batches version of expiration_maintenance | As a python code expert, you are capable of creating scripts from specifications. |
Compute the refresh time for the given expiration delay | Make a summary of the following Python 3 code
def compute_refresh_time(self):
if self.z == 0:
self.z = 1E-10
s = float(self.expiration) * (1.0/(self.nbr_bits)) * (1.0/(self.counter_init - 1 + (1.0/(self.z * (self.nbr_slices + 1)))))
return s | As a Python code composer, you craft elegant and concise scripts. |
def generate():
################################################################################
### Build new network
net = Network(id='Example7_Brunel2000')
net.notes = 'Example 7: based on network of Brunel 2000'
net.parameters = { 'g': 4,
'eta': 1,
... | Write a Python 3 function for
generating a new network of the same order as the current network. | You are a Python code architect, reviewing and designing scalable and efficient code |
Allocate resources to vertices on cores arbitrarily using a simple greedy algorithm. | Explain what the following Python 3 code does
def allocate(vertices_resources, nets, machine, constraints, placements):
allocation = {}
# Globally reserved resource ranges {resource, [slice, ...], ...}
globally_reserved = defaultdict(list)
# Locally reserved resource ranges {(x, y): {resource, [slice, ... | You are a Python code generator, capable of creating scripts from specifications. |
def create(self, port, qos_policy):
"""Apply QoS rules on port for the first time.
:param port: port object.
:param qos_policy: the QoS policy to be applied on port.
"""
LOG.info("Setting QoS policy %(qos_policy)s on port %(port)s",
dict(qos_policy=qos_policy, p... | Create a Python 3 function for
creating the Nagios related resources for the given port. | As a python code expert, you are capable of creating scripts from specifications. |
def delete(self, port, qos_policy=None):
"""Remove QoS rules from port.
:param port: port object.
:param qos_policy: the QoS policy to be removed from port.
"""
LOG.info("Deleting QoS policy %(qos_policy)s on port %(port)s",
dict(qos_policy=qos_policy, port=port... | Can you create a Python 3 function that
deletes the QoS rules from the specified port. | You are a Python code analyst, evaluating scripts for potential improvements. |
Register a task function. | How would you explain what the following Python 3 function does
def add(self, func: Callable, name: Optional[str]=None,
queue: Optional[str]=None, max_retries: Optional[Number]=None,
periodicity: Optional[timedelta]=None):
"""Register a task function.
:arg func: a callable to be... | You are a Python code architect, reviewing and designing scalable and efficient code |
Schedule a job to be executed as soon as possible. | Explain what the following Python 3 code does
def schedule(self, task: Schedulable, *args, **kwargs):
self._require_attached_tasks()
self._spin.schedule(task, *args, **kwargs) | As a python code expert, you are capable of creating scripts from specifications. |
Schedule a job to be executed in the future. | How would you explain what the following Python 3 function does
def schedule_at(self, task: Schedulable, at: datetime, *args, **kwargs):
self._require_attached_tasks()
self._spin.schedule_at(task, at, *args, **kwargs) | You are a Python code generator, capable of creating scripts from specifications. |
def schedule(self, task: Schedulable, *args, **kwargs):
"""Add a job to be executed ASAP to the batch.
:arg task: the task or its name to execute in the background
:arg args: args to be passed to the task function
:arg kwargs: kwargs to be passed to the task function
"""
... | Can you create a Python 3 function that
adds a job to be executed ASAP to the batch. | You are a Python code architect, reviewing and designing scalable and efficient code |
Add a job to be executed in the future | Can you generate a brief explanation for the following Python 3 code
def schedule_at(self, task: Schedulable, at: datetime, *args, **kwargs):
self.jobs_to_create.append((task, at, args, kwargs)) | You are a Python code analyst, evaluating scripts for potential improvements. |
Unpack the version - related parts of an sver response packet into a new sver object. | Make a summary of the following Python 3 code
def unpack_sver_response_version(packet):
software_name = packet.data.decode("utf-8")
legacy_version_field = packet.arg2 >> 16
if legacy_version_field != 0xFFFF:
# Legacy version encoding: just encoded in decimal fixed-point in the
# integer.
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Utility method for finding full path to a filename as string | Here you have a function in Python 3, explain what it does
def _locate_file(f, base_dir):
if base_dir == None:
return f
file_name = os.path.join(base_dir, f)
real = os.path.realpath(file_name)
#print_v('- Located %s at %s'%(f,real))
return real | You are a Python code architect, reviewing and designing scalable and efficient code |
Generate a network from a NeuroML model. | How would you explain what the following Python 3 function does
def generate_network(nl_model,
handler,
seed=1234,
always_include_props=False,
include_connections=True,
include_inputs=True,
b... | As a Python code analyst, you investigate and solve complex coding mysteries |
def check_to_generate_or_run(argv, sim):
"""
Useful method for calling in main method after network and simulation are
generated, to handle some standard export options like -jnml, -graph etc.
"""
print_v("Checking arguments: %s to see whether anything should be run in simulation %s (net: %s).... | Implement a function in Python 3 to
check if any of the arguments to generate or run are passed to the main method. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _extract_pynn_components_to_neuroml(nl_model, nml_doc=None):
"""
Parse the NeuroMLlite description for cell, synapses and inputs described as
PyNN elements (e.g. IF_cond_alpha, DCSource) and parameters, and convert
these to the equivalent elements in a NeuroMLDocument
"""
if nml_doc =... | Can you create a Python 3 function that
extracts the equivalent elements of the cell synapses and inputs from a NeuroML document. | As a Python code composer, you craft elegant and concise scripts. |
def generate_neuroml2_from_network(nl_model,
nml_file_name=None,
print_summary=True,
seed=1234,
format='xml',
base_dir=None,
... | How would you code a function in Python 3 to
generate and save a NeuroML2 file from a NeuroML model. | As a Python code analyst, you investigate and solve complex coding mysteries |
Generates the NEURON files from the NeuroML file. | Can you generate the documentation for the following Python 3 function
def _generate_neuron_files_from_neuroml(network, verbose=False, dir_for_mod_files = None):
print_v("------------- Generating NEURON files from NeuroML for %s (default dir: %s)..." % (network.id, dir_for_mod_files))
nml_src_files = []
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def generate_and_run(simulation,
simulator,
network=None,
return_results=False,
base_dir=None,
target_dir=None,
num_processors=1):
"""
Generates the network in the specified simulato... | Create a Python 3 function for
generating the network in the specified simulator and runs it. | You are a Python code analyst, evaluating scripts for potential improvements. |
Print a summary of the returned traces and spike times
| Here you have a function in Python 3, explain what it does
def _print_result_info(traces, events):
print_v('Returning %i traces:'%len(traces))
for r in sorted(traces.keys()):
x = traces[r]
print_v(' %s (%s): %s -> %s (min: %s, max: %s, len: %i)'%(r, type(x), x[0],x[-1],min(x),max(x),len(x)))
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Connect the specified input to a wire. | Can you generate the documentation for the following Python 3 function
def connect_input(self, name, wire):
self._inputs[name] = wire
wire.sinks.append(self) | As a Python code composer, you craft elegant and concise scripts. |
Write the configuration for this gate to memory. | How would you explain what the following Python 3 function does
def _write_config(self, memory):
memory.seek(0)
memory.write(struct.pack("<5I",
# sim_length
self._simulator.length,
# input_a_key
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Probe the specified wire. | Can you generate a brief explanation for the following Python 3 code
def connect_input(self, wire):
self._input = wire
wire.sinks.append(self) | You are a Python code analyst, evaluating scripts for potential improvements. |
Write the configuration for this probe to memory. | Can you generate a brief explanation for the following Python 3 code
def _write_config(self, memory):
memory.seek(0)
memory.write(struct.pack("<II",
# sim_length
self._simulator.length,
# input_key
... | As a Python code composer, you craft elegant and concise scripts. |
Read back the probed results. Returns ------- str
A string of 0 s and 1 s one for each millisecond of simulation. | Can you generate a brief explanation for the following Python 3 code
def _read_results(self, memory):
# Seek to the simulation data and read it all back
memory.seek(8)
bits = bitarray(endian="little")
bits.frombytes(memory.read())
self.recorded_data = bits.to01() | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _write_config(self, memory):
"""Write the configuration for this stimulus to memory."""
memory.seek(0)
memory.write(struct.pack("<II",
# sim_length
self._simulator.length,
# output_key
... | Implement a Python 3 function for
writing the configuration for this stimulus to memory. | As a Python code analyst, you investigate and solve complex coding mysteries |
Create a new _Wire with a unique routing key. | Given the following Python 3 function, write the documentation
def _new_wire(self, source, sinks=None):
# Assign sequential routing key to new nets.
wire = _Wire(source, sinks if sinks is not None else [], len(self._wires))
self._wires.append(wire)
return wire | As a Python code analyst, you investigate and solve complex coding mysteries |
Execute a notebook and return a Notebook object. | Can you tell what is the following Python 3 function doing
def execute_notebook(nb_path, pkg_dir, dataframes, write_notebook=False, env=None):
import nbformat
from metapack.jupyter.preprocessors import AddEpilog, AddProlog
from metapack.jupyter.exporters import ExecutePreprocessor, Config
from os.path ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def convert_documentation(nb_path):
"""Run only the document conversion portion of the notebook conversion
The final document will not be completel
"""
with open(nb_path) as f:
nb = nbformat.reads(f.read(), as_version=4)
doc = ExtractInlineMetatabDoc(package_url="metapack+file:" + dirna... | Create a Python 3 function to
convert the notebook to a single document. | You are a Python code generator, capable of creating scripts from specifications. |
Create a metadata dict from a MetatabDoc for Document conversion | Can you tell what is the following Python 3 function doing
def doc_metadata(doc):
r = doc['Root'].as_dict()
r.update(doc['Contacts'].as_dict())
r['author'] = r.get('author', r.get('creator', r.get('wrangler')))
return r | As a python code expert, you are capable of creating scripts from specifications. |
Extract the metatab lines from a notebook and return a Metapack doc | Can you generate a brief explanation for the following Python 3 code
def extract_notebook_metatab(nb_path: Path):
from metatab.rowgenerators import TextRowGenerator
import nbformat
with nb_path.open() as f:
nb = nbformat.read(f, as_version=4)
lines = '\n'.join(['Declare: metatab-latest'] + [g... | As a python code expert, you are capable of creating scripts from specifications. |
Publish a notebook to a wordpress post using Gutenberg blocks. | Explain what the following Python 3 code does
def publish_wp(site_name, output_file, resources, args):
"""Publish a notebook to a wordpress post, using Gutenberg blocks.
Here is what the metadata looks like, in a section of the notebook tagged 'frontmatter'
show_input: hide
github: https://github.com... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add a single resource to the cache. | Here you have a function in Python 3, explain what it does
def add_single_resource(self, ref, **properties):
t = self.doc.find_first('Root.Datafile', value=ref)
if t:
self.prt("Datafile exists for '{}', deleting".format(ref))
self.doc.remove_term(t)
term_name = self.cl... | You are a Python code generator, capable of creating scripts from specifications. |
def add_resource(self, ref, **properties):
"""Add one or more resources entities, from a url and property values,
possibly adding multiple entries for an excel spreadsheet or ZIP file"""
raise NotImplementedError("Still uses decompose_url")
du = Bunch(decompose_url(ref))
added... | Write a Python 3 function for
adding one or more resources entities from a url and property values | As a Python code analyst, you investigate and solve complex coding mysteries |
def _clean_doc(self, doc=None):
"""Clean the doc before writing it, removing unnecessary properties and doing other operations."""
if doc is None:
doc = self.doc
resources = doc['Resources']
# We don't need these anymore because all of the data written into the package is ... | Can you create a Python 3 function that
cleans the doc before writing it. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Load all of the resources from the datafiles into the package. | Can you generate a brief explanation for the following Python 3 code
def _load_resources(self, abs_path=False):
from metapack.doc import MetapackDoc
assert type(self.doc) == MetapackDoc
for r in self.datafiles:
# Special handling for SQL is probably a really bad idea. It should be... | You are a Python code analyst, evaluating scripts for potential improvements. |
Copy all of the documentation files into the database | Make a summary of the following Python 3 code
def _load_documentation_files(self):
for t in self.doc.find(['Root.Documentation', 'Root.Image', 'Root.Notebook']):
resource = self._get_ref_contents(t)
if not resource:
continue
if t.term_is('Root.Documentatio... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _load_files(self):
"""Load other files"""
def copy_dir(path):
for (dr, _, files) in walk(path):
for fn in files:
if '__pycache__' in fn:
continue
relpath = dr.replace(self.source_dir, '').strip('/')
... | Create a Python 3 function for
loading other files from source directory | As a Python code translator, you convert algorithms and pseudocode into Python. |
After a save create a link to the saved file using a non - versioned name | Can you generate a brief explanation for the following Python 3 code
def create_nv_link(self):
from os.path import abspath, islink
from os import unlink, symlink
nv_name = self.doc.as_version(None)
from_path = abspath(self._last_write_path or self.package_path.path)
to_path =... | As a Python code analyst, you investigate and solve complex coding mysteries |
def register_periodic_tasks(self, tasks: Iterable[Task]):
"""Register tasks that need to be scheduled periodically."""
for task in tasks:
self._scheduler.enter(
int(task.periodicity.total_seconds()),
0,
self._schedule_periodic_task,
... | Can you implement a function in Python 3 that
registers tasks that need to be scheduled periodically. | You are a Python code architect, reviewing and designing scalable and efficient code |
def next_future_periodic_delta(self) -> Optional[float]:
"""Give the amount of seconds before the next periodic task is due."""
try:
next_event = self._scheduler.queue[0]
except IndexError:
return None
now = time.monotonic()
next_event_time = next_event[0... | Create a Python 3 function for
giving the amount of seconds before the next periodic task is due. | As a Python code composer, you craft elegant and concise scripts. |
Get the next periodic task schedule. | Can you generate a brief explanation for the following Python 3 code
def inspect_periodic_tasks(self) -> List[Tuple[int, str]]:
return [(int(e[0]), e[3][0].name) for e in self._scheduler.queue] | You are a Python code generator, capable of creating scripts from specifications. |
def get_jobs_from_queue(self, queue: str, max_jobs: int) -> List[Job]:
"""Get jobs from a queue."""
rv = list()
while len(rv) < max_jobs:
try:
job_json_string = self._get_queue(queue).get(block=False)
except Empty:
break
job = ... | Implement a Python 3 function for
getting jobs from a queue. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the default local index file from the download cache | Here you have a function in Python 3, explain what it does
def search_index_file():
from metapack import Downloader
from os import environ
return environ.get('METAPACK_SEARCH_INDEX',
Downloader.get_instance().cache.getsyspath('index.json')) | You are a Python code architect, reviewing and designing scalable and efficient code |
def update(self,o):
"""Update from another index or index dict"""
self.open()
try:
self._db.update(o._db)
except AttributeError:
self._db.update(o) | How would you code a function in Python 3 to
update from another index or index dict | As a python code expert, you are capable of creating scripts from specifications. |
Print Tile bounding box as geometry. | How would you explain what the following Python 3 function does
def bbox(ctx, tile):
geom = TilePyramid(
ctx.obj['grid'],
tile_size=ctx.obj['tile_size'],
metatiling=ctx.obj['metatiling']
).tile(*tile).bbox(pixelbuffer=ctx.obj['pixelbuffer'])
if ctx.obj['output_format'] in ['WKT', 'Ti... | You are a Python code architect, reviewing and designing scalable and efficient code |
Print a tile containing POINT.. | Can you generate a brief explanation for the following Python 3 code
def tile(ctx, point, zoom):
tile = TilePyramid(
ctx.obj['grid'],
tile_size=ctx.obj['tile_size'],
metatiling=ctx.obj['metatiling']
).tile_from_xy(*point, zoom=zoom)
if ctx.obj['output_format'] == 'Tile':
clic... | You are a Python code generator, capable of creating scripts from specifications. |
def tiles(ctx, bounds, zoom):
"""Print Tiles from bounds."""
tiles = TilePyramid(
ctx.obj['grid'],
tile_size=ctx.obj['tile_size'],
metatiling=ctx.obj['metatiling']
).tiles_from_bounds(bounds, zoom=zoom)
if ctx.obj['output_format'] == 'Tile':
for tile in tiles:
... | Write a Python 3 function for
printing Tiles from bounds. | You are a Python code analyst, evaluating scripts for potential improvements. |
def snap_bbox(ctx, bounds, zoom):
"""Snap bbox to tile grid."""
click.echo(box(*tilematrix.snap_bounds(
bounds=bounds,
tile_pyramid=TilePyramid(
ctx.obj['grid'],
tile_size=ctx.obj['tile_size'],
metatiling=ctx.obj['metatiling']
),
zoom=zoom,
... | Can you create a Python 3 function that
snaps bounding box to tile grid. | You are a Python code analyst, evaluating scripts for potential improvements. |
Generates a random sequential initial placement for the chips in the system. | How would you explain what the following Python 3 function does
def _initial_placement(movable_vertices, vertices_resources, machine, random):
# Initially fill chips in the system in a random order
locations = list(machine)
random.shuffle(locations)
location_iter = iter(locations)
# Greedily place ... | You are a Python code architect, reviewing and designing scalable and efficient code |
A simple annealing based placement algorithm. | Can you generate a brief explanation for the following Python 3 code
def place(vertices_resources, nets, machine, constraints,
effort=1.0, random=default_random, on_temperature_change=None,
kernel=default_kernel, kernel_kwargs={}):
"""A flat Simulated Annealing based placement algorithm.
Th... | As a Python code composer, you craft elegant and concise scripts. |
Update a citation dictionary by editing the Author field | Given the following Python 3 function, write the documentation
def make_citation_dict(td):
from datetime import datetime
if isinstance(td, dict):
d = td
name = d['name_link']
else:
d = td.as_dict()
d['_term'] = td
try:
d['name_link'] = td.name
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return a dict with BibText key - value pairs for metatab data. | Here you have a function in Python 3, explain what it does
def make_metatab_citation_dict(t):
try:
if parse_app_url(t.url).proto == 'metatab':
try:
url = parse_app_url(str(t.resolved_url)).resource_url
doc = t.row_generator.generator.package
except... | As a Python code composer, you craft elegant and concise scripts. |
def _bibliography(doc, terms, converters=[], format='html'):
"""
Render citations, from a document or a doct of dicts
If the input is a dict, each key is the name of the citation, and the value is a BibTex
formatted dict
:param doc: A MetatabDoc, or a dict of BibTex dicts
:return:
"""
... | Write a Python 3 script to
render citations from a document or a dict of dicts | As a Python code analyst, you investigate and solve complex coding mysteries |
Create a Jinja context for display | Make a summary of the following Python 3 code
def display_context(doc):
from rowgenerators.exceptions import DownloadError
context = {s.name.lower(): s.as_dict() for s in doc if s.name.lower() != 'schema'}
#import json
#print(json.dumps(context, indent=4))
mandatory_sections = ['documentation', '... | As a Python code analyst, you investigate and solve complex coding mysteries |
A generator which iterates over a set of vertices in a breadth - first vertex order in terms of connectivity. | Given the following Python 3 function, write the documentation
def breadth_first_vertex_order(vertices_resources, nets):
# Special case: no vertices, just stop immediately
if len(vertices_resources) == 0:
return
# Enumerate the set of nets attached to each vertex
vertex_neighbours = defaultdict... | You are a Python code generator, capable of creating scripts from specifications. |
Places vertices in breadth - first order onto chips in the machine. | Given the following Python 3 function, write the documentation
def place(vertices_resources, nets, machine, constraints, chip_order=None):
return sequential_place(vertices_resources, nets,
machine, constraints,
breadth_first_vertex_order(vertices_resources,
... | As a python code expert, you are capable of creating scripts from specifications. |
Returns a random xkcd comic object for a random xkcd comic. | Can you tell what is the following Python 3 function doing
def getRandomComic():
random.seed()
numComics = getLatestComicNum()
number = random.randint(1, numComics)
return Comic(number) | As a Python code analyst, you investigate and solve complex coding mysteries |
def getComic(number, silent=True):
""" Produces a :class:`Comic` object with index equal to the provided argument.
Prints an error in the event of a failure (i.e. the number is less than zero
or greater than the latest comic number) and returns an empty Comic object.
Arguments:
an integer or string that repr... | Write a Python 3 script for
returning a : class : Comic object with the provided index equal to the provided argument. | You are a Python code analyst, evaluating scripts for potential improvements. |
def getWhatIfArchive():
""" Parses the xkcd What If archive. getWhatIfArchive passes the HTML text of
the archive page into a :class:`WhatIfArchiveParser` and then calls
the parser's :func:`WhatIfArchiveParser.getWhatIfs` method and returns the dictionary produced.
This function returns a dictionary mapping art... | Can you create a Python 3 function that
parses the xkcd What If archive page and returns the dictionary produced by the parser. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a randomly generated WhatIf object using the Python standard library
random number generator. | Here you have a function in Python 3, explain what it does
def getRandomWhatIf():
random.seed()
archive = getWhatIfArchive()
latest = getLatestWhatIfNum(archive)
number = random.randint(1, latest)
return archive[number] | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a : class:`WhatIf` object corresponding to the What If article of the passed index. | Can you generate a brief explanation for the following Python 3 code
def getWhatIf(number):
archive = getWhatIfArchive()
latest = getLatestWhatIfNum(archive)
if type(number) is str and number.isdigit():
number = int(number)
if number > latest or latest <= 0:
return None
return archive[number] | You are a Python code analyst, evaluating scripts for potential improvements. |
This function is used to convert a unicode string to ASCII. | Can you tell what is the following Python 3 function doing
def convertToAscii(string, error="?"):
running = True
asciiString = string
while running:
try:
asciiString = asciiString.encode('ascii')
except UnicodeError as unicode:
start = unicode.start
end = unicode.end
asciiString = asciiString[:start... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Downloads the image of the comic onto your computer. | Can you tell what is the following Python 3 function doing
def download(self, output="", outputFile="", silent=True):
image = urllib.urlopen(self.imageLink).read()
#Process optional input to work out where the dowload will go and what it'll be called
if output != "":
output = os.path.abspath(os.path.expanduse... | As a python code expert, you are capable of creating scripts from specifications. |
def replace_local_hyperlinks(
text, base_url="https://github.com/project-rig/rig/blob/master/"):
"""Replace local hyperlinks in RST with absolute addresses using the given
base URL.
This is used to make links in the long description function correctly
outside of the repository (e.g. when publis... | Can you create a Python 3 function that
replaces local hyperlinks in RST with absolute addresses using the given base_url. | You are a Python code analyst, evaluating scripts for potential improvements. |
def dump_index(args, idx):
"""Create a metatab file for the index"""
import csv
import sys
from metatab import MetatabDoc
doc = MetatabDoc()
pack_section = doc.new_section('Packages', ['Identifier', 'Name', 'Nvname', 'Version', 'Format'])
r = doc['Root']
r.new_term('Root.Title', 'Pa... | Write a Python 3 script for
creating a metatab file for the index | You are a Python code analyst, evaluating scripts for potential improvements. |
Setup the layer two agent. | Given the following Python 3 function, write the documentation
def _setup(self):
agent_config = CONF.get("AGENT", {})
self._worker_count = agent_config.get('worker_count')
self._phys_net_map = agent_config.get(
'physical_network_vswitch_mappings', [])
self._local_network_vswi... | You are a Python code generator, capable of creating scripts from specifications. |
Setup the RPC client for the current agent. | Can you generate the documentation for the following Python 3 function
def _setup_rpc(self):
self._plugin_rpc = agent_rpc.PluginApi(topics.PLUGIN)
self._state_rpc = agent_rpc.PluginReportStateAPI(topics.PLUGIN)
self._client = n_rpc.get_client(self.target)
self._consumers.extend([
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Callback for adding ports. | Given the following Python 3 function, write the documentation
def _process_added_port_event(self, port_name):
LOG.info("Hyper-V VM vNIC added: %s", port_name)
self._added_ports.add(port_name) | As a Python code analyst, you investigate and solve complex coding mysteries |
def _load_physical_network_mappings(self, phys_net_vswitch_mappings):
"""Load all the information regarding the physical network."""
for mapping in phys_net_vswitch_mappings:
parts = mapping.split(':')
if len(parts) != 2:
LOG.debug('Invalid physical network mappin... | Create a Python 3 function to
load all the information regarding the physical network. | As a Python code composer, you craft elegant and concise scripts. |
Get the vswitch name for the received network information. | Can you generate the documentation for the following Python 3 function
def _get_vswitch_name(self, network_type, physical_network):
if network_type != constants.TYPE_LOCAL:
vswitch_name = self._get_vswitch_for_physical_network(
physical_network)
else:
vswitch_name... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _get_vswitch_for_physical_network(self, phys_network_name):
"""Get the vswitch name for the received network name."""
for pattern in self._physical_network_mappings:
if phys_network_name is None:
phys_network_name = ''
if re.match(pattern, phys_network_name):
... | Can you implement a function in Python 3 that
gets the vswitch name for the received network name. | You are a Python code generator, capable of creating scripts from specifications. |
def _get_network_vswitch_map_by_port_id(self, port_id):
"""Get the vswitch name for the received port id."""
for network_id, vswitch in six.iteritems(self._network_vswitch_map):
if port_id in vswitch['ports']:
return (network_id, vswitch)
# If the port was not found,... | Implement a Python 3 function for
getting the vswitch name for the received port id. | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.