Instruction:
Can you implement a function in Python 3 that
wraps for core place - and - route tasks for common case.

Response:
def place_and_route_wrapper(vertices_resources, vertices_applications,
                            nets, net_keys,
                            system_info, constraints=[],
                            place=default_place, place_kwargs={},
                            allocate=default_allocate, allocate_kwargs={},
                            route=default_route, route_kwargs={},
                            minimise_tables_methods=(remove_default_entries,
                                                     ordered_covering),
                            core_resource=Cores, sdram_resource=SDRAM,
                            sram_resource=SRAM):
    """Wrapper for core place-and-route tasks for the common case.

    This function takes a set of vertices and nets and produces placements,
    allocations, minimised routing tables and application loading information.

    .. note::

        This function replaces the deprecated :py:func:`.wrapper` function and
        makes use of the additional information provided by the
        :py:class:`~rig.machine_control.machine_controller.SystemInfo` object
        to infer the constraints required by most applications such as
        reserving non-idle cores such as the monitor processor.

    Parameters
    ----------
    vertices_resources : {vertex: {resource: quantity, ...}, ...}
        A dictionary from vertex to the required resources for that vertex.
        This dictionary must include an entry for every vertex in the
        application.

        Resource requirements are specified by a dictionary `{resource:
        quantity, ...}` where `resource` is some resource identifier and
        `quantity` is a non-negative integer representing the quantity of that
        resource required.
    vertices_applications : {vertex: application, ...}
        A dictionary from vertices to the application binary to load
        onto cores associated with that vertex. Applications are given as a
        string containing the file name of the binary to load.
    nets : [:py:class:`~rig.netlist.Net`, ...]
        A list (in no particular order) defining the nets connecting vertices.
    net_keys : {:py:class:`~rig.netlist.Net`: (key, mask), ...}
        A dictionary from nets to (key, mask) tuples to be used in SpiNNaker
        routing tables for routes implementing this net. The key and mask
        should be given as 32-bit integers.
    system_info : \
            :py:class:`~rig.machine_control.machine_controller.SystemInfo`
        A data structure which defines the resources available in the target
        SpiNNaker machine, typically returned by
        :py:meth:`rig.machine_control.MachineController.get_system_info`. This
        information will be used internally to build a
        :py:class:`~rig.place_and_route.Machine` and set of
        :py:mod:`rig.place_and_route.constraints` which describe the SpiNNaker
        machine used and ensure placement, allocation and routing only use
        working and unused chips, cores, memory and links. If greater control
        over these datastructures is required this wrapper may not be
        appropriate.
    constraints : [constraint, ...]
        **Optional.** A list of additional constraints on placement, allocation
        and routing.  Available constraints are provided in the
        :py:mod:`rig.place_and_route.constraints` module. These constraints
        will be added to those derrived from the ``system_info`` argument which
        restrict placement and allocation to only idle cores.
    place : function (Default: :py:func:`rig.place_and_route.place`)
        **Optional.** Placement algorithm to use.
    place_kwargs : dict (Default: {})
        **Optional.** Algorithm-specific arguments for the placer.
    allocate : function (Default: :py:func:`rig.place_and_route.allocate`)
        **Optional.** Allocation algorithm to use.
    allocate_kwargs : dict (Default: {})
        **Optional.** Algorithm-specific arguments for the allocator.
    route : function (Default: :py:func:`rig.place_and_route.route`)
        **Optional.** Routing algorithm to use.
    route_kwargs : dict (Default: {})
        **Optional.** Algorithm-specific arguments for the router.
    minimise_tables_methods : [:py:func:`rig.routing_table.minimise`, ...]
        **Optional.** An iterable of routing table minimisation algorithms to
        use when routing tables outgrow the space available.  Each method is
        tried in the order presented and the first to meet the required target
        length for a given chip is used. Consequently less computationally
        costly algorithms should be nearer the start of the list. The default
        methods will try to remove default routes
        (:py:meth:`rig.routing_table.remove_default_routes.minimise`) and then
        fall back on the ordered covering algorithm
        (:py:meth:`rig.routing_table.ordered_covering.minimise`).
    core_resource : resource (Default: :py:data:`~rig.place_and_route.Cores`)
        **Optional.** The resource identifier used for cores.
    sdram_resource : resource (Default: :py:data:`~rig.place_and_route.SDRAM`)
        **Optional.** The resource identifier used for SDRAM.
    sram_resource : resource (Default: :py:data:`~rig.place_and_route.SRAM`)
        **Optional.** The resource identifier used for SRAM (System RAM).

    Returns
    -------
    placements : {vertex: (x, y), ...}
        A dictionary from vertices to the chip coordinate produced by
        placement.
    allocations : {vertex: {resource: slice, ...}, ...}
        A dictionary from vertices to the resources allocated to it. Resource
        allocations are dictionaries from resources to a :py:class:`slice`
        defining the range of the given resource type allocated to the vertex.
        These :py:class:`slice` objects have `start` <= `end` and `step` set to
        None.
    application_map : {application: {(x, y): set([core_num, ...]), ...}, ...}
        A dictionary from application to the set of cores it should be loaded
        onto. The set of cores is given as a dictionary from chip to sets of
        core numbers.
    routing_tables : {(x, y): \
                      [:py:class:`~rig.routing_table.RoutingTableEntry`, \
                       ...], ...}
        The generated routing tables. Provided as a dictionary from chip to a
        list of routing table entries.
    """
    # Infer place-and-route data-structures from SystemInfo
    machine = build_machine(system_info,
                            core_resource=core_resource,
                            sdram_resource=sdram_resource,
                            sram_resource=sram_resource)
    base_constraints = build_core_constraints(system_info, core_resource)
    constraints = base_constraints + constraints

    # Place/Allocate/Route
    placements = place(vertices_resources, nets, machine, constraints,
                       **place_kwargs)
    allocations = allocate(vertices_resources, nets, machine, constraints,
                           placements, **allocate_kwargs)
    routes = route(vertices_resources, nets, machine, constraints, placements,
                   allocations, core_resource, **route_kwargs)

    # Build data-structures ready to feed to the machine loading functions
    application_map = build_application_map(vertices_applications, placements,
                                            allocations, core_resource)

    # Build routing tables from the generated routes
    routing_tables = routing_tree_to_tables(routes, net_keys)

    # Minimise the routing tables, if required
    target_lengths = build_routing_table_target_lengths(system_info)
    routing_tables = minimise_tables(routing_tables,
                                     target_lengths,
                                     minimise_tables_methods)

    return placements, allocations, application_map, routing_tables


