Instruction:
How would you explain what the following Python 3 function does
def write_across_link(self, address, data, x, y, link):
        if address % 4:
            raise ValueError("Addresses must be word-aligned.")
        if len(data) % 4:
            raise ValueError("Data must be a whole number of words.")

        length_bytes = len(data)
        cur_byte = 0

        # Write the requested data, one SCP packet worth at a time
        while length_bytes > 0:
            to_write = min(length_bytes, (self.scp_data_length & ~0b11))
            cur_data = data[cur_byte:cur_byte + to_write]
            self._send_scp(x, y, 0, SCPCommands.link_write,
                           arg1=address, arg2=to_write, arg3=int(link),
                           data=cur_data, expected_args=0)

            # Move to the next block to write
            address += to_write
            cur_byte += to_write
            length_bytes -= to_write

Response: Write a bytestring to an address in memory on a neigbouring chip.


Instruction:
Can you create a Python 3 function that
reads a bytestring from an address in memory on a neigbouring chip.

Response:
def read_across_link(self, address, length_bytes, x, y, link):
        """Read a bytestring from an address in memory on a neigbouring chip.

        .. warning::

            This function is intended for low-level debug use only and is not
            optimised for performance nor intended for more general use.

        This method instructs a monitor processor to send 'PEEK'
        nearest-neighbour packets to a neighbouring chip. These packets are
        handled directly by the SpiNNaker router in the neighbouring chip,
        potentially allowing advanced debug or recovery of a chip rendered
        otherwise unreachable.

        Parameters
        ----------
        address : int
            The address at which to start reading the data. Only addresses in
            the system-wide address map may be accessed. Addresses must be word
            aligned.
        length_bytes : int
            The number of bytes to read from memory. Must be a multiple of four
            (i.e. a whole number of words). Large reads are transparently
            broken into multiple SCP link-read commands.
        x : int
        y : int
            The coordinates of the chip from which the command will be sent,
            *not* the coordinates of the chip on which the read will be
            performed.
        link : :py:class:`rig.links.Links`
            The link down which the read should be sent.

        Returns
        -------
        :py:class:`bytes`
            The data is read back from memory as a bytestring.
        """
        if address % 4:
            raise ValueError("Addresses must be word-aligned.")
        if length_bytes % 4:
            raise ValueError("Lengths must be multiples of words.")

        # Prepare the buffer to receive the incoming data
        data = bytearray(length_bytes)
        mem = memoryview(data)

        # Read the requested data, one SCP packet worth at a time
        while length_bytes > 0:
            to_read = min(length_bytes, (self.scp_data_length & ~0b11))
            response = self._send_scp(x, y, 0, SCPCommands.link_read,
                                      arg1=address,
                                      arg2=to_read,
                                      arg3=int(link),
                                      expected_args=0)

            # Accumulate the incoming data and advance the memoryview through
            # the buffer.
            mem[:to_read] = response.data
            mem = mem[to_read:]

            # Move to the next block to read
            address += to_read
            length_bytes -= to_read

        return bytes(data)


Instruction:
Given the following Python 3 function, write the documentation
def read_struct_field(self, struct_name, field_name, x, y, p=0):
        # Look up the struct and field
        field, address, pack_chars = \
            self._get_struct_field_and_address(struct_name, field_name)
        length = struct.calcsize(pack_chars)

        # Perform the read
        data = self.read(address, length, x, y, p)

        # Unpack the data
        unpacked = struct.unpack(pack_chars, data)

        if field.length == 1:
            return unpacked[0]
        else:
            return unpacked

Response: Read the value out of a struct field.


Instruction:
Write a Python 3 function for
writing a value into a struct field.

Response:
def write_struct_field(self, struct_name, field_name, values, x, y, p=0):
        """Write a value into a struct.

        This method is particularly useful for writing values into the ``sv``
        struct which contains some configuration data.  See ``sark.h`` for
        details.

        Parameters
        ----------
        struct_name : string
            Name of the struct to write to, e.g., `"sv"`
        field_name : string
            Name of the field to write, e.g., `"random"`
        values :
            Value(s) to be written into the field.

        .. warning::
            Fields which are arrays must currently be written in their
            entirety.
        """
        # Look up the struct and field
        field, address, pack_chars = \
            self._get_struct_field_and_address(struct_name, field_name)

        if field.length != 1:
            assert len(values) == field.length
            data = struct.pack(pack_chars, *values)
        else:
            data = struct.pack(pack_chars, values)

        # Perform the write
        self.write(address, data, x, y, p)


Instruction:
How would you explain what the following Python 3 function does
def _get_vcpu_field_and_address(self, field_name, x, y, p):
        vcpu_struct = self.structs[b"vcpu"]
        field = vcpu_struct[six.b(field_name)]
        address = (self.read_struct_field("sv", "vcpu_base", x, y) +
                   vcpu_struct.size * p) + field.offset
        pack_chars = b"<" + field.pack_chars
        return field, address, pack_chars

Response: Get the field and address for a VCPU struct field.


Instruction:
Given the following Python 3 function, write the documentation
def read_vcpu_struct_field(self, field_name, x, y, p):
        # Get the base address of the VCPU struct for this chip, then advance
        # to get the correct VCPU struct for the requested core.
        field, address, pack_chars = \
            self._get_vcpu_field_and_address(field_name, x, y, p)

        # Perform the read
        length = struct.calcsize(pack_chars)
        data = self.read(address, length, x, y)

        # Unpack and return
        unpacked = struct.unpack(pack_chars, data)

        if field.length == 1:
            return unpacked[0]
        else:
            # If the field is a string then truncate it and return
            if b"s" in pack_chars:
                return unpacked[0].strip(b"\x00").decode("utf-8")

            # Otherwise just return. (Note: at the time of writing, no fields
            # in the VCPU struct are of this form.)
            return unpacked

Response: Reads a value out of the VCPU struct for a specific core.


Instruction:
How would you explain what the following Python 3 function does
def write_vcpu_struct_field(self, field_name, value, x, y, p):
        field, address, pack_chars = \
            self._get_vcpu_field_and_address(field_name, x, y, p)

        # Pack the data
        if b"s" in pack_chars:
            data = struct.pack(pack_chars, value.encode('utf-8'))
        elif field.length == 1:
            data = struct.pack(pack_chars, value)
        else:
            # NOTE: At the time of writing no VCPU struct fields are of this
            # form.
            data = struct.pack(pack_chars, *value)  # pragma: no cover

        # Perform the write
        self.write(address, data, x, y)

Response: Writes a value to the VCPU struct for a specific core.


Instruction:
Explain what the following Python 3 code does
def get_processor_status(self, p, x, y):
        # Get the VCPU base
        address = (self.read_struct_field("sv", "vcpu_base", x, y) +
                   self.structs[b"vcpu"].size * p)

        # Get the VCPU data
        data = self.read(address, self.structs[b"vcpu"].size, x, y)

        # Build the kwargs that describe the current state
        state = {
            name.decode('utf-8'): struct.unpack(
                f.pack_chars,
                data[f.offset:f.offset+struct.calcsize(f.pack_chars)]
            )[0] for (name, f) in iteritems(self.structs[b"vcpu"].fields)
        }
        state["registers"] = [state.pop("r{}".format(i)) for i in range(8)]
        state["user_vars"] = [state.pop("user{}".format(i)) for i in range(4)]
        state["app_name"] = state["app_name"].strip(b'\x00').decode('utf-8')
        state["cpu_state"] = consts.AppState(state["cpu_state"])
        state["rt_code"] = consts.RuntimeException(state["rt_code"])

        sw_ver = state.pop("sw_ver")
        state["version"] = ((sw_ver >> 16) & 0xFF,
                            (sw_ver >> 8) & 0xFF,
                            (sw_ver >> 0) & 0xFF)

        for newname, oldname in [("iobuf_address", "iobuf"),
                                 ("program_state_register", "psr"),
                                 ("stack_pointer", "sp"),
                                 ("link_register", "lr"), ]:
            state[newname] = state.pop(oldname)
        state.pop("__PAD")
        return ProcessorStatus(**state)

Response: Get the status of a given core and the application executing on it.


Instruction:
Here you have a function in Python 3, explain what it does
def get_iobuf(self, p, x, y):
        return self.get_iobuf_bytes(p, x, y).decode("utf-8")

Response: Read the messages from the IOBUF buffer on a specific core.


Instruction:
Explain what the following Python 3 code does
def get_iobuf_bytes(self, p, x, y):
        # The IOBUF data is stored in a linked-list of blocks of memory in
        # SDRAM. The size of each block is given in SV
        iobuf_size = self.read_struct_field("sv", "iobuf_size", x, y)

        # The first block in the list is given in the core's VCPU field
        address = self.read_vcpu_struct_field("iobuf", x, y, p)

        iobuf = b""

        while address:
            # The IOBUF data is proceeded by a header which gives the next
            # address and also the length of the string in the current buffer.
            iobuf_data = self.read(address, iobuf_size + 16, x, y)
            address, time, ms, length = struct.unpack("<4I", iobuf_data[:16])
            iobuf += iobuf_data[16:16 + length]

        return iobuf

Response: Read raw bytes into the IOBUF buffer on a specific core.


Instruction:
Write a Python 3 script to
return the values of the router diagnostic counters.

Response:
def get_router_diagnostics(self, x, y):
        """Get the values of the router diagnostic counters.

        Returns
        -------
        :py:class:`~.RouterDiagnostics`
            Description of the state of the counters.
        """
        # Read the block of memory
        data = self.read(0xe1000300, 64, x=x, y=y)

        # Convert to 16 ints, then process that as the appropriate tuple type
        return RouterDiagnostics(*struct.unpack("<16I", data))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def iptag_set(self, iptag, addr, port, x, y):
        # Format the IP address
        ip_addr = struct.pack('!4B',
                              *map(int, socket.gethostbyname(addr).split('.')))
        self._send_scp(x, y, 0, SCPCommands.iptag,
                       int(consts.IPTagCommands.set) << 16 | iptag,
                       port, struct.unpack('<I', ip_addr)[0])

