output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Evaluate a node s related attributes and return the result.
Can you tell what is the following Python 3 function doing def _eval(self, node): try: handler = self.nodes[type(node)] except KeyError: raise ValueError("Sorry, {0} is not available in this evaluator".format(type(node).__name__)) return handler(node)
As a Python code translator, you convert algorithms and pseudocode into Python.
def _eval_num(self, node): """ Evaluate a numerical node :param node: Node to eval :return: Result of node """ if self.floats: return node.n else: return int(node.n)
Write a Python 3 function for evaluating a numerical node.
As a Python code composer, you craft elegant and concise scripts.
Evaluate a unary operator node. Currently just supports positive and negative Currently just supports negative
Here you have a function in Python 3, explain what it does def _eval_unaryop(self, node): return self.operators[type(node.op)](self._eval(node.operand))
As a python code expert, you are capable of creating scripts from specifications.
Evaluate a binary operator node.
How would you explain what the following Python 3 function does def _eval_binop(self, node): return self.operators[type(node.op)](self._eval(node.left), self._eval(node.right))
You are a Python code generator, capable of creating scripts from specifications.
def _eval_call(self, node): """ Evaluate a function call :param node: Node to eval :return: Result of node """ try: func = self.functions[node.func.id] except KeyError: raise NameError(node.func.id) value = func( *(sel...
Write a Python 3 script for evaluating a function call and return the result
You are a Python code architect, reviewing and designing scalable and efficient code
def roll_dice(self): # Roll dice with current roll """ Rolls dicebag and sets last_roll and last_explanation to roll results :return: Roll results. """ roll = roll_dice(self.roll, floats=self.floats, functions=self.functions) self._last_roll = roll[0] self._las...
Implement a function in Python 3 to roll dice with current roll
As a Python code analyst, you investigate and solve complex coding mysteries
Sets the _roll attribute of the object.
How would you explain what the following Python 3 function does def roll(self, value): if type(value) != str: # Make sure dice roll is a str raise TypeError('Dice roll must be a string in dice notation') try: roll_dice(value) # Make sure dice roll parses as a valid roll and not...
You are a Python code generator, capable of creating scripts from specifications.
Look for pdb. set_trace() commands in python files.
How would you explain what the following Python 3 function does def run(files, temp_folder, arg=''): "Look for pdb.set_trace() commands in python files." parser = get_parser() args = parser.parse_args(arg.split()) py_files = filter_python_files(files) if args.ignore: orig_file_list = origin...
As a python code expert, you are capable of creating scripts from specifications.
Returns an iterator of valid checks in the installed checkers package.
Can you tell what is the following Python 3 function doing def checks(): checkers_dir = os.path.dirname(checkers.__file__) mod_names = [name for _, name, _ in pkgutil.iter_modules([checkers_dir])] for name in mod_names: mod = importlib.import_module("checkers.{0}".format(name)) # Does the m...
As a python code expert, you are capable of creating scripts from specifications.
A context manager that returns the list of files to check.
Given the following Python 3 function, write the documentation def files_to_check(commit_only): global TEMP_FOLDER safe_directory = tempfile.mkdtemp() TEMP_FOLDER = safe_directory files = get_files(commit_only=commit_only, copy_dest=safe_directory) try: yield files finally: shu...
As a Python code composer, you craft elegant and concise scripts.
Run the configured code checks.
Can you tell what is the following Python 3 function doing def main(commit_only=True): global TEMP_FOLDER exit_code = 0 hook_checks = HookConfig(get_config_file()) with files_to_check(commit_only) as files: for name, mod in checks(): default = getattr(mod, 'DEFAULT', 'off') ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get copies of files for analysis.
Can you generate the documentation for the following Python 3 function def get_files(commit_only=True, copy_dest=None): "Get copies of files for analysis." if commit_only: real_files = bash( "git diff --cached --name-status | " "grep -v -E '^D' | " "awk '{ print ( $(N...
As a Python code composer, you craft elegant and concise scripts.
def create_fake_copies(files, destination): """ Create copies of the given list of files in the destination given. Creates copies of the actual files to be committed using git show :<filename> Return a list of destination files. """ dest_files = [] for filename in files: leaf_d...
Write a Python 3 script to create a fake copy of the given list of files in the given destination.
As a Python code composer, you craft elegant and concise scripts.
def filter_python_files(files): "Get all python files from the list of files." py_files = [] for f in files: # If we end in .py, or if we don't have an extension and file says that # we are a python script, then add us to the list extension = os.path.splitext(f)[-1] if exten...
Can you write a function in Python 3 where it gets all python files from the list of files.
As a Python code translator, you convert algorithms and pseudocode into Python.
def configuration(self, plugin): """ Get plugin configuration. Return a tuple of (on|off|default, args) """ conf = self.config.get(plugin, "default;").split(';') if len(conf) == 1: conf.append('') return tuple(conf)
Create a Python 3 function for getting the configuration of a specific plugin.
You are a Python code generator, capable of creating scripts from specifications.
def run(files, temp_folder): "Check frosted errors in the code base." try: import frosted # NOQA except ImportError: return NO_FROSTED_MSG py_files = filter_python_files(files) cmd = 'frosted {0}'.format(' '.join(py_files)) return bash(cmd).value()
Write a Python 3 script for checking frosted errors in the code base.
You are a Python code architect, reviewing and designing scalable and efficient code
Run isort on a list of python files.
Can you generate a brief explanation for the following Python 3 code def run(files, temp_folder): try: import isort # NOQA except ImportError: return NO_ISORT_MSG py_files = filter_python_files(files) # --quiet because isort >= 4.1 outputs its logo in the console by default. retur...
As a Python code analyst, you investigate and solve complex coding mysteries
def run(files, temp_folder, arg=None): "Check we're not committing to a blocked branch" parser = get_parser() argos = parser.parse_args(arg.split()) current_branch = bash('git symbolic-ref HEAD').value() current_branch = current_branch.replace('refs/heads/', '').strip() if current_branch in arg...
Implement a function in Python 3 to check we re not committing to a blocked branch
You are a Python code architect, reviewing and designing scalable and efficient code
def run(files, temp_folder, arg=None): "Check coding convention of the code base." try: import pylint except ImportError: return NO_PYLINT_MSG # set default level of threshold arg = arg or SCORE py_files = filter_python_files(files) if not py_files: return False ...
Implement a function in Python 3 to check coding convention of the code base.
You are a Python code generator, capable of creating scripts from specifications.
def run(files, temp_folder): "Check to see if python files are py3 compatible" errors = [] for py_file in filter_python_files(files): # We only want to show errors if we CAN'T compile to py3. # but we want to show all the errors at once. b = bash('python3 -m py_compile {0}'.format(py...
Create a Python 3 function to check to see if python files are py3 compatible
As a python code expert, you are capable of creating scripts from specifications.
def run(files, temp_folder): "Check flake8 errors in the code base." try: import flake8 # NOQA except ImportError: return NO_FLAKE_MSG try: from flake8.engine import get_style_guide except ImportError: # We're on a new version of flake8 from flake8.api.legacy...
Write a Python 3 function that can check flake8 errors in the code base.
You are a Python code generator, capable of creating scripts from specifications.
def tictactoe(w, i, player, opponent, grid=None): "Put two strategies to a classic battle of wits." grid = grid or empty_grid while True: w.render_to_terminal(w.array_from_text(view(grid))) if is_won(grid): print(whose_move(grid), "wins.") break if not success...
Can you implement a function in Python 3 that puts two strategies to a classic battle of wits.
As a Python code analyst, you investigate and solve complex coding mysteries
def memo(f): "Return a function like f that remembers and reuses results of past calls." table = {} def memo_f(*args): try: return table[args] except KeyError: table[args] = value = f(*args) return value return memo_f
Create a Python 3 function to return a function like f that remembers and reuses results of past calls.
You are a Python code generator, capable of creating scripts from specifications.
Just ask for a move.
Explain what the following Python 3 code does def human_play(w, i, grid): "Just ask for a move." plaint = '' prompt = whose_move(grid) + " move? [1-9] " while True: w.render_to_terminal(w.array_from_text(view(grid) + '\n\n' + plaint + prompt)) ...
As a Python code composer, you craft elegant and concise scripts.
def max_play(w, i, grid): "Play like Spock, except breaking ties by drunk_value." return min(successors(grid), key=lambda succ: (evaluate(succ), drunk_value(succ)))
Write a Python 3 script to play like Spock except breaking ties by drunk_value.
You are a Python code architect, reviewing and designing scalable and efficient code
def drunk_value(grid): "Return the expected value to the player if both players play at random." if is_won(grid): return -1 succs = successors(grid) return -average(map(drunk_value, succs)) if succs else 0
How would you implement a function in Python 3 that returns the expected value to the player if both players play at random.
As a Python code composer, you craft elegant and concise scripts.
Return the value for the player to move assuming perfect play.
Here you have a function in Python 3, explain what it does def evaluate(grid): "Return the value for the player to move, assuming perfect play." if is_won(grid): return -1 succs = successors(grid) return -min(map(evaluate, succs)) if succs else 0
As a Python code translator, you convert algorithms and pseudocode into Python.
def is_won(grid): "Did the latest move win the game?" p, q = grid return any(way == (way & q) for way in ways_to_win)
Can you create a Python 3 function that does the latest move win the game?
As a Python code composer, you craft elegant and concise scripts.
Try to move : return a new grid or None if illegal.
Can you tell what is the following Python 3 function doing def apply_move(grid, move): "Try to move: return a new grid, or None if illegal." p, q = grid bit = 1 << move return (q, p | bit) if 0 == (bit & (p | q)) else None
As a python code expert, you are capable of creating scripts from specifications.
def player_marks(grid): "Return two results: the player's mark and their opponent's." p, q = grid return 'XO' if sum(player_bits(p)) == sum(player_bits(q)) else 'OX'
How would you implement a function in Python 3 that returns two results : the player s mark and their opponents.
As a python code expert, you are capable of creating scripts from specifications.
def view(grid): "Show a grid human-readably." p_mark, q_mark = player_marks(grid) return grid_format % tuple(p_mark if by_p else q_mark if by_q else '.' for by_p, by_q in zip(*map(player_bits, grid)))
Create a Python 3 function to show a grid human - readably.
As a Python code translator, you convert algorithms and pseudocode into Python.
Helper function to map row to SDPA index values.
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,...
As a python code expert, you are capable of creating scripts from specifications.
Write the SDP relaxation to SDPA format.
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....
You are a Python code analyst, evaluating scripts for potential improvements.
Convert the SDP relaxation to a human - readable format.
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(candidate...
You are a Python code generator, capable of creating scripts from specifications.
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)...
How would you code a function in Python 3 to write the SDP relaxation to a human - readable format.
As a Python code analyst, you investigate and solve complex coding mysteries
create request header function :param url: URL for the new :class:`Request` object.
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 = hm...
You are a Python code architect, reviewing and designing scalable and efficient code
Adds bytes to be internal buffer to be read
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)))
You are a Python code generator, capable of creating scripts from specifications.
Wait for stdin to read and an event.
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, ...
As a python code expert, you are capable of creating scripts from specifications.
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)
Write a Python 3 script to return an event or None if no events occur before timeout.
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the number of characters read and adds them to self. unread_bytes.
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 ...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns a callback that creates events.
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
You are a Python code architect, reviewing and designing scalable and efficient code
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): s...
How would you code a function in Python 3 to return a callback that schedules events for the future.
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a callback function to create events interrupting current event requests.
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 t...
As a python code expert, you are capable of creating scripts from specifications.
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....
Create a Python 3 function for solving the SDP relaxation.
You are a Python code architect, reviewing and designing scalable and efficient code
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 ...
Write a Python 3 function for giving a dual problem returns the SOS decomposition of the dual problem.
As a Python code analyst, you investigate and solve complex coding mysteries
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:`ncpol2sd...
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 fo...
You are a Python code analyst, evaluating scripts for potential improvements.
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.choic...
Can you create a Python 3 function that generates a complete CC number.
As a Python code analyst, you investigate and solve complex coding mysteries
Loads the specified module and updates the object with the data from it.
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: ...
You are a Python code architect, reviewing and designing scalable and efficient code
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,...
How would you code a function in Python 3 to return a message from tick if game is over
You are a Python code analyst, evaluating scripts for potential improvements.
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):...
Can you write a function in Python 3 where it returns a message to be displayed if game is over else None
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns an FSArray of the size of the window containing msg
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)
You are a Python code generator, capable of creating scripts from specifications.
Renders the array to the terminal and places the cursor position.
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 righ...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the terminal row column of the cursor.
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: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Returns the number of lines moved down the cursor.
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 ...
You are a Python code generator, capable of creating scripts from specifications.
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_cur...
Create a Python 3 function to return the how far down the cursor moved.
As a Python code analyst, you investigate and solve complex coding mysteries
Renders the given array to the terminal. Returns the number of lines scrolled offscreen.
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 se...
You are a Python code generator, capable of creating scripts from specifications.
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 informa...
Implement a function in Python 3 to solve the SDP relaxation on the current object.
You are a Python code architect, reviewing and designing scalable and efficient code
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_monom...
How would you implement a function in Python 3 that processes a single monomial when building the moment matrix.
You are a Python code analyst, evaluating scripts for potential improvements.
Generate the moment matrix of the monomials.
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_...
You are a Python code generator, capable of creating scripts from specifications.
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: ...
Create a Python 3 function to return the index of a monomial.
As a Python code analyst, you investigate and solve complex coding mysteries
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 ...
How would you code a function in Python 3 to push a sparse vector representation of a polynomial into the F structure.
As a Python code composer, you craft elegant and concise scripts.
Generate localizing matrices for the inequality constraints of the SDP relaxation.
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 se...
As a Python code translator, you convert algorithms and pseudocode into Python.
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 equal...
Write a Python 3 function for generating the localizing matrices for the given set of equalities and the given list of moment equalities.
You are a Python code analyst, evaluating scripts for potential improvements.
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 ...
Implement a Python 3 function for attempting to remove equalities by solving the linear equations.
As a Python code analyst, you investigate and solve complex coding mysteries
def _calculate_block_structure(self, inequalities, equalities, momentinequalities, momentequalities, extramomentmatrix, removeequalities, block_struct=None): """Calculates the block_struct array for the outp...
How would you implement a function in Python 3 that calculates the block structure for the current object.
You are a Python code analyst, evaluating scripts for potential improvements.
Processes the constraints and generates localizing matrices. Useful for creating the localizing matrices.
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 ...
You are a Python code generator, capable of creating scripts from specifications.
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 ...
Write a Python 3 script for setting or change the objective function of the polynomial optimization problem.
As a Python code translator, you convert algorithms and pseudocode into Python.
This function is used to detect the rank loop in the solution matrix.
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)
You are a Python code analyst, evaluating scripts for potential improvements.
Given a solution of the dual problem and a constraint returns the corresponding dual block.
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 solv...
As a Python code composer, you craft elegant and concise scripts.
Writes the relaxation to a file.
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 Ex...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the SDP relaxation of a noncommutative polynomial optimization.
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, ...
As a Python code composer, you craft elegant and concise scripts.
Flatten a list of lists to a list.
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: ...
As a Python code analyst, you investigate and solve complex coding mysteries
Simplify a polynomial for uniform handling later.
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...
As a Python code translator, you convert algorithms and pseudocode into Python.
Separate the constant factor from a monomial.
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...
As a python code expert, you are capable of creating scripts from specifications.
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) ...
Can you create a Python 3 function that gets the support of a polynomial.
You are a Python code analyst, evaluating scripts for potential improvements.
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_...
Implement a Python 3 function for getting the support variables of a polynomial.
As a Python code translator, you convert algorithms and pseudocode into Python.
Construct a monomial with the coefficient separated from an element in a polynomial.
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.i...
As a python code expert, you are capable of creating scripts from specifications.
Given a list of monomials it counts those that have a certain degree and less.
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
You are a Python code analyst, evaluating scripts for potential improvements.
Helper function to remove monomials from the basis.
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 e...
You are a Python code architect, reviewing and designing scalable and efficient code
Generates a number of commutative or noncommutative variables.
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 co...
As a Python code composer, you craft elegant and concise scripts.
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-...
Can you write a function in Python 3 where it generates a number of commutative or noncommutative operators.
As a Python code translator, you convert algorithms and pseudocode into Python.
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.physi...
Create a Python 3 function to generate all noncommutative monomials up to a degree.
As a Python code composer, you craft elegant and concise scripts.
Returns the degree of a noncommutative polynomial.
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_mu...
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns whether the polynomial has complex coefficients.
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(): ...
You are a Python code analyst, evaluating scripts for potential improvements.
Return all monomials of a certain degree.
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 ...
You are a Python code architect, reviewing and designing scalable and efficient code
Return a list of monomials up to a given degree.
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)...
As a Python code analyst, you investigate and solve complex coding mysteries
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
Can you create a Python 3 function that returns a list of monomials up of a given degree.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Write a Python 3 script for saving a monomial dictionary for debugging purposes.
You are a Python code architect, reviewing and designing scalable and efficient code
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
How would you code a function in Python 3 to build a permutation matrix for a permutation.
You are a Python code architect, reviewing and designing scalable and efficient code
Convert all inequalities to >=0 form.
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 operatio...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the value of a board by its name.
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(...
You are a Python code generator, capable of creating scripts from specifications.
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]
How would you implement a function in Python 3 that returns best next board in order of x
You are a Python code analyst, evaluating scripts for potential improvements.
Returns either x or o if one of them won otherwise None
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
As a Python code composer, you craft elegant and concise scripts.
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 Bo...
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 ...
As a python code expert, you are capable of creating scripts from specifications.
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/permis...
How would you implement a function in Python 3 that shares a track with a list of users.
As a Python code analyst, you investigate and solve complex coding mysteries
Helper function to convert the SDP problem to PICOS and call CVXOPT solver and parse the output.
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...
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert an SDP relaxation to a PICOS problem.
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', (bloc...
As a python code expert, you are capable of creating scripts from specifications.
Convert an SDP relaxation to a CVXPY problem.
Here you have a function in Python 3, explain what it does def convert_to_cvxpy(sdp): from cvxpy import Minimize, Problem, Variable row_offsets = [0] cumulative_sum = 0 for block_size in sdp.block_struct: cumulative_sum += block_size ** 2 row_offsets.append(cumulative_sum) x = Variab...
You are a Python code analyst, evaluating scripts for potential improvements.
Get the forward neighbors of a site in a 2D lattice.
Can you tell what is the following Python 3 function doing def get_neighbors(index, lattice_length, width=0, periodic=False): if width == 0: width = lattice_length neighbors = [] coords = divmod(index, width) if coords[1] < width - 1: neighbors.append(index + 1) elif periodic and wid...
As a Python code composer, you craft elegant and concise scripts.
Get the next neighbors of a given set of sites.
Explain what the following Python 3 code does def get_next_neighbors(indices, lattice_length, width=0, distance=1, periodic=False): """Get the forward neighbors at a given distance of a site or set of sites in a lattice. :param index: Linear index of operator. :type index: int. ...
As a python code expert, you are capable of creating scripts from specifications.