Instruction:
Can you generate the documentation for the following Python 3 function
def wrapper(vertices_resources, vertices_applications,
            nets, net_keys,
            machine, constraints=[],
            reserve_monitor=True, align_sdram=True,
            place=default_place, place_kwargs={},
            allocate=default_allocate, allocate_kwargs={},
            route=default_route, route_kwargs={},
            core_resource=Cores, sdram_resource=SDRAM):
    """Wrapper for core place-and-route tasks for the common case.
    At a high level this function essentially takes a set of vertices and nets
    and produces placements, memory allocations, routing tables and application
    loading information.

    .. warning::

        This function is deprecated. New users should use
        :py:func:`.place_and_route_wrapper` along with
        :py:meth:`rig.machine_control.MachineController.get_system_info` in
        place of this function. The new wrapper automatically reserves cores
        and SDRAM already in use in the target machine, improving on the
        behaviour of this wrapper which blindly reserves certain ranges of
        resources presuming only core 0 (the monitor processor) is not idle.

    Parameters
    ----------
    vertices_resources : {vertex: {resource: quantity, ...}, ...}
        A dictionary from vertex to the required resources for that vertex.
        This dictionary must include an entry for every vertex in the
        application.
        Resource requirements are specified by a dictionary `{resource:
        quantity, ...}` where `resource` is some resource identifier and
        `quantity` is a non-negative integer representing the quantity of that
        resource required.
    vertices_applications : {vertex: application, ...}
        A dictionary from vertices to the application binary to load
        onto cores associated with that vertex. Applications are given as a
        string containing the file name of the binary to load.
    nets : [:py:class:`~rig.netlist.Net`, ...]
        A list (in no particular order) defining the nets connecting vertices.
    net_keys : {:py:class:`~rig.netlist.Net`: (key, mask), ...}
        A dictionary from nets to (key, mask) tuples to be used in SpiNNaker
        routing tables for routes implementing this net. The key and mask
        should be given as 32-bit integers.
    machine : :py:class:`rig.place_and_route.Machine`
        A data structure which defines the resources available in the target
        SpiNNaker machine.
    constraints : [constraint, ...]
        A list of constraints on placement, allocation and routing. Available
        constraints are provided in the
        :py:mod:`rig.place_and_route.constraints` module.
    reserve_monitor : bool (Default: True)
        **Optional.** If True, reserve core zero since it will be used as the
        monitor processor using a
        :py:class:`rig.place_and_route.constraints.ReserveResourceConstraint`.
    align_sdram : bool (Default: True)
        **Optional.** If True, SDRAM allocations will be aligned to 4-byte
        addresses.  Specifically, the supplied constraints will be augmented
        with an `AlignResourceConstraint(sdram_resource, 4)`.
    place : function (Default: :py:func:`rig.place_and_route.place`)
        **Optional.** Placement algorithm to use.
    place_kwargs : dict (Default: {})
        **Optional.** Algorithm-specific arguments for the placer.
    allocate : function (Default: :py:func:`rig.place_and_route.allocate`)
        **Optional.** Allocation algorithm to use.
    allocate_kwargs : dict (Default: {})
        **Optional.** Algorithm-specific arguments for the allocator.
    route : function (Default: :py:func:`rig.place_and_route.route`)
        **Optional.** Routing algorithm to use.
    route_kwargs : dict (Default: {})
        **Optional.** Algorithm-specific arguments for the router.
    core_resource : resource (Default: :py:data:`~rig.place_and_route.Cores`)
        **Optional.** The resource identifier used for cores.
    sdram_resource : resource (Default: :py:data:`~rig.place_and_route.SDRAM`)
        **Optional.** The resource identifier used for SDRAM.

    Returns
    -------
    placements : {vertex: (x, y), ...}
        A dictionary from vertices to the chip coordinate produced by
        placement.
    allocations : {vertex: {resource: slice, ...}, ...}
        A dictionary from vertices to the resources allocated to it. Resource
        allocations are dictionaries from resources to a :py:class:`slice`
        defining the range of the given resource type allocated to the vertex.
        These :py:class:`slice` objects have `start` <= `end` and `step` set to
        None.
    application_map : {application: {(x, y): set([core_num, ...]), ...}, ...}
        A dictionary from application to the set of cores it should be loaded
        onto. The set of cores is given as a dictionary from chip to sets of
        core numbers.
    routing_tables : {(x, y): \
                      [:py:class:`~rig.routing_table.RoutingTableEntry`, \
                       ...], ...}
        The generated routing tables. Provided as a dictionary from chip to a
        list of routing table entries.
    """
    warnings.warn("rig.place_and_route.wrapper is deprecated "
                  "use rig.place_and_route.place_and_route_wrapper instead in "
                  "new applications.",
                  DeprecationWarning)
    constraints = constraints[:]

    # Augment constraints with (historically) commonly used constraints
    if reserve_monitor:
        constraints.append(
            ReserveResourceConstraint(core_resource, slice(0, 1)))
    if align_sdram:
        constraints.append(AlignResourceConstraint(sdram_resource, 4))

    # Place/Allocate/Route
    placements = place(vertices_resources, nets, machine, constraints,
                       **place_kwargs)
    allocations = allocate(vertices_resources, nets, machine, constraints,
                           placements, **allocate_kwargs)
    routes = route(vertices_resources, nets, machine, constraints, placements,
                   allocations, core_resource, **route_kwargs)

    # Build data-structures ready to feed to the machine loading functions
    application_map = build_application_map(vertices_applications, placements,
                                            allocations, core_resource)

    # Build data-structures ready to feed to the machine loading functions
    from rig.place_and_route.utils import build_routing_tables
    routing_tables = build_routing_tables(routes, net_keys)

    return placements, allocations, application_map, routing_tables

Response: A function that creates a common case with the common case.


Instruction:
Make a summary of the following Python 3 code
def get_region_for_chip(x, y, level=3):
    shift = 6 - 2*level

    bit = ((x >> shift) & 3) + 4*((y >> shift) & 3)  # bit in bits 15:0 to set

    mask = 0xffff ^ ((4 << shift) - 1)  # in {0xfffc, 0xfff0, 0xffc0, 0xff00}
    nx = x & mask  # The mask guarantees that bits 1:0 will be cleared
    ny = y & mask  # The mask guarantees that bits 1:0 will be cleared

    #        sig bits x | sig bits y |  2-bit level  | region select bits
    region = (nx << 24) | (ny << 16) | (level << 16) | (1 << bit)
    return region

Response: Returns the region word for the given chip co -ordinates.


Instruction:
Write a Python 3 script for
generating a reduced set of flood fill parameters.

Response:
def compress_flood_fill_regions(targets):
    """Generate a reduced set of flood fill parameters.

    Parameters
    ----------
    targets : {(x, y) : set([c, ...]), ...}
        For each used chip a set of core numbers onto which an application
        should be loaded.  E.g., the output of
        :py:func:`~rig.place_and_route.util.build_application_map` when indexed
        by an application.

    Yields
    ------
    (region, core mask)
        Pair of integers which represent a region of a SpiNNaker machine and a
        core mask of selected cores within that region for use in flood-filling
        an application.  `region` and `core_mask` are both integer
        representations of bit fields that are understood by SCAMP.

        The pairs are yielded in an order suitable for direct use with SCAMP's
        flood-fill core select (FFCS) method of loading.
    """
    t = RegionCoreTree()

    for (x, y), cores in iteritems(targets):
        for p in cores:
            t.add_core(x, y, p)

    return sorted(t.get_regions_and_coremasks())


Instruction:
Can you generate the documentation for the following Python 3 function
def get_regions_and_coremasks(self):
        region_code = ((self.base_x << 24) | (self.base_y << 16) |
                       (self.level << 16))

        # Generate core masks for any regions which are selected at this level
        # Create a mapping from subregion mask to core numbers
        subregions_cores = collections.defaultdict(lambda: 0x0)
        for core, subregions in enumerate(self.locally_selected):
            if subregions:  # If any subregions are selected on this level
                subregions_cores[subregions] |= 1 << core

        # Order the locally selected items and then yield them
        for (subregions, coremask) in sorted(subregions_cores.items()):
            yield (region_code | subregions), coremask

        if self.level < 3:
            # Iterate through the subregions and recurse, we iterate through in
            # the order which ensures that anything we yield is in increasing
            # order.
            for i in (4*x + y for y in range(4) for x in range(4)):
                subregion = self.subregions[i]
                if subregion is not None:
                    for (region, coremask) in \
                            subregion.get_regions_and_coremasks():
                        yield (region, coremask)

Response: Generate a set of ordered paired region and core masks.