Response: Set the value of an IPTag.


Instruction:
Can you tell what is the following Python 3 function doing
def iptag_get(self, iptag, x, y):
        ack = self._send_scp(x, y, 0, SCPCommands.iptag,
                             int(consts.IPTagCommands.get) << 16 | iptag, 1,
                             expected_args=0)
        return IPTag.from_bytestring(ack.data)

Response: Get the value of an IPTag.


Instruction:
Write a Python 3 script for
clearing an IPTag. Parameters ---------- iptag : int Index of the IPTag to clear.

Response:
def iptag_clear(self, iptag, x, y):
        """Clear an IPTag.

        Parameters
        ----------
        iptag : int
            Index of the IPTag to clear.
        """
        self._send_scp(x, y, 0, SCPCommands.iptag,
                       int(consts.IPTagCommands.clear) << 16 | iptag)


Instruction:
Given the following Python 3 function, write the documentation
def set_led(self, led, action=None, x=Required, y=Required):
        if isinstance(led, int):
            leds = [led]
        else:
            leds = led
        arg1 = sum(LEDAction.from_bool(action) << (led * 2) for led in leds)
        self._send_scp(x, y, 0, SCPCommands.led, arg1=arg1, expected_args=0)

Response: Set or toggle the state of an LED.


Instruction:
Implement a Python 3 function for
filling a region of memory with the specified byte.

Response:
def fill(self, address, data, size, x, y, p):
        """Fill a region of memory with the specified byte.

        Parameters
        ----------
        data : int
            Data with which to fill memory. If `address` and `size` are word
            aligned then `data` is assumed to be a word; otherwise it is
            assumed to be a byte.

        Notes
        -----
        If the address and size are word aligned then a fast fill method will
        be used, otherwise a much slower write will be incurred.
        """
        if size % 4 or address % 4:
            # If neither the size nor the address are word aligned we have to
            # use `write` as `sark_word_set` can only work with words.
            # Convert the data into a string and then write:
            data = struct.pack('<B', data) * size
            self.write(address, data, x, y, p)
        else:
            # We can perform a fill, this will call `sark_word_set` internally.
            self._send_scp(x, y, p, SCPCommands.fill, address, data, size)


Instruction:
Explain what the following Python 3 code does
def sdram_alloc(self, size, tag=0, x=Required, y=Required,
                    app_id=Required, clear=False):
        """Allocate a region of SDRAM for an application.

        Requests SARK to allocate a block of SDRAM for an application and
        raises a :py:exc:`.SpiNNakerMemoryError` on failure. This allocation
        will be freed when the application is stopped.

        Parameters
        ----------
        size : int
            Number of bytes to attempt to allocate in SDRAM.
        tag : int
            8-bit tag that can be looked up by a SpiNNaker application to
            discover the address of the allocated block. The tag must be unique
            for this ``app_id`` on this chip. Attempting to allocate two blocks
            on the same chip and for the same ``app_id`` will fail. If ``0``
            (the default) then no tag is applied.

            For example, if some SDRAM is allocated with ``tag=12``, a
            SpiNNaker application can later discover the address using::

                void *allocated_data = sark_tag_ptr(12, 0);

            A common convention is to allocate one block of SDRAM per
            application core and give each allocation the associated core
            number as its tag. This way the underlying SpiNNaker applications
            can simply call::

                void *allocated_data = sark_tag_ptr(sark_core_id(), 0);

        clear : bool
            If True the requested memory will be filled with zeros before the
            pointer is returned.  If False (the default) the memory will be
            left as-is.

        Returns
        -------
        int
            Address of the start of the region.

            The allocated SDRAM remains valid until either the 'stop' signal is
            sent to the application ID associated with the allocation or
            :py:meth:`.sdram_free` is called on the address returned.

        Raises
        ------
        rig.machine_control.machine_controller.SpiNNakerMemoryError
            If the memory cannot be allocated, the tag is already taken or it
            is invalid.
        """
        assert 0 <= tag < 256

        # Construct arg1 (app_id << 8) | op code
        arg1 = app_id << 8 | consts.AllocOperations.alloc_sdram

        # Send the packet and retrieve the address
        rv = self._send_scp(x, y, 0, SCPCommands.alloc_free, arg1, size, tag)
        if rv.arg1 == 0:  # Allocation failed
            tag_in_use = False
            if tag != 0:
                # If a tag was specified then read the allocation table to see
                # if the tag was already in use or whether we ran out of
                # memory.
                alloc_tags = self.read_struct_field("sv", "alloc_tag", x, y)
                index = (app_id << 8) + tag
                entry = self.read(alloc_tags + index, 4, x, y)
                tag_in_use = (entry != 0)

            raise SpiNNakerMemoryError(size, x, y, tag, tag_in_use)

        # Get the address
        address = rv.arg1

        if clear:
            # Clear the memory if so desired
            self.fill(address, 0, size, x, y, 0)

        return address

Response: Allocate a block of SDRAM for an application.


Instruction:
Write a Python 3 script to
like sdram_alloc but returns a File - like object which allows safe reading and writing to the block holding the memory.

Response:
def sdram_alloc_as_filelike(self, size, tag=0, x=Required, y=Required,
                                app_id=Required, clear=False):
        """Like :py:meth:`.sdram_alloc` but returns a :py:class:`file-like
        object <.MemoryIO>` which allows safe reading and writing to the block
        that is allocated.

        Returns
        -------
        :py:class:`.MemoryIO`
            File-like object which allows accessing the newly allocated region
            of memory. For example::

                >>> # Read, write and seek through the allocated memory just
                >>> # like a file
                >>> mem = mc.sdram_alloc_as_filelike(12)  # doctest: +SKIP
                >>> mem.write(b"Hello, world")            # doctest: +SKIP
                12
                >>> mem.seek(0)                           # doctest: +SKIP
                >>> mem.read(5)                           # doctest: +SKIP
                b"Hello"
                >>> mem.read(7)                           # doctest: +SKIP
                b", world"

                >>> # Reads and writes are truncated to the allocated region,
                >>> # preventing accidental clobbering/access of memory.
                >>> mem.seek(0)                           # doctest: +SKIP
                >>> mem.write(b"How are you today?")      # doctest: +SKIP
                12
                >>> mem.seek(0)                           # doctest: +SKIP
                >>> mem.read(100)                         # doctest: +SKIP
                b"How are you "

            See the :py:class:`.MemoryIO` class for details of other features
            of these file-like views of SpiNNaker's memory.

        Raises
        ------
        rig.machine_control.machine_controller.SpiNNakerMemoryError
            If the memory cannot be allocated, or the tag is already taken or
            invalid.
        """
        # Perform the malloc
        start_address = self.sdram_alloc(size, tag, x, y, app_id, clear)
        return MemoryIO(self, x, y, start_address, start_address + size)


Instruction:
How would you explain what the following Python 3 function does
def sdram_free(self, ptr, x=Required, y=Required):
        self._send_scp(x, y, 0, SCPCommands.alloc_free,
                       consts.AllocOperations.free_sdram_by_ptr, ptr)

Response: Free an allocated block of memory in SDRAM.


Instruction:
Explain what the following Python 3 code does
def _get_next_nn_id(self):
        self._nn_id = self._nn_id + 1 if self._nn_id < 126 else 1
        return self._nn_id * 2

Response: Get the next nearest neighbour ID.


Instruction:
Can you tell what is the following Python 3 function doing
def _send_ffs(self, pid, n_blocks, fr):
        sfr = fr | (1 << 31)
        self._send_scp(
            255, 255, 0, SCPCommands.nearest_neighbour_packet,
            (NNCommands.flood_fill_start << 24) | (pid << 16) |
            (n_blocks << 8), 0x0, sfr
        )

Response: Send a flood - fill start packet.


Instruction:
Write a Python 3 script for
sending a flood - fill core select packet.

Response:
def _send_ffcs(self, region, core_mask, fr):
        """Send a flood-fill core select packet.

        This packet was added in a patched SC&MP 1.34*. Each packet includes a
        region and a core mask; every core that is in the region ORs the core
        mask with a mask it stores locally. On receiving a flood-fill end (FFE)
        packet the application is loaded to the cores specified by this
        composed core mask.

        FFCS packets should be sent in ascending order of
        `(region << 18) | core`.

        * See https://bitbucket.org/mundya/scamp/branch/new-ff2
        """
        arg1 = (NNCommands.flood_fill_core_select << 24) | core_mask
        arg2 = region
        self._send_scp(255, 255, 0, SCPCommands.nearest_neighbour_packet,
                       arg1, arg2, fr)


Instruction:
Make a summary of the following Python 3 code
def _send_ffd(self, pid, aplx_data, address):
        block = 0
        pos = 0
        aplx_size = len(aplx_data)

        while pos < aplx_size:
            # Get the next block of data, send and progress the block
            # counter and the address
            data = aplx_data[pos:pos + self.scp_data_length]
            data_size = len(data)
            size = data_size // 4 - 1

            arg1 = (NNConstants.forward << 24 | NNConstants.retry << 16 | pid)
            arg2 = (block << 16) | (size << 8)
            self._send_scp(255, 255, 0, SCPCommands.flood_fill_data,
                           arg1, arg2, address, data)

            # Increment the address and the block counter
            block += 1
            address += data_size
            pos += data_size

Response: Send flood - fill data packets.


