text
stringlengths
81
112k
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...
Vertically center the text within the cell's grid. Like this:: +--------+ +--------+ | foobar | | | | | | | | | --> | foobar | | | | | | | | | +--------+ +--------+ Paramete...
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...
Calculate reasonable height and width for tree given N tips 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.styl...
Add text offset from tips of tree with correction for orientation, and fixed_order which is usually used in multitree plotting. 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 p...
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 ...
Adds 2 newlines to the end of text 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 ...
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...
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...
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 ('') def make_empty_table(row_count, ...
\ The linear estimation of the parameter vector :math:`\beta` given by .. math:: \beta = (X^T X)^-1 X^T y 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....
Return a generator of formatters codes of type typ 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
List of names for series in dataset. It will always return a list or names with length given by :class:`~.DynData.count`. 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...
Dump the timeseries using a specific ``format``. 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 Formatt...
expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIVIDE expression | expression EQUAL expression | expression CONCAT expression | expression S...
expression : LPAREN expression RPAREN | LSQUARE expression RSQUARE 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] = t...
Combine the side of cell1's grid text with cell2's text. For example:: cell1 cell2 merge "RIGHT" +-----+ +------+ +-----+------+ | foo | | dog | | foo | dog | | | +------+ | +------+ | | | cat | | | cat | | | +------+ ...
Iterates over (valid) attributes of a class. Args: cls (object): the class to iterate over Yields: (str, obj) tuples: the class-level attributes. def iterclass(cls): """Iterates over (valid) attributes of a class. Args: cls (object): the class to iterate over Yields: ...
Returns a tcp socket to (host/port). Retries forever if connection fails 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()...
Worker thread. Connect to host/port, pull data from q until done is set 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 a...
Log metric name with value val. You must include at least one tag as a kwarg 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...
Scans COM1 through COM255 for available serial ports returns a list of available ports def available_ports(): """ Scans COM1 through COM255 for available serial ports returns a list of available ports """ ports = [] for i in range(256): try: ...
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. def get_current_response(self): """ reads the current response data from the object and returns it in a dict. Curr...
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. 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 ...
Returns the device at the specified index 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]
gets the value from the device's base timer 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
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 def poll_for_response(self): """ Polls...
Sets the pulse duration for events in miliseconds when activate_line is called 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 ...
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...
The inverse of activate_line. If a line is active, it deactivates it. This has the same parameters as activate_line() 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. ...
Initializes the device with the proper keymaps and name 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)...
Send an XID command to the device 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
Returns a list of all Xid devices connected to your computer. 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() ...
returns device at a given index. Raises ValueError if the device at the passed in index doesn't exist. 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 = sca...
Append receiver. def connect(self, receiver): """Append receiver.""" if not callable(receiver): raise ValueError('Invalid receiver: %s' % receiver) self.receivers.append(receiver)
Remove receiver. def disconnect(self, receiver): """Remove receiver.""" try: self.receivers.remove(receiver) except ValueError: raise ValueError('Unknown receiver: %s' % receiver)
Send signal. def send(self, instance, *args, **kwargs): """Send signal.""" for receiver in self.receivers: receiver(instance, *args, **kwargs)
Support read slaves. def select(cls, *args, **kwargs): """Support read slaves.""" query = super(Model, cls).select(*args, **kwargs) query.database = cls._get_read_database() return query
Send signals. 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. 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)
Get database from given URI/Object. def get_database(obj, **params): """Get database from given URI/Object.""" if isinstance(obj, string_types): return connect(obj, **params) return obj
Initialize application. 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....
Close connection to database. 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
Bind model to self database. 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 ...
Return self.application models. 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...
Create a new migration. 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=se...
Run migrations. 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_...
Rollback migrations. 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'],...
List migrations. 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'], ...
Merge migrations. 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'], ...
Integrate a Flask-Script. 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)) ...
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 ...
load liac-arff to pandas DataFrame :param dict arff:arff dict created liac-arff :rtype: DataFrame :return: pandas DataFrame def __load(arff): """ load liac-arff to pandas DataFrame :param dict arff:arff dict created liac-arff :rtype: DataFrame :return: pandas DataFrame """ attrs...
dump DataFrame to liac-arff :param DataFrame df: :param str relation: :param str description: :rtype: dict :return: liac-arff dict def __dump(df,relation='data',description=''): """ dump DataFrame to liac-arff :param DataFrame df: :param str relation: :param str description...
dump DataFrame to file :param DataFrame df: :param file fp: def dump(df,fp): """ dump DataFrame to file :param DataFrame df: :param file fp: """ arff = __dump(df) liacarff.dump(arff,fp)
Insert `marker` at `offset` into `text`, and return the marked line. .. code-block:: python >>> markup_line('0\\n1234\\n56', 3) 1>>!<<234 def markup_line(text, offset, marker='>>!<<'): """Insert `marker` at `offset` into `text`, and return the marked line. .. code-block:: python ...
Initialize a tokenizer. Should only be called by the :func:`~textparser.Parser.tokenize` method in the parser. 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)] ...
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...
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...
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...
Width at given level :param level: :return: def width(self, level): """ Width at given level :param level: :return: """ return self.x_at_y(level, reverse=True) - self.x_at_y(level)
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...
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 >...
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: ...
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...
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...
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...
Displays a simple message box with text and a single OK button. Returns the text of the button clicked on. 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_SETFOR...
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. 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 ...
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...
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...
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, ... def interpn(*args, **kw): """Interpolation on N-D. ai = interpn(x, y, z, ..., a, xi, yi, zi, ...
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, ... def npinterpn(*args, **kw): """Interpolation on N-D. ai = interpn(x, y, z, ..., a, xi, yi, zi...
Generate a dictionary of fields for a given Peewee model. See `model_form` docstring for description of parameters. 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 `mo...
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...
Displays a simple message box with text and a single OK button. Returns the text of the button clicked on. 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_IMPOR...
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. 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 b...
Displays a message box with text input, and OK & Cancel buttons. Returns the text entered, or None if Cancel was clicked. 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....
Display a msg, a title, and a set of buttons. The buttons are defined by the members of the choices list. Return the text of the button that the user selected. @arg msg: the msg to be displayed. @arg title: the window title @arg choices: a list or tuple of the choices to be displayed def _buttonbo...
Put the buttons in the buttons frame def __put_buttons_in_buttonframe(choices): """Put the buttons in the buttons frame""" global __widgetTexts, __firstWidget, buttonsFrame __firstWidget = None __widgetTexts = {} i = 0 for buttonText in choices: tempButton = tk.Button(buttonsFrame, t...
Show a box in which a user can enter some text. You may optionally specify some default text, which will appear in the enterbox when it is displayed. Returns the text that the user entered, or None if he cancels the operation. def __fillablebox(msg, title='', default='', mask=None, root=None, timeout=None)...
Parse the login xml response :param response: the login response from the RETS server :return: None def parse(self, response): """ Parse the login xml response :param response: the login response from the RETS server :return: None """ self.headers = respo...
Reads lines of XML and delimits, strips, and returns. 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()]
Takes a response socket connection and iteratively parses and yields the results as python dictionaries. :param response: a Requests response object with stream=True :return: def generator(self, response): """ Takes a response socket connection and iteratively parses and yields the resu...
Takes a urlinfo object and returns a flat dictionary. def flatten_urlinfo(urlinfo, shorter_keys=True): """ Takes a urlinfo object and returns a flat dictionary.""" def flatten(value, prefix=""): if is_string(value): _result[prefix[1:]] = value return try: len...
Create URI and signature headers based on AWS V4 signing process. Refer to https://docs.aws.amazon.com/AlexaWebInfoService/latest/ApiReferenceArticle.html for request params. :param request_params: dictionary of request parameters :return: URL and header to be passed to requests.get def create_...
Provide information about supplied domain as specified by the response group :param domain: Any valid URL :param response_group: Any valid urlinfo response group :return: Traffic and/or content data of the domain in XML format def urlinfo(self, domain, response_group = URLINFO_RESPONSE_GROUPS):...
Provide traffic history of supplied domain :param domain: Any valid URL :param response_group: Any valid traffic history response group :return: Traffic and/or content data of the domain in XML format def traffichistory(self, domain, response_group=TRAFFICINFO_RESPONSE_GROUPS, myrange=31, start...
Provide category browse information of specified domain :param domain: Any valid URL :param path: Valid category path :param response_group: Any valid traffic history response group :return: Traffic and/or content data of the domain in XML format def cat_browse(self, domain, path, respo...
Add a capability of the RETS board :param name: The name of the capability :param uri: The capability URI given by the RETS board :return: None def add_capability(self, name, uri): """ Add a capability of the RETS board :param name: The name of the capability :pa...
Login to the RETS board and return an instance of Bulletin :return: Bulletin instance def login(self): """ Login to the RETS board and return an instance of Bulletin :return: Bulletin instance """ response = self._request('Login') parser = OneXLogin() par...
Get resource metadata :param resource: The name of the resource to get metadata for :return: list def get_resource_metadata(self, resource=None): """ Get resource metadata :param resource: The name of the resource to get metadata for :return: list """ res...
Get metadata for a given resource: class :param resource: The name of the resource :param resource_class: The name of the class to get metadata from :return: list def get_table_metadata(self, resource, resource_class): """ Get metadata for a given resource: class :param ...
Get possible lookup values for a given field :param resource: The name of the resource :param lookup_name: The name of the the field to get lookup values for :return: list def get_lookup_values(self, resource, lookup_name): """ Get possible lookup values for a given field ...
Get the Metadata. The Session initializes with 'COMPACT-DECODED' as the format type. If that returns a DTD error then we change to the 'STANDARD-XML' format and try again. :param meta_id: The name of the resource, class, or lookup to get metadata for :param metadata_type: The RETS metadata type ...
Get the first object from a Resource :param resource: The name of the resource :param object_type: The type of object to fetch :param content_id: The unique id of the item to get objects for :param location: The path to get Objects from :return: Object def get_preferred_object(s...
Get a list of Objects from a resource :param resource: The resource to get objects from :param object_type: The type of object to fetch :param content_ids: The unique id of the item to get objects for :param object_ids: ids of the objects to download :param location: The path to ...
Preform a search on the RETS board :param resource: The resource that contains the class to search :param resource_class: The class to search :param search_filter: The query as a dict :param dmql_query: The query in dmql format :param limit: Limit search values count :par...
Make a _request to the RETS server :param capability: The name of the capability to use to get the URI :param options: Options to put into the _request :return: Response def _request(self, capability, options=None, stream=False): """ Make a _request to the RETS server :p...
Hash the user agent and user agent password Section 3.10 of https://www.nar.realtor/retsorg.nsf/retsproto1.7d6.pdf :return: md5 def _user_agent_digest_hash(self): """ Hash the user agent and user agent password Section 3.10 of https://www.nar.realtor/retsorg.nsf/retsproto1.7d6.p...