Instruction:
Given the following Python 3 function, write the documentation
def add_core(self, x, y, p):
        # Check that the co-ordinate is contained in this region
        if ((p < 0 or p > 17) or
                (x < self.base_x or x >= self.base_x + self.scale) or
                (y < self.base_y or y >= self.base_y + self.scale)):
            raise ValueError((x, y, p))

        # Determine which subregion this refers to
        subregion = ((x >> self.shift) & 0x3) + 4*((y >> self.shift) & 0x3)

        if self.level == 3:
            # If level-3 then we just add to the locally selected regions
            self.locally_selected[p] |= 1 << subregion
        elif not self.locally_selected[p] & (1 << subregion):
            # If the subregion isn't in `locally_selected` for this core number
            # then add the core to the subregion.
            if self.subregions[subregion] is None:
                # "Lazy": if the subtree doesn't exist yet then add it
                base_x = int(self.base_x + (self.scale / 4) * (subregion % 4))
                base_y = int(self.base_y + (self.scale / 4) * (subregion // 4))
                self.subregions[subregion] = RegionCoreTree(base_x, base_y,
                                                            self.level + 1)

            # If the subregion reports that all of its subregions for this core
            # are selected then we need to add it to `locally_selected`.
            if self.subregions[subregion].add_core(x, y, p):
                self.locally_selected[p] |= 1 << subregion

        # If all subregions are selected for this core and this is not the top
        # level in the hierarchy then return True after emptying the local
        # selection for the core.
        if self.locally_selected[p] == 0xffff and self.level != 0:
            self.locally_selected[p] = 0x0
            return True
        else:
            return False

Response: Add a new core to the region tree.


Instruction:
How would you explain what the following Python 3 function does
def send_scp(self, *args, **kwargs):
        # Retrieve contextual arguments from the keyword arguments.  The
        # context system ensures that these values are present.
        cabinet = kwargs.pop("cabinet")
        frame = kwargs.pop("frame")
        board = kwargs.pop("board")
        return self._send_scp(cabinet, frame, board, *args, **kwargs)

Response: Transmit an SCP Packet to a specific board.


Instruction:
Make a summary of the following Python 3 code
def _send_scp(self, cabinet, frame, board, *args, **kwargs):
        # Find the connection which best matches the specified coordinates,
        # preferring direct connections to a board when available.
        connection = self.connections.get((cabinet, frame, board), None)
        if connection is None:
            connection = self.connections.get((cabinet, frame), None)
        assert connection is not None, \
            "No connection available to ({}, {}, {})".format(cabinet,
                                                             frame,
                                                             board)

        # Determine the size of packet we expect in return, this is usually the
        # size that we are informed we should expect by SCAMP/SARK or else is
        # the default.
        if self._scp_data_length is None:
            length = consts.SCP_SVER_RECEIVE_LENGTH_MAX
        else:
            length = self._scp_data_length

        return connection.send_scp(length, 0, 0, board, *args, **kwargs)

Response: Send an SCP packet to the specified board.


Instruction:
Given the following Python 3 function, write the documentation
def get_software_version(self, cabinet, frame, board):
        sver = self._send_scp(cabinet, frame, board, SCPCommands.sver)

        # Format the result
        # arg1
        code_block = (sver.arg1 >> 24) & 0xff
        frame_id = (sver.arg1 >> 16) & 0xff
        can_id = (sver.arg1 >> 8) & 0xff
        board_id = sver.arg1 & 0xff

        # arg2 (version field unpacked separately)
        buffer_size = (sver.arg2 & 0xffff)

        software_name, version, version_labels = \
            unpack_sver_response_version(sver)

        return BMPInfo(code_block, frame_id, can_id, board_id, version,
                       buffer_size, sver.arg3, software_name, version_labels)

Response: Get the software version for a given BMP.


Instruction:
Can you implement a function in Python 3 that
sets the power of the specified Chip.

Response:
def set_power(self, state, cabinet, frame, board,
                  delay=0.0, post_power_on_delay=5.0):
        """Control power to the SpiNNaker chips and FPGAs on a board.

        Returns
        -------
        state : bool
            True for power on, False for power off.
        board : int or iterable
            Specifies the board to control the power of. This may also be an
            iterable of multiple boards (in the same frame). The command will
            actually be sent board 0, regardless of the set of boards
            specified.
        delay : float
            Number of seconds delay between power state changes of different
            boards.
        post_power_on_delay : float
            Number of seconds for this command to block once the power on
            command has been carried out. A short delay (default) is useful at
            this point since power-supplies and SpiNNaker chips may still be
            coming on line immediately after the power-on command is sent.

            .. warning::
                If the set of boards to be powered-on does not include board 0,
                this timeout should be extended by 2-3 seconds. This is due to
                the fact that BMPs immediately acknowledge power-on commands to
                boards other than board 0 but wait for the FPGAs to be loaded
                before responding when board 0 is powered on.
        """
        if isinstance(board, int):
            boards = [board]
        else:
            boards = list(board)

        arg1 = int(delay * 1000) << 16 | (1 if state else 0)
        arg2 = sum(1 << b for b in boards)

        # Allow additional time for response when powering on (since FPGAs must
        # be loaded). Also, always send the command to board 0. This is
        # required by the BMPs which do not correctly handle the power-on
        # command being sent to anything but board 0. Though this is a bug in
        # the BMP firmware, it is considered sufficiently easy to work-around
        # that no fix is planned.
        self._send_scp(cabinet, frame, 0, SCPCommands.power,
                       arg1=arg1, arg2=arg2,
                       timeout=consts.BMP_POWER_ON_TIMEOUT if state else 0.0,
                       expected_args=0)
        if state:
            time.sleep(post_power_on_delay)


Instruction:
Implement a Python 3 function for
setting or toggle the state of an LED.

Response:
def set_led(self, led, action=None,
                cabinet=Required, frame=Required, board=Required):
        """Set or toggle the state of an LED.

        .. note::
            At the time of writing, LED 7 is only set by the BMP on start-up to
            indicate that the watchdog timer reset the board. After this point,
            the LED is available for use by applications.

        Parameters
        ----------
        led : int or iterable
            Number of the LED or an iterable of LEDs to set the state of (0-7)
        action : bool or None
            State to set the LED to. True for on, False for off, None to
            toggle (default).
        board : int or iterable
            Specifies the board to control the LEDs of. This may also be an
            iterable of multiple boards (in the same frame). The command will
            actually be sent to the first board in the iterable.
        """
        if isinstance(led, int):
            leds = [led]
        else:
            leds = led
        if isinstance(board, int):
            boards = [board]
        else:
            boards = list(board)
            board = boards[0]

        # LED setting actions
        arg1 = sum(LEDAction.from_bool(action) << (led * 2) for led in leds)

        # Bitmask of boards to control
        arg2 = sum(1 << b for b in boards)

        self._send_scp(cabinet, frame, board, SCPCommands.led, arg1=arg1,
                       arg2=arg2, expected_args=0)


Instruction:
How would you implement a function in Python 3 that
reads the value of an FPGA register.

Response:
def read_fpga_reg(self, fpga_num, addr, cabinet, frame, board):
        """Read the value of an FPGA (SPI) register.

        See the SpI/O project's spinnaker_fpga design's `README`_ for a listing
        of FPGA registers. The SpI/O project can be found on GitHub at:
        https://github.com/SpiNNakerManchester/spio/

        .. _README: https://github.com/SpiNNakerManchester/spio/\
                    blob/master/designs/spinnaker_fpgas/README.md#spi-interface

        Parameters
        ----------
        fpga_num : int
            FPGA number (0, 1 or 2) to communicate with.
        addr : int
            Register address to read to (will be rounded down to the nearest
            32-bit word boundary).

        Returns
        -------
        int
            The 32-bit value at that address.
        """
        arg1 = addr & (~0x3)
        arg2 = 4  # Read a 32-bit value
        arg3 = fpga_num
        response = self._send_scp(cabinet, frame, board, SCPCommands.link_read,
                                  arg1=arg1, arg2=arg2, arg3=arg3,
                                  expected_args=0)
        return struct.unpack("<I", response.data)[0]


Instruction:
Here you have a function in Python 3, explain what it does
def write_fpga_reg(self, fpga_num, addr, value, cabinet, frame, board):
        arg1 = addr & (~0x3)
        arg2 = 4  # Write a 32-bit value
        arg3 = fpga_num
        self._send_scp(cabinet, frame, board, SCPCommands.link_write,
                       arg1=arg1, arg2=arg2, arg3=arg3,
                       data=struct.pack("<I", value), expected_args=0)

Response: Write the value to a 32 - bit register in the specified board.


Instruction:
Implement a Python 3 function for
reading the ADC data from the BMP including voltages and temperature.

Response:
def read_adc(self, cabinet, frame, board):
        """Read ADC data from the BMP including voltages and temperature.

        Returns
        -------
        :py:class:`.ADCInfo`
        """
        response = self._send_scp(cabinet, frame, board, SCPCommands.bmp_info,
                                  arg1=BMPInfoType.adc, expected_args=0)
        data = struct.unpack("<"   # Little-endian
                             "8H"  # uint16_t adc[8]
                             "4h"  # int16_t t_int[4]
                             "4h"  # int16_t t_ext[4]
                             "4h"  # int16_t fan[4]
                             "I"   # uint32_t warning
                             "I",  # uint32_t shutdown
                             response.data)

        return ADCInfo(
            voltage_1_2c=data[1] * BMP_V_SCALE_2_5,
            voltage_1_2b=data[2] * BMP_V_SCALE_2_5,
            voltage_1_2a=data[3] * BMP_V_SCALE_2_5,
            voltage_1_8=data[4] * BMP_V_SCALE_2_5,
            voltage_3_3=data[6] * BMP_V_SCALE_3_3,
            voltage_supply=data[7] * BMP_V_SCALE_12,
            temp_top=float(data[8]) * BMP_TEMP_SCALE,
            temp_btm=float(data[9]) * BMP_TEMP_SCALE,
            temp_ext_0=((float(data[12]) * BMP_TEMP_SCALE)
                        if data[12] != BMP_MISSING_TEMP else None),
            temp_ext_1=((float(data[13]) * BMP_TEMP_SCALE)
                        if data[13] != BMP_MISSING_TEMP else None),
            fan_0=float(data[16]) if data[16] != BMP_MISSING_FAN else None,
            fan_1=float(data[17]) if data[17] != BMP_MISSING_FAN else None,
        )


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_resources(res_a, res_b):
    return {resource: value + res_b.get(resource, 0)
            for resource, value in iteritems(res_a)}

Response: Return the resources after adding res_b s resources to res_a.


Instruction:
Write a Python 3 script for
returning the resources remaining after subtracting res_b s resources from res_a.

Response:
def subtract_resources(res_a, res_b):
    """Return the resources remaining after subtracting res_b's resources from
    res_a.

    Parameters
    ----------
    res_a : dict
        Dictionary `{resource: value, ...}`.
    res_b : dict
        Dictionary `{resource: value, ...}`. Must be a (non-strict) subset of
        res_a. If A resource is not present in res_b, the value is presumed to
        be 0.
    """
    return {resource: value - res_b.get(resource, 0)
            for resource, value in iteritems(res_a)}


Instruction:
Write a Python 3 script for
returning the resources available after a specified reserve resource constraint has been applied.

Response:
def resources_after_reservation(res, constraint):
    """Return the resources available after a specified
    ReserveResourceConstraint has been applied.

    Note: the caller is responsible for testing that the constraint is
    applicable to the core whose resources are being constrained.

    Note: this function does not pay attention to the specific position of the
    reserved regieon, only its magnitude.
    """
    res = res.copy()
    res[constraint.resource] -= (constraint.reservation.stop -
                                 constraint.reservation.start)
    return res


Instruction:
How would you implement a function in Python 3 that
applies the changes implied by a reserve resource constraint to a single resource in the specified machine model.

Response:
def apply_reserve_resource_constraint(machine, constraint):
    """Apply the changes implied by a reserve resource constraint to a
    machine model."""
    if constraint.location is None:
        # Compensate for globally reserved resources
        machine.chip_resources \
            = resources_after_reservation(
                machine.chip_resources, constraint)
        if overallocated(machine.chip_resources):
            raise InsufficientResourceError(
                "Cannot meet {}".format(constraint))
        for location in machine.chip_resource_exceptions:
            machine.chip_resource_exceptions[location] \
                = resources_after_reservation(
                    machine.chip_resource_exceptions[location],
                    constraint)
            if overallocated(machine[location]):
                raise InsufficientResourceError(
                    "Cannot meet {}".format(constraint))
    else:
        # Compensate for reserved resources at a specified location
        machine[constraint.location] = resources_after_reservation(
            machine[constraint.location], constraint)
        if overallocated(machine[constraint.location]):
            raise InsufficientResourceError(
                "Cannot meet {}".format(constraint))


Instruction:
How would you explain what the following Python 3 function does
def apply_same_chip_constraints(vertices_resources, nets, constraints):
    # Make a copy of the basic structures to be modified by this function
    vertices_resources = vertices_resources.copy()
    nets = nets[:]
    constraints = constraints[:]

    substitutions = []

    for same_chip_constraint in constraints:
        if not isinstance(same_chip_constraint, SameChipConstraint):
            continue

        # Skip constraints which don't actually merge anything...
        if len(same_chip_constraint.vertices) <= 1:
            continue

        # The new (merged) vertex with which to replace the constrained
        # vertices
        merged_vertex = MergedVertex(same_chip_constraint.vertices)
        substitutions.append(merged_vertex)

        # A set containing the set of vertices to be merged (to remove
        # duplicates)
        merged_vertices = set(same_chip_constraint.vertices)

        # Remove the merged vertices from the set of vertices resources and
        # accumulate the total resources consumed. Note add_resources is not
        # used since we don't know if the resources consumed by each vertex are
        # overlapping.
        total_resources = {}
        for vertex in merged_vertices:
            resources = vertices_resources.pop(vertex)
            for resource, value in iteritems(resources):
                total_resources[resource] = (total_resources.get(resource, 0) +
                                             value)
        vertices_resources[merged_vertex] = total_resources

        # Update any nets which pointed to a merged vertex
        for net_num, net in enumerate(nets):
            net_changed = False

            # Change net sources
            if net.source in merged_vertices:
                net_changed = True
                net = Net(merged_vertex, net.sinks, net.weight)

            # Change net sinks
            for sink_num, sink in enumerate(net.sinks):
                if sink in merged_vertices:
                    if not net_changed:
                        net = Net(net.source, net.sinks, net.weight)
                    net_changed = True
                    net.sinks[sink_num] = merged_vertex

            if net_changed:
                nets[net_num] = net

        # Update any constraints which refer to a merged vertex
        for constraint_num, constraint in enumerate(constraints):
            if isinstance(constraint, LocationConstraint):
                if constraint.vertex in merged_vertices:
                    constraints[constraint_num] = LocationConstraint(
                        merged_vertex, constraint.location)
            elif isinstance(constraint, SameChipConstraint):
                if not set(constraint.vertices).isdisjoint(merged_vertices):
                    constraints[constraint_num] = SameChipConstraint([
                        merged_vertex if v in merged_vertices else v
                        for v in constraint.vertices
                    ])
            elif isinstance(constraint, RouteEndpointConstraint):
                if constraint.vertex in merged_vertices:
                    constraints[constraint_num] = RouteEndpointConstraint(
                        merged_vertex, constraint.route)

    return (vertices_resources, nets, constraints, substitutions)

Response: Modify a set of vertices_resources nets and constraints to account for all SameChipConstraints.


Instruction:
Write a Python 3 function for
giving a set of merged vertices remove them and add them to the supplied placements.

Response:
def finalise_same_chip_constraints(substitutions, placements):
    """Given a set of placements containing the supplied
    :py:class:`MergedVertex`, remove the merged vertices replacing them with
    their constituent vertices (changing the placements inplace).
    """
    for merged_vertex in reversed(substitutions):
        placement = placements.pop(merged_vertex)
        for v in merged_vertex.vertices:
            placements[v] = placement


Instruction:
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)

Response: Return the metatab document for the URL


Instruction:
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 absolute web URLs and may not be related to the location of the metadata.
            s = self.get_resource()
            rs = s.doc.resource(resource_name)
            return parse_app_url(rs.url)
        else:
            jt = self.join_target(resource_name)
            rs = jt.get_resource()
            t = rs.get_target()
        return t

Response: Return a URL to a local copy of a resource suitable for get_generator


Instruction:
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 = 'metapack'
        else:
            u = self

        return MetapackPackageUrl(str(u.clear_fragment()), downloader=self._downloader)

Response: Return the package URL associated with this metadata


Instruction:
Write a Python 3 script to
return a MetapackResourceUrl that includes a reference to the resource.

Response:
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)