Instruction:
Implement a function in Python 3 to
send a flood - fill end packet.

Response:
def _send_ffe(self, pid, app_id, app_flags, fr):
        """Send a flood-fill end packet.

        The cores and regions that the application should be loaded to will
        have been specified by a stream of flood-fill core select packets
        (FFCS).
        """
        arg1 = (NNCommands.flood_fill_end << 24) | pid
        arg2 = (app_id << 24) | (app_flags << 18)
        self._send_scp(255, 255, 0, SCPCommands.nearest_neighbour_packet,
                       arg1, arg2, fr)


Instruction:
Can you write a function in Python 3 where it
loads an application into a set of cores.

Response:
def load_application(self, *args, **kwargs):
        """Load an application to a set of application cores.

        This method guarantees that once it returns, all required cores will
        have been loaded. If this is not possible after a small number of
        attempts, a :py:exc:`.SpiNNakerLoadingError` will be raised.

        This method can be called in either of the following ways::

            load_application("/path/to/app.aplx", {(x, y): {core, ...}, ...})
            load_application({"/path/to/app.aplx": {(x, y): {core, ...}, ...},
                              ...})

        Note that the latter format is the same format produced by
        :py:func:`~rig.place_and_route.util.build_application_map`.

        Parameters
        ----------
        app_id : int
        wait : bool
            Leave the application in a wait state after successfully loading
            it.
        n_tries : int
            Number attempts to make to load the application.
        app_start_delay : float
            Time to pause (in seconds) after loading to ensure that the
            application successfully reaches the wait state before checking for
            success.
        use_count : bool
            If True (the default) then the targets dictionary will be assumed
            to represent _all_ the cores that will be loaded and a faster
            method to determine whether all applications have been loaded
            correctly will be used. If False a fallback method will be used.

        Raises
        ------
        rig.machine_control.machine_controller.SpiNNakerLoadingError
            This exception is raised after some cores failed to load after
            ``n_tries`` attempts.
        """
        # Get keyword arguments
        app_id = kwargs.pop("app_id")
        wait = kwargs.pop("wait")
        n_tries = kwargs.pop("n_tries")
        app_start_delay = kwargs.pop("app_start_delay")
        use_count = kwargs.pop("use_count", True)

        # Coerce the arguments into a single form.  If there are two arguments
        # then assume that we have filename and a map of chips and cores;
        # otherwise there should be ONE argument which is of the form of the
        # return value of `build_application_map`.
        application_map = {}
        if len(args) == 1:
            application_map = args[0]
        elif len(args) == 2:
            application_map = {args[0]: args[1]}
        else:
            raise TypeError(
                "load_application: accepts either 1 or 2 positional arguments:"
                "a map of filenames to targets OR a single filename and its"
                "targets"
            )

        # Count the number of cores being loaded
        core_count = sum(
            len(cores) for ts in six.itervalues(application_map) for
            cores in six.itervalues(ts)
        )

        # Mark all targets as unloaded
        unloaded = application_map

        # Try to load the applications, then determine which are unloaded
        tries = 0
        while unloaded != {} and tries <= n_tries:
            tries += 1

            # Load all unloaded applications, then pause to ensure they reach
            # the wait state
            self.flood_fill_aplx(unloaded, app_id=app_id, wait=True)
            time.sleep(app_start_delay)

            # If running in "fast" mode then check that the correct number of
            # cores are in the "wait" state, if so then break out of this loop.
            if (use_count and
                    core_count == self.count_cores_in_state("wait", app_id)):
                unloaded = {}
                continue

            # Query each target in turn to determine if it is loaded or
            # otherwise.  If it is loaded (in the wait state) then remove it
            # from the unloaded list.
            new_unloadeds = dict()
            for app_name, targets in iteritems(unloaded):
                unloaded_targets = {}
                for (x, y), cores in iteritems(targets):
                    unloaded_cores = set()
                    for p in cores:
                        # Read the struct value vcpu->cpu_state, if it is
                        # anything BUT wait then we mark this core as unloaded.
                        state = consts.AppState(
                            self.read_vcpu_struct_field("cpu_state", x, y, p)
                        )
                        if state is not consts.AppState.wait:
                            unloaded_cores.add(p)

                    if len(unloaded_cores) > 0:
                        unloaded_targets[(x, y)] = unloaded_cores
                if len(unloaded_targets) > 0:
                    new_unloadeds[app_name] = unloaded_targets
            unloaded = new_unloadeds

        # If there are still unloaded cores then we bail
        if unloaded != {}:
            raise SpiNNakerLoadingError(unloaded)

        # If not waiting then send the start signal
        if not wait:
            self.send_signal("start", app_id)


Instruction:
Create a Python 3 function for
transmitting a signal to applications.

Response:
def send_signal(self, signal, app_id):
        """Transmit a signal to applications.

        .. warning::
            In current implementations of SARK, signals are highly likely to
            arrive but this is not guaranteed (especially when the system's
            network is heavily utilised). Users should treat this mechanism
            with caution. Future versions of SARK may resolve this issue.

        Parameters
        ----------
        signal : string or :py:class:`~rig.machine_control.consts.AppSignal`
            Signal to transmit. This may be either an entry of the
            :py:class:`~rig.machine_control.consts.AppSignal` enum or, for
            convenience, the name of a signal (defined in
            :py:class:`~rig.machine_control.consts.AppSignal`) as a string.
        """
        if isinstance(signal, str):
            try:
                signal = getattr(consts.AppSignal, signal)
            except AttributeError:
                # The signal name is not present in consts.AppSignal! The next
                # test will throw an appropriate exception since no string can
                # be "in" an IntEnum.
                pass
        if signal not in consts.AppSignal:
            raise ValueError(
                "send_signal: Cannot transmit signal of type {}".format(
                    repr(signal)))

        # Construct the packet for transmission
        arg1 = consts.signal_types[signal]
        arg2 = (signal << 16) | 0xff00 | app_id
        arg3 = 0x0000ffff  # Meaning "transmit to all"
        self._send_scp(255, 255, 0, SCPCommands.signal, arg1, arg2, arg3)


Instruction:
Implement a Python 3 function for
counting the number of cores in a given state.

Response:
def count_cores_in_state(self, state, app_id):
        """Count the number of cores in a given state.

        .. warning::
            In current implementations of SARK, signals (which are used to
            determine the state of cores) are highly likely to arrive but this
            is not guaranteed (especially when the system's network is heavily
            utilised). Users should treat this mechanism with caution. Future
            versions of SARK may resolve this issue.

        Parameters
        ----------
        state : string or :py:class:`~rig.machine_control.consts.AppState` or
                iterable
            Count the number of cores currently in this state. This may be
            either an entry of the
            :py:class:`~rig.machine_control.consts.AppState` enum or, for
            convenience, the name of a state (defined in
            :py:class:`~rig.machine_control.consts.AppState`) as a string or
            an iterable of these, in which case the total count will be
            returned.
        """
        if (isinstance(state, collections.Iterable) and
                not isinstance(state, str)):
            # If the state is iterable then call for each state and return the
            # sum.
            return sum(self.count_cores_in_state(s, app_id) for s in state)

        if isinstance(state, str):
            try:
                state = getattr(consts.AppState, state)
            except AttributeError:
                # The state name is not present in consts.AppSignal! The next
                # test will throw an appropriate exception since no string can
                # be "in" an IntEnum.
                pass
        if state not in consts.AppState:
            raise ValueError(
                "count_cores_in_state: Unknown state {}".format(
                    repr(state)))

        # TODO Determine a way to nicely express a way to use the region data
        # stored in arg3.
        region = 0x0000ffff  # Largest possible machine, level 0
        level = (region >> 16) & 0x3
        mask = region & 0x0000ffff

        # Construct the packet
        arg1 = consts.diagnostic_signal_types[consts.AppDiagnosticSignal.count]
        arg2 = ((level << 26) | (1 << 22) |
                (consts.AppDiagnosticSignal.count << 20) | (state << 16) |
                (0xff << 8) | app_id)  # App mask for 1 app_id = 0xff
        arg3 = mask

        # Transmit and return the count
        return self._send_scp(
            255, 255, 0, SCPCommands.signal, arg1, arg2, arg3).arg1


Instruction:
How would you code a function in Python 3 to
block until the specified number of cores reach the specified state.

Response:
def wait_for_cores_to_reach_state(self, state, count, app_id,
                                      poll_interval=0.1, timeout=None):
        """Block until the specified number of cores reach the specified state.

        This is a simple utility-wrapper around the
        :py:meth:`.count_cores_in_state` method which polls the machine until
        (at least) the supplied number of cores has reached the specified
        state.

        .. warning::
            In current implementations of SARK, signals (which are used to
            determine the state of cores) are highly likely to arrive but this
            is not guaranteed (especially when the system's network is heavily
            utilised). As a result, in uncommon-but-possible circumstances,
            this function may never exit. Users should treat this function with
            caution. Future versions of SARK may resolve this issue.

        Parameters
        ----------
        state : string or :py:class:`~rig.machine_control.consts.AppState`
            The state to wait for cores to enter. This may be
            either an entry of the
            :py:class:`~rig.machine_control.consts.AppState` enum or, for
            convenience, the name of a state (defined in
            :py:class:`~rig.machine_control.consts.AppState`) as a string.
        count : int
            The (minimum) number of cores reach the specified state before this
            method terminates.
        poll_interval : float
            Number of seconds between state counting requests sent to the
            machine.
        timeout : float or Null
            Maximum number of seconds which may elapse before giving up. If
            None, keep trying forever.

        Returns
        -------
        int
            The number of cores in the given state (which will be less than the
            number required if the method timed out).
        """
        if timeout is not None:
            timeout_time = time.time() + timeout

        while True:
            cur_count = self.count_cores_in_state(state, app_id)
            if cur_count >= count:
                break

            # Stop if timeout elapsed
            if timeout is not None and time.time() > timeout_time:
                break

            # Pause before retrying
            time.sleep(poll_interval)

        return cur_count


