text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def should_collect(self, value): """Decide whether a given value should be collected."""
return ( # decorated with @transition isinstance(value, TransitionWrapper) # Relates to a compatible transition and value.trname in self.workflow.transitions # Either not bound to a state field or bound to the current one and (not value.fi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def collect(self, attrs): """Collect the implementations from a given attributes dict."""
for name, value in attrs.items(): if self.should_collect(value): transition = self.workflow.transitions[value.trname] if ( value.trname in self.implementations and value.trname in self.custom_implems ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_custom_implementations(self): """Retrieve a list of cutom implementations. Yields: (str, str, ImplementationProperty) tuples: The name of the attribute a...
for trname in self.custom_implems: attr = self.transitions_at[trname] implem = self.implementations[trname] yield (trname, attr, implem)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_function_hooks(self, func): """Looks at an object method and registers it for relevent transitions."""
for hook_kind, hooks in func.xworkflows_hook.items(): for field_name, hook in hooks: if field_name and field_name != self.state_field: continue for transition in self.workflow.transitions: if hook.applies_to(transition): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _may_override(self, implem, other): """Checks whether an ImplementationProperty may override an attribute."""
if isinstance(other, ImplementationProperty): # Overriding another custom implementation for the same transition # and field return (other.transition == implem.transition and other.field_name == self.state_field) elif isinstance(other, TransitionWrapper): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def fill_attrs(self, attrs): """Update the 'attrs' dict with generated ImplementationProperty."""
for trname, attrname in self.transitions_at.items(): implem = self.implementations[trname] if attrname in attrs: conflicting = attrs[attrname] if not self._may_override(implem, conflicting): raise ValueError( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transform(self, attrs): """Perform all actions on a given attribute dict."""
self.collect(attrs) self.add_missing_implementations() self.fill_attrs(attrs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_transition(self, transition, from_state, instance, *args, **kwargs): """Log a transition. Args: transition (Transition): the name of the performed trans...
logger = logging.getLogger('xworkflows.transitions') try: instance_repr = u(repr(instance), 'ignore') except (UnicodeEncodeError, UnicodeDecodeError): instance_repr = u("<bad repr>") logger.info( u("%s performed transition %s.%s (%s -> %s)"), instance...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _find_workflows(mcs, attrs): """Finds all occurrences of a workflow in the attributes definitions. Returns: dict(str => StateField): maps an attribute name ...
workflows = {} for attribute, value in attrs.items(): if isinstance(value, Workflow): workflows[attribute] = StateField(value) return workflows
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _add_transitions(mcs, field_name, workflow, attrs, implems=None): """Collect and enhance transition definitions to a workflow. Modifies the 'attrs' dict in-p...
new_implems = ImplementationList(field_name, workflow) if implems: new_implems.load_parent_implems(implems) new_implems.transform(attrs) return new_implems
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update(self): "Updates cartesian coordinates for drawing tree graph" # get new shape and clear for attrs self.edges = np.zeros((self.ttree.nnodes - 1, 2), dtype=int) self.verts = np.zeros((self.ttree.nnodes, 2), dtype=float) self.lines = [] self.coords =...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def update_idxs(self): "set root idx highest, tip idxs lowest ordered as ladderized" # internal nodes: root is highest idx idx = self.ttree.nnodes - 1 for node in self.ttree.treenode.traverse("levelorder"): if not node.is_leaf(): node.add_feature("idx", idx) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def tsiterator(ts, dateconverter=None, desc=None, clean=False, start_value=None, **kwargs): '''An iterator of timeseries as tuples.''' dateconverter = dateconverter or default_converter yield ['Date'] + ts.names() if clean == 'full': for dt, value in full_clean(ts, dateconverter, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_baselines(self): """ Modify coords to shift tree position for x,y baseline arguments. This is useful for arrangeing trees onto a Canvas with other plots,...
if self.style.xbaseline: if self.style.orient in ("up", "down"): self.coords.coords[:, 0] += self.style.xbaseline self.coords.verts[:, 0] += self.style.xbaseline else: self.coords.coords[:, 1] += self.style.xbaseline ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def add_tip_lines_to_axes(self): "add lines to connect tips to zero axis for tip_labels_align=True" # get tip-coords and align-coords from verts xpos, ypos, aedges, averts = self.get_tip_label_coords() if self.style.tip_labels_align: self.axes.graph( aedges,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assign_node_labels_and_sizes(self): "assign features of nodes to be plotted based on user kwargs" # shorthand nvals = self.ttree.get_node_values() # False == Hide nodes and labels unless user entered size if self.style.node_labels is False: self.node_labels = [...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def assign_tip_labels_and_colors(self): "assign tip labels based on user provided kwargs" # COLOR # tip color overrides tipstyle.fill if self.style.tip_labels_colors: #if self.style.tip_labels_style.fill: # self.style.tip_labels_style.fill = None if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_nodes_to_axes(self): """ Creates a new marker for every node from idx indexes and lists of node_values, node_colors, node_sizes, node_style, node_labels_...
# bail out if not any visible nodes (e.g., none w/ size>0) if all([i == "" for i in self.node_labels]): return # build markers for each node. marks = [] for nidx in self.ttree.get_node_values('idx', 1, 1): # select node value from deconstructed l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_tip_label_coords(self): """ Get starting position of tip labels text based on locations of the leaf nodes on the tree and style offset and align options....
# number of tips ns = self.ttree.ntips # x-coordinate of tips assuming down-face tip_xpos = self.coords.verts[:ns, 0] tip_ypos = self.coords.verts[:ns, 1] align_edges = None align_verts = None # handle orientations if self.style.orient in (0, 'd...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_dims_from_tree_size(self): "Calculate reasonable canvas height and width for tree given N tips" ntips = len(self.ttree) if self.style.orient in ("right", "left"): # height is long tip-wise dimension if not self.style.height: self.style.height = ma...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_longest_line_length(text): """Get the length longest line in a paragraph"""
lines = text.split("\n") length = 0 for i in range(len(lines)): if len(lines[i]) > length: length = len(lines[i]) return length
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def isnumeric(obj): ''' Return true if obj is a numeric value ''' from decimal import Decimal if type(obj) == Decimal: return True else: try: float(obj) except: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def significant_format(number, decimal_sep='.', thousand_sep=',', n=3): """Format a number according to a given number of significant figures. """
str_number = significant(number, n) # sign if float(number) < 0: sign = '-' else: sign = '' if str_number[0] == '-': str_number = str_number[1:] if '.' in str_number: int_part, dec_part = str_number.split('.') else: int_part, dec_part ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text_to_qcolor(text): """ Create a QColor from specified string Avoid warning from Qt when an invalid QColor is instantiated """
color = QColor() if not is_string(text): # testing for QString (PyQt API#1) text = str(text) if not is_text_string(text): return color if text.startswith('#') and len(text)==7: correct = '#0123456789abcdef' for char in text: if char.lower() not in correct: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_dialog(self): """Return FormDialog instance"""
dialog = self.parent() while not isinstance(dialog, QDialog): dialog = dialog.parent() return dialog
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get(self): """Return form result"""
# It is import to avoid accessing Qt C++ object as it has probably # already been destroyed, due to the Qt.WA_DeleteOnClose attribute if self.outfile: if self.result in ['list', 'dict', 'OrderedDict']: fd = open(self.outfile + '.py', 'w') fd.write(str...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def dates(self, desc=None): '''Returns an iterable over ``datetime.date`` instances in the timeseries.''' c = self.dateinverse for key in self.keys(desc=desc): yield c(key)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def named_series(self, ordering=None): '''Generator of tuples with name and serie data.''' series = self.series() if ordering: series = list(series) todo = dict(((n, idx) for idx, n in enumerate(self.names()))) for name in ordering: if n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def clone(self, date=None, data=None, name=None): '''Create a clone of timeseries''' name = name or self.name data = data if data is not None else self.values() ts = self.__class__(name) ts._dtype = self._dtype if date is None: # dates not provided ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def isconsistent(self): '''Check if the timeseries is consistent''' for dt1, dt0 in laggeddates(self): if dt1 <= dt0: return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def sd(self): '''Calculate standard deviation of timeseries''' v = self.var() if len(v): return np.sqrt(v) else: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def removeduplicates(self, entries = None): ''' Loop over children a remove duplicate entries. @return - a list of removed entries ''' removed = [] if entries == None: entries = {} new_children = [] for c in self.children: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def html2md(html_string): """ Convert a string or html file to a markdown table string. Parameters html_string : str Either the html string, or the filepath to t...
if os.path.isfile(html_string): file = open(html_string, 'r', encoding='utf-8') lines = file.readlines() file.close() html_string = ''.join(lines) table_data, spans, use_headers = html2data(html_string) if table_data == '': return '' return data2md(table_data)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def table_cells_2_spans(table, spans): """ Converts the table to a list of spans, for consistency. This method combines the table data with the span data into a ...
new_spans = [] for row in range(len(table)): for column in range(len(table[row])): span = get_span(spans, row, column) if not span: new_spans.append([[row, column]]) new_spans.extend(spans) new_spans = list(sorted(new_spans)) return new_spans
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rcts(self, command, *args, **kwargs): '''General function for applying a rolling R function to a timeserie''' cls = self.__class__ name = kwargs.pop('name','') date = kwargs.pop('date',None) data = kwargs.pop('data',None) kwargs.pop('bycolumn',None) ts ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_html_column_count(html_string): """ Gets the number of columns in an html table. Paramters --------- html_string : str Returns ------- int The number of ...
try: from bs4 import BeautifulSoup except ImportError: print("ERROR: You must have BeautifulSoup to use html2data") return soup = BeautifulSoup(html_string, 'html.parser') table = soup.find('table') if not table: return 0 column_counts = [] trs = table.find...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_cushions(table): """ Add space to start and end of each string in a list of lists Parameters table : list of lists of str A table of rows of strings. For...
for row in range(len(table)): for column in range(len(table[row])): lines = table[row][column].split("\n") for i in range(len(lines)): if not lines[i] == "": lines[i] = " " + lines[i].rstrip() + " " table[row][column] = "\n".join(lin...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def rollsingle(self, func, window=20, name=None, fallback=False, align='right', **kwargs): '''Efficient rolling window calculation for min, max type functions ''' rname = 'roll_{0}'.format(func) if fallback: rfunc = getattr(lib.fallback, rname) else: rfunc = getattr(li...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upgrade(): """Update database."""
op.create_table( 'transaction', sa.Column('issued_at', sa.DateTime(), nullable=True), sa.Column('id', sa.BigInteger(), nullable=False), sa.Column('remote_addr', sa.String(length=50), nullable=True), ) op.create_primary_key('pk_transaction', 'transaction', ['id']) if op._...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_newick(newick, root_node=None, format=0): """ Reads a newick tree from either a string or a file, and returns an ETE tree structure. A previously existe...
## check newick type as a string or filepath, Toytree parses urls to str's if isinstance(newick, six.string_types): if os.path.exists(newick): if newick.endswith('.gz'): import gzip nw = gzip.open(newick).read() else: nw = open...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _read_node_data(subnw, current_node, node_type, matcher, formatcode): """ Reads a leaf node from a subpart of the original newicktree """
if node_type == "leaf" or node_type == "single": if node_type == "leaf": node = current_node.add_child() else: node = current_node else: node = current_node subnw = subnw.strip() if not subnw and node_type == 'leaf' and formatcode != 100: r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_newick(rootnode, features=None, format=1, format_root_node=True, is_leaf_fn=None, dist_formatter=None, support_formatter=None, name_formatter=None): ...
newick = [] leaf = is_leaf_fn if is_leaf_fn else lambda n: not bool(n.children) for postorder, node in rootnode.iter_prepostorder(is_leaf_fn=is_leaf_fn): if postorder: newick.append(")") if node.up is not None or format_root_node: newick.append(format_node(no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_features_string(self, features=None): """ Generates the extended newick string NHX with extra data about a node."""
string = "" if features is None: features = [] elif features == []: features = self.features for pr in features: if hasattr(self, pr): raw = getattr(self, pr) if type(raw) in ITERABLE_TYPES: raw = '|'.join([str(i) for i in raw]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_column_width(column, table): """ Get the character width of a column in a table Parameters column : int The column index analyze table : list of lists of...
width = 3 for row in range(len(table)): cell_width = len(table[row][column]) if cell_width > width: width = cell_width return width
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def center_cell_text(cell): """ Horizontally center the text within a cell's grid Like this:: +---------+ +---------+ | foo | --> | foo | +---------+ +---------+...
lines = cell.text.split('\n') cell_width = len(lines[0]) - 2 truncated_lines = [''] for i in range(1, len(lines) - 1): truncated = lines[i][2:len(lines[i]) - 2].rstrip() truncated_lines.append(truncated) truncated_lines.append('') max_line_length = get_longest_line_length('\n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hamming_distance(word1, word2): """ Computes the Hamming distance. [Reference]: https://en.wikipedia.org/wiki/Hamming_distance [Article]: Hamming, Richard W....
from operator import ne if len(word1) != len(word2): raise WrongLengthException('The words need to be of the same length!') return sum(map(ne, word1, word2))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def polygen(*coefficients): '''Polynomial generating function''' if not coefficients: return lambda i: 0 else: c0 = coefficients[0] coefficients = coefficients[1:] def _(i): v = c0 for c in coefficients: v += c*i ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ensure_table_strings(table): """ Force each cell in the table to be a string Parameters table : list of lists Returns ------- table : list of lists of str ""...
for row in range(len(table)): for column in range(len(table[row])): table[row][column] = str(table[row][column]) return table
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def left_sections(self): """ The number of sections that touch the left side. During merging, the cell's text will grow to include other cells. This property kee...
lines = self.text.split('\n') sections = 0 for i in range(len(lines)): if lines[i].startswith('+'): sections += 1 sections -= 1 return sections
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def right_sections(self): """ The number of sections that touch the right side. Returns ------- sections : int The number of sections on the right """
lines = self.text.split('\n') sections = 0 for i in range(len(lines)): if lines[i].endswith('+'): sections += 1 return sections - 1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def top_sections(self): """ The number of sections that touch the top side. Returns ------- sections : int The number of sections on the top """
top_line = self.text.split('\n')[0] sections = len(top_line.split('+')) - 2 return sections
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bottom_sections(self): """ The number of cells that touch the bottom side. Returns ------- sections : int The number of sections on the top """
bottom_line = self.text.split('\n')[-1] sections = len(bottom_line.split('+')) - 2 return sections
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_header(self): """ Whether or not the cell is a header Any header cell will have "=" instead of "-" on its border. For example, this is a header cell:: +--...
bottom_line = self.text.split('\n')[-1] if is_only(bottom_line, ['+', '=']): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_git_changeset(filename=None): """Returns a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMM...
dirname = os.path.dirname(filename or __file__) git_show = sh('git show --pretty=format:%ct --quiet HEAD', cwd=dirname) timestamp = git_show.partition('\n')[0] try: timestamp = datetime.datetime.utcfromtimestamp(int(timestamp)) except ValueError: return Non...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def process_tag(node): """ Recursively go through a tag's children, converting them, then convert the tag itself. """
text = '' exceptions = ['table'] for element in node.children: if isinstance(element, NavigableString): text += element elif not node.name in exceptions: text += process_tag(element) try: convert_fn = globals()["convert_%s" % node.name.lower()] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def laggeddates(ts, step=1): '''Lagged iterator over dates''' if step == 1: dates = ts.dates() if not hasattr(dates, 'next'): dates = dates.__iter__() dt0 = next(dates) for dt1 in dates: yield dt1, dt0 dt0 = dt1 else: whi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def make_skiplist(*args, use_fallback=False): '''Create a new skiplist''' sl = fallback.Skiplist if use_fallback else Skiplist return sl(*args)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data2md(table): """ Creates a markdown table. The first row will be headers. Parameters table : list of lists of str A list of rows containing strings. If an...
table = copy.deepcopy(table) table = ensure_table_strings(table) table = multis_2_mono(table) table = add_cushions(table) widths = [] for column in range(len(table[0])): widths.append(get_column_width(column, table)) output = '|' for i in range(len(table[0])): output...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def v_center_cell_text(cell): """ Vertically center the text within the cell's grid. Like this:: +--------+ +--------+ | foobar | | | | | | | | | --> | foobar | ...
lines = cell.text.split('\n') cell_width = len(lines[0]) - 2 truncated_lines = [] for i in range(1, len(lines) - 1): truncated = lines[i][1:len(lines[i]) - 1] truncated_lines.append(truncated) total_height = len(truncated_lines) empty_lines_above = 0 for i in range(len(tr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data2rst(table, spans=[[[0, 0]]], use_headers=True, center_cells=False, center_headers=False): """ Convert a list of lists of str into a reStructuredText Gri...
table = copy.deepcopy(table) table_ok = check_table(table) if not table_ok == "": return "ERROR: " + table_ok if not spans == [[[0, 0]]]: for span in spans: span_ok = check_span(span, table) if not span_ok == "": return "ERROR: " + span_ok ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def set_dims_from_tree_size(self): "Calculate reasonable height and width for tree given N tips" tlen = len(self.treelist[0]) if self.style.orient in ("right", "left"): # long tip-wise dimension if not self.style.height: self.style.height = max(275, min(10...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_p(element, text): """ Adds 2 newlines to the end of text """
depth = -1 while element: if (not element.name == '[document]' and not element.parent.get('id') == '__RESTRUCTIFY_WRAPPER__'): depth += 1 element = element.parent if text: text = ' ' * depth + text return text
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_output_column_widths(table, spans): """ Gets the widths of the columns of the output table Parameters table : list of lists of str The table of rows of t...
widths = [] for column in table[0]: widths.append(3) for row in range(len(table)): for column in range(len(table[row])): span = get_span(spans, row, column) column_count = get_span_column_count(span) if column_count == 1: text_row = span...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def make_empty_table(row_count, column_count): """ Make an empty table Parameters row_count : int The number of rows in the new table column_count : int The numb...
table = [] while row_count > 0: row = [] for column in range(column_count): row.append('') table.append(row) row_count -= 1 return table
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def oftype(self, typ): '''Return a generator of formatters codes of type typ''' for key, val in self.items(): if val.type == typ: yield key
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def names(self, with_namespace=False): '''List of names for series in dataset. It will always return a list or names with length given by :class:`~.DynData.count`. ''' N = self.count() names = self.name.split(settings.splittingnames)[:N] n = 0 while len(n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dump(self, format=None, **kwargs): """Dump the timeseries using a specific ``format``. """
formatter = Formatters.get(format, None) if not format: return self.display() elif not formatter: raise FormattingException('Formatter %s not available' % format) else: return formatter(self, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge_cells(cell1, cell2, direction): """ Combine the side of cell1's grid text with cell2's text. For example:: cell1 cell2 merge "RIGHT" +-----+ +------+ +...
cell1_lines = cell1.text.split("\n") cell2_lines = cell2.text.split("\n") if direction == "RIGHT": for i in range(len(cell1_lines)): cell1_lines[i] = cell1_lines[i] + cell2_lines[i][1::] cell1.text = "\n".join(cell1_lines) cell1.column_count += cell2.column_count ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log(self, name, val, **tags): """Log metric name with value val. You must include at least one tag as a kwarg"""
global _last_timestamp, _last_metrics # do not allow .log after closing assert not self.done.is_set(), "worker thread has been closed" # check if valid metric name assert all(c in _valid_metric_chars for c in name), "invalid metric name " + name val = float(val) #Duck...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def available_ports(): """ Scans COM1 through COM255 for available serial ports returns a list of available ports """
ports = [] for i in range(256): try: p = Serial('COM%d' % i) p.close() ports.append(p) except SerialException: pass return ports
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_current_response(self): """ reads the current response data from the object and returns it in a dict. Currently 'time' is reported as 0 until clock drift...
response = {'port': 0, 'pressed': False, 'key': 0, 'time': 0} if len(self.__response_structs_queue) > 0: # make a copy just in case any other internal members of # XidConnection were tracking the structure r...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def detect_xid_devices(self): """ For all of the com ports connected to the computer, send an XID command '_c1'. If the device response with '_xid', it is an xid...
self.__xid_cons = [] for c in self.__com_ports: device_found = False for b in [115200, 19200, 9600, 57600, 38400]: con = XidConnection(c, b) try: con.open() except SerialException: continue...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def device_at_index(self, index): """ Returns the device at the specified index """
if index >= len(self.__xid_cons): raise ValueError("Invalid device index") return self.__xid_cons[index]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query_base_timer(self): """ gets the value from the device's base timer """
(_, _, time) = unpack('<ccI', self.con.send_xid_command("e3", 6)) return time
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def poll_for_response(self): """ Polls the device for user input If there is a keymapping for the device, the key map is applied to the key reported from the dev...
key_state = self.con.check_for_keypress() if key_state != NO_KEY_DETECTED: response = self.con.get_current_response() if self.keymap is not None: response['key'] = self.keymap[response['key']] else: response['key'] -= 1 ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_pulse_duration(self, duration): """ Sets the pulse duration for events in miliseconds when activate_line is called """
if duration > 4294967295: raise ValueError('Duration is too long. Please choose a value ' 'less than 4294967296.') big_endian = hex(duration)[2:] if len(big_endian) % 2 != 0: big_endian = '0'+big_endian little_endian = [] f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def activate_line(self, lines=None, bitmask=None, leave_remaining_lines=False): """ Triggers an output line on StimTracker. There are 8 output lines on StimTrack...
if lines is None and bitmask is None: raise ValueError('Must set one of lines or bitmask') if lines is not None and bitmask is not None: raise ValueError('Can only set one of lines or bitmask') if bitmask is not None: if bitmask not in range(0, 256): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clear_line(self, lines=None, bitmask=None, leave_remaining_lines=False): """ The inverse of activate_line. If a line is active, it deactivates it. This has t...
if lines is None and bitmask is None: raise ValueError('Must set one of lines or bitmask') if lines is not None and bitmask is not None: raise ValueError('Can only set one of lines or bitmask') if bitmask is not None: if bitmask not in range(0, 256): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_device(self): """ Initializes the device with the proper keymaps and name """
try: product_id = int(self._send_command('_d2', 1)) except ValueError: product_id = self._send_command('_d2', 1) if product_id == 0: self._impl = ResponseDevice( self.con, 'Cedrus Lumina LP-400 Response Pad System', ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _send_command(self, command, expected_bytes): """ Send an XID command to the device """
response = self.con.send_xid_command(command, expected_bytes) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_xid_devices(): """ Returns a list of all Xid devices connected to your computer. """
devices = [] scanner = XidScanner() for i in range(scanner.device_count()): com = scanner.device_at_index(i) com.open() device = XidDevice(com) devices.append(device) return devices
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_xid_device(device_number): """ returns device at a given index. Raises ValueError if the device at the passed in index doesn't exist. """
scanner = XidScanner() com = scanner.device_at_index(device_number) com.open() return XidDevice(com)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self, receiver): """Append receiver."""
if not callable(receiver): raise ValueError('Invalid receiver: %s' % receiver) self.receivers.append(receiver)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def disconnect(self, receiver): """Remove receiver."""
try: self.receivers.remove(receiver) except ValueError: raise ValueError('Unknown receiver: %s' % receiver)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select(cls, *args, **kwargs): """Support read slaves."""
query = super(Model, cls).select(*args, **kwargs) query.database = cls._get_read_database() return query
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_app(self, app, database=None): """Initialize application."""
# Register application if not app: raise RuntimeError('Invalid application.') self.app = app if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['peewee'] = self app.config.setdefault('PEEWEE_CONNECTION_PARAMS', {}) app...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self, response): """Close connection to database."""
LOGGER.info('Closing [%s]', os.getpid()) if not self.database.is_closed(): self.database.close() return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def Model(self): """Bind model to self database."""
Model_ = self.app.config['PEEWEE_MODELS_CLASS'] meta_params = {'database': self.database} if self.slaves and self.app.config['PEEWEE_USE_READ_SLAVES']: meta_params['read_slaves'] = self.slaves Meta = type('Meta', (), meta_params) return type('Model', (Model_,), {'Me...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def models(self): """Return self.application models."""
Model_ = self.app.config['PEEWEE_MODELS_CLASS'] ignore = self.app.config['PEEWEE_MODELS_IGNORE'] models = [] if Model_ is not Model: try: mod = import_module(self.app.config['PEEWEE_MODELS_MODULE']) for model in dir(mod): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cmd_create(self, name, auto=False): """Create a new migration."""
LOGGER.setLevel('INFO') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], migrate_table=self.app.config['PEEWEE_MIGRATE_TABLE']) if auto: auto = self.models route...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cmd_rollback(self, name): """Rollback migrations."""
from peewee_migrate.router import Router, LOGGER LOGGER.setLevel('INFO') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], migrate_table=self.app.config['PEEWEE_MIGRATE_TABLE']) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cmd_merge(self): """Merge migrations."""
from peewee_migrate.router import Router, LOGGER LOGGER.setLevel('DEBUG') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], migrate_table=self.app.config['PEEWEE_MIGRATE_TABLE']) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def manager(self): """Integrate a Flask-Script."""
from flask_script import Manager, Command manager = Manager(usage="Migrate database.") manager.add_command('create', Command(self.cmd_create)) manager.add_command('migrate', Command(self.cmd_migrate)) manager.add_command('rollback', Command(self.cmd_rollback)) manager.a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def markup_line(text, offset, marker='>>!<<'): """Insert `marker` at `offset` into `text`, and return the marked line. .. code-block:: python 1>>!<<234 """
begin = text.rfind('\n', 0, offset) begin += 1 end = text.find('\n', offset) if end == -1: end = len(text) return text[begin:offset] + marker + text[offset:end]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rescale(self, factor=1.0, allow_cast=True): """ Rescales self.y by given factor, if allow_cast is set to True and division in place is impossible - casting a...
try: self.y /= factor except TypeError as e: logger.warning("Division in place is impossible: %s", e) if allow_cast: self.y = self.y / factor else: logger.error("allow_cast flag set to True should help") rai...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_domain(self, domain): """ Creating new Curve object in memory with domain passed as a parameter. New domain must include in the original domain. Copie...
logger.info('Running %(name)s.change_domain() with new domain range:[%(ymin)s, %(ymax)s]', {"name": self.__class__, "ymin": np.min(domain), "ymax": np.max(domain)}) # check if new domain includes in the original domain if np.max(domain) > np.max(self.x) or np.min(domain) < ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def medfilt(vector, window): """ Apply a window-length median filter to a 1D array vector. Should get rid of 'spike' value 15. [1. 1. 1. 1. 1.] [15. 1. 1. 1. 1.]...
if not window % 2 == 1: raise ValueError("Median filter length must be odd.") if not vector.ndim == 1: raise ValueError("Input must be one-dimensional.") k = (window - 1) // 2 # window movement result = np.zeros((len(vector), window), dtype=vector.dtype) result[:, k] = vector ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def model_fields(model, allow_pk=False, only=None, exclude=None, field_args=None, converter=None): """ Generate a dictionary of fields for a given Peewee model. ...
converter = converter or ModelConverter() field_args = field_args or {} model_fields = list(model._meta.sorted_fields) if not allow_pk: model_fields.pop(0) if only: model_fields = [x for x in model_fields if x.name in only] elif exclude: model_fields = [x for x in mode...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prompt(text='', title='' , default='', root=None, timeout=None): """Displays a message box with text input, and OK & Cancel buttons. Returns the text entered...
assert TKINTER_IMPORT_SUCCEEDED, 'Tkinter is required for pymsgbox' return __fillablebox(text, title, default=default, mask=None,root=root, timeout=timeout)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_line(line): """Reads lines of XML and delimits, strips, and returns."""
name, value = '', '' if '=' in line: name, value = line.split('=', 1) return [name.strip(), value.strip()]