sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
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...
Generates the extended newick string NHX with extra data about a node.
entailment
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 str The table of rows of strings. For this to be accurate, each string must only be 1 line long. ...
Get the character width of a column in a table Parameters ---------- column : int The column index analyze table : list of lists of str The table of rows of strings. For this to be accurate, each string must only be 1 line long. Returns ------- width : int
entailment
def get_text_mark(ttree): """ makes a simple Text Mark object""" if ttree._orient in ["right"]: angle = 0. ypos = ttree.verts[-1*len(ttree.tree):, 1] if ttree._kwargs["tip_labels_align"]: xpos = [ttree.verts[:, 0].max()] * len(ttree.tree) start = xpos ...
makes a simple Text Mark object
entailment
def get_edge_mark(ttree): """ makes a simple Graph Mark object""" ## tree style if ttree._kwargs["tree_style"] in ["c", "cladogram"]: a=ttree.edges vcoordinates=ttree.verts else: a=ttree._lines vcoordinates=ttree._coords ## fixed args a...
makes a simple Graph Mark object
entailment
def split_styles(mark): """ get shared styles """ markers = [mark._table[key] for key in mark._marker][0] nstyles = [] for m in markers: ## fill and stroke are already rgb() since already in markers msty = toyplot.style.combine({ "fill": m.mstyle['fill'], "st...
get shared styles
entailment
def center_cell_text(cell): """ Horizontally center the text within a cell's grid Like this:: +---------+ +---------+ | foo | --> | foo | +---------+ +---------+ Parameters ---------- cell : dashtable.data2rst.Cell Returns ------- cell : da...
Horizontally center the text within a cell's grid Like this:: +---------+ +---------+ | foo | --> | foo | +---------+ +---------+ Parameters ---------- cell : dashtable.data2rst.Cell Returns ------- cell : dashtable.data2rst.Cell
entailment
def hamming_distance(word1, word2): """ Computes the Hamming distance. [Reference]: https://en.wikipedia.org/wiki/Hamming_distance [Article]: Hamming, Richard W. (1950), "Error detecting and error correcting codes", Bell System Technical Journal 29 (2): 147–160 """ from operator import ...
Computes the Hamming distance. [Reference]: https://en.wikipedia.org/wiki/Hamming_distance [Article]: Hamming, Richard W. (1950), "Error detecting and error correcting codes", Bell System Technical Journal 29 (2): 147–160
entailment
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 ...
Polynomial generating function
entailment
def timeseries(name='', backend=None, date=None, data=None, **kwargs): '''Create a new :class:`dynts.TimeSeries` instance using a ``backend`` and populating it with provided the data. :parameter name: optional timeseries name. For multivarate timeseries the :func:`dynts.tsname` ut...
Create a new :class:`dynts.TimeSeries` instance using a ``backend`` and populating it with provided the data. :parameter name: optional timeseries name. For multivarate timeseries the :func:`dynts.tsname` utility function can be used to build it. :parameter b...
entailment
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][colum...
Force each cell in the table to be a string Parameters ---------- table : list of lists Returns ------- table : list of lists of str
entailment
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 keeps track of the number of sections that are touching the left side. For example:: +-----+----...
The number of sections that touch the left side. During merging, the cell's text will grow to include other cells. This property keeps track of the number of sections that are touching the left side. For example:: +-----+-----+ section --> | foo | dog | <-- ...
entailment
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)): i...
The number of sections that touch the right side. Returns ------- sections : int The number of sections on the right
entailment
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 secti...
The number of sections that touch the top side. Returns ------- sections : int The number of sections on the top
entailment
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 ret...
The number of cells that touch the bottom side. Returns ------- sections : int The number of sections on the top
entailment
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:: +-----+ | foo | +=====+ while this cell is not:: +-----+ ...
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:: +-----+ | foo | +=====+ while this cell is not:: +-----+ | foo | +-----+ Retu...
entailment
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 YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the developmen...
Returns a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the development version numbers.
entailment
def headers_present(html_string): """ Checks if the html table contains headers and returns True/False Parameters ---------- html_string : str Returns ------- bool """ try: from bs4 import BeautifulSoup except ImportError: print("ERROR: You must have Beautif...
Checks if the html table contains headers and returns True/False Parameters ---------- html_string : str Returns ------- bool
entailment
def extract_spans(html_string): """ Creates a list of the spanned cell groups of [row, column] pairs. Parameters ---------- html_string : str Returns ------- list of lists of lists of int """ try: from bs4 import BeautifulSoup except ImportError: print("ERRO...
Creates a list of the spanned cell groups of [row, column] pairs. Parameters ---------- html_string : str Returns ------- list of lists of lists of int
entailment
def translation(first, second): """Create an index of mapped letters (zip to dict).""" if len(first) != len(second): raise WrongLengthException('The lists are not of the same length!') return dict(zip(first, second))
Create an index of mapped letters (zip to dict).
entailment
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 e...
Recursively go through a tag's children, converting them, then convert the tag itself.
entailment
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...
Lagged iterator over dates
entailment
def make_skiplist(*args, use_fallback=False): '''Create a new skiplist''' sl = fallback.Skiplist if use_fallback else Skiplist return sl(*args)
Create a new skiplist
entailment
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 any of these strings consist of multiple lines, they will be converted to single line because markdown ta...
Creates a markdown table. The first row will be headers. Parameters ---------- table : list of lists of str A list of rows containing strings. If any of these strings consist of multiple lines, they will be converted to single line because markdown tables do not support multiline ce...
entailment
def v_center_cell_text(cell): """ Vertically center the text within the cell's grid. Like this:: +--------+ +--------+ | foobar | | | | | | | | | --> | foobar | | | | | | | | | ...
Vertically center the text within the cell's grid. Like this:: +--------+ +--------+ | foobar | | | | | | | | | --> | foobar | | | | | | | | | +--------+ +--------+ Paramete...
entailment
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 Grid Table Parameters ---------- table : list of lists of str spans : list of lists of lists of int, optional These ...
Convert a list of lists of str into a reStructuredText Grid Table Parameters ---------- table : list of lists of str spans : list of lists of lists of int, optional These are [row, column] pairs of cells that are merged in the table. Rows and columns start in the top left of the table.F...
entailment
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...
Calculate reasonable height and width for tree given N tips
entailment
def add_tip_labels_to_axes(self): """ Add text offset from tips of tree with correction for orientation, and fixed_order which is usually used in multitree plotting. """ # get tip-coords and replace if using fixed_order if self.style.orient in ("up", "down"): ...
Add text offset from tips of tree with correction for orientation, and fixed_order which is usually used in multitree plotting.
entailment
def fit_tip_labels(self): """ Modifies display range to ensure tip labels fit. This is a bit hackish still. The problem is that the 'extents' range of the rendered text is totally correct. So we add a little buffer here. Should add for user to be able to modify this if needed. I...
Modifies display range to ensure tip labels fit. This is a bit hackish still. The problem is that the 'extents' range of the rendered text is totally correct. So we add a little buffer here. Should add for user to be able to modify this if needed. If not using edge lengths then need to ...
entailment
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: ...
Adds 2 newlines to the end of text
entailment
def simple2data(text): """ Convert a simple table to data (the kind used by DashTable) Parameters ---------- text : str A valid simple rst table Returns ------- table : list of lists of str spans : list of lists of lists of int A span is a [row, column] pair that de...
Convert a simple table to data (the kind used by DashTable) Parameters ---------- text : str A valid simple rst table Returns ------- table : list of lists of str spans : list of lists of lists of int A span is a [row, column] pair that defines a group of merged cel...
entailment
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 text spans : list of lists of int The [row, column] pairs of combined cells Returns ------- wid...
Gets the widths of the columns of the output table Parameters ---------- table : list of lists of str The table of rows of text spans : list of lists of int The [row, column] pairs of combined cells Returns ------- widths : list of int The widths of each column in t...
entailment
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 number of columns in the new table Returns ------- table : list of lists of str Each cell ...
Make an empty table Parameters ---------- row_count : int The number of rows in the new table column_count : int The number of columns in the new table Returns ------- table : list of lists of str Each cell will be an empty str ('')
entailment
def beta(self): '''\ The linear estimation of the parameter vector :math:`\beta` given by .. math:: \beta = (X^T X)^-1 X^T y ''' t = self.X.transpose() XX = dot(t,self.X) XY = dot(t,self.y) return linalg.solve(XX,XY)
\ The linear estimation of the parameter vector :math:`\beta` given by .. math:: \beta = (X^T X)^-1 X^T y
entailment
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
Return a generator of formatters codes of type typ
entailment
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...
List of names for series in dataset. It will always return a list or names with length given by :class:`~.DynData.count`.
entailment
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...
Dump the timeseries using a specific ``format``.
entailment
def p_expression_binop(p): '''expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIVIDE expression | expression EQUAL expression | expression CONCAT expressio...
expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIVIDE expression | expression EQUAL expression | expression CONCAT expression | expression S...
entailment
def p_expression_group(p): '''expression : LPAREN expression RPAREN | LSQUARE expression RSQUARE''' v = p[1] if v == '(': p[0] = functionarguments(p[2]) elif v == '[': p[0] = tsentry(p[2])
expression : LPAREN expression RPAREN | LSQUARE expression RSQUARE
entailment
def merge_cells(cell1, cell2, direction): """ Combine the side of cell1's grid text with cell2's text. For example:: cell1 cell2 merge "RIGHT" +-----+ +------+ +-----+------+ | foo | | dog | | foo | dog | | | +------+ | +------+ | | ...
Combine the side of cell1's grid text with cell2's text. For example:: cell1 cell2 merge "RIGHT" +-----+ +------+ +-----+------+ | foo | | dog | | foo | dog | | | +------+ | +------+ | | | cat | | | cat | | | +------+ ...
entailment
def iterclass(cls): """Iterates over (valid) attributes of a class. Args: cls (object): the class to iterate over Yields: (str, obj) tuples: the class-level attributes. """ for field in dir(cls): if hasattr(cls, field): value = getattr(cls, field) yi...
Iterates over (valid) attributes of a class. Args: cls (object): the class to iterate over Yields: (str, obj) tuples: the class-level attributes.
entailment
def _mksocket(host, port, q, done, stop): """Returns a tcp socket to (host/port). Retries forever if connection fails""" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(2) attempt = 0 while not stop.is_set(): try: s.connect((host, port)) return s ...
Returns a tcp socket to (host/port). Retries forever if connection fails
entailment
def _push(host, port, q, done, mps, stop, test_mode): """Worker thread. Connect to host/port, pull data from q until done is set""" sock = None retry_line = None while not ( stop.is_set() or ( done.is_set() and retry_line == None and q.empty()) ): stime = time.time() if sock == None and...
Worker thread. Connect to host/port, pull data from q until done is set
entailment
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 nam...
Log metric name with value val. You must include at least one tag as a kwarg
entailment
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) ...
Scans COM1 through COM255 for available serial ports returns a list of available ports
entailment
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 issues are resolved. """ response = {'port': 0, 'pressed': False, ...
reads the current response data from the object and returns it in a dict. Currently 'time' is reported as 0 until clock drift issues are resolved.
entailment
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 device. """ self.__xid_cons = [] for c in self.__com_ports: device_found = False ...
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 device.
entailment
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]
Returns the device at the specified index
entailment
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
gets the value from the device's base timer
entailment
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 device. If a response is waiting to be processed, the response is appended to the internal response_queue ...
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 device. If a response is waiting to be processed, the response is appended to the internal response_queue
entailment
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....
Sets the pulse duration for events in miliseconds when activate_line is called
entailment
def activate_line(self, lines=None, bitmask=None, leave_remaining_lines=False): """ Triggers an output line on StimTracker. There are 8 output lines on StimTracker that can be raised in any combination. To raise lines 1 and 7, for example, you pass in the ...
Triggers an output line on StimTracker. There are 8 output lines on StimTracker that can be raised in any combination. To raise lines 1 and 7, for example, you pass in the list: activate_line(lines=[1, 7]). To raise a single line, pass in just an integer, or a list with a sing...
entailment
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 the same parameters as activate_line() """ if lines is None and bitmask is None: raise ...
The inverse of activate_line. If a line is active, it deactivates it. This has the same parameters as activate_line()
entailment
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 = Re...
Initializes the device with the proper keymaps and name
entailment
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
Send an XID command to the device
entailment
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) ...
Returns a list of all Xid devices connected to your computer.
entailment
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)
returns device at a given index. Raises ValueError if the device at the passed in index doesn't exist.
entailment
def connect(self, receiver): """Append receiver.""" if not callable(receiver): raise ValueError('Invalid receiver: %s' % receiver) self.receivers.append(receiver)
Append receiver.
entailment
def disconnect(self, receiver): """Remove receiver.""" try: self.receivers.remove(receiver) except ValueError: raise ValueError('Unknown receiver: %s' % receiver)
Remove receiver.
entailment
def send(self, instance, *args, **kwargs): """Send signal.""" for receiver in self.receivers: receiver(instance, *args, **kwargs)
Send signal.
entailment
def select(cls, *args, **kwargs): """Support read slaves.""" query = super(Model, cls).select(*args, **kwargs) query.database = cls._get_read_database() return query
Support read slaves.
entailment
def save(self, force_insert=False, **kwargs): """Send signals.""" created = force_insert or not bool(self.pk) self.pre_save.send(self, created=created) super(Model, self).save(force_insert=force_insert, **kwargs) self.post_save.send(self, created=created)
Send signals.
entailment
def delete_instance(self, *args, **kwargs): """Send signals.""" self.pre_delete.send(self) super(Model, self).delete_instance(*args, **kwargs) self.post_delete.send(self)
Send signals.
entailment
def get_database(obj, **params): """Get database from given URI/Object.""" if isinstance(obj, string_types): return connect(obj, **params) return obj
Get database from given URI/Object.
entailment
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'] = se...
Initialize application.
entailment
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
Close connection to database.
entailment
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', ()...
Bind model to self database.
entailment
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...
Return self.application models.
entailment
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_MIG...
Create a new migration.
entailment
def cmd_migrate(self, name=None, fake=False): """Run 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'], ...
Run migrations.
entailment
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'], ...
Rollback migrations.
entailment
def cmd_list(self): """List 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_ta...
List migrations.
entailment
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_...
Merge migrations.
entailment
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...
Integrate a Flask-Script.
entailment
def restart_program(): """ DOES NOT WORK WELL WITH MOPIDY Hack from https://www.daniweb.com/software-development/python/code/260268/restart-your-python-program to support updating the settings, since mopidy is not able to do that yet Restarts the current program Note: this function does not ...
DOES NOT WORK WELL WITH MOPIDY Hack from https://www.daniweb.com/software-development/python/code/260268/restart-your-python-program to support updating the settings, since mopidy is not able to do that yet Restarts the current program Note: this function does not return. Any cleanup action (like ...
entailment
def __load(arff): """ load liac-arff to pandas DataFrame :param dict arff:arff dict created liac-arff :rtype: DataFrame :return: pandas DataFrame """ attrs = arff['attributes'] attrs_t = [] for attr in attrs: if isinstance(attr[1], list): attrs_t.append("%s@{%s}" ...
load liac-arff to pandas DataFrame :param dict arff:arff dict created liac-arff :rtype: DataFrame :return: pandas DataFrame
entailment
def __dump(df,relation='data',description=''): """ dump DataFrame to liac-arff :param DataFrame df: :param str relation: :param str description: :rtype: dict :return: liac-arff dict """ attrs = [] for col in df.columns: attr = col.split('@') if attr[1].count('...
dump DataFrame to liac-arff :param DataFrame df: :param str relation: :param str description: :rtype: dict :return: liac-arff dict
entailment
def dump(df,fp): """ dump DataFrame to file :param DataFrame df: :param file fp: """ arff = __dump(df) liacarff.dump(arff,fp)
dump DataFrame to file :param DataFrame df: :param file fp:
entailment
def markup_line(text, offset, marker='>>!<<'): """Insert `marker` at `offset` into `text`, and return the marked line. .. code-block:: python >>> markup_line('0\\n1234\\n56', 3) 1>>!<<234 """ begin = text.rfind('\n', 0, offset) begin += 1 end = text.find('\n', offset) ...
Insert `marker` at `offset` into `text`, and return the marked line. .. code-block:: python >>> markup_line('0\\n1234\\n56', 3) 1>>!<<234
entailment
def tokenize_init(spec): """Initialize a tokenizer. Should only be called by the :func:`~textparser.Parser.tokenize` method in the parser. """ tokens = [Token('__SOF__', '__SOF__', 0)] re_token = '|'.join([ '(?P<{}>{})'.format(name, regex) for name, regex in spec ]) return tokens,...
Initialize a tokenizer. Should only be called by the :func:`~textparser.Parser.tokenize` method in the parser.
entailment
def tokenize(self, text): """Tokenize given string `text`, and return a list of tokens. Raises :class:`~textparser.TokenizeError` on failure. This method should only be called by :func:`~textparser.Parser.parse()`, but may very well be overridden if the default implementation do...
Tokenize given string `text`, and return a list of tokens. Raises :class:`~textparser.TokenizeError` on failure. This method should only be called by :func:`~textparser.Parser.parse()`, but may very well be overridden if the default implementation does not match the parser needs...
entailment
def parse(self, text, token_tree=False, match_sof=False): """Parse given string `text` and return the parse tree. Raises :class:`~textparser.ParseError` on failure. Returns a parse tree of tokens if `token_tree` is ``True``. .. code-block:: python >>> MyParser().parse('Hell...
Parse given string `text` and return the parse tree. Raises :class:`~textparser.ParseError` on failure. Returns a parse tree of tokens if `token_tree` is ``True``. .. code-block:: python >>> MyParser().parse('Hello, World!') ['Hello', ',', 'World', '!'] >>> tr...
entailment
def x_at_y(self, y, reverse=False): """ Calculates inverse profile - for given y returns x such that f(x) = y If given y is not found in the self.y, then interpolation is used. By default returns first result looking from left, if reverse argument set to True, looks from ...
Calculates inverse profile - for given y returns x such that f(x) = y If given y is not found in the self.y, then interpolation is used. By default returns first result looking from left, if reverse argument set to True, looks from right. If y is outside range of self.y then np.n...
entailment
def width(self, level): """ Width at given level :param level: :return: """ return self.x_at_y(level, reverse=True) - self.x_at_y(level)
Width at given level :param level: :return:
entailment
def normalize(self, dt, allow_cast=True): """ Normalize to 1 over [-dt, +dt] area, if allow_cast is set to True, division not in place and casting may occur. If division in place is not possible and allow_cast is False an exception is raised. >>> a = Profile([[0, 0], [1,...
Normalize to 1 over [-dt, +dt] area, if allow_cast is set to True, division not in place and casting may occur. If division in place is not possible and allow_cast is False an exception is raised. >>> a = Profile([[0, 0], [1, 5], [2, 10], [3, 5], [4, 0]]) >>> a.normalize(1, allo...
entailment
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 and not in place division may occur occur. If in place is impossible and allow_cast is set to False - an exception is ra...
Rescales self.y by given factor, if allow_cast is set to True and division in place is impossible - casting and not in place division may occur occur. If in place is impossible and allow_cast is set to False - an exception is raised. Check simple rescaling by 2 with no casting >...
entailment
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. Copies values from original curve and uses interpolation to calculate values for new points in domain. Calculate y ...
Creating new Curve object in memory with domain passed as a parameter. New domain must include in the original domain. Copies values from original curve and uses interpolation to calculate values for new points in domain. Calculate y - values of example curve with changed domain: ...
entailment
def rebinned(self, step=0.1, fixp=0): """ Provides effective way to compute new domain basing on step and fixp parameters. Then using change_domain() method to create new object with calculated domain and returns it. fixp doesn't have to be inside original domain. Retur...
Provides effective way to compute new domain basing on step and fixp parameters. Then using change_domain() method to create new object with calculated domain and returns it. fixp doesn't have to be inside original domain. Return domain of a new curve specified by fixp=0 and st...
entailment
def evaluate_at_x(self, arg, def_val=0): """ Returns Y value at arg of self. Arg can be a scalar, but also might be np.array or other iterable (like list). If domain of self is not wide enough to interpolate the value of Y, method will return def_val for those arguments i...
Returns Y value at arg of self. Arg can be a scalar, but also might be np.array or other iterable (like list). If domain of self is not wide enough to interpolate the value of Y, method will return def_val for those arguments instead. Check the interpolation when arg in domain o...
entailment
def subtract(self, curve2, new_obj=False): """ Method that calculates difference between 2 curves (or subclasses of curves). Domain of self must be in domain of curve2 what means min(self.x) >= min(curve2.x) and max(self.x) <= max(curve2.x). Might modify self, and can ret...
Method that calculates difference between 2 curves (or subclasses of curves). Domain of self must be in domain of curve2 what means min(self.x) >= min(curve2.x) and max(self.x) <= max(curve2.x). Might modify self, and can return the result or None Use subtract as -= operator, ch...
entailment
def alert(text='', title='', button='OK'): """Displays a simple message box with text and a single OK button. Returns the text of the button clicked on.""" messageBoxFunc(0, text, title, MB_OK | MB_SETFOREGROUND | MB_TOPMOST) return button
Displays a simple message box with text and a single OK button. Returns the text of the button clicked on.
entailment
def confirm(text='', title='', buttons=['OK', 'Cancel']): """Displays a message box with OK and Cancel buttons. Number and text of buttons can be customized. Returns the text of the button clicked on.""" retVal = messageBoxFunc(0, text, title, MB_OKCANCEL | MB_ICONQUESTION | MB_SETFOREGROUND | MB_TOPMOST) i...
Displays a message box with OK and Cancel buttons. Number and text of buttons can be customized. Returns the text of the button clicked on.
entailment
def subtract(curve1, curve2, def_val=0): """ Function calculates difference between curve1 and curve2 and returns new object which domain is an union of curve1 and curve2 domains Returned object is of type type(curve1) and has same metadata as curve1 object :param curve1: first curve to cal...
Function calculates difference between curve1 and curve2 and returns new object which domain is an union of curve1 and curve2 domains Returned object is of type type(curve1) and has same metadata as curve1 object :param curve1: first curve to calculate the difference :param curve2: second curve...
entailment
def medfilt(vector, window): """ Apply a window-length median filter to a 1D array vector. Should get rid of 'spike' value 15. >>> print(medfilt(np.array([1., 15., 1., 1., 1.]), 3)) [1. 1. 1. 1. 1.] The 'edge' case is a bit tricky... >>> print(medfilt(np.array([15., 1., 1., 1., 1.]), 3)) ...
Apply a window-length median filter to a 1D array vector. Should get rid of 'spike' value 15. >>> print(medfilt(np.array([1., 15., 1., 1., 1.]), 3)) [1. 1. 1. 1. 1.] The 'edge' case is a bit tricky... >>> print(medfilt(np.array([15., 1., 1., 1., 1.]), 3)) [15. 1. 1. 1. 1.] Inspired by...
entailment
def interpn(*args, **kw): """Interpolation on N-D. ai = interpn(x, y, z, ..., a, xi, yi, zi, ...) where the arrays x, y, z, ... define a rectangular grid and a.shape == (len(x), len(y), len(z), ...) are the values interpolate at xi, yi, zi, ... """ method = kw.pop('method', 'cubic') if kw: raise ValueError(...
Interpolation on N-D. ai = interpn(x, y, z, ..., a, xi, yi, zi, ...) where the arrays x, y, z, ... define a rectangular grid and a.shape == (len(x), len(y), len(z), ...) are the values interpolate at xi, yi, zi, ...
entailment
def npinterpn(*args, **kw): """Interpolation on N-D. ai = interpn(x, y, z, ..., a, xi, yi, zi, ...) where the arrays x, y, z, ... define a rectangular grid and a.shape == (len(x), len(y), len(z), ...) are the values interpolate at xi, yi, zi, ... """ method = kw.pop('method', 'cubic') if kw: raise ValueErro...
Interpolation on N-D. ai = interpn(x, y, z, ..., a, xi, yi, zi, ...) where the arrays x, y, z, ... define a rectangular grid and a.shape == (len(x), len(y), len(z), ...) are the values interpolate at xi, yi, zi, ...
entailment
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. See `model_form` docstring for description of parameters. """ converter = converter or ModelConverter() field_args = ...
Generate a dictionary of fields for a given Peewee model. See `model_form` docstring for description of parameters.
entailment
def model_form(model, base_class=Form, allow_pk=False, only=None, exclude=None, field_args=None, converter=None): """ Create a wtforms Form for a given Peewee model class:: from wtfpeewee.orm import model_form from myproject.myapp.models import User UserForm = model_form(...
Create a wtforms Form for a given Peewee model class:: from wtfpeewee.orm import model_form from myproject.myapp.models import User UserForm = model_form(User) :param model: A Peewee model class :param base_class: Base form class to extend from. Must be a ``wtforms.Form...
entailment
def alert(text='', title='', button=OK_TEXT, root=None, timeout=None): """Displays a simple message box with text and a single OK button. Returns the text of the button clicked on.""" assert TKINTER_IMPORT_SUCCEEDED, 'Tkinter is required for pymsgbox' return _buttonbox(msg=text, title=title, choices=[str(bu...
Displays a simple message box with text and a single OK button. Returns the text of the button clicked on.
entailment
def confirm(text='', title='', buttons=[OK_TEXT, CANCEL_TEXT], root=None, timeout=None): """Displays a message box with OK and Cancel buttons. Number and text of buttons can be customized. Returns the text of the button clicked on.""" assert TKINTER_IMPORT_SUCCEEDED, 'Tkinter is required for pymsgbox' retur...
Displays a message box with OK and Cancel buttons. Number and text of buttons can be customized. Returns the text of the button clicked on.
entailment
def prompt(text='', title='' , default='', root=None, timeout=None): """Displays a message box with text input, and OK & Cancel buttons. Returns the text entered, or None if Cancel was clicked.""" assert TKINTER_IMPORT_SUCCEEDED, 'Tkinter is required for pymsgbox' return __fillablebox(text, title, default=d...
Displays a message box with text input, and OK & Cancel buttons. Returns the text entered, or None if Cancel was clicked.
entailment