Instruction:
Can you generate a brief explanation for the following Python 3 code
def convert_row_to_sdpa_index(block_struct, row_offsets, row):
    block_index = bisect_left(row_offsets[1:], row + 1)
    width = block_struct[block_index]
    row = row - row_offsets[block_index]
    i, j = divmod(row, width)
    return block_index, i, j

Response: Helper function to map row to SDPA index values.


Instruction:
Can you tell what is the following Python 3 function doing
def write_to_sdpa(sdp, filename):
    # Coefficient matrices
    row_offsets = [0]
    cumulative_sum = 0
    for block_size in sdp.block_struct:
        cumulative_sum += block_size ** 2
        row_offsets.append(cumulative_sum)
    multiplier = 1
    if sdp.F.dtype == np.complex128:
        multiplier = 2
    lines = [[] for _ in range(multiplier*sdp.n_vars+1)]
    for row in range(len(sdp.F.rows)):
        if len(sdp.F.rows[row]) > 0:
            col_index = 0
            block_index, i, j = convert_row_to_sdpa_index(sdp.block_struct,
                                                          row_offsets, row)
            for k in sdp.F.rows[row]:
                value = sdp.F.data[row][col_index]
                col_index += 1
                if k == 0:
                    value *= -1
                if sdp.F.dtype == np.float64:
                    lines[k].append('{0}\t{1}\t{2}\t{3}\n'.format(
                        block_index + 1, i + 1, j + 1, value))
                else:
                    bs = sdp.block_struct[block_index]
                    if value.real != 0:
                        lines[k].append('{0}\t{1}\t{2}\t{3}\n'.format(
                            block_index + 1, i + 1, j + 1, value.real))
                        lines[k].append('{0}\t{1}\t{2}\t{3}\n'.format(
                            block_index + 1, i + bs + 1, j + bs + 1,
                            value.real))
                    if value.imag != 0:
                        lines[k + sdp.n_vars].append(
                            '{0}\t{1}\t{2}\t{3}\n'.format(
                                block_index + 1, i + 1, j + bs + 1,
                                value.imag))
                        lines[k + sdp.n_vars].append(
                            '{0}\t{1}\t{2}\t{3}\n'.format(
                                block_index + 1, j + 1, i + bs + 1,
                                -value.imag))
    file_ = open(filename, 'w')
    file_.write('"file ' + filename + ' generated by ncpol2sdpa"\n')
    file_.write(str(multiplier*sdp.n_vars) + ' = number of vars\n')
    # bloc structure
    block_struct = [multiplier*blk_size
                    for blk_size in sdp.block_struct]
    file_.write(str(len(block_struct)) + ' = number of blocs\n')
    file_.write(str(block_struct).replace('[', '(')
                .replace(']', ')'))
    file_.write(' = BlocStructure\n')
    # c vector (objective)
    objective = \
        str(list(sdp.obj_facvar)).replace('[', '').replace(']', '')
    if multiplier == 2:
        objective += ', ' + objective
    file_.write('{'+objective+'}\n')
    for k, line in enumerate(lines):
        if line == []:
            continue
        for item in line:
            file_.write('{0}\t'.format(k)+item)
    file_.close()

Response: Write the SDP relaxation to SDPA format.


Instruction:
Given the following Python 3 function, write the documentation
def convert_to_human_readable(sdp):

    objective = ""
    indices_in_objective = []
    for i, tmp in enumerate(sdp.obj_facvar):
        candidates = [key for key, v in
                      sdp.monomial_index.items() if v == i+1]
        if len(candidates) > 0:
            monomial = convert_monomial_to_string(candidates[0])
        else:
            monomial = ""
        if tmp > 0:
            objective += "+"+str(tmp)+monomial
            indices_in_objective.append(i)
        elif tmp < 0:
            objective += str(tmp)+monomial
            indices_in_objective.append(i)

    matrix_size = 0
    cumulative_sum = 0
    row_offsets = [0]
    block_offset = [0]
    for bs in sdp.block_struct:
        matrix_size += abs(bs)
        cumulative_sum += bs ** 2
        row_offsets.append(cumulative_sum)
        block_offset.append(matrix_size)

    matrix = []
    for i in range(matrix_size):
        matrix_line = ["0"] * matrix_size
        matrix.append(matrix_line)

    for row in range(len(sdp.F.rows)):
        if len(sdp.F.rows[row]) > 0:
            col_index = 0
            for k in sdp.F.rows[row]:
                value = sdp.F.data[row][col_index]
                col_index += 1
                block_index, i, j = convert_row_to_sdpa_index(
                    sdp.block_struct, row_offsets, row)
                candidates = [key for key, v in
                              sdp.monomial_index.items()
                              if v == k]
                if len(candidates) > 0:
                    monomial = convert_monomial_to_string(candidates[0])
                else:
                    monomial = ""
                offset = block_offset[block_index]
                if matrix[offset+i][offset+j] == "0":
                    matrix[offset+i][offset+j] = ("%s%s" % (value, monomial))
                else:
                    if value.real > 0:
                        matrix[offset+i][offset+j] += ("+%s%s" % (value,
                                                                  monomial))
                    else:
                        matrix[offset+i][offset+j] += ("%s%s" % (value,
                                                                 monomial))
    return objective, matrix

Response: Convert the SDP relaxation to a human - readable format.


Instruction:
How would you code a function in Python 3 to
write the SDP relaxation to a human - readable format.

Response:
def write_to_human_readable(sdp, filename):
    """Write the SDP relaxation to a human-readable format.

    :param sdp: The SDP relaxation to write.
    :type sdp: :class:`ncpol2sdpa.sdp`.
    :param filename: The name of the file.
    :type filename: str.
    """
    objective, matrix = convert_to_human_readable(sdp)
    f = open(filename, 'w')
    f.write("Objective:" + objective + "\n")
    for matrix_line in matrix:
        f.write(str(list(matrix_line)).replace('[', '').replace(']', '')
                .replace('\'', ''))
        f.write('\n')
    f.close()