Instruction:
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 forms for CSV package URLS:
            # - A CSV package, which can only have absolute URLs
            # - A Filesystem package, which can have relative URLs.

            # The complication is that the filsystem package usually has a metadata file named
            # DEFAULT_METATAB_FILE, which can distinguish it from a CSV package, but it's also possible
            # to have a filesystem package with a non standard package name.

            # So, this clause can happed for two cases: A CSV package or a Filesystem package with a nonstandard
            # metadata file name.

            # For CSV packages, need to get the package and open it to get the resource URL, because
            # they are always absolute web URLs and may not be related to the location of the metadata.

            s = self.get_resource()
            rs = s.metadata_url.doc.resource(resource_name)
            if rs is not None:
                t = parse_app_url(rs.url)
            else:
                raise ResourceError("No resource for '{}' in '{}' ".format(resource_name, self))

        else:
            jt = self.join_target(resource_name)

            try:
                rs = jt.get_resource()
            except DownloadError:
                raise ResourceError(
                    "Failed to download resource for '{}' for '{}' in '{}'".format(jt, resource_name, self))
            t = rs.get_target()

        return t

Response: Resolve a resource URL to a local copy of a resource.


Instruction:
Create a Python 3 function to
return the package URL associated with this metadata

Response:
def package_url(self):
        """Return the package URL associated with this metadata"""
        return MetapackDocumentUrl(str(self.clear_fragment()), downloader=self._downloader).package_url


Instruction:
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')

            if not packages:
                return None

            package = packages.pop(0)

            try:
                resource_str = '#' + url.target_file if url.fragment[0] else ''

                return parse_app_url(package['url'] + resource_str, downloader=url.downloader)
            except KeyError as e:
                return None

        return _search_function

Response: 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.


Instruction:
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

Response: Search for a url by returning the value from the first callback that returns a non - None value


Instruction:
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

Response: Ensure all of the important directories in a source package exist


Instruction:
Can you implement a function in Python 3 that
reads a notebook and extract the metatab document. Only returns the first document

Response:
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.reads(f.read(), as_version=4)

    for cell in nb.cells:
        source = ''.join(cell['source']).strip()
        if source.startswith('%%metatab'):
            return MetatabDoc(TextRowGenerator(source))


Instruction:
Write a Python 3 script for
returning the package directory for a Notebook that is part of a package.

Response:
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_name

    return ensure_source_package_dir(nb_path, pkg_name), pkg_name


Instruction:
Implement a Python 3 function for
adding schema entiries to a metatab doc from a dataframe