Instruction:
How would you explain what the following Python 3 function does
def load_routing_tables(self, routing_tables, app_id):
        for (x, y), table in iteritems(routing_tables):
            self.load_routing_table_entries(table, x=x, y=y, app_id=app_id)

Response: Allocate space for an load multicast routing tables.


Instruction:
How would you explain what the following Python 3 function does
def load_routing_table_entries(self, entries, x, y, app_id):
        count = len(entries)

        # Try to allocate room for the entries
        rv = self._send_scp(
            x, y, 0, SCPCommands.alloc_free,
            (app_id << 8) | consts.AllocOperations.alloc_rtr, count
        )
        rtr_base = rv.arg1  # Index of the first allocated entry, 0 if failed

        if rtr_base == 0:
            raise SpiNNakerRouterError(count, x, y)

        # Determine where to write into memory
        buf = self.read_struct_field("sv", "sdram_sys", x, y)

        # Build the data to write in, then perform the write
        data = bytearray(16 * len(entries))
        for i, entry in enumerate(entries):
            # Build the route as a 32-bit value
            route = 0x00000000
            for r in entry.route:
                route |= 1 << r

            struct.pack_into(consts.RTE_PACK_STRING, data, i*16,
                             i, 0, route, entry.key, entry.mask)
        self.write(buf, data, x, y)

        # Perform the load of the data into the router
        self._send_scp(
            x, y, 0, SCPCommands.router,
            (count << 16) | (app_id << 8) | consts.RouterOperations.load,
            buf, rtr_base
        )

Response: Load routing table entries into memory.


Instruction:
Can you write a function in Python 3 where it
dumps the multicast routing table of a given chip.

Response:
def get_routing_table_entries(self, x, y):
        """Dump the multicast routing table of a given chip.

        Returns
        -------
        [(:py:class:`~rig.routing_table.RoutingTableEntry`, app_id, core) \
          or None, ...]
            Ordered list of routing table entries with app_ids and
            core numbers.
        """
        # Determine where to read from, perform the read
        rtr_addr = self.read_struct_field("sv", "rtr_copy", x, y)
        read_size = struct.calcsize(consts.RTE_PACK_STRING)
        rtr_data = self.read(rtr_addr, consts.RTR_ENTRIES * read_size, x, y)

        # Read each routing table entry in turn
        table = list()
        while len(rtr_data) > 0:
            entry, rtr_data = rtr_data[:read_size], rtr_data[read_size:]
            table.append(unpack_routing_table_entry(entry))
        return table


Instruction:
Given the following Python 3 function, write the documentation
def clear_routing_table_entries(self, x, y, app_id):
        # Construct the arguments
        arg1 = (app_id << 8) | consts.AllocOperations.free_rtr_by_app
        self._send_scp(x, y, 0, SCPCommands.alloc_free, arg1, 0x1)