Instruction:
Explain what the following Python 3 code does
def make_header(url,
                access_key=None,
                secret_key=None):
    ''' create request header function
    :param url: URL for the new :class:`Request` object.
    '''
    nonce = nounce()
    url    = url
    message = nonce + url
    signature = hmac.new(secret_key.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest()
    headers = {
       'ACCESS-KEY'      : access_key,
       'ACCESS-NONCE'    : nonce,
       'ACCESS-SIGNATURE': signature
    }
    return headers

Response:
create request header function
    :param url: URL for the new :class:`Request` object.


Instruction:
Can you generate the documentation for the following Python 3 function
def unget_bytes(self, string):

        self.unprocessed_bytes.extend(string[i:i + 1]
                                      for i in range(len(string)))

Response: Adds bytes to be internal buffer to be read


Instruction:
Explain what the following Python 3 code does
def _wait_for_read_ready_or_timeout(self, timeout):
        remaining_timeout = timeout
        t0 = time.time()
        while True:
            try:
                (rs, _, _) = select.select(
                    [self.in_stream.fileno()] + self.readers,
                    [], [], remaining_timeout)
                if not rs:
                    return False, None
                r = rs[0]  # if there's more than one, get it in the next loop
                if r == self.in_stream.fileno():
                    return True, None
                else:
                    os.read(r, 1024)
                    if self.queued_interrupting_events:
                        return False, self.queued_interrupting_events.pop(0)
                    elif remaining_timeout is not None:
                        remaining_timeout = max(0, t0 + timeout - time.time())
                        continue
                    else:
                        continue

            except select.error:
                if self.sigints:
                    return False, self.sigints.pop()
                if remaining_timeout is not None:
                    remaining_timeout = max(timeout - (time.time() - t0), 0)

Response: Wait for stdin to read and an event.


Instruction:
Write a Python 3 script to
return an event or None if no events occur before timeout.

Response:
def send(self, timeout=None):
        """Returns an event or None if no events occur before timeout."""
        if self.sigint_event and is_main_thread():
            with ReplacedSigIntHandler(self.sigint_handler):
                return self._send(timeout)
        else:
            return self._send(timeout)


Instruction:
Here you have a function in Python 3, explain what it does
def _nonblocking_read(self):
        with Nonblocking(self.in_stream):
            if PY3:
                try:
                    data = os.read(self.in_stream.fileno(), READ_SIZE)
                except BlockingIOError:
                    return 0
                if data:
                    self.unprocessed_bytes.extend(data[i:i+1] for i in range(len(data)))
                    return len(data)
                else:
                    return 0
            else:
                try:
                    data = os.read(self.in_stream.fileno(), READ_SIZE)
                except OSError:
                    return 0
                else:
                    self.unprocessed_bytes.extend(data)
                    return len(data)

Response: Returns the number of characters read and adds them to self. unread_bytes.


Instruction:
Here you have a function in Python 3, explain what it does
def event_trigger(self, event_type):
        def callback(**kwargs):
            self.queued_events.append(event_type(**kwargs))
        return callback

Response: Returns a callback that creates events.


Instruction:
How would you code a function in Python 3 to
return a callback that schedules events for the future.

Response:
def scheduled_event_trigger(self, event_type):
        """Returns a callback that schedules events for the future.

        Returned callback function will add an event of type event_type
        to a queue which will be checked the next time an event is requested."""
        def callback(when, **kwargs):
            self.queued_scheduled_events.append((when, event_type(when=when, **kwargs)))
        return callback


Instruction:
Here you have a function in Python 3, explain what it does
def threadsafe_event_trigger(self, event_type):
        readfd, writefd = os.pipe()
        self.readers.append(readfd)

        def callback(**kwargs):
            self.queued_interrupting_events.append(event_type(**kwargs))  #TODO use a threadsafe queue for this
            logger.warning('added event to events list %r', self.queued_interrupting_events)
            os.write(writefd, b'interrupting event!')
        return callback

Response: Returns a callback function to create events interrupting current event requests.


Instruction:
Create a Python 3 function for
solving the SDP relaxation.

Response:
def solve_sdp(sdp, solver=None, solverparameters=None):
    """Call a solver on the SDP relaxation. Upon successful solution, it
    returns the primal and dual objective values along with the solution
    matrices.

    :param sdpRelaxation: The SDP relaxation to be solved.
    :type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`.
    :param solver: The solver to be called, either `None`, "sdpa", "mosek",
                   "cvxpy", "scs", or "cvxopt". The default is `None`,
                   which triggers autodetect.
    :type solver: str.
    :param solverparameters: Parameters to be passed to the solver. Actual
                             options depend on the solver:

                             SDPA:

                               - `"executable"`:
                                 Specify the executable for SDPA. E.g.,
                                 `"executable":"/usr/local/bin/sdpa"`, or
                                 `"executable":"sdpa_gmp"`
                               - `"paramsfile"`: Specify the parameter file

                             Mosek:
                             Refer to the Mosek documentation. All
                             arguments are passed on.

                             Cvxopt:
                             Refer to the PICOS documentation. All
                             arguments are passed on.

                             Cvxpy:
                             Refer to the Cvxpy documentation. All
                             arguments are passed on.

                             SCS:
                             Refer to the Cvxpy documentation. All
                             arguments are passed on.
    :type solverparameters: dict of str.
    :returns: tuple of the primal and dual optimum, and the solutions for the
              primal and dual.
    :rtype: (float, float, list of `numpy.array`, list of `numpy.array`)
    """
    solvers = autodetect_solvers(solverparameters)
    solver = solver.lower() if solver is not None else solver
    if solvers == []:
        raise Exception("Could not find any SDP solver. Please install SDPA," +
                        " Mosek, Cvxpy, or Picos with Cvxopt")
    elif solver is not None and solver not in solvers:
        print("Available solvers: " + str(solvers))
        if solver == "cvxopt":
            try:
                import cvxopt
            except ImportError:
                pass
            else:
                raise Exception("Cvxopt is detected, but Picos is not. "
                                "Please install Picos to use Cvxopt")
        raise Exception("Could not detect requested " + solver)
    elif solver is None:
        solver = solvers[0]
    primal, dual, x_mat, y_mat, status = None, None, None, None, None
    tstart = time.time()
    if solver == "sdpa":
        primal, dual, x_mat, y_mat, status = \
          solve_with_sdpa(sdp, solverparameters)
    elif solver == "cvxpy":
        primal, dual, x_mat, y_mat, status = \
          solve_with_cvxpy(sdp, solverparameters)
    elif solver == "scs":
        if solverparameters is None:
            solverparameters_ = {"solver": "SCS"}
        else:
            solverparameters_ = solverparameters.copy()
            solverparameters_["solver"] = "SCS"
        primal, dual, x_mat, y_mat, status = \
          solve_with_cvxpy(sdp, solverparameters_)
    elif solver == "mosek":
        primal, dual, x_mat, y_mat, status = \
          solve_with_mosek(sdp, solverparameters)
    elif solver == "cvxopt":
        primal, dual, x_mat, y_mat, status = \
          solve_with_cvxopt(sdp, solverparameters)
        # We have to compensate for the equality constraints
        for constraint in sdp.constraints[sdp._n_inequalities:]:
            idx = sdp._constraint_to_block_index[constraint]
            sdp._constraint_to_block_index[constraint] = (idx[0],)
    else:
        raise Exception("Unkown solver: " + solver)
    sdp.solution_time = time.time() - tstart
    sdp.primal = primal
    sdp.dual = dual
    sdp.x_mat = x_mat
    sdp.y_mat = y_mat
    sdp.status = status
    return primal, dual, x_mat, y_mat


Instruction:
Write a Python 3 function for
giving a dual problem returns the SOS decomposition of the dual problem.

Response:
def get_sos_decomposition(sdp, y_mat=None, threshold=0.0):
    """Given a solution of the dual problem, it returns the SOS
    decomposition.

    :param sdp: The SDP relaxation to be solved.
    :type sdp: :class:`ncpol2sdpa.sdp`.
    :param y_mat: Optional parameter providing the dual solution of the
                  moment matrix. If not provided, the solution is extracted
                  from the sdp object.
    :type y_mat: :class:`numpy.array`.
    :param threshold: Optional parameter for specifying the threshold value
                      below which the eigenvalues and entries of the
                      eigenvectors are disregarded.
    :type threshold: float.
    :returns: The SOS decomposition of [sigma_0, sigma_1, ..., sigma_m]
    :rtype: list of :class:`sympy.core.exp.Expr`.
    """
    if len(sdp.monomial_sets) != 1:
        raise Exception("Cannot automatically match primal and dual " +
                        "variables.")
    elif len(sdp.y_mat[1:]) != len(sdp.constraints):
        raise Exception("Cannot automatically match constraints with blocks " +
                        "in the dual solution.")
    elif sdp.status == "unsolved" and y_mat is None:
        raise Exception("The SDP relaxation is unsolved and dual solution " +
                        "is not provided!")
    elif sdp.status != "unsolved" and y_mat is None:
        y_mat = sdp.y_mat
    sos = []
    for y_mat_block in y_mat:
        term = 0
        vals, vecs = np.linalg.eigh(y_mat_block)
        for j, val in enumerate(vals):
            if val < -0.001:
                raise Exception("Large negative eigenvalue: " + val +
                                ". Matrix cannot be positive.")
            elif val > 0:
                sub_term = 0
                for i, entry in enumerate(vecs[:, j]):
                    sub_term += entry * sdp.monomial_sets[0][i]
                term += val * sub_term**2
        term = expand(term)
        new_term = 0
        if term.is_Mul:
            elements = [term]
        else:
            elements = term.as_coeff_mul()[1][0].as_coeff_add()[1]
        for element in elements:
            _, coeff = separate_scalar_factor(element)
            if abs(coeff) > threshold:
                new_term += element
        sos.append(new_term)
    return sos


Instruction:
Implement a Python 3 function for
giving a solution of the dual problem and a monomial, it returns the inner product of the corresponding coefficient matrix and the dual solution. It can be restricted to certain blocks. :param sdp: The SDP relaxation. :type sdp: :class:`ncpol2sdpa.sdp`. :param monomial: The monomial for which the value is requested. :type monomial: :class:`sympy.core.exp.Expr`. :param monomial: The monomial for which the value is requested. :type monomial: :class:`sympy.core.exp.Expr`. :param blocks: Optional parameter to specify the blocks to be included. :type blocks: list of `int`. :returns: The value of the monomial in the solved relaxation. :rtype: float.

Response:
def extract_dual_value(sdp, monomial, blocks=None):
    """Given a solution of the dual problem and a monomial, it returns the
    inner product of the corresponding coefficient matrix and the dual
    solution. It can be restricted to certain blocks.

    :param sdp: The SDP relaxation.
    :type sdp: :class:`ncpol2sdpa.sdp`.
    :param monomial: The monomial for which the value is requested.
    :type monomial: :class:`sympy.core.exp.Expr`.
    :param monomial: The monomial for which the value is requested.
    :type monomial: :class:`sympy.core.exp.Expr`.
    :param blocks: Optional parameter to specify the blocks to be included.
    :type blocks: list of `int`.
    :returns: The value of the monomial in the solved relaxation.
    :rtype: float.
    """
    if sdp.status == "unsolved":
        raise Exception("The SDP relaxation is unsolved!")
    if blocks is None:
        blocks = [i for i, _ in enumerate(sdp.block_struct)]
    if is_number_type(monomial):
        index = 0
    else:
        index = sdp.monomial_index[monomial]
    row_offsets = [0]
    cumulative_sum = 0
    for block_size in sdp.block_struct:
        cumulative_sum += block_size ** 2
        row_offsets.append(cumulative_sum)
    result = 0
    for row in range(len(sdp.F.rows)):
        if len(sdp.F.rows[row]) > 0:
            col_index = 0
            for k in sdp.F.rows[row]:
                if k != index:
                    continue
                value = sdp.F.data[row][col_index]
                col_index += 1
                block_index, i, j = convert_row_to_sdpa_index(
                    sdp.block_struct, row_offsets, row)
                if block_index in blocks:
                    result += -value*sdp.y_mat[block_index][i][j]
    return result


Instruction:
Can you create a Python 3 function that
generates a complete CC number.

Response:
def completed_number(prefix, length):
    """
    'prefix' is the start of the CC number as a string, any number of digits.
    'length' is the length of the CC number to generate. Typically 13 or 16
    """
    ccnumber = prefix
    # generate digits
    while len(ccnumber) < (length - 1):
        digit = random.choice(['0',  '1', '2', '3', '4', '5', '6', '7', '8', '9'])
        ccnumber.append(digit)
    # Calculate sum
    sum = 0
    pos = 0
    reversedCCnumber = []
    reversedCCnumber.extend(ccnumber)
    reversedCCnumber.reverse()
    while pos < length - 1:
        odd = int( reversedCCnumber[pos] ) * 2
        if odd > 9:
            odd -= 9
        sum += odd
        if pos != (length - 2):
            sum += int( reversedCCnumber[pos+1] )
        pos += 2
    # Calculate check digit
    checkdigit = ((sum / 10 + 1) * 10 - sum) % 10
    ccnumber.append( str(int(checkdigit)) )
    return ''.join(ccnumber)


Instruction:
How would you explain what the following Python 3 function does
def load_module(self, fullname):
        mod = super(JsonLoader, self).load_module(fullname)

        try:
            with codecs.open(self.cfg_file, 'r', 'utf-8') as f:
                mod.__dict__.update(json.load(f))
        except ValueError:
            # if raise here, traceback will contain ValueError
            self.e = "ValueError"
            self.err_msg = sys.exc_info()[1]

        if self.e == "ValueError":
            err_msg = "\nJson file not valid: "
            err_msg += self.cfg_file + '\n'
            err_msg += str(self.err_msg)
            raise InvalidJsonError(err_msg)

        return mod

Response: Loads the specified module and updates the object with the data from it.


Instruction:
How would you code a function in Python 3 to
return a message from tick if game is over

Response:
def process_event(self, c):
        """Returns a message from tick() to be displayed if game is over"""
        if c == "":
            sys.exit()
        elif c in key_directions:
            self.move_entity(self.player, *vscale(self.player.speed, key_directions[c]))
        else:
            return "try arrow keys, w, a, s, d, or ctrl-D (you pressed %r)" % c
        return self.tick()


Instruction:
Can you write a function in Python 3 where it
returns a message to be displayed if game is over else None

Response:
def tick(self):
        """Returns a message to be displayed if game is over, else None"""
        for npc in self.npcs:
            self.move_entity(npc, *npc.towards(self.player))
        for entity1, entity2 in itertools.combinations(self.entities, 2):
            if (entity1.x, entity1.y) == (entity2.x, entity2.y):
                if self.player in (entity1, entity2):
                    return 'you lost on turn %d' % self.turn
                entity1.die()
                entity2.die()

        if all(npc.speed == 0 for npc in self.npcs):
            return 'you won on turn %d' % self.turn
        self.turn += 1
        if self.turn % 20 == 0:
            self.player.speed = max(1, self.player.speed - 1)
            self.player.display = on_blue(green(bold(unicode_str(self.player.speed))))


Instruction:
Can you tell what is the following Python 3 function doing
def array_from_text(self, msg):
        rows, columns = self.t.height, self.t.width
        return self.array_from_text_rc(msg, rows, columns)

Response: Returns an FSArray of the size of the window containing msg


Instruction:
How would you explain what the following Python 3 function does
def render_to_terminal(self, array, cursor_pos=(0, 0)):
        # TODO there's a race condition here - these height and widths are
        # super fresh - they might change between the array being constructed
        # and rendered
        # Maybe the right behavior is to throw away the render
        # in the signal handler?
        height, width = self.height, self.width

        for_stdout = self.fmtstr_to_stdout_xform()
        if not self.hide_cursor:
            self.write(self.t.hide_cursor)
        if (height != self._last_rendered_height or
                width != self._last_rendered_width):
            self.on_terminal_size_change(height, width)

        current_lines_by_row = {}
        rows = list(range(height))
        rows_for_use = rows[:len(array)]
        rest_of_rows = rows[len(array):]

        # rows which we have content for and don't require scrolling
        for row, line in zip(rows_for_use, array):
            current_lines_by_row[row] = line
            if line == self._last_lines_by_row.get(row, None):
                continue
            self.write(self.t.move(row, 0))
            self.write(for_stdout(line))
            if len(line) < width:
                self.write(self.t.clear_eol)

        # rows onscreen that we don't have content for
        for row in rest_of_rows:
            if self._last_lines_by_row and row not in self._last_lines_by_row:
                continue
            self.write(self.t.move(row, 0))
            self.write(self.t.clear_eol)
            self.write(self.t.clear_bol)
            current_lines_by_row[row] = None

        logger.debug(
            'lines in last lines by row: %r' % self._last_lines_by_row.keys()
        )
        logger.debug(
            'lines in current lines by row: %r' % current_lines_by_row.keys()
        )
        self.write(self.t.move(*cursor_pos))
        self._last_lines_by_row = current_lines_by_row
        if not self.hide_cursor:
            self.write(self.t.normal_cursor)

Response: Renders the array to the terminal and places the cursor position.


Instruction:
Make a summary of the following Python 3 code
def get_cursor_position(self):
        # TODO would this be cleaner as a parameter?
        in_stream = self.in_stream

        query_cursor_position = u"\x1b[6n"
        self.write(query_cursor_position)

        def retrying_read():
            while True:
                try:
                    c = in_stream.read(1)
                    if c == '':
                        raise ValueError("Stream should be blocking - should't"
                                         " return ''. Returned %r so far",
                                         (resp,))
                    return c
                except IOError:
                    raise ValueError(
                        'cursor get pos response read interrupted'
                    )
                    # find out if this ever really happens - if so, continue

        resp = ''
        while True:
            c = retrying_read()
            resp += c
            m = re.search('(?P<extra>.*)'
                          '(?P<CSI>\x1b\[|\x9b)'
                          '(?P<row>\\d+);(?P<column>\\d+)R', resp, re.DOTALL)
            if m:
                row = int(m.groupdict()['row'])
                col = int(m.groupdict()['column'])
                extra = m.groupdict()['extra']
                if extra:
                    if self.extra_bytes_callback:
                        self.extra_bytes_callback(
                            extra.encode(in_stream.encoding)
                        )
                    else:
                        raise ValueError(("Bytes preceding cursor position "
                                          "query response thrown out:\n%r\n"
                                          "Pass an extra_bytes_callback to "
                                          "CursorAwareWindow to prevent this")
                                         % (extra,))
                return (row - 1, col - 1)

Response: Returns the terminal row column of the cursor.


Instruction:
How would you explain what the following Python 3 function does
def get_cursor_vertical_diff(self):
        # Probably called by a SIGWINCH handler, and therefore
        # will do cursor querying until a SIGWINCH doesn't happen during
        # the query. Calls to the function from a signal handler COULD STILL
        # HAPPEN out of order -
        # they just can't interrupt the actual cursor query.
        if self.in_get_cursor_diff:
            self.another_sigwinch = True
            return 0

        cursor_dy = 0
        while True:
            self.in_get_cursor_diff = True
            self.another_sigwinch = False
            cursor_dy += self._get_cursor_vertical_diff_once()
            self.in_get_cursor_diff = False
            if not self.another_sigwinch:
                return cursor_dy

Response: Returns the number of lines moved down the cursor.


Instruction:
Create a Python 3 function to
return the how far down the cursor moved.

Response:
def _get_cursor_vertical_diff_once(self):
        """Returns the how far down the cursor moved."""
        old_top_usable_row = self.top_usable_row
        row, col = self.get_cursor_position()
        if self._last_cursor_row is None:
            cursor_dy = 0
        else:
            cursor_dy = row - self._last_cursor_row
            logger.info('cursor moved %d lines down' % cursor_dy)
            while self.top_usable_row > -1 and cursor_dy > 0:
                self.top_usable_row += 1
                cursor_dy -= 1
            while self.top_usable_row > 1 and cursor_dy < 0:
                self.top_usable_row -= 1
                cursor_dy += 1
        logger.info('top usable row changed from %d to %d', old_top_usable_row,
                    self.top_usable_row)
        logger.info('returning cursor dy of %d from curtsies' % cursor_dy)
        self._last_cursor_row = row
        return cursor_dy


Instruction:
Can you generate the documentation for the following Python 3 function
def render_to_terminal(self, array, cursor_pos=(0, 0)):
        for_stdout = self.fmtstr_to_stdout_xform()
        # caching of write and tc (avoiding the self. lookups etc) made
        # no significant performance difference here
        if not self.hide_cursor:
            self.write(self.t.hide_cursor)

        # TODO race condition here?
        height, width = self.t.height, self.t.width
        if (height != self._last_rendered_height or
                width != self._last_rendered_width):
            self.on_terminal_size_change(height, width)

        current_lines_by_row = {}
        rows_for_use = list(range(self.top_usable_row, height))

        # rows which we have content for and don't require scrolling
        # TODO rename shared
        shared = min(len(array), len(rows_for_use))
        for row, line in zip(rows_for_use[:shared], array[:shared]):
            current_lines_by_row[row] = line
            if line == self._last_lines_by_row.get(row, None):
                continue
            self.write(self.t.move(row, 0))
            self.write(for_stdout(line))
            if len(line) < width:
                self.write(self.t.clear_eol)

        # rows already on screen that we don't have content for
        rest_of_lines = array[shared:]
        rest_of_rows = rows_for_use[shared:]
        for row in rest_of_rows:  # if array too small
            if self._last_lines_by_row and row not in self._last_lines_by_row:
                continue
            self.write(self.t.move(row, 0))
            self.write(self.t.clear_eol)
            # TODO probably not necessary - is first char cleared?
            self.write(self.t.clear_bol)
            current_lines_by_row[row] = None

        # lines for which we need to scroll down to render
        offscreen_scrolls = 0
        for line in rest_of_lines:  # if array too big
            self.scroll_down()
            if self.top_usable_row > 0:
                self.top_usable_row -= 1
            else:
                offscreen_scrolls += 1
            current_lines_by_row = dict(
                (k - 1, v) for k, v in current_lines_by_row.items()
            )
            logger.debug('new top_usable_row: %d' % self.top_usable_row)
            # since scrolling moves the cursor
            self.write(self.t.move(height - 1, 0))
            self.write(for_stdout(line))
            current_lines_by_row[height - 1] = line

        logger.debug(
            'lines in last lines by row: %r' % self._last_lines_by_row.keys()
        )
        logger.debug(
            'lines in current lines by row: %r' % current_lines_by_row.keys()
        )
        self._last_cursor_row = max(
            0, cursor_pos[0] - offscreen_scrolls + self.top_usable_row
        )
        self._last_cursor_column = cursor_pos[1]
        self.write(
            self.t.move(self._last_cursor_row, self._last_cursor_column)
        )
        self._last_lines_by_row = current_lines_by_row
        if not self.hide_cursor:
            self.write(self.t.normal_cursor)
        return offscreen_scrolls

Response: Renders the given array to the terminal. Returns the number of lines scrolled offscreen.


Instruction:
Implement a function in Python 3 to
solve the SDP relaxation on the current object.

Response:
def solve(self, solver=None, solverparameters=None):
        """Call a solver on the SDP relaxation. Upon successful solution, it
        returns the primal and dual objective values along with the solution
        matrices. It also sets these values in the `sdpRelaxation` object,
        along with some status information.

        :param sdpRelaxation: The SDP relaxation to be solved.
        :type sdpRelaxation: :class:`ncpol2sdpa.SdpRelaxation`.
        :param solver: The solver to be called, either `None`, "sdpa", "mosek",
                       "cvxpy", "scs", or "cvxopt". The default is `None`,
                       which triggers autodetect.
        :type solver: str.
        :param solverparameters: Parameters to be passed to the solver. Actual
                                 options depend on the solver:

                                 SDPA:

                                   - `"executable"`:
                                     Specify the executable for SDPA. E.g.,
                                     `"executable":"/usr/local/bin/sdpa"`, or
                                     `"executable":"sdpa_gmp"`
                                   - `"paramsfile"`: Specify the parameter file

                                 Mosek:
                                 Refer to the Mosek documentation. All
                                 arguments are passed on.

                                 Cvxopt:
                                 Refer to the PICOS documentation. All
                                 arguments are passed on.

                                 Cvxpy:
                                 Refer to the Cvxpy documentation. All
                                 arguments are passed on.

                                 SCS:
                                 Refer to the Cvxpy documentation. All
                                 arguments are passed on.

        :type solverparameters: dict of str.
        """
        if self.F is None:
            raise Exception("Relaxation is not generated yet. Call "
                            "'SdpRelaxation.get_relaxation' first")
        solve_sdp(self, solver, solverparameters)


Instruction:
How would you implement a function in Python 3 that
processes a single monomial when building the moment matrix.

Response:
def _process_monomial(self, monomial, n_vars):
        """Process a single monomial when building the moment matrix.
        """
        processed_monomial, coeff = separate_scalar_factor(monomial)
        # Are we substituting this moment?
        try:
            substitute = self.moment_substitutions[processed_monomial]
            if not isinstance(substitute, (int, float, complex)):
                result = []
                if not isinstance(substitute, Add):
                    args = [substitute]
                else:
                    args = substitute.args
                for arg in args:
                    if is_number_type(arg):
                        if iscomplex(arg):
                            result.append((0, coeff*complex(arg)))
                        else:
                            result.append((0, coeff*float(arg)))
                    else:
                        result += [(k, coeff*c2)
                                   for k, c2 in self._process_monomial(arg,
                                                                       n_vars)]
            else:
                result = [(0, coeff*substitute)]
        except KeyError:
            # Have we seen this monomial before?
            try:
                # If yes, then we improve sparsity by reusing the
                # previous variable to denote this entry in the matrix
                k = self.monomial_index[processed_monomial]
            except KeyError:
                # If no, it still may be possible that we have already seen its
                # conjugate. If the problem is real-valued, a monomial and its
                # conjugate should be equal (Hermiticity becomes symmetry)
                if not self.complex_matrix:
                    try:
                    # If we have seen the conjugate before, we just use the
                    # conjugate monomial instead
                        processed_monomial_adjoint = \
                              apply_substitutions(processed_monomial.adjoint(),
                                                  self.substitutions)
                        k = self.monomial_index[processed_monomial_adjoint]
                    except KeyError:
                        # Otherwise we define a new entry in the associated
                        # array recording the monomials, and add an entry in
                        # the moment matrix
                        k = n_vars + 1
                        self.monomial_index[processed_monomial] = k
                else:
                    k = n_vars + 1
                    self.monomial_index[processed_monomial] = k
            result = [(k, coeff)]
        return result


Instruction:
Make a summary of the following Python 3 code
def _generate_moment_matrix(self, n_vars, block_index, processed_entries,
                                monomialsA, monomialsB, ppt=False):
        """Generate the moment matrix of monomials.

        Arguments:
        n_vars -- current number of variables
        block_index -- current block index in the SDP matrix
        monomials -- |W_d| set of words of length up to the relaxation level
        """
        row_offset = 0
        if block_index > 0:
            for block_size in self.block_struct[0:block_index]:
                row_offset += block_size ** 2
        N = len(monomialsA)*len(monomialsB)
        func = partial(assemble_monomial_and_do_substitutions,
                       monomialsA=monomialsA, monomialsB=monomialsB, ppt=ppt,
                       substitutions=self.substitutions,
                       pure_substitution_rules=self.pure_substitution_rules)
        if self._parallel:
            pool = Pool()
            # This is just a guess and can be optimized
            chunksize = int(max(int(np.sqrt(len(monomialsA) * len(monomialsB) *
                                        len(monomialsA) / 2) / cpu_count()),
                                1))
        for rowA in range(len(monomialsA)):
            if self._parallel:
                iter_ = pool.map(func, [(rowA, columnA, rowB, columnB)
                                        for rowB in range(len(monomialsB))
                                        for columnA in range(rowA,
                                                             len(monomialsA))
                                        for columnB in range((rowA == columnA)*rowB,
                                                             len(monomialsB))],
                                 chunksize)
                print_criterion = processed_entries + len(iter_)
            else:
                iter_ = imap(func, [(rowA, columnA, rowB, columnB)
                                    for columnA in range(rowA, len(monomialsA))
                                    for rowB in range(len(monomialsB))
                                    for columnB in range((rowA == columnA)*rowB,
                                                         len(monomialsB))])
            for columnA, rowB, columnB, monomial in iter_:
                processed_entries += 1
                n_vars = self._push_monomial(monomial, n_vars,
                                             row_offset, rowA,
                                             columnA, N, rowB,
                                             columnB, len(monomialsB),
                                             prevent_substitutions=True)
                if self.verbose > 0 and (not self._parallel or
                                         processed_entries == self.n_vars or
                                         processed_entries == print_criterion):
                    percentage = processed_entries / self.n_vars
                    time_used = time.time()-self._time0
                    eta = (1.0 / percentage) * time_used - time_used
                    hours = int(eta/3600)
                    minutes = int((eta-3600*hours)/60)
                    seconds = eta-3600*hours-minutes*60

                    msg = ""
                    if self.verbose > 1 and self._parallel:
                        msg = ", working on block {:0} with {:0} processes with a chunksize of {:0d}"\
                              .format(block_index, cpu_count(),
                                      chunksize)
                    msg = "{:0} (done: {:.2%}, ETA {:02d}:{:02d}:{:03.1f}"\
                          .format(n_vars, percentage, hours, minutes, seconds) + \
                          msg
                    msg = "\r\x1b[KCurrent number of SDP variables: " + msg + ")"
                    sys.stdout.write(msg)
                    sys.stdout.flush()

        if self._parallel:
            pool.close()
            pool.join()
        if self.verbose > 0:
            sys.stdout.write("\r")
        return n_vars, block_index + 1, processed_entries

Response: Generate the moment matrix of the monomials.


Instruction:
Create a Python 3 function to
return the index of a monomial.

Response:
def _get_index_of_monomial(self, element, enablesubstitution=True,
                               daggered=False):
        """Returns the index of a monomial.
        """
        result = []
        processed_element, coeff1 = separate_scalar_factor(element)
        if processed_element in self.moment_substitutions:
            r = self._get_index_of_monomial(self.moment_substitutions[processed_element], enablesubstitution)
            return [(k, coeff*coeff1) for k, coeff in r]
        if enablesubstitution:
            processed_element = \
                apply_substitutions(processed_element, self.substitutions,
                                    self.pure_substitution_rules)
        # Given the monomial, we need its mapping L_y(w) to push it into
        # a corresponding constraint matrix
        if is_number_type(processed_element):
            return [(0, coeff1)]
        elif processed_element.is_Add:
            monomials = processed_element.args
        else:
            monomials = [processed_element]
        for monomial in monomials:
            monomial, coeff2 = separate_scalar_factor(monomial)
            coeff = coeff1*coeff2
            if is_number_type(monomial):
                result.append((0, coeff))
                continue
            k = -1
            if monomial != 0:
                if monomial.as_coeff_Mul()[0] < 0:
                    monomial = -monomial
                    coeff = -1.0 * coeff
            try:
                new_element = self.moment_substitutions[monomial]
                r = self._get_index_of_monomial(self.moment_substitutions[new_element], enablesubstitution)
                result += [(k, coeff*coeff3) for k, coeff3 in r]
            except KeyError:
                try:
                    k = self.monomial_index[monomial]
                    result.append((k, coeff))
                except KeyError:
                    if not daggered:
                        dag_result = self._get_index_of_monomial(monomial.adjoint(),
                                                                 daggered=True)
                        result += [(k, coeff0*coeff) for k, coeff0 in dag_result]
                    else:
                        raise RuntimeError("The requested monomial " +
                                           str(monomial) + " could not be found.")
        return result


Instruction:
How would you code a function in Python 3 to
push a sparse vector representation of a polynomial into the F structure.

Response:
def __push_facvar_sparse(self, polynomial, block_index, row_offset, i, j):
        """Calculate the sparse vector representation of a polynomial
        and pushes it to the F structure.
        """
        width = self.block_struct[block_index - 1]
        # Preprocess the polynomial for uniform handling later
        # DO NOT EXPAND THE POLYNOMIAL HERE!!!!!!!!!!!!!!!!!!!
        # The simplify_polynomial bypasses the problem.
        # Simplifying here will trigger a bug in SymPy related to
        # the powers of daggered variables.
        # polynomial = polynomial.expand()
        if is_number_type(polynomial) or polynomial.is_Mul:
            elements = [polynomial]
        else:
            elements = polynomial.as_coeff_mul()[1][0].as_coeff_add()[1]
        # Identify its constituent monomials
        for element in elements:
            results = self._get_index_of_monomial(element)
            # k identifies the mapped value of a word (monomial) w
            for (k, coeff) in results:
                if k > -1 and coeff != 0:
                    self.F[row_offset + i * width + j, k] += coeff


Instruction:
Can you tell what is the following Python 3 function doing
def __process_inequalities(self, block_index):
        initial_block_index = block_index
        row_offsets = [0]
        for block, block_size in enumerate(self.block_struct):
            row_offsets.append(row_offsets[block] + block_size ** 2)

        if self._parallel:
            pool = Pool()
        for k, ineq in enumerate(self.constraints):
            block_index += 1
            monomials = self.localizing_monomial_sets[block_index -
                                                      initial_block_index-1]
            lm = len(monomials)
            if isinstance(ineq, str):
                self.__parse_expression(ineq, row_offsets[block_index-1])
                continue
            if ineq.is_Relational:
                ineq = convert_relational(ineq)
            func = partial(moment_of_entry, monomials=monomials, ineq=ineq,
                           substitutions=self.substitutions)
            if self._parallel and lm > 1:
                chunksize = max(int(np.sqrt(lm*lm/2) /
                                    cpu_count()), 1)
                iter_ = pool.map(func, ([row, column] for row in range(lm)
                                        for column in range(row, lm)),
                                 chunksize)
            else:
                iter_ = imap(func, ([row, column] for row in range(lm)
                                    for column in range(row, lm)))
            if block_index > self.constraint_starting_block + \
                    self._n_inequalities and lm > 1:
                is_equality = True
            else:
                is_equality = False
            for row, column, polynomial in iter_:
                if is_equality:
                    row, column = 0, 0
                self.__push_facvar_sparse(polynomial, block_index,
                                          row_offsets[block_index-1],
                                          row, column)
                if is_equality:
                    block_index += 1
            if is_equality:
                block_index -= 1
            if self.verbose > 0:
                sys.stdout.write("\r\x1b[KProcessing %d/%d constraints..." %
                                 (k+1, len(self.constraints)))
                sys.stdout.flush()
        if self._parallel:
            pool.close()
            pool.join()

        if self.verbose > 0:
            sys.stdout.write("\n")
        return block_index

Response: Generate localizing matrices for the inequality constraints of the SDP relaxation.


Instruction:
Write a Python 3 function for
generating the localizing matrices for the given set of equalities and the given list of moment equalities.

Response:
def __process_equalities(self, equalities, momentequalities):
        """Generate localizing matrices

        Arguments:
        equalities -- list of equality constraints
        equalities -- list of moment equality constraints
        """
        monomial_sets = []
        n_rows = 0
        le = 0
        if equalities is not None:
            for equality in equalities:
                le += 1
                # Find the order of the localizing matrix
                if equality.is_Relational:
                    equality = convert_relational(equality)
                eq_order = ncdegree(equality)
                if eq_order > 2 * self.level:
                    raise Exception("An equality constraint has degree %d. "
                                    "Choose a higher level of relaxation."
                                    % eq_order)
                localization_order = (2 * self.level - eq_order)//2
                index = find_variable_set(self.variables, equality)
                localizing_monomials = \
                    pick_monomials_up_to_degree(self.monomial_sets[index],
                                                localization_order)
                if len(localizing_monomials) == 0:
                    localizing_monomials = [S.One]
                localizing_monomials = unique(localizing_monomials)
                monomial_sets.append(localizing_monomials)
                n_rows += len(localizing_monomials) * \
                    (len(localizing_monomials) + 1) // 2
        if momentequalities is not None:
            for _ in momentequalities:
                le += 1
                monomial_sets.append([S.One])
                n_rows += 1
        A = np.zeros((n_rows, self.n_vars + 1), dtype=self.F.dtype)
        n_rows = 0
        if self._parallel:
            pool = Pool()
        for i, equality in enumerate(flatten([equalities, momentequalities])):
            func = partial(moment_of_entry, monomials=monomial_sets[i],
                           ineq=equality, substitutions=self.substitutions)
            lm = len(monomial_sets[i])
            if self._parallel and lm > 1:
                chunksize = max(int(np.sqrt(lm*lm/2) /
                                    cpu_count()), 1)
                iter_ = pool.map(func, ([row, column] for row in range(lm)
                                        for column in range(row, lm)),
                                 chunksize)
            else:
                iter_ = imap(func, ([row, column] for row in range(lm)
                                    for column in range(row, lm)))
            # Process M_y(gy)(u,w) entries
            for row, column, polynomial in iter_:
                # Calculate the moments of polynomial entries
                if isinstance(polynomial, str):
                    self.__parse_expression(equality, -1, A[n_rows])
                else:
                    A[n_rows] = self._get_facvar(polynomial)
                n_rows += 1
                if self.verbose > 0:
                    sys.stdout.write("\r\x1b[KProcessing %d/%d equalities..." %
                                     (i+1, le))
                    sys.stdout.flush()
        if self._parallel:
            pool.close()
            pool.join()

        if self.verbose > 0:
            sys.stdout.write("\n")
        return A


Instruction:
Implement a Python 3 function for
attempting to remove equalities by solving the linear equations.

Response:
def __remove_equalities(self, equalities, momentequalities):
        """Attempt to remove equalities by solving the linear equations.
        """
        A = self.__process_equalities(equalities, momentequalities)
        if min(A.shape != np.linalg.matrix_rank(A)):
            print("Warning: equality constraints are linearly dependent! "
                  "Results might be incorrect.", file=sys.stderr)
        if A.shape[0] == 0:
            return
        c = np.array(self.obj_facvar)
        if self.verbose > 0:
            print("QR decomposition...")
        Q, R = np.linalg.qr(A[:, 1:].T, mode='complete')
        n = np.max(np.nonzero(np.sum(np.abs(R), axis=1) > 0)) + 1
        x = np.dot(Q[:, :n], np.linalg.solve(np.transpose(R[:n, :]), -A[:, 0]))
        self._new_basis = lil_matrix(Q[:, n:])
        # Transforming the objective function
        self._original_obj_facvar = self.obj_facvar
        self._original_constant_term = self.constant_term
        self.obj_facvar = self._new_basis.T.dot(c)
        self.constant_term += c.dot(x)
        x = np.append(1, x)
        # Transforming the moment matrix and localizing matrices
        new_F = lil_matrix((self.F.shape[0], self._new_basis.shape[1] + 1))
        new_F[:, 0] = self.F[:, :self.n_vars+1].dot(x).reshape((new_F.shape[0],
                                                                1))
        new_F[:, 1:] = self.F[:, 1:self.n_vars+1].\
            dot(self._new_basis)
        self._original_F = self.F
        self.F = new_F
        self.n_vars = self._new_basis.shape[1]
        if self.verbose > 0:
            print("Number of variables after solving the linear equations: %d"
                  % self.n_vars)


Instruction:
How would you implement a function in Python 3 that
calculates the block structure for the current object.

Response:
def _calculate_block_structure(self, inequalities, equalities,
                                   momentinequalities, momentequalities,
                                   extramomentmatrix, removeequalities,
                                   block_struct=None):
        """Calculates the block_struct array for the output file.
        """
        if block_struct is None:
            if self.verbose > 0:
                print("Calculating block structure...")
            self.block_struct = []
            if self.parameters is not None:
                self.block_struct += [1 for _ in self.parameters]
            for monomials in self.monomial_sets:
                if len(monomials) > 0 and isinstance(monomials[0], list):
                    self.block_struct.append(len(monomials[0]))
                else:
                    self.block_struct.append(len(monomials))
            if extramomentmatrix is not None:
                for _ in extramomentmatrix:
                    for monomials in self.monomial_sets:
                        if len(monomials) > 0 and \
                                isinstance(monomials[0], list):
                            self.block_struct.append(len(monomials[0]))
                        else:
                            self.block_struct.append(len(monomials))
        else:
            self.block_struct = block_struct
        degree_warning = False
        if inequalities is not None:
            self._n_inequalities = len(inequalities)
            n_tmp_inequalities = len(inequalities)
        else:
            self._n_inequalities = 0
            n_tmp_inequalities = 0
        constraints = flatten([inequalities])
        if momentinequalities is not None:
            self._n_inequalities += len(momentinequalities)
            constraints += momentinequalities
        if not removeequalities:
            constraints += flatten([equalities])
        monomial_sets = []
        for k, constraint in enumerate(constraints):
            # Find the order of the localizing matrix
            if k < n_tmp_inequalities or k >= self._n_inequalities:
                if isinstance(constraint, str):
                    ineq_order = 2 * self.level
                else:
                    if constraint.is_Relational:
                        constraint = convert_relational(constraint)
                    ineq_order = ncdegree(constraint)
                    if iscomplex(constraint):
                        self.complex_matrix = True
                if ineq_order > 2 * self.level:
                    degree_warning = True
                localization_order = (2*self.level - ineq_order)//2
                if self.level == -1:
                    localization_order = 0
                if self.localizing_monomial_sets is not None and \
                        self.localizing_monomial_sets[k] is not None:
                    localizing_monomials = self.localizing_monomial_sets[k]
                else:
                    index = find_variable_set(self.variables, constraint)
                    localizing_monomials = \
                        pick_monomials_up_to_degree(self.monomial_sets[index],
                                                    localization_order)
                ln = len(localizing_monomials)
                if ln == 0:
                    localizing_monomials = [S.One]
            else:
                localizing_monomials = [S.One]
                ln = 1
            localizing_monomials = unique(localizing_monomials)
            monomial_sets.append(localizing_monomials)
            if k < self._n_inequalities:
                self.block_struct.append(ln)
            else:
                monomial_sets += [None for _ in range(ln*(ln+1)//2-1)]
                monomial_sets.append(localizing_monomials)
                monomial_sets += [None for _ in range(ln*(ln+1)//2-1)]
                self.block_struct += [1 for _ in range(ln*(ln+1))]

        if degree_warning and self.verbose > 0:
            print("A constraint has degree %d. Either choose a higher level "
                  "relaxation or ensure that a mixed-order relaxation has the"
                  " necessary monomials" % (ineq_order), file=sys.stderr)

        if momentequalities is not None:
            for moment_eq in momentequalities:
                self._moment_equalities.append(moment_eq)
                if not removeequalities:
                    monomial_sets += [[S.One], [S.One]]
                    self.block_struct += [1, 1]
        self.localizing_monomial_sets = monomial_sets


Instruction:
Can you generate the documentation for the following Python 3 function
def process_constraints(self, inequalities=None, equalities=None,
                            momentinequalities=None, momentequalities=None,
                            block_index=0, removeequalities=False):
        """Process the constraints and generate localizing matrices. Useful
        only if the moment matrix already exists. Call it if you want to
        replace your constraints. The number of the respective types of
        constraints and the maximum degree of each constraint must remain the
        same.

        :param inequalities: Optional parameter to list inequality constraints.
        :type inequalities: list of :class:`sympy.core.exp.Expr`.
        :param equalities: Optional parameter to list equality constraints.
        :type equalities: list of :class:`sympy.core.exp.Expr`.
        :param momentinequalities: Optional parameter of inequalities defined
                                   on moments.
        :type momentinequalities: list of :class:`sympy.core.exp.Expr`.
        :param momentequalities: Optional parameter of equalities defined
                                 on moments.
        :type momentequalities: list of :class:`sympy.core.exp.Expr`.
        :param removeequalities: Optional parameter to attempt removing the
                                 equalities by solving the linear equations.

        :param removeequalities: Optional parameter to attempt removing the
                                 equalities by solving the linear equations.
        :type removeequalities: bool.
        """
        self.status = "unsolved"
        if block_index == 0:
            if self._original_F is not None:
                self.F = self._original_F
                self.obj_facvar = self._original_obj_facvar
                self.constant_term = self._original_constant_term
                self.n_vars = len(self.obj_facvar)
                self._new_basis = None
            block_index = self.constraint_starting_block
            self.__wipe_F_from_constraints()
        self.constraints = flatten([inequalities])
        self._constraint_to_block_index = {}
        for constraint in self.constraints:
            self._constraint_to_block_index[constraint] = (block_index, )
            block_index += 1
        if momentinequalities is not None:
            for mineq in momentinequalities:
                self.constraints.append(mineq)
                self._constraint_to_block_index[mineq] = (block_index, )
                block_index += 1
        if not (removeequalities or equalities is None):
            # Equalities are converted to pairs of inequalities
            for k, equality in enumerate(equalities):
                if equality.is_Relational:
                    equality = convert_relational(equality)
                self.constraints.append(equality)
                self.constraints.append(-equality)
                ln = len(self.localizing_monomial_sets[block_index-
                                                       self.constraint_starting_block])
                self._constraint_to_block_index[equality] = (block_index,
                                                             block_index+ln*(ln+1)//2)
                block_index += ln*(ln+1)
        if momentequalities is not None and not removeequalities:
            for meq in momentequalities:
                self.constraints += [meq, flip_sign(meq)]
                self._constraint_to_block_index[meq] = (block_index,
                                                        block_index+1)
                block_index += 2
        block_index = self.constraint_starting_block
        self.__process_inequalities(block_index)
        if removeequalities:
            self.__remove_equalities(equalities, momentequalities)

Response: Processes the constraints and generates localizing matrices. Useful for creating the localizing matrices.


Instruction:
Write a Python 3 script for
setting or change the objective function of the polynomial optimization problem.

Response:
def set_objective(self, objective, extraobjexpr=None):
        """Set or change the objective function of the polynomial optimization
        problem.

        :param objective: Describes the objective function.
        :type objective: :class:`sympy.core.expr.Expr`
        :param extraobjexpr: Optional parameter of a string expression of a
                             linear combination of moment matrix elements to be
                             included in the objective function
        :type extraobjexpr: str.
        """
        if objective is not None:
            facvar = \
                self._get_facvar(simplify_polynomial(objective,
                                                     self.substitutions))
            self.obj_facvar = facvar[1:]
            self.constant_term = facvar[0]
            if self.verbose > 0 and facvar[0] != 0:
                print("Warning: The objective function has a non-zero %s "
                      "constant term. It is not included in the SDP objective."
                      % facvar[0], file=sys.stderr)
        else:
            self.obj_facvar = self._get_facvar(0)[1:]
        if extraobjexpr is not None:
            for sub_expr in extraobjexpr.split(']'):
                startindex = 0
                if sub_expr.startswith('-') or sub_expr.startswith('+'):
                    startindex = 1
                ind = sub_expr.find('[')
                if ind > -1:
                    idx = sub_expr[ind+1:].split(",")
                    i, j = int(idx[0]), int(idx[1])
                    mm_ind = int(sub_expr[startindex:ind])
                    if sub_expr.find('*') > -1:
                        value = float(sub_expr[:sub_expr.find('*')])
                    elif sub_expr.startswith('-'):
                        value = -1.0
                    else:
                        value = 1.0
                    base_row_offset = sum([bs**2 for bs in
                                           self.block_struct[:mm_ind]])
                    width = self.block_struct[mm_ind]
                    for column in self.F[base_row_offset + i*width + j].rows[0]:
                        self.obj_facvar[column-1] = \
                            value*self.F[base_row_offset + i*width + j, column]


Instruction:
Make a summary of the following Python 3 code
def find_solution_ranks(self, xmat=None, baselevel=0):
        return find_solution_ranks(self, xmat=xmat, baselevel=baselevel)

Response: This function is used to detect the rank loop in the solution matrix.


Instruction:
Can you tell what is the following Python 3 function doing
def get_dual(self, constraint, ymat=None):
        if not isinstance(constraint, Expr):
            raise Exception("Not a monomial or polynomial!")
        elif self.status == "unsolved" and ymat is None:
            raise Exception("SDP relaxation is not solved yet!")
        elif ymat is None:
            ymat = self.y_mat
        index = self._constraint_to_block_index.get(constraint)
        if index is None:
            raise Exception("Constraint is not in the dual!")
        if len(index) == 2:
            return ymat[index[0]], self.y_mat[index[1]]
        else:
            return ymat[index[0]]

Response: Given a solution of the dual problem and a constraint returns the corresponding dual block.


Instruction:
Explain what the following Python 3 code does
def write_to_file(self, filename, filetype=None):
        if filetype == "sdpa" and not filename.endswith(".dat-s"):
            raise Exception("SDPA files must have .dat-s extension!")
        if filetype == "mosek" and not filename.endswith(".task"):
            raise Exception("Mosek files must have .task extension!")
        elif filetype is None and filename.endswith(".dat-s"):
            filetype = "sdpa"
        elif filetype is None and filename.endswith(".csv"):
            filetype = "csv"
        elif filetype is None and filename.endswith(".task"):
            filetype = "mosek"
        elif filetype is None:
            raise Exception("Cannot detect filetype from extension!")

        if filetype == "sdpa":
            write_to_sdpa(self, filename)
        elif filetype == "mosek":
            task = convert_to_mosek(self)
            task.writedata(filename)
        elif filetype == "csv":
            write_to_human_readable(self, filename)
        else:
            raise Exception("Unknown filetype")

Response: Writes the relaxation to a file.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_relaxation(self, level, objective=None, inequalities=None,
                       equalities=None, substitutions=None,
                       momentinequalities=None, momentequalities=None,
                       momentsubstitutions=None,
                       removeequalities=False, extramonomials=None,
                       extramomentmatrices=None, extraobjexpr=None,
                       localizing_monomials=None, chordal_extension=False):
        """Get the SDP relaxation of a noncommutative polynomial optimization
        problem.

        :param level: The level of the relaxation. The value -1 will skip
                      automatic monomial generation and use only the monomials
                      supplied by the option `extramonomials`.
        :type level: int.
        :param obj: Optional parameter to describe the objective function.
        :type obj: :class:`sympy.core.exp.Expr`.
        :param inequalities: Optional parameter to list inequality constraints.
        :type inequalities: list of :class:`sympy.core.exp.Expr`.
        :param equalities: Optional parameter to list equality constraints.
        :type equalities: list of :class:`sympy.core.exp.Expr`.
        :param substitutions: Optional parameter containing monomials that can
                              be replaced (e.g., idempotent variables).
        :type substitutions: dict of :class:`sympy.core.exp.Expr`.
        :param momentinequalities: Optional parameter of inequalities defined
                                   on moments.
        :type momentinequalities: list of :class:`sympy.core.exp.Expr`.
        :param momentequalities: Optional parameter of equalities defined
                                 on moments.
        :type momentequalities: list of :class:`sympy.core.exp.Expr`.
        :param momentsubstitutions: Optional parameter containing moments that
                                    can be replaced.
        :type momentsubstitutions: dict of :class:`sympy.core.exp.Expr`.
        :param removeequalities: Optional parameter to attempt removing the
                                 equalities by solving the linear equations.
        :type removeequalities: bool.
        :param extramonomials: Optional paramter of monomials to be included,
                               on top of the requested level of relaxation.
        :type extramonomials: list of :class:`sympy.core.exp.Expr`.
        :param extramomentmatrices: Optional paramter of duplicating or adding
                               moment matrices.  A new moment matrix can be
                               unconstrained (""), a copy  of the first one
                               ("copy"), and satisfying a partial positivity
                               constraint ("ppt"). Each new moment matrix is
                               requested as a list of string of these options.
                               For instance, adding a single new moment matrix
                               as a copy of the first would be
                               ``extramomentmatrices=[["copy"]]``.
        :type extramomentmatrices: list of list of str.
        :param extraobjexpr: Optional parameter of a string expression of a
                             linear combination of moment matrix elements to be
                             included in the objective function.
        :type extraobjexpr: str.
        :param localizing_monomials: Optional parameter to specify sets of
                                     localizing monomials for each constraint.
                                     The internal order of constraints is
                                     inequalities first, followed by the
                                     equalities. If the parameter is specified,
                                     but for a certain constraint the automatic
                                     localization is requested, leave None in
                                     its place in this parameter.
        :type localizing_monomials: list of list of `sympy.core.exp.Expr`.
        :param chordal_extension: Optional parameter to request a sparse
                                  chordal extension.
        :type chordal_extension: bool.

        """
        if self.level < -1:
            raise Exception("Invalid level of relaxation")
        self.level = level
        if substitutions is None:
            self.substitutions = {}
        else:
            self.substitutions = substitutions
            for lhs, rhs in substitutions.items():
                if not is_pure_substitution_rule(lhs, rhs):
                    self.pure_substitution_rules = False
                if iscomplex(lhs) or iscomplex(rhs):
                    self.complex_matrix = True
        if momentsubstitutions is not None:
            self.moment_substitutions = momentsubstitutions.copy()
            # If we have a real-valued problem, the moment matrix is symmetric
            # and moment substitutions also apply to the conjugate monomials
            if not self.complex_matrix:
                for key, val in self.moment_substitutions.copy().items():
                    adjoint_monomial = apply_substitutions(key.adjoint(),
                                                           self.substitutions)
                    self.moment_substitutions[adjoint_monomial] = val
        if chordal_extension:
            self.variables = find_variable_cliques(self.variables, objective,
                                                   inequalities, equalities,
                                                   momentinequalities,
                                                   momentequalities)
        self.__generate_monomial_sets(extramonomials)
        self.localizing_monomial_sets = localizing_monomials

        # Figure out basic structure of the SDP
        self._calculate_block_structure(inequalities, equalities,
                                        momentinequalities, momentequalities,
                                        extramomentmatrices,
                                        removeequalities)
        self._estimate_n_vars()
        if extramomentmatrices is not None:
            for parameters in extramomentmatrices:
                copy = False
                for parameter in parameters:
                    if parameter == "copy":
                        copy = True
                if copy:
                    self.n_vars += self.n_vars + 1
                else:
                    self.n_vars += (self.block_struct[0]**2)/2
        if self.complex_matrix:
            dtype = np.complex128
        else:
            dtype = np.float64
        self.F = lil_matrix((sum([bs**2 for bs in self.block_struct]),
                                    self.n_vars + 1), dtype=dtype)

        if self.verbose > 0:
            print(('Estimated number of SDP variables: %d' % self.n_vars))
            print('Generating moment matrix...')
        # Generate moment matrices
        new_n_vars, block_index = self.__add_parameters()
        self._time0 = time.time()
        new_n_vars, block_index = \
            self._generate_all_moment_matrix_blocks(new_n_vars, block_index)
        if extramomentmatrices is not None:
            new_n_vars, block_index = \
                self.__add_extra_momentmatrices(extramomentmatrices,
                                                new_n_vars, block_index)
        # The initial estimate for the size of F was overly generous.
        self.n_vars = new_n_vars
        # We don't correct the size of F, because that would trigger
        # memory copies, and extra columns in lil_matrix are free anyway.
        # self.F = self.F[:, 0:self.n_vars + 1]

        if self.verbose > 0:
            print(('Reduced number of SDP variables: %d' % self.n_vars))
        # Objective function
        self.set_objective(objective, extraobjexpr)
        # Process constraints
        self.constraint_starting_block = block_index
        self.process_constraints(inequalities, equalities, momentinequalities,
                                 momentequalities, block_index,
                                 removeequalities)

Response: Returns the SDP relaxation of a noncommutative polynomial optimization.


Instruction:
Given the following Python 3 function, write the documentation
def flatten(lol):
    new_list = []
    for element in lol:
        if element is None:
            continue
        elif not isinstance(element, list) and not isinstance(element, tuple):
            new_list.append(element)
        elif len(element) > 0:
            new_list.extend(flatten(element))
    return new_list

Response: Flatten a list of lists to a list.


Instruction:
Here you have a function in Python 3, explain what it does
def simplify_polynomial(polynomial, monomial_substitutions):
    if isinstance(polynomial, (int, float, complex)):
        return polynomial
    polynomial = (1.0 * polynomial).expand(mul=True,
                                           multinomial=True)
    if is_number_type(polynomial):
        return polynomial
    if polynomial.is_Mul:
        elements = [polynomial]
    else:
        elements = polynomial.as_coeff_mul()[1][0].as_coeff_add()[1]
    new_polynomial = 0
    # Identify its constituent monomials
    for element in elements:
        monomial, coeff = separate_scalar_factor(element)
        monomial = apply_substitutions(monomial, monomial_substitutions)
        new_polynomial += coeff * monomial
    return new_polynomial

Response: Simplify a polynomial for uniform handling later.


Instruction:
How would you explain what the following Python 3 function does
def __separate_scalar_factor(monomial):
    scalar_factor = 1
    if is_number_type(monomial):
        return S.One, monomial
    if monomial == 0:
        return S.One, 0
    comm_factors, _ = split_commutative_parts(monomial)
    if len(comm_factors) > 0:
        if isinstance(comm_factors[0], Number):
            scalar_factor = comm_factors[0]
    if scalar_factor != 1:
        return monomial / scalar_factor, scalar_factor
    else:
        return monomial, scalar_factor

Response: Separate the constant factor from a monomial.


Instruction:
Can you create a Python 3 function that
gets the support of a polynomial.

Response:
def get_support(variables, polynomial):
    """Gets the support of a polynomial.
    """
    support = []
    if is_number_type(polynomial):
        support.append([0] * len(variables))
        return support
    for monomial in polynomial.expand().as_coefficients_dict():
        tmp_support = [0] * len(variables)
        mon, _ = __separate_scalar_factor(monomial)
        symbolic_support = flatten(split_commutative_parts(mon))
        for s in symbolic_support:
            if isinstance(s, Pow):
                base = s.base
                if is_adjoint(base):
                    base = base.adjoint()
                tmp_support[variables.index(base)] = s.exp
            elif is_adjoint(s):
                tmp_support[variables.index(s.adjoint())] = 1
            elif isinstance(s, (Operator, Symbol)):
                tmp_support[variables.index(s)] = 1
        support.append(tmp_support)
    return support


Instruction:
Implement a Python 3 function for
getting the support variables of a polynomial.

Response:
def get_support_variables(polynomial):
    """Gets the support of a polynomial.
    """
    support = []
    if is_number_type(polynomial):
        return support
    for monomial in polynomial.expand().as_coefficients_dict():
        mon, _ = __separate_scalar_factor(monomial)
        symbolic_support = flatten(split_commutative_parts(mon))
        for s in symbolic_support:
            if isinstance(s, Pow):
                base = s.base
                if is_adjoint(base):
                    base = base.adjoint()
                support.append(base)
            elif is_adjoint(s):
                support.append(s.adjoint())
            elif isinstance(s, Operator):
                support.append(s)
    return support


Instruction:
Here you have a function in Python 3, explain what it does
def separate_scalar_factor(element):
    coeff = 1.0
    monomial = S.One
    if isinstance(element, (int, float, complex)):
        coeff *= element
        return monomial, coeff
    for var in element.as_coeff_mul()[1]:
        if not (var.is_Number or var.is_imaginary):
            monomial = monomial * var
        else:
            if var.is_Number:
                coeff = float(var)
            # If not, then it is imaginary
            else:
                coeff = 1j * coeff
    coeff = float(element.as_coeff_mul()[0]) * coeff
    return monomial, coeff

Response:
Construct a monomial with the coefficient separated
    from an element in a polynomial.


Instruction:
Here you have a function in Python 3, explain what it does
def count_ncmonomials(monomials, degree):
    ncmoncount = 0
    for monomial in monomials:
        if ncdegree(monomial) <= degree:
            ncmoncount += 1
        else:
            break
    return ncmoncount

Response: Given a list of monomials it counts those that have a certain degree and less.


Instruction:
Can you generate the documentation for the following Python 3 function
def apply_substitutions(monomial, monomial_substitutions, pure=False):
    if is_number_type(monomial):
        return monomial
    original_monomial = monomial
    changed = True
    if not pure:
        substitutions = monomial_substitutions
    else:
        substitutions = {}
        for lhs, rhs in monomial_substitutions.items():
            irrelevant = False
            for atom in lhs.atoms():
                if atom.is_Number:
                    continue
                if not monomial.has(atom):
                    irrelevant = True
                    break
            if not irrelevant:
                substitutions[lhs] = rhs
    while changed:
        for lhs, rhs in substitutions.items():
            monomial = fast_substitute(monomial, lhs, rhs)
        if original_monomial == monomial:
            changed = False
        original_monomial = monomial
    return monomial

Response: Helper function to remove monomials from the basis.


Instruction:
Can you generate the documentation for the following Python 3 function
def generate_variables(name, n_vars=1, hermitian=None, commutative=True):

    variables = []
    for i in range(n_vars):
        if n_vars > 1:
            var_name = '%s%s' % (name, i)
        else:
            var_name = '%s' % name
        if commutative:
            if hermitian is None or hermitian:
                variables.append(Symbol(var_name, real=True))
            else:
                variables.append(Symbol(var_name, complex=True))
        elif hermitian is not None and hermitian:
            variables.append(HermitianOperator(var_name))
        else:
            variables.append(Operator(var_name))
    return variables

Response: Generates a number of commutative or noncommutative variables.


Instruction:
Can you write a function in Python 3 where it
generates a number of commutative or noncommutative operators.

Response:
def generate_operators(name, n_vars=1, hermitian=None, commutative=False):
    """Generates a number of commutative or noncommutative operators

    :param name: The prefix in the symbolic representation of the noncommuting
                 variables. This will be suffixed by a number from 0 to
                 n_vars-1 if n_vars > 1.
    :type name: str.
    :param n_vars: The number of variables.
    :type n_vars: int.
    :param hermitian: Optional parameter to request Hermitian variables .
    :type hermitian: bool.
    :param commutative: Optional parameter to request commutative variables.
                        Commutative variables are Hermitian by default.
    :type commutative: bool.

    :returns: list of :class:`sympy.physics.quantum.operator.Operator` or
              :class:`sympy.physics.quantum.operator.HermitianOperator`
              variables

    :Example:

    >>> generate_variables('y', 2, commutative=True)
    ￼[y0, y1]
    """

    variables = []
    for i in range(n_vars):
        if n_vars > 1:
            var_name = '%s%s' % (name, i)
        else:
            var_name = '%s' % name
        if hermitian is not None and hermitian:
            variables.append(HermitianOperator(var_name))
        else:
            variables.append(Operator(var_name))
        variables[-1].is_commutative = commutative
    return variables


Instruction:
Create a Python 3 function to
generate all noncommutative monomials up to a degree.

Response:
def get_monomials(variables, degree):
    """Generates all noncommutative monomials up to a degree

    :param variables: The noncommutative variables to generate monomials from
    :type variables: list of :class:`sympy.physics.quantum.operator.Operator`
                     or
                     :class:`sympy.physics.quantum.operator.HermitianOperator`.
    :param degree: The maximum degree.
    :type degree: int.

    :returns: list of monomials.
    """
    if degree == -1:
        return []
    if not variables:
        return [S.One]
    else:
        _variables = variables[:]
        _variables.insert(0, 1)
        ncmonomials = [S.One]
        ncmonomials.extend(var for var in variables)
        for var in variables:
            if not is_hermitian(var):
                ncmonomials.append(var.adjoint())
        for _ in range(1, degree):
            temp = []
            for var in _variables:
                for new_var in ncmonomials:
                    temp.append(var * new_var)
                    if var != 1 and not is_hermitian(var):
                        temp.append(var.adjoint() * new_var)
            ncmonomials = unique(temp[:])
        return ncmonomials


Instruction:
How would you explain what the following Python 3 function does
def ncdegree(polynomial):
    degree = 0
    if is_number_type(polynomial):
        return degree
    polynomial = polynomial.expand()
    for monomial in polynomial.as_coefficients_dict():
        subdegree = 0
        for variable in monomial.as_coeff_mul()[1]:
            if isinstance(variable, Pow):
                subdegree += variable.exp
            elif not isinstance(variable, Number) and variable != I:
                subdegree += 1
        if subdegree > degree:
            degree = subdegree
    return degree

Response: Returns the degree of a noncommutative polynomial.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def iscomplex(polynomial):
    if isinstance(polynomial, (int, float)):
        return False
    if isinstance(polynomial, complex):
        return True
    polynomial = polynomial.expand()
    for monomial in polynomial.as_coefficients_dict():
        for variable in monomial.as_coeff_mul()[1]:
            if isinstance(variable, complex) or variable == I:
                return True
    return False

Response: Returns whether the polynomial has complex coefficients.


Instruction:
How would you explain what the following Python 3 function does
def get_all_monomials(variables, extramonomials, substitutions, degree,
                      removesubstitutions=True):
    """Return the monomials of a certain degree.
    """
    monomials = get_monomials(variables, degree)
    if extramonomials is not None:
        monomials.extend(extramonomials)
    if removesubstitutions and substitutions is not None:
        monomials = [monomial for monomial in monomials if monomial not
                     in substitutions]
        monomials = [remove_scalar_factor(apply_substitutions(monomial,
                                                              substitutions))
                     for monomial in monomials]
    monomials = unique(monomials)
    return monomials

Response: Return all monomials of a certain degree.


Instruction:
Can you generate the documentation for the following Python 3 function
def pick_monomials_up_to_degree(monomials, degree):
    ordered_monomials = []
    if degree >= 0:
        ordered_monomials.append(S.One)
    for deg in range(1, degree + 1):
        ordered_monomials.extend(pick_monomials_of_degree(monomials, deg))
    return ordered_monomials

Response: Return a list of monomials up to a given degree.


Instruction:
Can you create a Python 3 function that
returns a list of monomials up of a given degree.

Response:
def pick_monomials_of_degree(monomials, degree):
    """Collect all monomials up of a given degree.
    """
    selected_monomials = []
    for monomial in monomials:
        if ncdegree(monomial) == degree:
            selected_monomials.append(monomial)
    return selected_monomials


Instruction:
Write a Python 3 script for
saving a monomial dictionary for debugging purposes.

Response:
def save_monomial_index(filename, monomial_index):
    """Save a monomial dictionary for debugging purposes.

    :param filename: The name of the file to save to.
    :type filename: str.
    :param monomial_index: The monomial index of the SDP relaxation.
    :type monomial_index: dict of :class:`sympy.core.expr.Expr`.

    """
    monomial_translation = [''] * (len(monomial_index) + 1)
    for key, k in monomial_index.items():
        monomial_translation[k] = convert_monomial_to_string(key)
    file_ = open(filename, 'w')
    for k in range(len(monomial_translation)):
        file_.write('%s %s\n' % (k, monomial_translation[k]))
    file_.close()


Instruction:
How would you code a function in Python 3 to
build a permutation matrix for a permutation.

Response:
def build_permutation_matrix(permutation):
    """Build a permutation matrix for a permutation.
    """
    matrix = lil_matrix((len(permutation), len(permutation)))
    column = 0
    for row in permutation:
        matrix[row, column] = 1
        column += 1
    return matrix


Instruction:
Explain what the following Python 3 code does
def convert_relational(relational):
    rel = relational.rel_op
    if rel in ['==', '>=', '>']:
        return relational.lhs-relational.rhs
    elif rel in ['<=', '<']:
        return relational.rhs-relational.lhs
    else:
        raise Exception("The relational operation ' + rel + ' is not "
                        "implemented!")

Response: Convert all inequalities to >=0 form.


Instruction:
How would you explain what the following Python 3 function does
def value(board, who='x'):
    w = board.winner()
    if w == who:
        return 1
    if w == opp(who):
        return -1
    if board.turn == 9:
        return 0

    if who == board.whose_turn:
        return max([value(b, who) for b in board.possible()])
    else:
        return min([value(b, who) for b in board.possible()])

Response: Returns the value of a board by its name.


Instruction:
How would you implement a function in Python 3 that
returns best next board in order of x

Response:
def ai(board, who='x'):
    """
    Returns best next board

    >>> b = Board(); b._rows = [['x', 'o', ' '], ['x', 'o', ' '], [' ', ' ', ' ']]
    >>> ai(b)
    < Board |xo.xo.x..| >
    """
    return sorted(board.possible(), key=lambda b: value(b, who))[-1]


Instruction:
Can you generate a brief explanation for the following Python 3 code
def winner(self):
        for c in 'xo':
            for comb in [(0,3,6), (1,4,7), (2,5,8), (0,1,2), (3,4,5), (6,7,8), (0,4,8), (2,4,6)]:
                if all(self.spots[p] == c for p in comb):
                    return c
        return None

Response: Returns either x or o if one of them won otherwise None


Instruction:
How would you code a function in Python 3 to
get the sparse SDP relaxation of a Bell inequality. :param A_configuration: The definition of measurements of Alice. :type A_configuration: list of list of int. :param B_configuration: The definition of measurements of Bob. :type B_configuration: list of list of int. :param I: The matrix describing the Bell inequality in the Collins-Gisin picture. :type I: list of list of int.

Response:
def get_relaxation(self, A_configuration, B_configuration, I):
        """Get the sparse SDP relaxation of a Bell inequality.

        :param A_configuration: The definition of measurements of Alice.
        :type A_configuration: list of list of int.
        :param B_configuration: The definition of measurements of Bob.
        :type B_configuration: list of list of int.
        :param I: The matrix describing the Bell inequality in the
                  Collins-Gisin picture.
        :type I: list of list of int.
        """
        coefficients = collinsgisin_to_faacets(I)
        M, ncIndices = get_faacets_moment_matrix(A_configuration,
                                                 B_configuration, coefficients)
        self.n_vars = M.max() - 1
        bs = len(M)  # The block size
        self.block_struct = [bs]
        self.F = lil_matrix((bs**2, self.n_vars + 1))
        # Constructing the internal representation of the constraint matrices
        # See Section 2.1 in the SDPA manual and also Yalmip's internal
        # representation
        for i in range(bs):
            for j in range(i, bs):
                if M[i, j] != 0:
                    self.F[i*bs+j, abs(M[i, j])-1] = copysign(1, M[i, j])
        self.obj_facvar = [0 for _ in range(self.n_vars)]
        for i in range(1, len(ncIndices)):
            self.obj_facvar[abs(ncIndices[i])-2] += \
                copysign(1, ncIndices[i])*coefficients[i]


Instruction:
How would you implement a function in Python 3 that
shares a track with a list of users.

Response:
def share(track_id=None, url=None, users=None):
    """
    Returns list of users track has been shared with.
    Either track or url need to be provided.
    """

    client = get_client()

    if url:
        track_id = client.get('/resolve', url=url).id

    if not users:
        return client.get('/tracks/%d/permissions' % track_id)

    permissions = {'user_id': []}

    for username in users:
        # check cache for user
        user = settings.users.get(username, None)
        if user:
            permissions['user_id'].append(user['id'])
        else:
            user = client.get('/resolve', url='http://soundcloud.com/%s' % username)
            permissions['user_id'].append(user.id)
            settings.users[username] = user.obj
    settings.save()

    return client.put('/tracks/%d/permissions' % track_id, permissions=permissions)


Instruction:
Can you tell what is the following Python 3 function doing
def solve_with_cvxopt(sdp, solverparameters=None):
    P = convert_to_picos(sdp)
    P.set_option("solver", "cvxopt")
    P.set_option("verbose", sdp.verbose)
    if solverparameters is not None:
        for key, value in solverparameters.items():
            P.set_option(key, value)
    solution = P.solve()
    x_mat = [np.array(P.get_valued_variable('X'))]
    y_mat = [np.array(P.get_constraint(i).dual)
             for i in range(len(P.constraints))]
    return -solution["cvxopt_sol"]["primal objective"] + \
        sdp.constant_term, \
        -solution["cvxopt_sol"]["dual objective"] + \
        sdp.constant_term, \
        x_mat, y_mat, solution["status"]

Response:
Helper function to convert the SDP problem to PICOS
    and call CVXOPT solver and parse the output.


Instruction:
How would you explain what the following Python 3 function does
def convert_to_picos(sdp, duplicate_moment_matrix=False):
    import picos as pic
    import cvxopt as cvx
    P = pic.Problem(verbose=sdp.verbose)
    block_size = sdp.block_struct[0]
    if sdp.F.dtype == np.float64:
        X = P.add_variable('X', (block_size, block_size), vtype="symmetric")
        if duplicate_moment_matrix:
            Y = P.add_variable('Y', (block_size, block_size), vtype="symmetric")
    else:
        X = P.add_variable('X', (block_size, block_size), vtype="hermitian")
        if duplicate_moment_matrix:
            Y = P.add_variable('X', (block_size, block_size), vtype="hermitian")
    row_offset = 0
    theoretical_n_vars = sdp.block_struct[0]**2
    eq_block_start = sdp.constraint_starting_block+sdp._n_inequalities
    block_idx = 0
    while (block_idx < len(sdp.block_struct)):
        block_size = sdp.block_struct[block_idx]
        x, Ix, Jx = [], [], []
        c, Ic, Jc = [], [], []
        for i, row in enumerate(sdp.F.rows[row_offset:row_offset +
                                                     block_size**2]):
            for j, column in enumerate(row):
                if column > 0:
                    x.append(sdp.F.data[row_offset+i][j])
                    Ix.append(i)
                    Jx.append(column-1)
                    i0 = (i//block_size)+(i % block_size)*block_size
                    if i != i0:
                        x.append(sdp.F.data[row_offset+i][j])
                        Ix.append(i0)
                        Jx.append(column-1)

                else:
                    c.append(sdp.F.data[row_offset+i][j])
                    Ic.append(i%block_size)
                    Jc.append(i//block_size)
        permutation = cvx.spmatrix(x, Ix, Jx, (block_size**2,
                                               theoretical_n_vars))
        constant = cvx.spmatrix(c, Ic, Jc, (block_size, block_size))
        if duplicate_moment_matrix:
            constraint = X
        else:
            constraint = X.copy()
        for k in constraint.factors:
            constraint.factors[k] = permutation
        constraint._size = (block_size, block_size)
        if block_idx < eq_block_start:
            P.add_constraint(constant + constraint >> 0)
        else:
            P.add_constraint(constant + constraint == 0)
            row_offset += block_size**2
            block_idx += 1
        if duplicate_moment_matrix and \
                block_size == sdp.block_struct[0]:
            for k in Y.factors:
                Y.factors[k] = permutation
        row_offset += block_size**2
        block_idx += 1
    if len(np.nonzero(sdp.obj_facvar)[0]) > 0:
        x, Ix, Jx = [], [], []
        for k, val in enumerate(sdp.obj_facvar):
            if val != 0:
                x.append(val)
                Ix.append(0)
                Jx.append(k)
        permutation = cvx.spmatrix(x, Ix, Jx)
        objective = X.copy()
        for k in objective.factors:
            objective.factors[k] = permutation
        objective._size = (1, 1)
        P.set_objective('min', objective)
    return P

Response: Convert an SDP relaxation to a PICOS problem.