Response:
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
    from rowgenerators.generator.python import PandasDataframeSource
    from appurl import parse_app_url

    try:
        doc['Schema']
    except KeyError:
        doc.new_section('Schema', ['DataType', 'Altname', 'Description'])

    schema_name = resource.get_value('schema', resource.get_value('name'))

    schema_term = doc.find_first(term='Table', value=schema_name, section='Schema')

    if schema_term:
        logger.info("Found table for '{}'; skipping".format(schema_name))
        return

    path, name = extract_path_name(resource.url)

    logger.info("Processing {}".format(resource.url))

    si = PandasDataframeSource(parse_app_url(resource.url), df, cache=doc._cache, )

    try:
        ti = TypeIntuiter().run(si)
    except SourceError as e:
        logger.warn("Failed to process '{}'; {}".format(path, e))
        return
    except ConnectionError as e:
        logger.warn("Failed to download '{}'; {}".format(path, e))
        return

    table = doc['Schema'].new_term('Table', schema_name)

    logger.info("Adding table '{}' to metatab schema".format(schema_name))

    for i, c in enumerate(ti.to_rows()):
        raw_alt_name = alt_col_name(c['header'], i)
        alt_name = raw_alt_name if raw_alt_name != c['header'] else ''

        t = table.new_child('Column', c['header'],
                            datatype=type_map.get(c['resolved_type'], c['resolved_type']),
                            altname=alt_name,
                            description=df[c['header']].description \
                                        if hasattr(df, 'description') and df[c['header']].description else ''
                            )

    return table


Instruction:
Create a Python 3 function for
booting a SpiNNaker machine with the given hostname.

Response:
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 SpiNNaker chip to use to boot the system.
    boot_port : int
        The port number to sent boot packets to.
    scamp_binary : filename or None
        Filename of the binary to boot the machine with or None to use the
        SC&MP binary bundled with Rig.
    sark_struct : filename or None
        The 'sark.struct' file which defines the datastructures or None to use
        the one bundled with Rig.
    boot_delay : float
        Number of seconds to pause between sending boot data packets.
    post_boot_delay : float
        Number of seconds to wait after sending last piece of boot data to give
        SC&MP time to re-initialise the Ethernet interface. Note that this does
        *not* wait for the system to fully boot.
    sv_overrides : {name: value, ...}
        Values used to override the defaults in the 'sv' struct defined in the
        struct file.

    Notes
    -----
    The constants `rig.machine_control.boot.spinX_boot_options` provide boot
    parameters for specific SpiNNaker board revisions, for example::

        boot("board1", **spin3_boot_options)

    Will boot the Spin3 board connected with hostname "board1".

    Returns
    -------
    {struct_name: :py:class:`~rig.machine_control.struct_file.Struct`}
        Layout of structs in memory.
    """
    # Get the boot data if not specified.
    scamp_binary = (scamp_binary if scamp_binary is not None else
                    pkg_resources.resource_filename("rig", "boot/scamp.boot"))
    sark_struct = (sark_struct if sark_struct is not None else
                   pkg_resources.resource_filename("rig", "boot/sark.struct"))
    with open(scamp_binary, "rb") as f:
        boot_data = f.read()

    # Read the struct file and modify the "sv" struct to contain the
    # configuration values and write this into the boot data.
    with open(sark_struct, "rb") as f:
        struct_data = f.read()
    structs = struct_file.read_struct_file(struct_data)
    sv = structs[b"sv"]
    sv_overrides.update(kwargs)  # Allow non-explicit keyword arguments for SV
    sv.update_default_values(**sv_overrides)
    sv.update_default_values(unix_time=int(time.time()),
                             boot_sig=int(time.time()),
                             root_chip=1)
    struct_packed = sv.pack()
    assert len(struct_packed) >= 128  # Otherwise shoving this data in is nasty

    buf = bytearray(boot_data)
    buf[BOOT_DATA_OFFSET:BOOT_DATA_OFFSET+BOOT_DATA_LENGTH] = \
        struct_packed[:BOOT_DATA_LENGTH]
    assert len(buf) < DTCM_SIZE  # Assert that we fit in DTCM
    boot_data = bytes(buf)

    # Create a socket to communicate with the board
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.connect((hostname, boot_port))

    # Transmit the boot data as a series of SDP packets.  First determine
    # how many blocks must be sent and transmit that, then transmit each
    # block.
    n_blocks = (len(buf) + BOOT_BYTE_SIZE - 1) // BOOT_BYTE_SIZE
    assert n_blocks <= BOOT_MAX_BLOCKS

    boot_packet(sock, BootCommand.start, arg3=n_blocks - 1)
    time.sleep(boot_delay)

    block = 0
    while len(boot_data) > 0:
        # Get the data to transmit
        data, boot_data = (boot_data[:BOOT_BYTE_SIZE],
                           boot_data[BOOT_BYTE_SIZE:])

        # Transmit, delay and increment the block count
        a1 = ((BOOT_WORD_SIZE - 1) << 8) | block
        boot_packet(sock, BootCommand.send_block, a1, data=data)
        time.sleep(boot_delay)
        block += 1

    # Send the END command
    boot_packet(sock, BootCommand.end, 1)

    # Close the socket and give time to boot
    sock.close()
    time.sleep(post_boot_delay)

    return structs


Instruction:
Write a Python 3 function for
creating and transmit a boot packet to the machine.

Response:
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:class:`bytes`
        Optional data to include in the packet.
    """
    PROTOCOL_VERSION = 1

    # Generate the (network-byte order) header
    header = struct.pack("!H4I", PROTOCOL_VERSION, cmd, arg1, arg2, arg3)

    assert len(data) % 4 == 0  # Data should always be word-sized
    fdata = b""

    # Format the data from little- to network-/big-endian
    while len(data) > 0:
        word, data = (data[:4], data[4:])
        fdata += struct.pack("!I", struct.unpack("<I", word)[0])

    # Transmit the packet
    sock.send(header + fdata)


Instruction:
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)

Response: Produce a copy of this datastructure.


Instruction:
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]
                        for r in self[chip])
                    for chip in self))

Response: Test whether the resources available in this machine description are a subset of those available in another machine description.


Instruction:
Create a Python 3 function for
testing if a machine has wrap - around links installed.

