output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def _update_port_status_cache(self, device, device_bound=True):
"""Update the ports status cache."""
with self._cache_lock:
if device_bound:
self._bound_ports.add(device)
self._unbound_ports.discard(device)
else:
self._bound_ports.d... | Can you create a Python 3 function that
updates the ports status cache. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _create_event_listeners(self):
"""Create and bind the event listeners."""
LOG.debug("Create the event listeners.")
for event_type, callback in self._event_callback_pairs:
LOG.debug("Create listener for %r event", event_type)
listener = self._utils.get_vnic_event_liste... | Create a Python 3 function for
creating and bind the event listeners. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _port_bound(self, port_id, network_id, network_type, physical_network,
segmentation_id, port_security_enabled, set_port_sriov):
"""Bind the port to the recived network."""
LOG.debug("Binding port %s", port_id)
if network_id not in self._network_vswitch_map:
s... | Write a Python 3 script to
bind the port to the recived network. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Process the added ports. | Make a summary of the following Python 3 code
def process_added_port(self, device_details):
device = device_details['device']
port_id = device_details['port_id']
reprocess = True
try:
self._process_added_port(device_details)
LOG.debug("Updating cached port %s sta... | You are a Python code analyst, evaluating scripts for potential improvements. |
Process the new devices. | How would you explain what the following Python 3 function does
def _treat_devices_added(self):
try:
devices_details_list = self._plugin_rpc.get_devices_details_list(
self._context, self._added_ports, self._agent_id)
except Exception as exc:
LOG.debug("Unable to g... | As a Python code composer, you craft elegant and concise scripts. |
def _process_removed_port(self, device):
"""Process the removed ports."""
LOG.debug("Trying to remove the port %r", device)
self._update_port_status_cache(device, device_bound=False)
self._port_unbound(device, vnic_deleted=True)
LOG.debug("The port was successfully removed.")
... | Write a Python 3 function for
processing the removed ports. | As a Python code composer, you craft elegant and concise scripts. |
def _treat_devices_removed(self):
"""Process the removed devices."""
for device in self._removed_ports.copy():
eventlet.spawn_n(self._process_removed_port, device) | Can you create a Python 3 function that
processes the removed devices. | As a Python code analyst, you investigate and solve complex coding mysteries |
Process the information regarding the available ports. | Here you have a function in Python 3, explain what it does
def _work(self):
if self._refresh_cache:
# Inconsistent cache might cause exceptions. For example,
# if a port has been removed, it will be known in the next
# loop. Using the old switch port can cause exceptions.
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Build source packages.
The mp build program runs all of the resources listed in a Metatab file and
produces one or more Metapack packages with those resources localized. It
will always try to produce a Filesystem package, and may optionally produce
Excel, Zip and CSV packages.
Typical usage is to ... | Here you have a function in Python 3, explain what it does
def build(subparsers):
parser = subparsers.add_parser(
'build',
help='Build derived packages',
description=build.__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog='')
parser.set_defaults(run... | As a Python code analyst, you investigate and solve complex coding mysteries |
Create local Zip Excel and Filesystem packages and process the data. | Can you generate a brief explanation for the following Python 3 code
def metatab_derived_handler(m):
from metapack.exc import PackageError
from metapack.util import get_materialized_data_cache
from shutil import rmtree
create_list = []
url = None
doc = MetapackDoc(m.mt_file)
env = get_lib... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def init():
"""Initialize features that are normally initialized in the CLI"""
from metapack.appurl import SearchUrl
import metapack as mp
from os import environ
SearchUrl.initialize() # This makes the 'index:" urls work
mp.Downloader.context.update(environ) | Implement a function in Python 3 to
initialize features that are normally initialized in the CLI | As a Python code analyst, you investigate and solve complex coding mysteries |
Interpret a struct file defining the location of variables in memory. | Given the following Python 3 function, write the documentation
def read_struct_file(struct_data):
# Holders for all structs
structs = dict()
# Holders for the current struct
name = None
# Iterate over every line in the file
for i, l in enumerate(struct_data.splitlines()):
# Empty the l... | As a python code expert, you are capable of creating scripts from specifications. |
def num(value):
"""Convert a value from one of several bases to an int."""
if re_hex_num.match(value):
return int(value, base=16)
else:
return int(value) | Can you create a Python 3 function that
converts a value from one of several bases to an int. | You are a Python code analyst, evaluating scripts for potential improvements. |
def update_default_values(self, **updates):
"""Replace the default values of specified fields.
Parameters
----------
Parameters are taken as keyword-arguments of `field=new_value`.
Raises
------
KeyError
If a field doesn't exist in the struct.
... | Can you write a function in Python 3 where it
replaces the default values of specified fields in the internal structure. | You are a Python code analyst, evaluating scripts for potential improvements. |
def pack(self):
"""Pack the struct (and its default values) into a string of bytes.
Returns
-------
:py:class:`bytes`
Byte-string representation of struct containing default values.
"""
# Generate a buffer big enough to hold the packed values
data = b... | Can you create a Python 3 function that
packs the struct into a string of bytes. | As a Python code analyst, you investigate and solve complex coding mysteries |
Give the amount of seconds before the next future job is due. | Here you have a function in Python 3, explain what it does
def next_future_job_delta(self) -> Optional[float]:
job = self._get_next_future_job()
if not job:
return None
return (job.at - datetime.now(timezone.utc)).total_seconds() | You are a Python code analyst, evaluating scripts for potential improvements. |
Allocate and return a file - like view of a region of SDRAM for each vertex. | Can you generate a brief explanation for the following Python 3 code
def sdram_alloc_for_vertices(controller, placements, allocations,
core_as_tag=True, sdram_resource=SDRAM,
cores_resource=Cores, clear=False):
"""Allocate and return a file-like view of a re... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Advance the status of a job depending on its execution. | Can you generate the documentation for the following Python 3 function
def advance_job_status(namespace: str, job: Job, duration: float,
err: Optional[Exception]):
"""Advance the status of a job depending on its execution.
This function is called after a job has been executed. It calcula... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return a Tile object of this TilePyramid. | Explain what the following Python 3 code does
def tile(self, zoom, row, col):
return Tile(self, zoom, row, col) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the number of columns at zoom level. | Can you tell what is the following Python 3 function doing
def matrix_width(self, zoom):
validate_zoom(zoom)
width = int(math.ceil(self.grid.shape.width * 2**(zoom) / self.metatiling))
return 1 if width < 1 else width | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the number of rows at zoom level. | Make a summary of the following Python 3 code
def matrix_height(self, zoom):
validate_zoom(zoom)
height = int(math.ceil(self.grid.shape.height * 2**(zoom) / self.metatiling))
return 1 if height < 1 else height | As a python code expert, you are capable of creating scripts from specifications. |
Return the width of a tile in SRID units at zoom level. | Given the following Python 3 function, write the documentation
def tile_x_size(self, zoom):
warnings.warn(DeprecationWarning("tile_x_size is deprecated"))
validate_zoom(zoom)
return round(self.x_size / self.matrix_width(zoom), ROUND) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def tile_y_size(self, zoom):
"""
Height of a tile in SRID units at zoom level.
- zoom: zoom level
"""
warnings.warn(DeprecationWarning("tile_y_size is deprecated"))
validate_zoom(zoom)
return round(self.y_size / self.matrix_height(zoom), ROUND) | Write a Python 3 script to
return the height of a tile in SRID units at zoom level zoom. | As a Python code analyst, you investigate and solve complex coding mysteries |
Tile width in pixel. | Make a summary of the following Python 3 code
def tile_width(self, zoom):
warnings.warn(DeprecationWarning("tile_width is deprecated"))
validate_zoom(zoom)
matrix_pixel = 2**(zoom) * self.tile_size * self.grid.shape.width
tile_pixel = self.tile_size * self.metatiling
return matri... | As a Python code composer, you craft elegant and concise scripts. |
Return the height of the tile in pixel. | Given the following Python 3 function, write the documentation
def tile_height(self, zoom):
warnings.warn(DeprecationWarning("tile_height is deprecated"))
validate_zoom(zoom)
matrix_pixel = 2**(zoom) * self.tile_size * self.grid.shape.height
tile_pixel = self.tile_size * self.metatiling
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def pixel_x_size(self, zoom):
"""
Width of a pixel in SRID units at zoom level.
- zoom: zoom level
"""
validate_zoom(zoom)
return round(
(self.grid.right - self.grid.left) /
(self.grid.shape.width * 2**zoom * self.tile_size),
ROUND
... | Can you write a function in Python 3 where it
returns the width of a pixel in SRID units at zoom level zoom. | As a python code expert, you are capable of creating scripts from specifications. |
def pixel_y_size(self, zoom):
"""
Height of a pixel in SRID units at zoom level.
- zoom: zoom level
"""
validate_zoom(zoom)
return round(
(self.grid.top - self.grid.bottom) /
(self.grid.shape.height * 2**zoom * self.tile_size),
ROUND
... | Can you write a function in Python 3 where it
returns the height of a pixel in SRID units at zoom level zoom. | As a Python code composer, you craft elegant and concise scripts. |
Yield all tiles intersecting with bounds. | Here you have a function in Python 3, explain what it does
def tiles_from_bounds(self, bounds, zoom):
validate_zoom(zoom)
if not isinstance(bounds, tuple) or len(bounds) != 4:
raise ValueError("bounds must be a tuple of left, bottom, right, top values")
if not isinstance(bounds, Boun... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a list of metatiles intersecting with given bounding box. | Given the following Python 3 function, write the documentation
def tiles_from_bbox(self, geometry, zoom):
validate_zoom(zoom)
return self.tiles_from_bounds(geometry.bounds, zoom) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Yields all tiles intersecting with input geometry. | Explain what the following Python 3 code does
def tiles_from_geom(self, geometry, zoom):
validate_zoom(zoom)
if geometry.is_empty:
return
if not geometry.is_valid:
raise ValueError("no valid geometry: %s" % geometry.type)
if geometry.geom_type == "Point":
... | As a python code expert, you are capable of creating scripts from specifications. |
def tile_from_xy(self, x, y, zoom, on_edge_use="rb"):
"""
Return tile covering a point defined by x and y values.
- x: x coordinate
- y: y coordinate
- zoom: zoom level
- on_edge_use: determine which Tile to pick if Point hits a grid edge
- rb: right bottom (... | Write a Python 3 function that can
return a tile covering a point defined by x y and zoom level. | You are a Python code generator, capable of creating scripts from specifications. |
Get metadata for all ladders. | Given the following Python 3 function, write the documentation
def get_ladders_metadata(session, parsed):
ladders = {}
for ladder in parsed.find_all('a', href=re.compile(LADDER_URL_REGEX)):
ladders[ladder.text] = get_ladder_metadata(session, ladder['href'])
return ladders | You are a Python code architect, reviewing and designing scalable and efficient code |
Get metadata for all games. | Explain what the following Python 3 code does
def get_metadata(session, games):
for data in games.values():
parsed = make_scrape_request(session, data['url'])
return {
'ladders': get_ladders_metadata(session, parsed)
} | You are a Python code generator, capable of creating scripts from specifications. |
Update metadata files in the given path. | Explain what the following Python 3 code does
def update_metadata(session, path=DATA_PATH):
with open(os.path.join(path, 'games.json')) as handle:
games = json.loads(handle.read())
for key, data in get_metadata(session, games).items():
with open(os.path.join(path, '{}.json'.format(key)), '... | You are a Python code generator, capable of creating scripts from specifications. |
def sample_counters(mc, system_info):
"""Sample every router counter in the machine."""
return {
(x, y): mc.get_router_diagnostics(x, y) for (x, y) in system_info
} | Can you create a Python 3 function that
samples every router counter in the machine. | You are a Python code analyst, evaluating scripts for potential improvements. |
def deltas(last, now):
"""Return the change in counter values (accounting for wrap-around)."""
return {
xy: RouterDiagnostics(*((n - l) & 0xFFFFFFFF
for l, n in zip(last[xy], now[xy])))
for xy in last
} | Create a Python 3 function to
return the change in counter values. | You are a Python code architect, reviewing and designing scalable and efficient code |
Monitor the counters on a specified machine taking a snap - shot every
time the generator f yields. | Can you tell what is the following Python 3 function doing
def monitor_counters(mc, output, counters, detailed, f):
# Print CSV header
output.write("time,{}{}\n".format("x,y," if detailed else "",
",".join(counters)))
system_info = mc.get_system_info()
# Make an i... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return a generator function which yields every time the user presses
return. | How would you explain what the following Python 3 function does
def press_enter(multiple=False, silent=False):
def f():
try:
while True:
if silent:
yield input()
else:
sys.stderr.write("<press enter> ")
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Listen for a ping broadcast message from an unbooted SpiNNaker board on port 54321. | Explain what the following Python 3 code does
def listen(timeout=6.0, port=BOOT_PORT):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Don't take control of this socket in the system (i.e. allow other
# processes to bind to it) since we're listening for broadcasts.
s.setsockopt(socket.SOL_SOCKE... | You are a Python code generator, capable of creating scripts from specifications. |
Remove any files we ve uploaded from the cache. | Can you tell what is the following Python 3 function doing
def clear_cache(m, files_processed):
for what, reason, url, path in files_processed:
cp = m.doc.downloader.cache_path(url)
if m.cache.exists(cp):
m.cache.remove(cp) | You are a Python code generator, capable of creating scripts from specifications. |
Fill NaNs with NaNs in the categoricals of the archive with NaNs. | Explain what the following Python 3 code does
def fill_categorical_na(df, nan_cat='NA'):
for col in df.columns[df.isna().any()].tolist():
if df[col].dtype.name != 'category':
# If not categorical, fill with a blank, which creates and
# empty cell in CSV.
df[col] = df[col... | You are a Python code generator, capable of creating scripts from specifications. |
gets the unique ip addresses of the executors of the current application | Given the following Python 3 function, write the documentation
def executor_ips(sc):
try:
app_id = sc.applicationId
except AttributeError:
app_id = sc.getConf().get('spark.app.id')
# for getting the url (see: https://github.com/apache/spark/pull/15000)
try:
base_url = sc.u... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a new SparkContext object with added properties set to the properties of the SparkContext object. | Can you tell what is the following Python 3 function doing
def change(sc=None, app_name='customSpark', master=None, wait='ips', min_cores=None, min_ips=None, timeout=30,
refresh_rate=0.5, fail_on_timeout=False, **kwargs):
""" Returns a new Spark Context (sc) object with added properties set
:par... | As a python code expert, you are capable of creating scripts from specifications. |
Regroups an rdd into groups of size groups | How would you explain what the following Python 3 function does
def regroup(rdd, groups=10, check_first=False):
if check_first:
first = rdd.first()
if isinstance(first, (list, tuple, collections.Iterable)):
if len(first) != 2:
raise ValueError('first item was not not... | You are a Python code architect, reviewing and designing scalable and efficient code |
Saves an rdd to a pickle file. | Can you tell what is the following Python 3 function doing
def save_rdd_as_pickle(rdd, path, batch_size=10, overwrite=False):
if os.path.isdir(path):
if overwrite:
logging.getLogger('pySparkUtils').info('Deleting files from: %s' % path)
shutil.rmtree(path)
logging.ge... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Loads an RDD that was saved as one pickle file per partition and returns it as a new instance of
. | Make a summary of the following Python 3 code
def load_rdd_from_pickle(sc, path, min_partitions=None, return_type='images'):
if min_partitions is None:
min_partitions = sc.defaultParallelism
rdd = sc.pickleFile(path, minPartitions=min_partitions)
rdd = rdd.flatMap(lambda x: x)
if return_typ... | As a Python code composer, you craft elegant and concise scripts. |
Return a geopandas dataframe | Make a summary of the following Python 3 code
def geo(self):
import geopandas as gpd
from shapely.geometry.polygon import BaseGeometry
from shapely.wkt import loads
gdf = gpd.GeoDataFrame(self)
first = next(gdf.iterrows())[1].geometry
if isinstance(first, str):
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def rows(self):
"""Yield rows like a partition does, with a header first, then rows. """
yield [self.index.name] + list(self.columns)
for t in self.itertuples():
yield list(t) | Can you create a Python 3 function that
yields the rows of the table. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _matches_node_set_props(type_info, node_set_props):
"""
Check whether the node_set properties match the given model type definition
"""
matches = None
for key in node_set_props:
ns_val = node_set_props[key]
if key in type_info:
if ns_val==type_info[key]:
... | Write a Python 3 script for
checking whether the node_set properties match the given model type definition | You are a Python code generator, capable of creating scripts from specifications. |
def get_neuroml_from_sonata(sonata_filename, id, generate_lems = True, format='xml'):
"""
Return a NeuroMLDocument with (most of) the contents of the Sonata model
"""
from neuroml.hdf5.NetworkBuilder import NetworkBuilder
neuroml_handler = NetworkBuilder()
sr = SonataReader(filename=s... | How would you implement a function in Python 3 that
gets a NeuroML document from a Sonata model | You are a Python code analyst, evaluating scripts for potential improvements. |
Search the strings in a config file for a substitutable value | Explain what the following Python 3 code does
def subs(self, path):
#print_v('Checking for: \n %s, \n %s \n in %s'%(self.substitutes,self.init_substitutes,path))
if type(path) == int or type(path) == float:
return path
for s in self.init_substitutes:
if path.startswith... | You are a Python code architect, reviewing and designing scalable and efficient code |
Parse the Sonata file and call the appropriate methods in the handler. | Can you generate a brief explanation for the following Python 3 code
def parse(self, handler):
########################################################################
# load the main configuration scripts
main_config_filename = os.path.abspath(self.parameters['filename'])
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def add_neuroml_components(self, nml_doc):
"""
Based on cell & synapse properties found, create the corresponding NeuroML components
"""
is_nest = False
print_v("Adding NeuroML cells to: %s"%nml_doc.id)
#pp.pprint(self.pop_comp_info)
for c in... | Create a Python 3 function to
add the components of the NeuroML cell to the doc. | You are a Python code analyst, evaluating scripts for potential improvements. |
def generate_lems_file(self, nml_file_name, nml_doc):
"""
Generate a LEMS file to use in simulations of the NeuroML file
"""
#pp.pprint(self.simulation_config)
#pp.pprint(self.pop_comp_info)
#pp.pprint(self.node_set_mappings)
if 'output' in s... | Write a Python 3 function that can
generate a LEMS file to use in simulations of the NeuroML file. | As a Python code analyst, you investigate and solve complex coding mysteries |
Clip input geometry to SRS bounds of given TilePyramid. | Can you tell what is the following Python 3 function doing
def clip_geometry_to_srs_bounds(geometry, pyramid, multipart=False):
if not geometry.is_valid:
raise ValueError("invalid geometry given")
pyramid_bbox = box(*pyramid.bounds)
# Special case for global tile pyramids if geometry extends over t... | As a Python code analyst, you investigate and solve complex coding mysteries |
Extend bounds to be aligned with union of tile bboxes. | Can you generate the documentation for the following Python 3 function
def snap_bounds(bounds=None, tile_pyramid=None, zoom=None, pixelbuffer=0):
bounds = Bounds(*bounds)
validate_zoom(zoom)
lb = _tile_from_xy(tile_pyramid, bounds.left, bounds.bottom, zoom, on_edge_use="rt")
rt = _tile_from_xy(tile_pyra... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _verify_shape_bounds(shape, bounds):
"""Verify that shape corresponds to bounds apect ratio."""
if not isinstance(shape, (tuple, list)) or len(shape) != 2:
raise TypeError(
"shape must be a tuple or list with two elements: %s" % str(shape)
)
if not isinstance(bounds, (tuple, ... | Create a Python 3 function for
verifying that shape corresponds to bounds apect ratio. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _tile_intersecting_tilepyramid(tile, tp):
"""Return all tiles from tilepyramid intersecting with tile."""
if tile.tp.grid != tp.grid:
raise ValueError("Tile and TilePyramid source grids must be the same.")
tile_metatiling = tile.tile_pyramid.metatiling
pyramid_metatiling = tp.metatiling
... | Write a Python 3 script to
return all tiles from tilepyramid intersecting with tile. | As a python code expert, you are capable of creating scripts from specifications. |
def _global_tiles_from_bounds(tp, bounds, zoom):
"""Return also Tiles if bounds cross the antimeridian."""
seen = set()
# clip to tilepyramid top and bottom bounds
left, right = bounds.left, bounds.right
top = tp.top if bounds.top > tp.top else bounds.top
bottom = tp.bottom if bounds.bottom < t... | Can you create a Python 3 function that
yields all tiles that overlap the given bounds. | As a Python code analyst, you investigate and solve complex coding mysteries |
Yield all tiles intersecting with bounds. | Can you generate a brief explanation for the following Python 3 code
def _tiles_from_cleaned_bounds(tp, bounds, zoom):
lb = _tile_from_xy(tp, bounds.left, bounds.bottom, zoom, on_edge_use="rt")
rt = _tile_from_xy(tp, bounds.right, bounds.top, zoom, on_edge_use="lb")
for tile_id in product([zoom], range(rt.r... | As a Python code composer, you craft elegant and concise scripts. |
The mp open command will open a CSV resoruce with a system application such as Excel or OpenOffice. | Can you generate a brief explanation for the following Python 3 code
def open_args(subparsers):
parser = subparsers.add_parser(
'open',
help='open a CSV resoruce with a system application',
description=open_args.__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def ner_net(source, destinations, width, height, wrap_around=False, radius=10):
"""Produce a shortest path tree for a given net using NER.
This is the kernel of the NER algorithm.
Parameters
----------
source : (x, y)
The coordinate of the source vertex.
destinations : iterable([(x, y)... | Implement a function in Python 3 to
produce a shortest path tree for a given net using NER. This is the kernel of the NER algorithm. Parameters ---------- source : (x, y) The coordinate of the source vertex. destinations : iterable([(x, y), ...]) The coordinates of destination vertices. width : int Width of the system ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def copy_and_disconnect_tree(root, machine):
"""Copy a RoutingTree (containing nothing but RoutingTrees), disconnecting
nodes which are not connected in the machine.
Note that if a dead chip is part of the input RoutingTree, no corresponding
node will be included in the copy. The assumption behind this... | Write a Python 3 script to
copy a RoutingTree and disconnects nodes which are not connected in the given machine. | You are a Python code architect, reviewing and designing scalable and efficient code |
def a_star(sink, heuristic_source, sources, machine, wrap_around):
"""Use A* to find a path from any of the sources to the sink.
Note that the heuristic means that the search will proceed towards
heuristic_source without any concern for any other sources. This means that
the algorithm may miss a very c... | Can you write a function in Python 3 where it
uses A* to find a path from any of the sources to the sink. | You are a Python code analyst, evaluating scripts for potential improvements. |
def avoid_dead_links(root, machine, wrap_around=False):
"""Modify a RoutingTree to route-around dead links in a Machine.
Uses A* to reconnect disconnected branches of the tree (due to dead links
in the machine).
Parameters
----------
root : :py:class:`~rig.place_and_route.routing_tree.RoutingT... | How would you code a function in Python 3 to
modify a RoutingTree to route - around dead links in a Machine. | As a Python code translator, you convert algorithms and pseudocode into Python. |
This method generates a routing tree for a set of vertices and nets. | How would you explain what the following Python 3 function does
def route(vertices_resources, nets, machine, constraints, placements,
allocations={}, core_resource=Cores, radius=20):
"""Routing algorithm based on Neighbour Exploring Routing (NER).
Algorithm refrence: J. Navaridas et al. SpiNNaker: En... | As a Python code composer, you craft elegant and concise scripts. |
Given a string return true if it matches the supplied list of regular expressions. | Make a summary of the following Python 3 code
def match(string, patterns):
if patterns is None:
return True
else:
return any(re.match(pattern, string)
for pattern in patterns) | As a python code expert, you are capable of creating scripts from specifications. |
Yields a list of processes that are in a SpiNNaker system. | How would you explain what the following Python 3 function does
def get_process_list(mc, x_=None, y_=None, p_=None,
app_ids=None, applications=None, states=None):
"""Scan a SpiNNaker system's cores filtering by the specified features.
Generates
-------
(x, y, core, state, runtime_e... | You are a Python code generator, capable of creating scripts from specifications. |
def build_machine(system_info,
core_resource=Cores,
sdram_resource=SDRAM,
sram_resource=SRAM):
"""Build a :py:class:`~rig.place_and_route.Machine` object from a
:py:class:`~rig.machine_control.machine_controller.SystemInfo` object.
.. note::
Lin... | Can you implement a function in Python 3 that
builds a SpiNNaker machine from a SystemInfo object. | You are a Python code generator, capable of creating scripts from specifications. |
def _get_minimal_core_reservations(core_resource, cores, chip=None):
"""Yield a minimal set of
:py:class:`~rig.place_and_route.constraints.ReserveResourceConstraint`
objects which reserve the specified set of cores.
Parameters
----------
core_resource : resource type
The type of resourc... | How would you implement a function in Python 3 that
yields a minimal set of ReserveResourceConstraint objects which reserve the specified set of cores. | As a Python code analyst, you investigate and solve complex coding mysteries |
def build_core_constraints(system_info, core_resource=Cores):
"""Return a set of place-and-route
:py:class:`~rig.place_and_route.constraints.ReserveResourceConstraint`
which reserve any cores that that are already in use.
The returned list of
:py:class:`~rig.place_and_route.constraints.ReserveResou... | How would you implement a function in Python 3 that
builds a set of place - and - route constraints that reserve all cores that are not already in use. | You are a Python code generator, capable of creating scripts from specifications. |
def build_application_map(vertices_applications, placements, allocations,
core_resource=Cores):
"""Build a mapping from application to a list of cores where the
application is used.
This utility function assumes that each vertex is associated with a
specific application.
... | Write a Python 3 script to
build a mapping from application to a list of cores where the application is used. | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert a set of routing trees into a set of routing tables. | Given the following Python 3 function, write the documentation
def build_routing_tables(routes, net_keys, omit_default_routes=True):
from rig.routing_table import routing_tree_to_tables, remove_default_routes
warnings.warn(
"build_routing_tables() is deprecated, see "
"rig.routing_table.routing... | You are a Python code architect, reviewing and designing scalable and efficient code |
def register_sentry(raven_client, namespace: Optional[str]=None,
send_retries: bool=False):
"""Register the Sentry integration.
Exceptions making jobs fail are sent to Sentry.
:param raven_client: configured Raven client used to sent errors to Sentry
:param namespace: optionally on... | Write a Python 3 function that can
register the Sentry integration. | As a python code expert, you are capable of creating scripts from specifications. |
Add a resource entry to the file | How would you explain what the following Python 3 function does
def add_resource(mt_file, ref, cache):
if isinstance(mt_file, MetapackDoc):
doc = mt_file
else:
doc = MetapackDoc(mt_file)
if not 'Resources' in doc:
doc.new_section('Resources')
doc['Resources'].args = [e for e i... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return Tile boundaries.
- pixelbuffer: tile buffer in pixels | Given the following Python 3 function, write the documentation
def bounds(self, pixelbuffer=0):
left = self._left
bottom = self._bottom
right = self._right
top = self._top
if pixelbuffer:
offset = self.pixel_x_size * float(pixelbuffer)
left -= offset
... | As a Python code composer, you craft elegant and concise scripts. |
def affine(self, pixelbuffer=0):
"""
Return an Affine object of tile.
- pixelbuffer: tile buffer in pixels
"""
return Affine(
self.pixel_x_size,
0,
self.bounds(pixelbuffer).left,
0,
-self.pixel_y_size,
self.... | Can you write a function in Python 3 where it
returns an Affine object of tile. | As a Python code analyst, you investigate and solve complex coding mysteries |
def shape(self, pixelbuffer=0):
"""
Return a tuple of tile height and width.
- pixelbuffer: tile buffer in pixels
"""
# apply pixelbuffers
height = self._base_shape.height + 2 * pixelbuffer
width = self._base_shape.width + 2 * pixelbuffer
if pixelbuffer a... | Create a Python 3 function for
returning a tuple of tile height and width. | You are a Python code analyst, evaluating scripts for potential improvements. |
Return True if tile is available in tile pyramid. | Can you generate the documentation for the following Python 3 function
def is_valid(self):
if not all([
isinstance(self.zoom, int),
self.zoom >= 0,
isinstance(self.row, int),
self.row >= 0,
isinstance(self.col, int),
self.col >= 0
]... | As a Python code composer, you craft elegant and concise scripts. |
def get_parent(self):
"""Return tile from previous zoom level."""
return None if self.zoom == 0 else self.tile_pyramid.tile(
self.zoom - 1, self.row // 2, self.col // 2
) | Implement a Python 3 function for
returning tile from previous zoom level. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_children(self):
"""Return tiles from next zoom level."""
next_zoom = self.zoom + 1
return [
self.tile_pyramid.tile(
next_zoom,
self.row * 2 + row_offset,
self.col * 2 + col_offset
)
for row_offset, col_of... | Write a Python 3 script to
return tiles from next zoom level. | As a Python code composer, you craft elegant and concise scripts. |
def get_neighbors(self, connectedness=8):
"""
Return tile neighbors.
Tile neighbors are unique, i.e. in some edge cases, where both the left
and right neighbor wrapped around the antimeridian is the same. Also,
neighbors ouside the northern and southern TilePyramid boundaries ar... | Write a Python 3 script for
returning the set of unique tile neighbors for this tile. | You are a Python code architect, reviewing and designing scalable and efficient code |
Add a new field to the BitField. | Can you generate the documentation for the following Python 3 function
def add_field(self, identifier, length=None, start_at=None, tags=None):
# Check for zero-length fields
if length is not None and length <= 0:
raise ValueError("Fields must be at least one bit in length.")
# Check... | As a Python code composer, you craft elegant and concise scripts. |
Generate an integer whose bits are set according to the values of the specified fields. | Can you generate the documentation for the following Python 3 function
def get_value(self, tag=None, field=None):
assert not (tag is not None and field is not None), \
"Cannot filter by tag and field simultaneously."
selected_fields = self._select_by_field_or_tag(tag, field)
# Chec... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a bitmask for all fields which exist in the current bit field. | Can you generate a brief explanation for the following Python 3 code
def get_mask(self, tag=None, field=None):
if tag is not None and field is not None:
raise TypeError("get_mask() takes exactly one keyword argument, "
"either 'field' or 'tag' (both given)")
sele... | As a python code expert, you are capable of creating scripts from specifications. |
Internal use only. Returns an OrderedDict of fields which match the supplied field or tag. | Given the following Python 3 function, write the documentation
def _select_by_field_or_tag(self, tag=None, field=None):
# Get the set of fields whose values will be included in the value
if field is not None:
# Select just the specified field (checking the field exists)
field_obj... | As a Python code composer, you craft elegant and concise scripts. |
Get the set of tags for a given field. | Here you have a function in Python 3, explain what it does
def get_tags(self, field):
return self.fields.get_field(field, self.field_values).tags.copy() | You are a Python code architect, reviewing and designing scalable and efficient code |
Get the location and length of a bitfield. | Here you have a function in Python 3, explain what it does
def get_location_and_length(self, field):
field_obj = self.fields.get_field(field, self.field_values)
if field_obj.length is None or field_obj.start_at is None:
raise ValueError(
"Field '{}' does not have a fixed siz... | You are a Python code architect, reviewing and designing scalable and efficient code |
Assign a position & length to any fields which do not have one. | Explain what the following Python 3 code does
def assign_fields(self):
# We must fix fields at every level of the hierarchy separately
# (otherwise fields of children won't be allowed to overlap). Here we
# do a breadth-first iteration over the hierarchy to fix fields with
# given starti... | You are a Python code analyst, evaluating scripts for potential improvements. |
Internal method to assign fields to a subset of all the potential fields. | Can you generate a brief explanation for the following Python 3 code
def _assign_fields(self, identifiers, field_values,
assign_positions, assigned_bits=0):
"""For internal use only. Assign lengths & positions to a subset of all
potential fields with the supplied field_values.
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Remove the geography from the files since it isn t particularly useful in Excel | Explain what the following Python 3 code does
def _load_resources(self):
for t in self.doc.find('Root.Table'):
for c in t.find('Table.Column'):
if c.get_value('datatype') == 'geometry':
c['transform'] = '^empty_str'
c['datatype'] = 'text'
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def user_policy_to_dict(doc):
"""Convert a bucket policy to a dict mapping principal/prefix names to 'R' or 'W' """
import json
if not isinstance(doc, dict):
doc = json.loads(doc)
d = {}
def get_statement(name):
for s in doc['Statement']:
if s['Sid'] == name:
... | Create a Python 3 function for
converting a bucket policy to a dict mapping principal and prefix names to R or W | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the statemtns in a bucket policy as a dict of dicts | Can you tell what is the following Python 3 function doing
def make_bucket_policy_statements(bucket):
import yaml
from os.path import dirname, join, abspath
import copy
import metatab
with open(join(dirname(abspath(metatab.__file__)), 'support', 'policy_parts.yaml')) as f:
parts = yaml.load... | As a Python code composer, you craft elegant and concise scripts. |
Create a bucket policy document from a permissions dict. | Make a summary of the following Python 3 code
def bucket_dict_to_policy(args, bucket_name, d):
import json
iam = get_resource(args, 'iam')
statements = make_bucket_policy_statements(bucket_name)
user_stats = set() # statement tripples
for (user, prefix), mode in d.items():
user_stats.... | You are a Python code architect, reviewing and designing scalable and efficient code |
def bucket_policy_to_dict(policy):
"""Produce a dictionary of read, write permissions for an existing bucket policy document"""
import json
if not isinstance(policy, dict):
policy = json.loads(policy)
statements = {s['Sid']: s for s in policy['Statement']}
d = {}
for rw in ('Read', '... | How would you code a function in Python 3 to
produce a dictionary of read write permissions for an existing bucket policy document | As a Python code analyst, you investigate and solve complex coding mysteries |
Get the local Account for a user name by fetching User and looking up
the arn. | Make a summary of the following Python 3 code
def get_iam_account(l, args, user_name):
iam = get_resource(args, 'iam')
user = iam.User(user_name)
user.load()
return l.find_or_new_account(user.arn) | As a python code expert, you are capable of creating scripts from specifications. |
def getSVD(data, k, getComponents=False, getS=False, normalization='mean'):
""" Wrapper for computeSVD that will normalize and handle a Thunder Images object
:param data: Thunder Images object
:param k: number of components to keep
:param getComponents: will return the components if true, otherwise wil... | Can you create a Python 3 function that
wraps for computeSVD that will normalize and handle a Thunder Images object | You are a Python code architect, reviewing and designing scalable and efficient code |
Convert a duration in seconds into a human friendly string. | Given the following Python 3 function, write the documentation
def human_duration(duration_seconds: float) -> str:
if duration_seconds < 0.001:
return '0 ms'
if duration_seconds < 1:
return '{} ms'.format(int(duration_seconds * 1000))
return '{} s'.format(int(duration_seconds)) | As a Python code analyst, you investigate and solve complex coding mysteries |
def call_with_retry(func: Callable, exceptions, max_retries: int,
logger: Logger, *args, **kwargs):
"""Call a function and retry it on failure."""
attempt = 0
while True:
try:
return func(*args, **kwargs)
except exceptions as e:
attempt += 1
... | Implement a function in Python 3 to
call a function and retry it on failure. | As a Python code composer, you craft elegant and concise scripts. |
def exponential_backoff(attempt: int, cap: int=1200) -> timedelta:
"""Calculate a delay to retry using an exponential backoff algorithm.
It is an exponential backoff with random jitter to prevent failures
from being retried at the same time. It is a good fit for most
applications.
:arg attempt: th... | Write a Python 3 script to
calculate a delay to retry using an exponential backoff algorithm. | 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.