Response: Clears the routing table entries associated with a given application.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_p2p_routing_table(self, x, y):
        table = {}

        # Get the dimensions of the system
        p2p_dims = self.read_struct_field("sv", "p2p_dims", x, y)
        width = (p2p_dims >> 8) & 0xFF
        height = (p2p_dims >> 0) & 0xFF

        # Read out the P2P table data, one column at a time (note that eight
        # entries are packed into each 32-bit word)
        col_words = (((height + 7) // 8) * 4)
        for col in range(width):
            # Read the entries for this row
            raw_table_col = self.read(
                consts.SPINNAKER_RTR_P2P + (((256 * col) // 8) * 4),
                col_words,
                x, y
            )

            row = 0
            while row < height:
                raw_word, raw_table_col = raw_table_col[:4], raw_table_col[4:]
                word, = struct.unpack("<I", raw_word)
                for entry in range(min(8, height - row)):
                    table[(col, row)] = \
                        consts.P2PTableEntry((word >> (3*entry)) & 0b111)
                    row += 1

        return table

Response: Dump the contents of a chip s P2P routing table.


Instruction:
Given the following Python 3 function, write the documentation
def get_chip_info(self, x, y):
        info = self._send_scp(x, y, 0, SCPCommands.info, expected_args=3)

        # Unpack values encoded in the argument fields
        num_cores = info.arg1 & 0x1F
        working_links = set(link for link in Links
                            if (info.arg1 >> (8 + link)) & 1)
        largest_free_rtr_mc_block = (info.arg1 >> 14) & 0x7FF
        ethernet_up = bool(info.arg1 & (1 << 25))

        # Unpack the values in the data payload
        data = struct.unpack_from("<18BHI", info.data)
        core_states = [consts.AppState(c) for c in data[:18]]
        local_ethernet_chip = ((data[18] >> 8) & 0xFF,
                               (data[18] >> 0) & 0xFF)
        ip_address = ".".join(str((data[19] >> i) & 0xFF)
                              for i in range(0, 32, 8))

        return ChipInfo(
            num_cores=num_cores,
            core_states=core_states[:num_cores],
            working_links=working_links,
            largest_free_sdram_block=info.arg2,
            largest_free_sram_block=info.arg3,
            largest_free_rtr_mc_block=largest_free_rtr_mc_block,
            ethernet_up=ethernet_up,
            ip_address=ip_address,
            local_ethernet_chip=local_ethernet_chip,
        )

Response: Get general information about the resources available on a chip.


Instruction:
Create a Python 3 function to
discover the integrity and resource availability of a whole SpiNNaker system. This command performs :py:meth:`.get_chip_info` on all working chips in the system returning an enhanced :py:class:`dict` (:py:class:`.SystemInfo`) containing a look-up from chip coordinate to :py:class:`.ChipInfo`. In addition to standard dictionary functionality, :py:class:`.SystemInfo` provides a number of convenience methods, which allow convenient iteration over various aspects of the information stored. .. note:: This method replaces the deprecated :py:meth:`.get_machine` method. To build a :py:class:`~rig.place_and_route.Machine` for place-and-route purposes, the :py:func:`rig.place_and_route.utils.build_machine` utility function may be used with :py:meth:`.get_system_info` like so:: >> from rig.place_and_route.utils import build_machine >> sys_info = mc.get_system_info() >> machine = build_machine(sys_info) Parameters ---------- x : int y : int The coordinates of the chip from which system exploration should begin, by default (255, 255). Most users will not need to change these parameters. Returns ------- :py:class:`.SystemInfo` An enhanced :py:class:`dict` object {(x, y): :py:class:`.ChipInfo`, ...} with a number of utility methods for accessing higher-level system information.

Response:
def get_system_info(self, x=255, y=255):
        """Discover the integrity and resource availability of a whole
        SpiNNaker system.

        This command performs :py:meth:`.get_chip_info` on all working chips in
        the system returning an enhanced :py:class:`dict`
        (:py:class:`.SystemInfo`) containing a look-up from chip coordinate to
        :py:class:`.ChipInfo`. In addition to standard dictionary
        functionality, :py:class:`.SystemInfo` provides a number of convenience
        methods, which allow convenient iteration over various aspects of the
        information stored.

        .. note::
            This method replaces the deprecated :py:meth:`.get_machine` method.
            To build a :py:class:`~rig.place_and_route.Machine` for
            place-and-route purposes, the
            :py:func:`rig.place_and_route.utils.build_machine` utility function
            may be used with :py:meth:`.get_system_info` like so::

                >> from rig.place_and_route.utils import build_machine
                >> sys_info = mc.get_system_info()
                >> machine = build_machine(sys_info)

        Parameters
        ----------
        x : int
        y : int
            The coordinates of the chip from which system exploration should
            begin, by default (255, 255). Most users will not need to change
            these parameters.

        Returns
        -------
        :py:class:`.SystemInfo`
            An enhanced :py:class:`dict` object {(x, y): :py:class:`.ChipInfo`,
            ...} with a number of utility methods for accessing higher-level
            system information.
        """
        # A quick way of getting a list of working chips
        p2p_tables = self.get_p2p_routing_table(x, y)

        # Calculate the extent of the system
        max_x = max(x_ for (x_, y_), r in iteritems(p2p_tables)
                    if r != consts.P2PTableEntry.none)
        max_y = max(y_ for (x_, y_), r in iteritems(p2p_tables)
                    if r != consts.P2PTableEntry.none)

        sys_info = SystemInfo(max_x + 1, max_y + 1)

        for (x, y), p2p_route in iteritems(p2p_tables):
            if p2p_route != consts.P2PTableEntry.none:
                try:
                    sys_info[(x, y)] = self.get_chip_info(x, y)
                except SCPError:
                    # The chip was listed in the P2P table but is not
                    # responding. Assume it is dead and don't include it in
                    # the info returned.
                    pass

        return sys_info


Instruction:
Can you implement a function in Python 3 that
iterates over the coordinates of Ethernet connected chips in the system.

Response:
def ethernet_connected_chips(self):
        """Iterate over the coordinates of Ethernet connected chips.

        Yields
        ------
        ((x, y), str)
            The coordinate and IP address of each Ethernet connected chip in
            the system.
        """
        for xy, chip_info in six.iteritems(self):
            if chip_info.ethernet_up:
                yield (xy, chip_info.ip_address)


Instruction:
Explain what the following Python 3 code does
def dead_chips(self):
        for x in range(self.width):
            for y in range(self.height):
                if (x, y) not in self:
                    yield (x, y)

Response: Yields the coordinates of all dead chips.


Instruction:
Can you write a function in Python 3 where it
generates the coordinates of all working links.

Response:
def links(self):
        """Generate the coordinates of all working links.

        Yields
        ------
        (x, y, :py:class:`rig.links.Links`)
            A working link leaving a chip from the perspective of the chip. For
            example ``(0, 0, Links.north)`` would be the link going north from
            chip (0, 0) to chip (0, 1).
        """
        for (x, y), chip_info in iteritems(self):
            for link in chip_info.working_links:
                yield (x, y, link)


Instruction:
Can you write a function in Python 3 where it
generates the coordinates of all dead links leaving working chips.

Response:
def dead_links(self):
        """Generate the coordinates of all dead links leaving working chips.

        Any link leading to a dead chip will also be included in the list of
        dead links. In non-torroidal SpiNNaker sysmtes (e.g. single SpiNN-5
        boards), links on the periphery of the system will be marked as dead.

        Yields
        ------
        (x, y, :py:class:`rig.links.Links`)
            A working link leaving a chip from the perspective of the chip. For
            example ``(0, 0, Links.north)`` would be the link going north from
            chip (0, 0) to chip (0, 1).
        """
        for (x, y), chip_info in iteritems(self):
            for link in Links:
                if link not in chip_info.working_links:
                    yield (x, y, link)


Instruction:
Can you tell what is the following Python 3 function doing
def cores(self):
        for (x, y), chip_info in iteritems(self):
            for p, state in enumerate(chip_info.core_states):
                yield (x, y, p, state)

Response: Yields the set of all cores in the system.


Instruction:
Can you create a Python 3 function that
reads a number of bytes from the SpiNNaker memory region.

Response:
def read(self, n_bytes=-1):
        """Read a number of bytes from the memory.

        .. note::
            Reads beyond the specified memory range will be truncated.

        .. note::
            Produces a :py:exc:`.TruncationWarning` if fewer bytes are read
            than requested. These warnings can be converted into exceptions
            using :py:func:`warnings.simplefilter`::

                >>> import warnings
                >>> from rig.machine_control.machine_controller \\
                ...     import TruncationWarning
                >>> warnings.simplefilter('error', TruncationWarning)

        Parameters
        ----------
        n_bytes : int
            A number of bytes to read.  If the number of bytes is negative or
            omitted then read all data until the end of memory region.

        Returns
        -------
        :py:class:`bytes`
            Data read from SpiNNaker as a bytestring.
        """
        # If n_bytes is negative then calculate it as the number of bytes left
        if n_bytes < 0:
            n_bytes = self._end_address - self.address

        # Determine how far to read, then read nothing beyond that point.
        if self.address + n_bytes > self._end_address:
            new_n_bytes = self._end_address - self.address
            warnings.warn("read truncated from {} to {} bytes".format(
                n_bytes, new_n_bytes), TruncationWarning, stacklevel=3)
            n_bytes = new_n_bytes

        if n_bytes <= 0:
            return b''

        # Perform the read and increment the offset
        data = self._parent._perform_read(self.address, n_bytes)
        self._offset += n_bytes
        return data


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write(self, bytes):
        if self.address + len(bytes) > self._end_address:
            n_bytes = self._end_address - self.address

            warnings.warn("write truncated from {} to {} bytes".format(
                len(bytes), n_bytes), TruncationWarning, stacklevel=3)
            bytes = bytes[:n_bytes]

        if len(bytes) == 0:
            return 0

        # Perform the write and increment the offset
        self._parent._perform_write(self.address, bytes)
        self._offset += len(bytes)
        return len(bytes)

Response: Writes the specified bytes to the memory.


Instruction:
Write a Python 3 script for
seeking to a new position in the memory region.

Response:
def seek(self, n_bytes, from_what=os.SEEK_SET):
        """Seek to a new position in the memory region.

        Parameters
        ----------
        n_bytes : int
            Number of bytes to seek.
        from_what : int
            As in the Python standard: `0` seeks from the start of the memory
            region, `1` seeks from the current position and `2` seeks from the
            end of the memory region. For example::

                mem.seek(-1, 2)  # Goes to the last byte in the region
                mem.seek(-5, 1)  # Goes 5 bytes before that point
                mem.seek(0)      # Returns to the start of the region

            Note that `os.SEEK_END`, `os.SEEK_CUR` and `os.SEEK_SET` are also
            valid arguments.
        """
        if from_what == 0:
            self._offset = n_bytes
        elif from_what == 1:
            self._offset += n_bytes
        elif from_what == 2:
            self._offset = (self._end_address - self._start_address) - n_bytes
        else:
            raise ValueError(
                "from_what: can only take values 0 (from start), "
                "1 (from current) or 2 (from end) not {}".format(from_what)
            )


Instruction:
How would you implement a function in Python 3 that
frees the memory referred to by the file - like.

Response:
def free(self):
        """Free the memory referred to by the file-like, any subsequent
        operations on this file-like or slices of it will fail.
        """
        # Free the memory
        self._machine_controller.sdram_free(self._start_address,
                                            self._x, self._y)

        # Mark as freed
        self._freed = True


Instruction:
Write a Python 3 script for
performing a read using the machine controller.

Response:
def _perform_read(self, addr, size):
        """Perform a read using the machine controller."""
        return self._machine_controller.read(addr, size, self._x, self._y, 0)


Instruction:
Create a Python 3 function to
perform a write using the machine controller.

Response:
def _perform_write(self, addr, data):
        """Perform a write using the machine controller."""
        return self._machine_controller.write(addr, data, self._x, self._y, 0)


Instruction:
Write a Python 3 script for
unpacking the SDP header from a bytestring into a packet.

Response:
def _unpack_sdp_into_packet(packet, bytestring):
    """Unpack the SDP header from a bytestring into a packet.

    Parameters
    ----------
    packet : :py:class:`.SDPPacket`
        Packet into which to store the unpacked header.
    bytestring : bytes
        Bytes from which to unpack the header data.
    """
    # Extract the header and the data from the packet
    packet.data = bytestring[10:]  # Everything but the header

    # Unpack the header
    (flags, packet.tag, dest_cpu_port, src_cpu_port,
     packet.dest_y, packet.dest_x,
     packet.src_y, packet.src_x) = struct.unpack_from('<2x8B', bytestring)
    packet.reply_expected = flags == FLAG_REPLY

    # Neaten up the combined VCPU and port fields
    packet.dest_cpu = dest_cpu_port & 0x1f
    packet.dest_port = (dest_cpu_port >> 5)  # & 0x07
    packet.src_cpu = src_cpu_port & 0x1f
    packet.src_port = (src_cpu_port >> 5)


Instruction:
Can you generate the documentation for the following Python 3 function
def packed_data(self):
        # Pack the header
        scp_header = struct.pack("<2H", self.cmd_rc, self.seq)

        # Potential loop intentionally unrolled
        if self.arg1 is not None:
            scp_header += struct.pack('<I', self.arg1)
        if self.arg2 is not None:
            scp_header += struct.pack('<I', self.arg2)
        if self.arg3 is not None:
            scp_header += struct.pack('<I', self.arg3)

        # Return the SCP header and the rest of the data
        return scp_header + self.data

Response: Pack the data for the SCP packet.


Instruction:
Write a Python 3 script for
wrapping around mmh3. hash64 to get us single 64 - bit value.

Response:
def hash64(key, seed):
    """
    Wrapper around mmh3.hash64 to get us single 64-bit value.

    This also does the extra work of ensuring that we always treat the
    returned values as big-endian unsigned long, like smhasher used to
    do.
    """
    hash_val = mmh3.hash64(key, seed)[0]
    return struct.unpack('>Q', struct.pack('q', hash_val))[0]


Instruction:
Can you write a function in Python 3 where it
generates a set of hash functions.

Response:
def generate_hashfunctions(nbr_bits, nbr_slices):
    """Generate a set of hash functions.

    The core method is a 64-bit murmur3 hash which has a good distribution.
    Multiple hashes can be generate using the previous hash value as a seed.
    """
    def _make_hashfuncs(key):
        if isinstance(key, text_type):
            key = key.encode('utf-8')
        else:
            key = str(key)
        rval = []
        current_hash = 0
        for i in range(nbr_slices):
            seed = current_hash
            current_hash = hash64(key, seed)
            rval.append(current_hash % nbr_bits)
        return rval
    return _make_hashfuncs


Instruction:
Write a Python 3 script to
return a dictionary containing the current context arguments.

Response:
def get_context_arguments(self):
        """Return a dictionary containing the current context arguments."""
        cargs = {}
        for context in self.__context_stack:
            cargs.update(context.context_arguments)
        return cargs


Instruction:
Write a Python 3 function for
reducing the size of a routing table by merging together entries where possible and removing any remaining default routes.

Response:
def minimise(routing_table, target_length):
    """Reduce the size of a routing table by merging together entries where
    possible and by removing any remaining default routes.

    .. warning::

        The input routing table *must* also include entries which could be
        removed and replaced by default routing.

    .. warning::

        It is assumed that the input routing table is not in any particular
        order and may be reordered into ascending order of generality (number
        of don't cares/Xs in the key-mask) without affecting routing
        correctness.  It is also assumed that if this table is unordered it is
        at least orthogonal (i.e., there are no two entries which would match
        the same key) and reorderable.

        .. note::

            If *all* the keys in the table are derived from a single instance
            of :py:class:`~rig.bitfield.BitField` then the table is guaranteed
            to be orthogonal and reorderable.

        .. note::

            Use :py:meth:`~rig.routing_table.expand_entries` to generate an
            orthogonal table and receive warnings if the input table is not
            orthogonal.

    Parameters
    ----------
    routing_table : [:py:class:`~rig.routing_table.RoutingTableEntry`, ...]
        Routing entries to be merged.
    target_length : int or None
        Target length of the routing table; the minimisation procedure will
        halt once either this target is reached or no further minimisation is
        possible. If None then the table will be made as small as possible.

    Raises
    ------
    MinimisationFailedError
        If the smallest table that can be produced is larger than
        `target_length`.

    Returns
    -------
    [:py:class:`~rig.routing_table.RoutingTableEntry`, ...]
        Reduced routing table entries.
    """
    table, _ = ordered_covering(routing_table, target_length, no_raise=True)
    return remove_default_routes(table, target_length)


Instruction:
Given the following Python 3 function, write the documentation
def ordered_covering(routing_table, target_length, aliases=dict(),
                     no_raise=False):
    """Reduce the size of a routing table by merging together entries where
    possible.

    .. warning::

        The input routing table *must* also include entries which could be
        removed and replaced by default routing.

    .. warning::

        It is assumed that the input routing table is not in any particular
        order and may be reordered into ascending order of generality (number
        of don't cares/Xs in the key-mask) without affecting routing
        correctness.  It is also assumed that if this table is unordered it is
        at least orthogonal (i.e., there are no two entries which would match
        the same key) and reorderable.

        .. note::

            If *all* the keys in the table are derived from a single instance
            of :py:class:`~rig.bitfield.BitField` then the table is guaranteed
            to be orthogonal and reorderable.

        .. note::

            Use :py:meth:`~rig.routing_table.expand_entries` to generate an
            orthogonal table and receive warnings if the input table is not
            orthogonal.

    Parameters
    ----------
    routing_table : [:py:class:`~rig.routing_table.RoutingTableEntry`, ...]
        Routing entries to be merged.
    target_length : int or None
        Target length of the routing table; the minimisation procedure will
        halt once either this target is reached or no further minimisation is
        possible. If None then the table will be made as small as possible.

    Other Parameters
    ----------------
    aliases : {(key, mask): {(key, mask), ...}, ...}
        Dictionary of which keys and masks in the routing table are
        combinations of other (now removed) keys and masks; this allows us to
        consider only the keys and masks the user actually cares about when
        determining if inserting a new entry will break the correctness of the
        table. This should be supplied when using this method to update an
        already minimised table.
    no_raise : bool
        If False (the default) then an error will be raised if the table cannot
        be minimised to be smaller than `target_length` and `target_length` is
        not None. If True then a table will be returned regardless of the size
        of the final table.

    Raises
    ------
    MinimisationFailedError
        If the smallest table that can be produced is larger than
        `target_length` and `no_raise` is False.

    Returns
    -------
    [:py:class:`~rig.routing_table.RoutingTableEntry`, ...]
        Reduced routing table entries.
    {(key, mask): {(key, mask), ...}, ...}
        A new aliases dictionary.
    """
    # Copy the aliases dictionary
    aliases = dict(aliases)

    # Perform an initial sort of the routing table in order of increasing
    # generality.
    routing_table = sorted(
        routing_table,
        key=lambda entry: _get_generality(entry.key, entry.mask)
    )

    while target_length is None or len(routing_table) > target_length:
        # Get the best merge
        merge = _get_best_merge(routing_table, aliases)

        # If there is no merge then stop
        if merge.goodness <= 0:
            break

        # Otherwise apply the merge, this returns a new routing table and a new
        # aliases dictionary.
        routing_table, aliases = merge.apply(aliases)

    # If the table is still too big then raise an error
    if (not no_raise and
            target_length is not None and
            len(routing_table) > target_length):
        raise MinimisationFailedError(target_length, len(routing_table))

    # Return the finished routing table and aliases table
    return routing_table, aliases

Response: Reduce the size of a routing table by merging together entries where possible.


Instruction:
Can you create a Python 3 function that
counts the number of Xs in the key - mask pair.

Response:
def _get_generality(key, mask):
    """Count the number of Xs in the key-mask pair.

    For example, there are 32 Xs in ``0x00000000/0x00000000``::

        >>> _get_generality(0x0, 0x0)
        32

    And no Xs in ``0xffffffff/0xffffffff``::

        >>> _get_generality(0xffffffff, 0xffffffff)
        0
    """
    xs = (~key) & (~mask)
    return sum(1 for i in range(32) if xs & (1 << i))


Instruction:
Implement a function in Python 3 to
inspect all possible merges and return the best merge and the best goodness for the calling method.

Response:
def _get_best_merge(routing_table, aliases):
    """Inspect all possible merges for the routing table and return the merge
    which would combine the greatest number of entries.

    Returns
    -------
    :py:class:`~.Merge`
    """
    # Create an empty merge to start with
    best_merge = _Merge(routing_table)
    best_goodness = 0

    # Look through every merge, discarding those that are no better than the
    # best we currently know about.
    for merge in _get_all_merges(routing_table):
        # If the merge isn't sufficiently good ignore it and move on
        if merge.goodness <= best_goodness:
            continue

        # After the merge refines itself to remove entries which would either
        # be aliased under other entries or entries which would cause the
        # aliasing of other entries we check if it is better than the current
        # best merge and reject it if it isn't.
        merge = _refine_merge(merge, aliases, min_goodness=best_goodness)
        if merge.goodness > best_goodness:
            # The merge we now have a reference to is better than the best
            # merge that we've previously encountered.
            best_merge = merge
            best_goodness = merge.goodness

    # Return the best merge and the best goodness for the calling method
    return best_merge


Instruction:
How would you code a function in Python 3 to
get all possible sets of entries to merge.

Response:
def _get_all_merges(routing_table):
    """Get possible sets of entries to merge.

    Yields
    ------
    :py:class:`~.Merge`
    """
    # Memorise entries that have been considered as part of a merge
    considered_entries = set()

    for i, entry in enumerate(routing_table):
        # If we've already considered this entry then skip
        if i in considered_entries:
            continue

        # Construct a merge by including other routing table entries below this
        # one which have equivalent routes.
        merge = set([i])
        merge.update(
            j for j, other_entry in enumerate(routing_table[i+1:], start=i+1)
            if entry.route == other_entry.route
        )

        # Mark all these entries as considered
        considered_entries.update(merge)

        # If the merge contains multiple entries then yield it
        if len(merge) > 1:
            yield _Merge(routing_table, merge)


Instruction:
Implement a Python 3 function for
determining the index in the routing table where a new entry should be inserted.

Response:
def _get_insertion_index(routing_table, generality):
    """Determine the index in the routing table where a new entry should be
    inserted.
    """
    # We insert before blocks of equivalent generality, so decrement the given
    # generality.
    generality -= 1

    # Wrapper for _get_generality which accepts a routing entry
    def gg(entry):
        return _get_generality(entry.key, entry.mask)

    # Perform a binary search through the routing table
    bottom = 0
    top = len(routing_table)
    pos = (top - bottom) // 2

    pg = gg(routing_table[pos])
    while pg != generality and bottom < pos < top:
        if pg < generality:
            bottom = pos  # Move up
        else:  # pg > generality
            top = pos  # Move down

        # Compute a new position
        pos = bottom + (top - bottom) // 2
        pg = gg(routing_table[pos])

    while (pos < len(routing_table) and
           gg(routing_table[pos]) <= generality):
        pos += 1

    return pos


Instruction:
Can you tell what is the following Python 3 function doing
def _refine_merge(merge, aliases, min_goodness):
    # Perform the down-check
    merge = _refine_downcheck(merge, aliases, min_goodness)

    # If the merge is still sufficiently good then continue to refine it.
    if merge.goodness > min_goodness:
        # Perform the up-check
        merge, changed = _refine_upcheck(merge, min_goodness)

        if changed and merge.goodness > min_goodness:
            # If the up-check removed any entries we need to re-perform the
            # down-check; but we do not need to re-perform the up-check as the
            # down check can only move the resultant merge nearer the top of
            # the routing table.
            merge = _refine_downcheck(merge, aliases, min_goodness)

    return merge

Response: Remove entries from a merge to generate a valid merge which may be


Instruction:
Explain what the following Python 3 code does
def _refine_upcheck(merge, min_goodness):
    # Remove any entries which would be covered by entries above the merge
    # position.
    changed = False
    for i in sorted(merge.entries, reverse=True):
        # Get all the entries that are between the entry we're looking at the
        # insertion index of the proposed merged index. If this entry would be
        # covered up by any of them then we remove it from the merge.
        entry = merge.routing_table[i]
        key, mask = entry.key, entry.mask
        if any(intersect(key, mask, other.key, other.mask) for other in
               merge.routing_table[i+1:merge.insertion_index]):
            # The entry would be partially or wholly covered by another entry,
            # remove it from the merge and return a new merge.
            merge = _Merge(merge.routing_table, merge.entries - {i})
            changed = True

            # Check if the merge is sufficiently good
            if merge.goodness <= min_goodness:
                merge = _Merge(merge.routing_table)  # Replace with empty merge
                break

    # Return the final merge
    return merge, changed

Response: Remove any entries which would be covered by the merge and return a new merge.


Instruction:
Make a summary of the following Python 3 code
def _refine_downcheck(merge, aliases, min_goodness):
    # Operation
    # ---------
    # While the merge is still better than `min_goodness` we determine which
    # entries below it in the table it covers. For each of these covered
    # entries we find which bits are Xs in the merged entry and are NOT Xs in
    # the covered entry.
    #
    # For example:
    #
    #     Merged entry:      ...0XXX1...
    #     Covered entry:     ...010XX...
    #     Bits of interest:      ^^
    #     Label used below:      mn
    #
    # NOTE:
    #   The covered entry may be of lower generality than the prospective
    #   merged entry if it is contained within the aliases dictionary (e.g.,
    #   ...010XX... may be part of
    #   ``aliases = {...XXXXX...: {..., ...010XX..., ...}, ...})``
    #
    # In this case there are 2 bits of interest highlighted. These are bits in
    # the merge entry whose value can be set (by removing entries from the
    # merge) to avoid covering the covered entry. Whenever we have multiple
    # covered entries we care only about the entries with the fewest number of
    # ``settable`` bits because these most constrain which entries we may
    # remove from the merge to avoid covering up the lower entry.
    #
    # NOTE:
    #   * If there is only 1 ``settable`` bit then we are very constrained in
    #     terms of which entries must be removed from the merge to avoid
    #     covering a lower entry.
    #   * If there are no ``settable`` bits then we cannot possibly avoid
    #     covering the lower entry - the only correct action is to return an
    #     empty merge.
    #
    # Assuming that there were no covered entries without any ``settable`` bits
    # (that is ``stringency > 0``) then ``bits_and_vals`` contains pairs of
    # bits and boolean values which indicate which values need to be removed
    # from which bit positions to avoid covering up lower entries. If the
    # example above were the only covered entry then ``bits_and_vals`` would
    # contain ``(m, True)`` to indicate that all entries containing Xs or 1s in
    # the left-most bit of interest could be removed to avoid the covered entry
    # and ``(n, False)`` to indicate that all entries containing Xs or 0s in
    # the right-most bit of interest could be removed to avoid covering the
    # entry.
    #
    # NOTE:
    #   ``bits_and_vals`` consists of a set of options (e.g., we *could* remove
    #   all entries with Xs or 1s in bit ``m`` *or* we could remove all entries
    #   with Xs or 0s in bit ``n``, either would resolve the above covering).
    #
    # To determine which course of action to take we build a dictionary mapping
    # each of the pairs in ``bits_and_vals`` to the entries that would need to
    # be removed to "set" that bit in the merged entry. For example, we might
    # end up with:
    #
    #     options = {(m, True): {1, 4, 5},
    #                (n, False): {3, 7}}
    #
    # Indicating that we'd need to remove entries 1, 4 and 5 from the merge to
    # "set" the mth bit of the merged to 0 or that we'd need to remove entries
    # 3 and 7 to set the nth bit of the merged entry to set the nth bit to 1.
    #
    # NOTE:
    #   The boolean part of the pair indicates which value needs to be removed
    #   (True -> remove all 1s and Xs; False -> remove all 0s and Xs). If all
    #   Xs and 1s in a given bit position are removed from a merge then the
    #   merged entry is guaranteed to have a 0 in the bit position. Vice-versa
    #   removing all Xs and 0s in a given bit position from a merge will result
    #   in a merged entry with a 1 in that position.
    #
    # As we want to make our merges as large as possible we select the smallest
    # set of entries to remove from the merge from ``options``.
    #
    # The whole process is then repeated since:
    #   * we ignored covered entries with more ``settable`` bits there may
    #     still be covered entries below the merged entry
    #   * after removing entries from the merge the merged entry is of lower
    #     generality and is therefore nearer the top of the table so new
    #     entries may be have become covered

    # Set of bit positions
    all_bits = tuple(1 << i for i in range(32))

    # While the merge is still worth considering continue to perform the
    # down-check.
    while merge.goodness > min_goodness:
        covered = list(_get_covered_keys_and_masks(merge, aliases))

        # If there are no covered entries (the merge is valid) then break out
        # of the loop.
        if not covered:
            break

        # For each covered entry work out which bits in the key-mask pair which
        # are not Xs are not covered by Xs in the merge key-mask pair. Only
        # keep track of the entries which have the fewest bits that we could
        # set.
        most_stringent = 33  # Not at all stringent
        bits_and_vals = set()
        for key, mask in covered:
            # Get the bit positions where there ISN'T an X in the covered entry
            # but there IS an X in the merged entry.
            settable = mask & ~merge.mask

            # Count the number of settable bits, if this is a more stringent
            # constraint than the previous constraint then ensure that we
            # record the new stringency and store which bits we need to set to
            # meet the constraint.
            n_settable = sum(1 for bit in all_bits if bit & settable)
            if n_settable <= most_stringent:
                if n_settable < most_stringent:
                    most_stringent = n_settable
                    bits_and_vals = set()

                # Add this settable mask and the required values to the
                # settables list.
                bits_and_vals.update((bit, not (key & bit)) for bit in
                                     all_bits if bit & settable)

        if most_stringent == 0:
            # If are there any instances where we could not possibly change a
            # bit to avoid aliasing an entry we'll return an empty merge and
            # give up.
            merge = _Merge(merge.routing_table, set())
            break
        else:
            # Get the smallest number of entries to remove to modify the
            # resultant key-mask to avoid covering a lower entry. Prefer to
            # modify more significant bits of the key mask.
            remove = set()  # Entries to remove
            for bit, val in sorted(bits_and_vals, reverse=True):
                working_remove = set()  # Holder for working remove set

                for i in merge.entries:
                    entry = merge.routing_table[i]

                    if ((not entry.mask & bit) or
                            (bool(entry.key & bit) is (not val))):
                        # If the entry has an X in this position then it will
                        # need to be removed regardless of whether we want to
                        # set a 0 or a 1 in this position, likewise it will
                        # need to be removed if it is a 0 and we want a 1 or
                        # vice-versa.
                        working_remove.add(i)

                # If the current remove set is empty or the new remove set is
                # smaller update the remove set.
                if not remove or len(working_remove) < len(remove):
                    remove = working_remove

            # Remove the selected entries from the merge
            merge = _Merge(merge.routing_table, merge.entries - remove)
    else:
        # NOTE: If there are no covered entries, that is, if the merge is
        # better than min goodness AND valid this `else` clause is not reached.
        # Ensure than an empty merge is returned if the above loop was aborted
        # early with a non-empty merge.
        merge = _Merge(merge.routing_table, set())

    return merge

Response: Return a new merge that can be used to reconstruct the merge.


Instruction:
How would you explain what the following Python 3 function does
def _get_covered_keys_and_masks(merge, aliases):
    # For every entry in the table below the insertion index see which keys
    # and masks would overlap with the key and mask of the merged entry.
    for entry in merge.routing_table[merge.insertion_index:]:
        key_mask = (entry.key, entry.mask)
        keys_masks = aliases.get(key_mask, [key_mask])

        for key, mask in keys_masks:
            if intersect(merge.key, merge.mask, key, mask):
                yield key, mask

Response: Get the keys and masks that would be covered by the given merge.


Instruction:
Write a Python 3 script to
apply the merge to the routing table it is defined against and get a new routing table and aliases dictionary.

Response:
def apply(self, aliases):
        """Apply the merge to the routing table it is defined against and get a
        new routing table and alias dictionary.

        Returns
        -------
        [:py:class:`~rig.routing_table.RoutingTableEntry`, ...]
            A new routing table which may be minimised further.
        {(key, mask): {(key, mask), ...}}
            A new aliases dictionary.
        """
        # Create a new routing table of the correct size
        new_size = len(self.routing_table) - len(self.entries) + 1
        new_table = [None for _ in range(new_size)]

        # Create a copy of the aliases dictionary
        aliases = dict(aliases)

        # Get the new entry
        new_entry = RoutingTableEntry(
            route=self.routing_table[next(iter(self.entries))].route,
            key=self.key, mask=self.mask, sources=self.sources
        )
        aliases[(self.key, self.mask)] = our_aliases = set([])

        # Iterate through the old table copying entries acrosss
        insert = 0
        for i, entry in enumerate(self.routing_table):
            # If this is the insertion point then insert
            if i == self.insertion_index:
                new_table[insert] = new_entry
                insert += 1

            if i not in self.entries:
                # If this entry isn't to be removed then copy it across to the
                # new table.
                new_table[insert] = entry
                insert += 1
            else:
                # If this entry is to be removed then add it to the aliases
                # dictionary.
                km = (entry.key, entry.mask)
                our_aliases.update(aliases.pop(km, {km}))

        # If inserting beyond the end of the old table then insert at the end
        # of the new table.
        if self.insertion_index == len(self.routing_table):
            new_table[insert] = new_entry

        return new_table, aliases


Instruction:
Create a Python 3 function for
finding pre - built packages in the _packages directory.

Response:
def find_packages(name, pkg_dir):
    """Locate pre-built packages in the _packages directory"""
    for c in (FileSystemPackageBuilder, ZipPackageBuilder, ExcelPackageBuilder):

        package_path, cache_path = c.make_package_path(pkg_dir, name)

        if package_path.exists():

            yield c.type_code, package_path, cache_path


Instruction:
Given the following Python 3 function, write the documentation
def new_args(subparsers):
    parser = subparsers.add_parser(
        'new',
        help='Create new Metatab packages',
        description=new_args.__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )

    parser.set_defaults(run_command=new_cmd)

    parser.add_argument('-o', '--origin', help="Dataset origin, usually a second-level domain name. Required")
    parser.add_argument('-d', '--dataset', help="Main dataset name. Required", required=True)
    parser.add_argument('-t', '--time', help="Temporal extents, usually a year, ISO8601 time, or interval. ")
    parser.add_argument('-s', '--space', help="Space, geographic extent, such as a name of a state or a Census geoid")
    parser.add_argument('-g', '--grain', help="Grain, the type of entity a row represents")
    parser.add_argument('-v', '--variant', help="Variant, any distinguishing string")
    parser.add_argument('-r', '--revision', help="Version, defaults to 1", default=1)

    parser.add_argument('-T', '--title', help="Set the title")

    parser.add_argument('-L', '--pylib', help="Configure a pylib directory for Python code extensions",
                        action='store_true')

    parser.add_argument('-E', '--example', help="Add examples of resources",
                        action='store_true')

    parser.add_argument('-J', '--jupyter', help="Create a Jupyter notebook source package",
                        action='store_true')

    parser.add_argument('--template', help="Metatab file template, defaults to 'metatab' ", default='metatab')
    parser.add_argument('-C', '--config', help="Path to config file. "
                                               "Defaults to ~/.metapack-defaults.csv or value of METAPACK_DEFAULTS env var."
                                               "Sets defaults for specia root terms and the Contacts section.")
    return parser

Response: Command line options for the new command


Instruction:
Write a Python 3 script for
initializing both bitarray and current_day_bitarray

Response:
def initialize_bitarray(self):
        """Initialize both bitarray.

        This BF contain two bit arrays instead of single one like a plain BF. bitarray
        is the main bit array where all the historical items are stored. It's the one
        used for the membership query. The second one, current_day_bitarray is the one
        used for creating the daily snapshot.
        """
        self.bitarray = bitarray.bitarray(self.nbr_bits)
        self.current_day_bitarray = bitarray.bitarray(self.nbr_bits)
        self.bitarray.setall(False)
        self.current_day_bitarray.setall(False)


Instruction:
How would you code a function in Python 3 to
initialize the period of the current BF.

Response:
def initialize_period(self, period=None):
        """Initialize the period of BF.

        :period: datetime.datetime for setting the period explicity.
        """
        if not period:
            self.current_period = dt.datetime.now()
        else:
            self.current_period = period
        self.current_period = dt.datetime(self.current_period.year, self.current_period.month, self.current_period.day)
        self.date = self.current_period.strftime("%Y-%m-%d")


Instruction:
How would you implement a function in Python 3 that
warms the previous snapshot during the day.

Response:
def warm(self, jittering_ratio=0.2):
        """Progressively load the previous snapshot during the day.

        Loading all the snapshots at once can takes a substantial amount of time. This method, if called
        periodically during the day will progressively load those snapshots one by one. Because many workers are
        going to use this method at the same time, we add a jittering to the period between load to avoid
        hammering the disk at the same time.
        """
        if self.snapshot_to_load == None:
            last_period = self.current_period - dt.timedelta(days=self.expiration-1)
            self.compute_refresh_period()
            self.snapshot_to_load = []
            base_filename = "%s/%s_%s_*.dat" % (self.snapshot_path, self.name, self.expiration)
            availables_snapshots = glob.glob(base_filename)
            for filename in availables_snapshots:
                snapshot_period = dt.datetime.strptime(filename.split('_')[-1].strip('.dat'), "%Y-%m-%d")
                if snapshot_period >= last_period:
                    self.snapshot_to_load.append(filename)
                    self.ready = False

        if self.snapshot_to_load and self._should_warm():
            filename = self.snapshot_to_load.pop()
            self._union_bf_from_file(filename)
            jittering = self.warm_period * (np.random.random()-0.5) * jittering_ratio
            self.next_snapshot_load = time.time() + self.warm_period + jittering
            if not self.snapshot_to_load:
                self.ready = True


Instruction:
Implement a function in Python 3 to
restore the state of the BF using previous snapshots.

Response:
def restore_from_disk(self, clean_old_snapshot=False):
        """Restore the state of the BF using previous snapshots.

        :clean_old_snapshot: Delete the old snapshot on the disk (period < current - expiration)
        """
        base_filename = "%s/%s_%s_*.dat" % (self.snapshot_path, self.name, self.expiration)
        availables_snapshots = glob.glob(base_filename)
        last_period = self.current_period - dt.timedelta(days=self.expiration-1)
        for filename in availables_snapshots:
            snapshot_period = dt.datetime.strptime(filename.split('_')[-1].strip('.dat'), "%Y-%m-%d")
            if snapshot_period <  last_period and not clean_old_snapshot:
                continue
            else:
                self._union_bf_from_file(filename)
                if snapshot_period == self.current_period:
                    self._union_bf_from_file(filename, current=True)

            if snapshot_period < last_period and clean_old_snapshot:
                os.remove(filename)
        self.ready = True


Instruction:
Write a Python 3 script for
saving the current state of the current day bitarray on disk.

Response:
def save_snaphot(self):
        """Save the current state of the current day bitarray on disk.

        Save the internal representation (bitarray) into a binary file using this format:
            filename : name_expiration_2013-01-01.dat
        """
        filename = "%s/%s_%s_%s.dat" % (self.snapshot_path, self.name, self.expiration, self.date)
        with open(filename, 'w') as f:
            f.write(zlib.compress(pickle.dumps(self.current_day_bitarray, protocol=pickle.HIGHEST_PROTOCOL)))


Instruction:
Can you generate the documentation for the following Python 3 function
def place(vertices_resources, nets, machine, constraints,
          vertex_order=None, chip_order=None):
    """Blindly places vertices in sequential order onto chips in the machine.

    This algorithm sequentially places vertices onto chips in the order
    specified (or in an undefined order if not specified). This algorithm is
    essentially the simplest possible valid placement algorithm and is intended
    to form the basis of other simple sequential and greedy placers.

    The algorithm proceeds by attempting to place each vertex on the a chip. If
    the vertex fits we move onto the next vertex (but keep filling the same
    vertex). If the vertex does not fit we move onto the next candidate chip
    until we find somewhere the vertex fits. The algorithm will raise an
    :py:exc:`rig.place_and_route.exceptions.InsufficientResourceError`
    if it has failed to fit a vertex on every chip.

    Parameters
    ----------
    vertex_order : None or iterable
        The order in which the vertices should be attemted to be placed.

        If None (the default), the vertices will be placed in the default
        iteration order of the ``vertices_resources`` argument. If an iterable,
        the iteration sequence should produce each vertex in vertices_resources
        *exactly once*.

    chip_order : None or iterable
        The order in which chips should be tried as a candidate location for a
        vertex.

        If None (the default), the chips will be used in the default iteration
        order of the ``machine`` object (a raster scan). If an iterable, the
        iteration sequence should produce (x, y) pairs giving the coordinates
        of chips to use. All working chip coordinates must be included in the
        iteration sequence *exactly once*. Additional chip coordinates of
        non-existant or dead chips are also allowed (and will simply be
        skipped).
    """
    # If no vertices to place, just stop (from here on we presume that at least
    # one vertex will be placed)
    if len(vertices_resources) == 0:
        return {}

    # Within the algorithm we modify the resource availability values in the
    # machine to account for the effects of the current placement. As a result,
    # an internal copy of the structure must be made.
    machine = machine.copy()

    # {vertex: (x, y), ...} gives the location of all vertices, updated
    # throughout the function.
    placements = {}

    # Handle constraints
    vertices_resources, nets, constraints, substitutions = \
        apply_same_chip_constraints(vertices_resources, nets, constraints)
    for constraint in constraints:
        if isinstance(constraint, LocationConstraint):
            # Location constraints are handled by recording the set of fixed
            # vertex locations and subtracting their resources from the chips
            # they're allocated to.
            location = constraint.location
            if location not in machine:
                raise InvalidConstraintError(
                    "Chip requested by {} unavailable".format(machine))
            vertex = constraint.vertex

            # Record the constrained vertex's location
            placements[vertex] = location

            # Make sure the vertex fits at the requested location (updating the
            # resource availability after placement)
            resources = vertices_resources[vertex]
            machine[location] = subtract_resources(machine[location],
                                                   resources)
            if overallocated(machine[location]):
                raise InsufficientResourceError(
                    "Cannot meet {}".format(constraint))
        elif isinstance(constraint,  # pragma: no branch
                        ReserveResourceConstraint):
            apply_reserve_resource_constraint(machine, constraint)

    if vertex_order is not None:
        # Must modify the vertex_order to substitute the merged vertices
        # inserted by apply_reserve_resource_constraint.
        vertex_order = list(vertex_order)
        for merged_vertex in substitutions:
            # Swap the first merged vertex for its MergedVertex object and
            # remove all other vertices from the merged set
            vertex_order[vertex_order.index(merged_vertex.vertices[0])] \
                = merged_vertex
            # Remove all other vertices in the MergedVertex
            already_removed = set([merged_vertex.vertices[0]])
            for vertex in merged_vertex.vertices[1:]:
                if vertex not in already_removed:
                    vertex_order.remove(vertex)
                    already_removed.add(vertex)

    # The set of vertices which have not been constrained, in iteration order
    movable_vertices = (v for v in (vertices_resources
                                    if vertex_order is None
                                    else vertex_order)
                        if v not in placements)

    # A cyclic iterator over all available chips
    chips = cycle(c for c in (machine if chip_order is None else chip_order)
                  if c in machine)
    chips_iter = iter(chips)

    try:
        cur_chip = next(chips_iter)
    except StopIteration:
        raise InsufficientResourceError("No working chips in machine.")

    # The last chip that we successfully placed something on. Used to detect
    # when we've tried all available chips and not found a suitable candidate
    last_successful_chip = cur_chip

    # Place each vertex in turn
    for vertex in movable_vertices:
        while True:
            resources_if_placed = subtract_resources(
                machine[cur_chip], vertices_resources[vertex])

            if not overallocated(resources_if_placed):
                # The vertex fits: record the resources consumed and move on to
                # the next vertex.
                placements[vertex] = cur_chip
                machine[cur_chip] = resources_if_placed
                last_successful_chip = cur_chip
                break
            else:
                # The vertex won't fit on this chip, move onto the next one
                # available.
                cur_chip = next(chips_iter)

                # If we've looped around all the available chips without
                # managing to place the vertex, give up!
                if cur_chip == last_successful_chip:
                    raise InsufficientResourceError(
                        "Ran out of chips while attempting to place vertex "
                        "{}".format(vertex))

    finalise_same_chip_constraints(substitutions, placements)

    return placements

Response: This function places vertices onto chips in the order specified by the argument.