Response:
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 of wrap-around links which are
        working to determine if wrap-around links are really present.

        Parameters
        ----------
        minimum_working : 0.0 <= float <= 1.0
            The minimum proportion of all wrap-around links which must be
            working for this function to return True.

        Returns
        -------
        bool
            True if the system has wrap-around links, False if not.
        """
        working = 0
        for x in range(self.width):
            if (x, 0, Links.south) in self:
                working += 1
            if (x, self.height - 1, Links.north) in self:
                working += 1
            if (x, 0, Links.south_west) in self:
                working += 1
            if (x, self.height - 1, Links.north_east) in self:
                working += 1

        for y in range(self.height):
            if (0, y, Links.west) in self:
                working += 1
            if (self.width - 1, y, Links.east) in self:
                working += 1

            # Don't re-count links counted when scanning the x-axis
            if y != 0 and (0, y, Links.south_west) in self:
                working += 1
            if (y != self.height - 1 and
                    (self.width - 1, y, Links.north_east) in self):
                working += 1

        total = (4 * self.width) + (4 * self.height) - 2

        return (float(working) / float(total)) >= minimum_working


Instruction:
Can you create a Python 3 function that
writes a Metatab doc to a CSV file and update the Modified time

Response:
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_file)

    if u.scheme == 'file':
        doc.write(mt_file)
        return True
    else:
        return False


Instruction:
Create a Python 3 function for
updating the resource properties in the schema.

Response:
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.raw_row_generator

    # Get columns information from the schema, or, if it is a package reference,
    # from the upstream schema

    upstream_columns = {e['name'].lower() if e['name'] else '': e for e in r.columns() or {}}

    # Just from the local schema
    schema_columns = {e['name'].lower() if e['name'] else '': e for e in r.schema_columns or {}}

    # Ask the generator if it can provide column descriptions and types
    generator_columns = {e['name'].lower() if e['name'] else '': e for e in rg.columns or {}}

    def get_col_value(col_name, value_name):

        v = None

        if not col_name:
            return None

        for d in [generator_columns, upstream_columns, orig_columns, schema_columns]:
            v_ = d.get(col_name.lower(), {}).get(value_name)
            if v_:
                v = v_

        return v

    # Look for new properties
    extra_properties = set()
    for d in [generator_columns, upstream_columns, orig_columns, schema_columns]:
        for k, v in d.items():
            for kk, vv in v.items():
                extra_properties.add(kk)

    # Remove the properties that are already accounted for
    extra_properties = extra_properties - {'pos', 'header', 'name', ''}

    # Add any extra properties, such as from upstream packages, to the schema.

    for ep in extra_properties:
        r.doc['Schema'].add_arg(ep)

    for c in schema_term.find('Table.Column'):

        for ep in extra_properties:
            t = c.get_or_new_child(ep)
            v = get_col_value(c.name, ep)
            if v:
                t.value = v
                added.append((c.name, ep, v))

    prt('Updated schema for {}. Set {} properties'.format(r.name, len(added)))


Instruction:
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
            return Path(expanduser(p))

    paths = [environ.get("METAPACK_CONFIG"), '~/.metapack.yaml', '/etc/metapack.yaml']

    for p in paths:

        if not p:
            continue

        p = pexp(p)

        if p.exists():
            with p.open() as f:
                config = yaml.safe_load(f)
                if not config:
                    config = {}

                config['_loaded_from'] = str(p)
                return config

    return None

Response: Return a configuration dict for the current user


Instruction:
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_path.exists():
        return open_package(package_path, downloader=downloader)

Response: Locate the build CSV package which will have distributions if it was generated


Instruction:
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 provisioning_configuration_id: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :rtype: :class:`ContinuousDeploymentOperation
         <vsts_info_provider.models.ContinuousDeploymentOperation>`
        :rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
         if raw=true
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        url = '/_apis/continuousdelivery/provisioningconfigurations/{provisioningConfigurationId}'
        path_format_arguments = {
            'provisioningConfigurationId': self._serialize.url("provisioning_configuration_id", provisioning_configuration_id, 'str')
        }
        url = self._client.format_url(url, **path_format_arguments)

        # Construct parameters
        query_parameters = {}

        # Construct headers
        header_parameters = {}
        header_parameters['Content-Type'] = 'application/json; charset=utf-8'
        if custom_headers:
            header_parameters.update(custom_headers)

        # Construct and send request
        request = self._client.get(url, query_parameters)
        response = self._client.send(request, header_parameters, **operation_config)
        if response.status_code not in [200]:
            print("GET", request.url, file=stderr)
            print("response:", response.status_code, file=stderr)
            print(response.text, file=stderr)
            raise HttpOperationError(self._deserialize, response)

        deserialized = None

        if response.status_code == 200:
            deserialized = self._deserialize('ProvisioningConfiguration', response)

        if raw:
            client_raw_response = ClientRawResponse(deserialized, response)
            return client_raw_response

        return deserialized

Response: Get a specific resource from the ContinuousDelivery API.


Instruction:
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
    ]

Response: Serialize EmailMessages to be passed as task argument.


Instruction:
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
    ]

Response: Deserialize EmailMessages passed as task argument.


Instruction:
How would you implement a function in Python 3 that
updates the count number using the estimation of the unset ratio

Response:
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 - self.estimate_z))


Instruction:
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

Response:
Decrement cell value if not zero
            This maintenance process need to execute each self. compute_refresh_time


Instruction:
Can you create a Python 3 function that
batches version of expiration maintenance dev

Response:
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()


Instruction:
How would you implement a function in Python 3 that
batches version of expiration_maintenance

Response:
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.refresh_head)
        if num_iterations != 0:
            self.estimate_z = float(nonzero) / float(num_iterations)
            self._estimate_count()
        processed_interval = num_iterations * self.compute_refresh_time()
        return processed_interval


Instruction:
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

Response: Compute the refresh time for the given expiration delay


Instruction:
Write a Python 3 function for
generating a new network of the same order as the current network.

Response:
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,
                       'order':   5,
                       'epsilon': 0.1,
                       'J':       0.1,
                       'delay':   1.5,
                       'tauMem':  20.0,
                       'tauSyn':  0.1,
                       'tauRef':  2.0,
                       'U0':      0.0,
                       'theta':   20.0}

    cell = Cell(id='ifcell', pynn_cell='IF_curr_alpha')

    cell.parameters = { 'tau_m':       'tauMem',
                        'tau_refrac':  'tauRef',
                        'v_rest':      'U0',
                        'v_reset':     'U0',
                        'v_thresh':    'theta',
                        'cm':          0.001,
                        "i_offset":    0}

    #cell = Cell(id='hhcell', neuroml2_source_file='test_files/hhcell.cell.nml')
    net.cells.append(cell)

    expoisson = Cell(id='expoisson', pynn_cell='SpikeSourcePoisson')
    expoisson.parameters = { 'rate':       '1000 * (eta*theta/(J*4*order*epsilon*tauMem)) * (4*order*epsilon)',
                             'start':      0,
                             'duration':   1e9}
    net.cells.append(expoisson)

    '''
    input_source = InputSource(id='iclamp0',
                               pynn_input='DCSource',
                               parameters={'amplitude':0.002, 'start':100., 'stop':900.})

    input_source = InputSource(id='poissonFiringSyn',
                               neuroml2_input='poissonFiringSynapse',
                               parameters={'average_rate':"eta", 'synapse':"ampa", 'spike_target':"./ampa"})

    net.input_sources.append(input_source)'''

    pE = Population(id='Epop', size='4*order', component=cell.id, properties={'color':'1 0 0'})
    pEpoisson = Population(id='Einput', size='4*order', component=expoisson.id, properties={'color':'.5 0 0'})
    pI = Population(id='Ipop', size='1*order', component=cell.id, properties={'color':'0 0 1'})

    net.populations.append(pE)
    net.populations.append(pEpoisson)
    net.populations.append(pI)

    net.synapses.append(Synapse(id='ampa',
                                pynn_receptor_type='excitatory',
                                pynn_synapse_type='curr_alpha',
                                parameters={'tau_syn':0.1}))
    net.synapses.append(Synapse(id='gaba',
                                pynn_receptor_type='inhibitory',
                                pynn_synapse_type='curr_alpha',
                                parameters={'tau_syn':0.1}))

    net.projections.append(Projection(id='projEinput',
                                      presynaptic=pEpoisson.id,
                                      postsynaptic=pE.id,
                                      synapse='ampa',
                                      delay=2,
                                      weight=0.02,
                                      one_to_one_connector=OneToOneConnector()))
    '''
    net.projections.append(Projection(id='projEE',
                                      presynaptic=pE.id,
                                      postsynaptic=pE.id,
                                      synapse='ampa',
                                      delay=2,
                                      weight=0.002,
                                      random_connectivity=RandomConnectivity(probability=.5)))'''

    net.projections.append(Projection(id='projEI',
                                      presynaptic=pE.id,
                                      postsynaptic=pI.id,
                                      synapse='ampa',
                                      delay=2,
                                      weight=0.02,
                                      random_connectivity=RandomConnectivity(probability=.5)))
    '''
    net.projections.append(Projection(id='projIE',
                                      presynaptic=pI.id,
                                      postsynaptic=pE.id,
                                      synapse='gaba',
                                      delay=2,
                                      weight=0.02,
                                      random_connectivity=RandomConnectivity(probability=.5)))

    net.inputs.append(Input(id='stim',
                            input_source=input_source.id,
                            population=pE.id,
                            percentage=50))'''

    #print(net)
    #print(net.to_json())
    new_file = net.to_json_file('%s.json'%net.id)

    ################################################################################
    ###   Build Simulation object & save as JSON

    sim = Simulation(id='SimExample7',
                     network=new_file,
                     duration='1000',
                     dt='0.025',
                     seed= 123,
                     recordTraces={pE.id:'*',pI.id:'*'},
                     recordSpikes={'all':'*'})

    sim.to_json_file()

    return sim, net


Instruction:
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, ...], ...}}
    locally_reserved = defaultdict(lambda: defaultdict(list))

    # Alignment of each resource
    alignments = defaultdict(lambda: 1)

    # Collect constraints
    for constraint in constraints:
        if isinstance(constraint, ReserveResourceConstraint):
            if constraint.location is None:
                globally_reserved[constraint.resource].append(
                    constraint.reservation)
            else:
                locally_reserved[constraint.location][
                    constraint.resource].append(constraint.reservation)
        elif isinstance(constraint, AlignResourceConstraint):
            alignments[constraint.resource] = constraint.alignment

    # A dictionary {(x, y): [vertex, ...], ...}
    chip_contents = defaultdict(list)
    for vertex, xy in iteritems(placements):
        chip_contents[xy].append(vertex)

    for xy, chip_vertices in iteritems(chip_contents):
        # Index of the next free resource in the current chip
        resource_pointers = {resource: 0
                             for resource in machine.chip_resources}

        for vertex in chip_vertices:
            vertex_allocation = {}

            # Make allocations, advancing resource pointers
            for resource, requirement in iteritems(vertices_resources[vertex]):
                proposed_allocation = None
                proposal_overlaps = True
                while proposal_overlaps:
                    # Check that the proposed allocation doesn't overlap a
                    # reserved area.
                    start = align(resource_pointers[resource],
                                  alignments[resource])
                    proposed_allocation = slice(start, start + requirement)
                    proposal_overlaps = False
                    if proposed_allocation.stop > machine[xy][resource]:
                        raise InsufficientResourceError(
                            "{} over-allocated on chip {}".format(resource,
                                                                  xy))
                    for reservation in globally_reserved[resource]:
                        if slices_overlap(proposed_allocation, reservation):
                            resource_pointers[resource] = reservation.stop
                            proposal_overlaps = True
                    local_reservations \
                        = locally_reserved.get(xy, {}).get(resource, [])
                    for reservation in local_reservations:
                        if slices_overlap(proposed_allocation, reservation):
                            resource_pointers[resource] = reservation.stop
                            proposal_overlaps = True

                # Getting here means the proposed allocation is not blocked
                # by any reservations
                vertex_allocation[resource] = proposed_allocation
                resource_pointers[resource] = proposed_allocation.stop

            allocation[vertex] = vertex_allocation

    return allocation

Response: Allocate resources to vertices on cores arbitrarily using a simple greedy algorithm.


Instruction:
Create a Python 3 function for
creating the Nagios related resources for the given port.

Response:
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, port=port))

        policy_data = self._get_policy_values(qos_policy)
        self._utils.set_port_qos_rule(port["port_id"], policy_data)


Instruction:
Can you create a Python 3 function that
deletes the QoS rules from the specified port.

Response:
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))

        self._utils.remove_port_qos_rule(port["port_id"])


Instruction:
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 executed
        :arg name: name of the task, used later to schedule jobs
        :arg queue: queue of the task, the default is used if not provided
        :arg max_retries: maximum number of retries, the default is used if
             not provided
        :arg periodicity: for periodic tasks, delay between executions as a
             timedelta

        >>> tasks = Tasks()
        >>> tasks.add(lambda x: x, name='do_nothing')
        """
        if not name:
            raise ValueError('Each Spinach task needs a name')
        if name in self._tasks:
            raise ValueError('A task named {} already exists'.format(name))

        if queue is None:
            if self.queue:
                queue = self.queue
            else:
                queue = const.DEFAULT_QUEUE

        if max_retries is None:
            if self.max_retries:
                max_retries = self.max_retries
            else:
                max_retries = const.DEFAULT_MAX_RETRIES

        if periodicity is None:
            periodicity = self.periodicity

        if queue and queue.startswith('_'):
            raise ValueError('Queues starting with "_" are reserved by '
                             'Spinach for internal use')

        self._tasks[name] = Task(func, name, queue, max_retries, periodicity)

Response: Register a task function.


Instruction:
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)

Response: Schedule a job to be executed as soon as possible.


Instruction:
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)

Response: Schedule a job to be executed in the future.


Instruction:
Can you create a Python 3 function that
adds a job to be executed ASAP to the batch.

Response:
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
        """
        at = datetime.now(timezone.utc)
        self.schedule_at(task, at, *args, **kwargs)


Instruction:
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))

Response: Add a job to be executed in the future


Instruction:
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.
        major = legacy_version_field // 100
        minor = legacy_version_field % 100
        patch = 0
        labels = ""
    else:
        # Semantic Version encoding: packed after the null-terminator of the
        # software name in the version string.
        software_name, _, version_number = software_name.partition("\0")

        match = VERSION_NUMBER_REGEX.match(version_number.rstrip("\0"))
        assert match, "Malformed version number: {}".format(version_number)

        major = int(match.group(1))
        minor = int(match.group(2))
        patch = int(match.group(3))
        labels = match.group(4) or ""

    return (software_name.rstrip("\0"), (major, minor, patch), labels)

Response: Unpack the version - related parts of an sver response packet into a new sver object.


Instruction:
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

Response: Utility method for finding full path to a filename as string


Instruction:
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,
                     base_dir=None):
    """
    Generate the network model as described in NeuroMLlite in a specific handler,
    e.g. NeuroMLHandler, PyNNHandler, etc.
    """

    pop_locations = {}
    cell_objects = {}
    synapse_objects = {}

    print_v("Starting net generation for %s%s..." % (nl_model.id,
                                ' (base dir: %s)' % base_dir if base_dir else ''))
    rng = random.Random(seed)

    if nl_model.network_reader:

        exec('from neuromllite.%s import %s' % (nl_model.network_reader.type, nl_model.network_reader.type))

        exec('network_reader = %s()' % (nl_model.network_reader.type))
        network_reader.parameters = nl_model.network_reader.parameters

        network_reader.parse(handler)
        pop_locations = network_reader.get_locations()

    else:
        notes = "Generated network: %s" % nl_model.id
        notes += "\n    Generation seed: %i" % (seed)
        if nl_model.parameters:
            notes += "\n    NeuroMLlite parameters: "
            for p in nl_model.parameters:
                notes += "\n        %s = %s" % (p, nl_model.parameters[p])
        handler.handle_document_start(nl_model.id, notes)
        temperature = '%sdegC' % nl_model.temperature if nl_model.temperature else None
        handler.handle_network(nl_model.id, nl_model.notes, temperature=temperature)

    nml2_doc_temp = _extract_pynn_components_to_neuroml(nl_model)

    for c in nl_model.cells:

        if c.neuroml2_source_file:
            from pyneuroml import pynml
            nml2_doc = pynml.read_neuroml2_file(_locate_file(c.neuroml2_source_file, base_dir),
                                                include_includes=True)
            cell_objects[c.id] = nml2_doc.get_by_id(c.id)

        if c.pynn_cell:
            cell_objects[c.id] = nml2_doc_temp.get_by_id(c.id)

    for s in nl_model.synapses:
        if s.neuroml2_source_file:
            from pyneuroml import pynml
            nml2_doc = pynml.read_neuroml2_file(_locate_file(s.neuroml2_source_file, base_dir),
                                                include_includes=True)
            synapse_objects[s.id] = nml2_doc.get_by_id(s.id)

        if s.pynn_synapse:
            synapse_objects[s.id] = nml2_doc_temp.get_by_id(s.id)

    for p in nl_model.populations:

        size = evaluate(p.size, nl_model.parameters)
        properties = p.properties if p.properties else {}
        if p.random_layout:
            properties['region'] = p.random_layout.region

        if not p.random_layout and not p.single_location and not always_include_props:

            # If there are no positions (abstract network), and <property>
            # is added to <population>, jLems doesn't like it... (it has difficulty
            # interpreting pop0[0]/v, etc.)
            # So better not to give properties...
            properties = {}

        if p.notes:
            handler.handle_population(p.id,
                                      p.component,
                                      size,
                                      cell_objects[p.component] if p.component in cell_objects else None,
                                      properties=properties,
                                      notes=p.notes)
        else:
            handler.handle_population(p.id,
                                      p.component,
                                      size,
                                      cell_objects[p.component] if p.component in cell_objects else None,
                                      properties=properties)

        pop_locations[p.id] = np.zeros((size, 3))

        for i in range(size):
            if p.random_layout:
                region = nl_model.get_child(p.random_layout.region, 'regions')

                x = region.x + rng.random() * region.width
                y = region.y + rng.random() * region.height
                z = region.z + rng.random() * region.depth
                pop_locations[p.id][i] = (x, y, z)

                handler.handle_location(i, p.id, p.component, x, y, z)

            if p.single_location:
                loc = p.single_location.location
                x = loc.x
                y = loc.y
                z = loc.z
                pop_locations[p.id][i] = (x, y, z)

                handler.handle_location(i, p.id, p.component, x, y, z)

        if hasattr(handler, 'finalise_population'):
            handler.finalise_population(p.id)

    if include_connections:
        for p in nl_model.projections:

            type = p.type if p.type else 'projection'

            handler.handle_projection(p.id,
                                      p.presynaptic,
                                      p.postsynaptic,
                                      p.synapse,
                                      synapse_obj=synapse_objects[p.synapse] if p.synapse in synapse_objects else None,
                                      pre_synapse_obj=synapse_objects[p.pre_synapse] if p.pre_synapse in synapse_objects else None,
                                      type=type)

            delay = p.delay if p.delay else 0
            weight = p.weight if p.weight else 1

            conn_count = 0
            if p.random_connectivity:
                for pre_i in range(len(pop_locations[p.presynaptic])):
                    for post_i in range(len(pop_locations[p.postsynaptic])):
                        flip = rng.random()
                        #print("Is cell %i conn to %i, prob %s - %s"%(pre_i, post_i, flip, p.random_connectivity.probability))
                        if flip < p.random_connectivity.probability:
                            weight = evaluate(weight, nl_model.parameters)
                            delay = evaluate(delay, nl_model.parameters)
                            #print_v("Adding connection %i with weight: %s, delay: %s"%(conn_count, weight, delay))
                            handler.handle_connection(p.id,
                                                      conn_count,
                                                      p.presynaptic,
                                                      p.postsynaptic,
                                                      p.synapse, \
                                                      pre_i, \
                                                      post_i, \
                                                      preSegId=0, \
                                                      preFract=0.5, \
                                                      postSegId=0, \
                                                      postFract=0.5, \
                                                      delay=delay, \
                                                      weight=weight)
                            conn_count += 1

            if p.convergent_connectivity:

                for post_i in range(len(pop_locations[p.postsynaptic])):

                    for count in range(int(p.convergent_connectivity.num_per_post)):
                        found = False
                        while not found:
                            pre_i = int(rng.random()*len(pop_locations[p.presynaptic]))
                            if p.presynaptic==p.postsynaptic and pre_i==post_i:
                                found=False
                            else:
                                found=True

                        weight = evaluate(weight, nl_model.parameters)
                        delay = evaluate(delay, nl_model.parameters)
                        print_v("Adding connection %i (%i->%i; %i to %s of post) with weight: %s, delay: %s"%(conn_count, pre_i, post_i, count, p.convergent_connectivity.num_per_post, weight, delay))
                        handler.handle_connection(p.id,
                                                  conn_count,
                                                  p.presynaptic,
                                                  p.postsynaptic,
                                                  p.synapse, \
                                                  pre_i, \
                                                  post_i, \
                                                  preSegId=0, \
                                                  preFract=0.5, \
                                                  postSegId=0, \
                                                  postFract=0.5, \
                                                  delay=delay, \
                                                  weight=weight)
                        conn_count += 1

            elif p.one_to_one_connector:
                for i in range(min(len(pop_locations[p.presynaptic]), len(pop_locations[p.postsynaptic]))):
                    weight = evaluate(weight, nl_model.parameters)
                    delay = evaluate(delay, nl_model.parameters)
                    #print_v("Adding connection %i with weight: %s, delay: %s"%(conn_count, weight, delay))
                    handler.handle_connection(p.id,
                                              conn_count,
                                              p.presynaptic,
                                              p.postsynaptic,
                                              p.synapse, \
                                              i, \
                                              i, \
                                              preSegId=0, \
                                              preFract=0.5, \
                                              postSegId=0, \
                                              postFract=0.5, \
                                              delay=delay, \
                                              weight=weight)
                    conn_count += 1

            handler.finalise_projection(p.id,
                                        p.presynaptic,
                                        p.postsynaptic,
                                        p.synapse)

    if include_inputs:
        for input in nl_model.inputs:

            handler.handle_input_list(input.id,
                                      input.population,
                                      input.input_source,
                                      size=0,
                                      input_comp_obj=None)

            input_count = 0
            for i in range(len(pop_locations[input.population])):
                flip = rng.random()
                weight = input.weight if input.weight else 1
                if flip * 100. < input.percentage:

                    number_per_cell = evaluate(input.number_per_cell, nl_model.parameters) if input.number_per_cell else 1

                    for j in range(number_per_cell):
                        handler.handle_single_input(input.id,
                                                    input_count,
                                                    i,
                                                    weight=evaluate(weight, nl_model.parameters))
                        input_count += 1

            handler.finalise_input_source(input.id)

    if hasattr(handler, 'finalise_document'):
        handler.finalise_document()

Response: Generate a network from a NeuroML model.


Instruction:
Implement a function in Python 3 to
check if any of the arguments to generate or run are passed to the main method.

Response:
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)..." %
               (argv, sim.id, sim.network))

    if len(argv)==1:
        print_v("No arguments found. Currently supported export formats:")
        print_v("   -nml |  -nmlh5 | -jnml | -jnmlnrn | -jnmlnetpyne | -netpyne | -pynnnrn "+\
                "| -pynnnest | -pynnbrian | -pynnneuroml | -sonata | -matrix[1-2] | -graph[1-6 n/d/f/c]")

    if '-pynnnest' in argv:
        generate_and_run(sim, simulator='PyNN_NEST')

    elif '-pynnnrn' in argv:
        generate_and_run(sim, simulator='PyNN_NEURON')

    elif '-pynnbrian' in argv:
        generate_and_run(sim, simulator='PyNN_Brian')

    elif '-jnml' in argv:
        generate_and_run(sim, simulator='jNeuroML')

    elif '-jnmlnrn' in argv:
        generate_and_run(sim, simulator='jNeuroML_NEURON')

    elif '-netpyne' in argv:
        generate_and_run(sim, simulator='NetPyNE')

    elif '-pynnneuroml' in argv:
        generate_and_run(sim, simulator='PyNN_NeuroML')

    elif '-sonata' in argv:
        generate_and_run(sim, simulator='sonata')

    elif '-nml' in argv or '-neuroml' in argv:

        network = load_network_json(sim.network)
        generate_neuroml2_from_network(network, validate=True)

    elif '-nmlh5' in argv or '-neuromlh5' in argv:

        network = load_network_json(sim.network)
        generate_neuroml2_from_network(network, validate=True, format='hdf5')

    else:
        for a in argv:

            if '-jnmlnetpyne' in a:
                num_processors = 1
                if len(a)>len('-jnmlnetpyne'):
                    num_processors = int(a[12:])
                generate_and_run(sim, simulator='jNeuroML_NetPyNE',num_processors=num_processors)
            elif 'graph' in a: # e.g. -graph3c
                generate_and_run(sim, simulator=a[1:]) # Will not "run" obviously...
            elif 'matrix' in a: # e.g. -matrix2
                generate_and_run(sim, simulator=a[1:])


Instruction:
Can you create a Python 3 function that
extracts the equivalent elements of the cell synapses and inputs from a NeuroML document.

Response:
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 == None:
        from neuroml import NeuroMLDocument
        nml_doc = NeuroMLDocument(id="temp")

    for c in nl_model.cells:

        if c.pynn_cell:

            if nml_doc.get_by_id(c.id) == None:
                import pyNN.neuroml
                cell_params = c.parameters if c.parameters else {}
                #print('------- %s: %s' % (c, cell_params))
                for p in cell_params:
                    cell_params[p] = evaluate(cell_params[p], nl_model.parameters)
                #print('====== %s: %s' % (c, cell_params))
                for proj in nl_model.projections:

                    synapse = nl_model.get_child(proj.synapse, 'synapses')
                    post_pop = nl_model.get_child(proj.postsynaptic, 'populations')
                    if post_pop.component == c.id:
                        #print("--------- Cell %s in post pop %s of %s uses %s"%(c.id,post_pop.id, proj.id, synapse))

                        if synapse.pynn_receptor_type == 'excitatory':
                            post = '_E'
                        elif synapse.pynn_receptor_type == 'inhibitory':
                            post = '_I'
                        for p in synapse.parameters:
                            cell_params['%s%s' % (p, post)] = synapse.parameters[p]

                temp_cell = eval('pyNN.neuroml.%s(**cell_params)' % c.pynn_cell)
                if c.pynn_cell != 'SpikeSourcePoisson':
                    temp_cell.default_initial_values['v'] = temp_cell.parameter_space['v_rest'].base_value

                cell_id = temp_cell.add_to_nml_doc(nml_doc, None)
                cell = nml_doc.get_by_id(cell_id)
                cell.id = c.id

    for s in nl_model.synapses:
        if nml_doc.get_by_id(s.id) == None:

            if s.pynn_synapse_type and s.pynn_receptor_type:
                import neuroml

                if s.pynn_synapse_type == 'cond_exp':
                    syn = neuroml.ExpCondSynapse(id=s.id, tau_syn=s.parameters['tau_syn'], e_rev=s.parameters['e_rev'])
                    nml_doc.exp_cond_synapses.append(syn)
                elif s.pynn_synapse_type == 'cond_alpha':
                    syn = neuroml.AlphaCondSynapse(id=s.id, tau_syn=s.parameters['tau_syn'], e_rev=s.parameters['e_rev'])
                    nml_doc.alpha_cond_synapses.append(syn)
                elif s.pynn_synapse_type == 'curr_exp':
                    syn = neuroml.ExpCurrSynapse(id=s.id, tau_syn=s.parameters['tau_syn'])
                    nml_doc.exp_curr_synapses.append(syn)
                elif s.pynn_synapse_type == 'curr_alpha':
                    syn = neuroml.AlphaCurrSynapse(id=s.id, tau_syn=s.parameters['tau_syn'])
                    nml_doc.alpha_curr_synapses.append(syn)

    for i in nl_model.input_sources:

        #if nml_doc.get_by_id(i.id) == None:

        if i.pynn_input:
            import pyNN.neuroml
            input_params = i.parameters if i.parameters else {}
            exec('input__%s = pyNN.neuroml.%s(**input_params)' % (i.id, i.pynn_input))
            exec('temp_input = input__%s' % i.id)
            pg_id = temp_input.add_to_nml_doc(nml_doc, None)
            #for pp in nml_doc.pulse_generators:
            #    print('PG: %s: %s'%(pp,pp.id))
            pg = nml_doc.get_by_id(pg_id)
            pg.id = i.id

    return nml_doc