sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def make_root(self, name): # noqa: D302 r""" Make a sub-node the root node of the tree. All nodes not belonging to the sub-tree are deleted :param name: New root node name :type name: :ref:`NodeName` :raises: * RuntimeError (Argument \`name\` is not valid) ...
r""" Make a sub-node the root node of the tree. All nodes not belonging to the sub-tree are deleted :param name: New root node name :type name: :ref:`NodeName` :raises: * RuntimeError (Argument \`name\` is not valid) * RuntimeError (Node *[name]* not in tre...
entailment
def print_node(self, name): # noqa: D302 r""" Print node information (parent, children and data). :param name: Node name :type name: :ref:`NodeName` :raises: * RuntimeError (Argument \`name\` is not valid) * RuntimeError (Node *[name]* not in tree) ...
r""" Print node information (parent, children and data). :param name: Node name :type name: :ref:`NodeName` :raises: * RuntimeError (Argument \`name\` is not valid) * RuntimeError (Node *[name]* not in tree) Using the same example tree created in :p...
entailment
def rename_node(self, name, new_name): # noqa: D302 r""" Rename a tree node. It is typical to have a root node name with more than one hierarchy level after using :py:meth:`ptrie.Trie.make_root`. In this instance the root node *can* be renamed as long as the new root name has t...
r""" Rename a tree node. It is typical to have a root node name with more than one hierarchy level after using :py:meth:`ptrie.Trie.make_root`. In this instance the root node *can* be renamed as long as the new root name has the same or less hierarchy levels as the existing root...
entailment
def search_tree(self, name): # noqa: D302 r""" Search tree for all nodes with a specific name. :param name: Node name to search for :type name: :ref:`NodeName` :raises: RuntimeError (Argument \`name\` is not valid) For example: >>> from __future__ import...
r""" Search tree for all nodes with a specific name. :param name: Node name to search for :type name: :ref:`NodeName` :raises: RuntimeError (Argument \`name\` is not valid) For example: >>> from __future__ import print_function >>> import pprint, ptri...
entailment
def find_root(filename, target='bids'): """Find base directory (root) for a filename. Parameters ---------- filename : instance of Path search the root for this file target: str 'bids' (the directory containing 'participants.tsv'), 'subject' (the directory starting with 'sub...
Find base directory (root) for a filename. Parameters ---------- filename : instance of Path search the root for this file target: str 'bids' (the directory containing 'participants.tsv'), 'subject' (the directory starting with 'sub-'), 'session' (the directory starting with ...
entailment
def find_in_bids(filename, pattern=None, generator=False, upwards=False, wildcard=True, **kwargs): """Find nearest file matching some criteria. Parameters ---------- filename : instance of Path search the root for this file pattern : str glob string for search crite...
Find nearest file matching some criteria. Parameters ---------- filename : instance of Path search the root for this file pattern : str glob string for search criteria of the filename of interest (remember to include '*'). The pattern is passed directly to rglob. wildcard : ...
entailment
def define_format(self, plotStyle, plotSize): #Default sizes for computer sizing_dict = {} sizing_dict['figure.figsize'] = (14, 8) sizing_dict['legend.fontsize'] = 15 sizing_dict['axes.labelsize'] = 20 sizing_dict['axes.titlesize'] = 24 sizing_dict['xtick.labelsi...
Seaborn color blind #0072B2 dark blue #009E73 green #D55E00 orangish #CC79A7 pink #F0E442 yellow #56B4E9 cyan #bcbd22 olive #adicional #7f7f7f grey #FFB5B8 skin
entailment
def get_xyz(self, list_of_names=None): """Get xyz coordinates for these electrodes Parameters ---------- list_of_names : list of str list of electrode names to use Returns ------- list of tuples of 3 floats (x, y, z) list of xyz coordinat...
Get xyz coordinates for these electrodes Parameters ---------- list_of_names : list of str list of electrode names to use Returns ------- list of tuples of 3 floats (x, y, z) list of xyz coordinates for all the electrodes TODO --...
entailment
def bces(y1,y1err,y2,y2err,cerr): """ Does the entire regression calculation for 4 slopes: OLS(Y|X), OLS(X|Y), bisector, orthogonal. Fitting form: Y=AX+B. Usage: >>> a,b,aerr,berr,covab=bces(x,xerr,y,yerr,cov) Output: - a,b : best-fit parameters a,b of the linear regression - aerr,berr : the standard deviations i...
Does the entire regression calculation for 4 slopes: OLS(Y|X), OLS(X|Y), bisector, orthogonal. Fitting form: Y=AX+B. Usage: >>> a,b,aerr,berr,covab=bces(x,xerr,y,yerr,cov) Output: - a,b : best-fit parameters a,b of the linear regression - aerr,berr : the standard deviations in a,b - covab : the covariance between ...
entailment
def bootstrap(v): """ Constructs Monte Carlo simulated data set using the Bootstrap algorithm. Usage: >>> bootstrap(x) where x is either an array or a list of arrays. If it is a list, the code returns the corresponding list of bootst...
Constructs Monte Carlo simulated data set using the Bootstrap algorithm. Usage: >>> bootstrap(x) where x is either an array or a list of arrays. If it is a list, the code returns the corresponding list of bootstrapped arrays assuming...
entailment
def bcesboot(y1,y1err,y2,y2err,cerr,nsim=10000): """ Does the BCES with bootstrapping. Usage: >>> a,b,aerr,berr,covab=bcesboot(x,xerr,y,yerr,cov,nsim) :param x,y: data :param xerr,yerr: measurement errors affecting x and y :param cov: covariance between the measurement errors (all are arrays) :param ns...
Does the BCES with bootstrapping. Usage: >>> a,b,aerr,berr,covab=bcesboot(x,xerr,y,yerr,cov,nsim) :param x,y: data :param xerr,yerr: measurement errors affecting x and y :param cov: covariance between the measurement errors (all are arrays) :param nsim: number of Monte Carlo simulations (bootstraps) :re...
entailment
def bcesboot_backup(y1,y1err,y2,y2err,cerr,nsim=10000): """ Does the BCES with bootstrapping. Usage: >>> a,b,aerr,berr,covab=bcesboot(x,xerr,y,yerr,cov,nsim) :param x,y: data :param xerr,yerr: measurement errors affecting x and y :param cov: covariance between the measurement errors (all are arrays) :param nsim: n...
Does the BCES with bootstrapping. Usage: >>> a,b,aerr,berr,covab=bcesboot(x,xerr,y,yerr,cov,nsim) :param x,y: data :param xerr,yerr: measurement errors affecting x and y :param cov: covariance between the measurement errors (all are arrays) :param nsim: number of Monte Carlo simulations (bootstraps) :returns: a,b ...
entailment
def ab(x): """ This method is the big bottleneck of the parallel BCES code. That's the reason why I put these calculations in a separate method, in order to distribute this among the cores. In the original BCES method, this is inside the main routine. Argument: [y1,y1err,y2,y2err,cerr,nsim] where nsim is the numb...
This method is the big bottleneck of the parallel BCES code. That's the reason why I put these calculations in a separate method, in order to distribute this among the cores. In the original BCES method, this is inside the main routine. Argument: [y1,y1err,y2,y2err,cerr,nsim] where nsim is the number of bootstrapp...
entailment
def bcesp(y1,y1err,y2,y2err,cerr,nsim=10000): """ Parallel implementation of the BCES with bootstrapping. Divide the bootstraps equally among the threads (cores) of the machine. It will automatically detect the number of cores available. Usage: >>> a,b,aerr,berr,covab=bcesp(x,xerr,y,yerr,cov,nsim) :param x,y: data ...
Parallel implementation of the BCES with bootstrapping. Divide the bootstraps equally among the threads (cores) of the machine. It will automatically detect the number of cores available. Usage: >>> a,b,aerr,berr,covab=bcesp(x,xerr,y,yerr,cov,nsim) :param x,y: data :param xerr,yerr: measurement errors affecting x an...
entailment
def mean(data): """Return the sample arithmetic mean of data.""" #: http://stackoverflow.com/a/27758326 n = len(data) if n < 1: raise ValueError('mean requires at least one data point') return sum(data)/n
Return the sample arithmetic mean of data.
entailment
def pstdev(data): """Calculates the population standard deviation.""" #: http://stackoverflow.com/a/27758326 n = len(data) if n < 2: raise ValueError('variance requires at least two data points') ss = _ss(data) pvar = ss/n # the population variance return pvar**0.5
Calculates the population standard deviation.
entailment
def median(lst): """ Calcuates the median value in a @lst """ #: http://stackoverflow.com/a/24101534 sortedLst = sorted(lst) lstLen = len(lst) index = (lstLen - 1) // 2 if (lstLen % 2): return sortedLst[index] else: return (sortedLst[index] + sortedLst[index + 1])/2.0
Calcuates the median value in a @lst
entailment
def send_email(recipients: list, subject: str, text: str, html: str='', sender: str='', files: list=[], exceptions: bool=False): """ :param recipients: List of recipients; or single email (str); or comma-separated email list (str); or list of name-email pairs (e.g. settings.ADMINS) :param subject: Subject o...
:param recipients: List of recipients; or single email (str); or comma-separated email list (str); or list of name-email pairs (e.g. settings.ADMINS) :param subject: Subject of the email :param text: Body (text) :param html: Body (html) :param sender: Sender email, or settings.DEFAULT_FROM_EMAIL if miss...
entailment
def remove_whitespace(s): """ Unsafely attempts to remove HTML whitespace. This is not an HTML parser which is why its considered 'unsafe', but it should work for most implementations. Just use on at your own risk. @s: #str -> HTML with whitespace removed, ignoring <pre>, script, t...
Unsafely attempts to remove HTML whitespace. This is not an HTML parser which is why its considered 'unsafe', but it should work for most implementations. Just use on at your own risk. @s: #str -> HTML with whitespace removed, ignoring <pre>, script, textarea and code tags
entailment
def hashtag_links(uri, s): """ Turns hashtag-like strings into HTML links @uri: /uri/ root for the hashtag-like @s: the #str string you're looking for |#|hashtags in -> #str HTML link |<a href="/uri/hashtag">hashtag</a>| """ for tag, after in hashtag_re.findall(s): _uri = '...
Turns hashtag-like strings into HTML links @uri: /uri/ root for the hashtag-like @s: the #str string you're looking for |#|hashtags in -> #str HTML link |<a href="/uri/hashtag">hashtag</a>|
entailment
def mentions_links(uri, s): """ Turns mentions-like strings into HTML links, @uri: /uri/ root for the hashtag-like @s: the #str string you're looking for |@|mentions in -> #str HTML link |<a href="/uri/mention">mention</a>| """ for username, after in mentions_re.findall(s): ...
Turns mentions-like strings into HTML links, @uri: /uri/ root for the hashtag-like @s: the #str string you're looking for |@|mentions in -> #str HTML link |<a href="/uri/mention">mention</a>|
entailment
def filter(self, query: Query): """Return a new filtered query. Use the tree to filter the query and return a new query "filtered". This query can be filtered again using another tree or even a manual filter. To manually filter query see : - https://docs.sqlalch...
Return a new filtered query. Use the tree to filter the query and return a new query "filtered". This query can be filtered again using another tree or even a manual filter. To manually filter query see : - https://docs.sqlalchemy.org/en/rel_1_2/orm/query.html?highlight...
entailment
def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : p...
Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : pos...
entailment
def print_progress_bar_multi_threads(nb_threads, suffix='', decimals=1, length=15, fill='█'): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) ...
Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : pos...
entailment
def upload(target): # type: (str) -> None """ Upload the release to a pypi server. TODO: Make sure the git directory is clean before allowing a release. Args: target (str): pypi target as defined in ~/.pypirc """ log.info("Uploading to pypi server <33>{}".format(target)) ...
Upload the release to a pypi server. TODO: Make sure the git directory is clean before allowing a release. Args: target (str): pypi target as defined in ~/.pypirc
entailment
def gen_pypirc(username=None, password=None): # type: (str, str) -> None """ Generate ~/.pypirc with the given credentials. Useful for CI builds. Can also get credentials through env variables ``PYPI_USER`` and ``PYPI_PASS``. Args: username (str): pypi username. If not given it...
Generate ~/.pypirc with the given credentials. Useful for CI builds. Can also get credentials through env variables ``PYPI_USER`` and ``PYPI_PASS``. Args: username (str): pypi username. If not given it will try to take it from the `` PYPI_USER`` env variable. passwo...
entailment
def pick_sdf(filename, directory=None): """Returns a full path to the chosen SDF file. The supplied file is not expected to contain a recognised SDF extension, this is added automatically. If a file with the extension `.sdf.gz` or `.sdf` is found the path to it (excluding the extension) is returned....
Returns a full path to the chosen SDF file. The supplied file is not expected to contain a recognised SDF extension, this is added automatically. If a file with the extension `.sdf.gz` or `.sdf` is found the path to it (excluding the extension) is returned. If this fails, `None` is returned. :param...
entailment
def main(): """Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send Slack messages with attachments! :return: None """ log = logging.getLogger(mod_logger + '.main') parser = argparse.ArgumentParser(descrip...
Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send Slack messages with attachments! :return: None
entailment
def set_text(self, text): """Sets the text attribute of the payload :param text: (str) Text of the message :return: None """ log = logging.getLogger(self.cls_logger + '.set_text') if not isinstance(text, basestring): msg = 'text arg must be a string' ...
Sets the text attribute of the payload :param text: (str) Text of the message :return: None
entailment
def set_icon(self, icon_url): """Sets the icon_url for the message :param icon_url: (str) Icon URL :return: None """ log = logging.getLogger(self.cls_logger + '.set_icon') if not isinstance(icon_url, basestring): msg = 'icon_url arg must be a string' ...
Sets the icon_url for the message :param icon_url: (str) Icon URL :return: None
entailment
def add_attachment(self, attachment): """Adds an attachment to the SlackMessage payload This public method adds a slack message to the attachment list. :param attachment: SlackAttachment object :return: None """ log = logging.getLogger(self.cls_logger + '.add_at...
Adds an attachment to the SlackMessage payload This public method adds a slack message to the attachment list. :param attachment: SlackAttachment object :return: None
entailment
def send(self): """Sends the Slack message This public method sends the Slack message along with any attachments, then clears the attachments array. :return: None :raises: OSError """ log = logging.getLogger(self.cls_logger + '.send') if self.attachment...
Sends the Slack message This public method sends the Slack message along with any attachments, then clears the attachments array. :return: None :raises: OSError
entailment
def send_cons3rt_agent_logs(self): """Sends a Slack message with an attachment for each cons3rt agent log :return: """ log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs') log.debug('Searching for log files in directory: {d}'.format(d=self.dep.cons3rt_agent_log...
Sends a Slack message with an attachment for each cons3rt agent log :return:
entailment
def send_text_file(self, text_file): """Sends a Slack message with the contents of a text file :param: test_file: (str) Full path to text file to send :return: None :raises: Cons3rtSlackerError """ log = logging.getLogger(self.cls_logger + '.send_text_file') if ...
Sends a Slack message with the contents of a text file :param: test_file: (str) Full path to text file to send :return: None :raises: Cons3rtSlackerError
entailment
def deploy(project, version, promote, quiet): """ Deploy the app to the target environment. The target environments can be configured using the ENVIRONMENTS conf variable. This will also collect all static files and compile translation messages """ from . import logic logic.deploy(project,...
Deploy the app to the target environment. The target environments can be configured using the ENVIRONMENTS conf variable. This will also collect all static files and compile translation messages
entailment
def devserver(port, admin_port, clear): # type: (int, int, bool) -> None """ Run devserver. """ from . import logic logic.devserver(port, admin_port, clear)
Run devserver.
entailment
def gaussian_filter1d_ppxf(spec, sig): """ Convolve a spectrum by a Gaussian with different sigma for every pixel. If all sigma are the same this routine produces the same output as scipy.ndimage.gaussian_filter1d, except for the border treatment. Here the first/last p pixels are filled with zeros. ...
Convolve a spectrum by a Gaussian with different sigma for every pixel. If all sigma are the same this routine produces the same output as scipy.ndimage.gaussian_filter1d, except for the border treatment. Here the first/last p pixels are filled with zeros. When creating a template library for SDSS data,...
entailment
def call_plugins(self, step): ''' For each plugins, check if a "step" method exist on it, and call it Args: step (str): The method to search and call on each plugin ''' for plugin in self.plugins: try: getattr(plugin, step)() e...
For each plugins, check if a "step" method exist on it, and call it Args: step (str): The method to search and call on each plugin
entailment
def run(self): """ Run the application """ self.call_plugins("on_run") if vars(self.arguments).get("version", None): self.logger.info("{app_name}: {version}".format(app_name=self.app_name, version=self.version)) else: if self.arguments.command == "...
Run the application
entailment
def pretend_option(fn): # type: (FunctionType) -> FunctionType """ Decorator to add a --pretend option to any click command. The value won't be passed down to the command, but rather handled in the callback. The value will be accessible through `peltak.core.context` under 'pretend' if the command n...
Decorator to add a --pretend option to any click command. The value won't be passed down to the command, but rather handled in the callback. The value will be accessible through `peltak.core.context` under 'pretend' if the command needs it. To get the current value you can do: >>> from peltak.comm...
entailment
def verbose_option(fn): """ Decorator to add a --verbose option to any click command. The value won't be passed down to the command, but rather handled in the callback. The value will be accessible through `peltak.core.context` under 'verbose' if the command needs it. To get the current value you can d...
Decorator to add a --verbose option to any click command. The value won't be passed down to the command, but rather handled in the callback. The value will be accessible through `peltak.core.context` under 'verbose' if the command needs it. To get the current value you can do: >>> from peltak.core...
entailment
def changelog(): # type: () -> str """ Print change log since last release. """ # Skip 'v' prefix versions = [x for x in git.tags() if versioning.is_valid(x[1:])] cmd = 'git log --format=%H' if versions: cmd += ' {}..HEAD'.format(versions[-1]) hashes = shell.run(cmd, capture=True)....
Print change log since last release.
entailment
def extract_changelog_items(text, tags): # type: (str) -> Dict[str, List[str]] """ Extract all tagged items from text. Args: text (str): Text to extract the tagged items from. Each tagged item is a paragraph that starts with a tag. It can also be a text list item. Retur...
Extract all tagged items from text. Args: text (str): Text to extract the tagged items from. Each tagged item is a paragraph that starts with a tag. It can also be a text list item. Returns: tuple[list[str], list[str], list[str]]: A tuple of `(features, chan...
entailment
def _(mcs, cls_name="Object", with_meta=None): """ Method to generate real metaclass to be used:: mc = ExtensibleType._("MyClass") # note this line @six.add_metaclass(mc) class MyClassBase(object): pass :param str cls_name: name ...
Method to generate real metaclass to be used:: mc = ExtensibleType._("MyClass") # note this line @six.add_metaclass(mc) class MyClassBase(object): pass :param str cls_name: name of generated class :param class with_meta: Mix ...
entailment
def get_class(mcs): """ Generates new class to gether logic of all available extensions :: mc = ExtensibleType._("MyClass") @six.add_metaclass(mc) class MyClassBase(object): pass # get class with all extensions ena...
Generates new class to gether logic of all available extensions :: mc = ExtensibleType._("MyClass") @six.add_metaclass(mc) class MyClassBase(object): pass # get class with all extensions enabled MyClass = m...
entailment
def _add_base_class(mcs, cls): """ Adds new class *cls* to base classes """ # Do all magic only if subclass had defined required attributes if getattr(mcs, '_base_classes_hash', None) is not None: meta = getattr(cls, 'Meta', None) _hash = getattr(meta, mcs._hashat...
Adds new class *cls* to base classes
entailment
def _(mcs, cls_name='Object', with_meta=None, hashattr='_name'): """ Method to generate real metaclass to be used :: # Create metaclass *mc* mc = ExtensibleByHashType._("MyClass", hashattr='name') # Create class using *mc* as metaclass ...
Method to generate real metaclass to be used :: # Create metaclass *mc* mc = ExtensibleByHashType._("MyClass", hashattr='name') # Create class using *mc* as metaclass @six.add_metaclass(mc) class MyClassBase(object): ...
entailment
def get_class(mcs, name, default=False): """ Generates new class to gether logic of all available extensions :: # Create metaclass *mc* mc = ExtensibleByHashType._("MyClass", hashattr='name') # Use metaclass *mc* to create base class for extensions ...
Generates new class to gether logic of all available extensions :: # Create metaclass *mc* mc = ExtensibleByHashType._("MyClass", hashattr='name') # Use metaclass *mc* to create base class for extensions @six.add_metaclass(mc) ...
entailment
def get_registered_names(mcs): """ Return's list of names (keys) registered in this tree. For each name specific classes exists """ return [k for k, v in six.iteritems(mcs._base_classes_hash) if v]
Return's list of names (keys) registered in this tree. For each name specific classes exists
entailment
def get_last_day_of_month(t: datetime) -> int: """ Returns day number of the last day of the month :param t: datetime :return: int """ tn = t + timedelta(days=32) tn = datetime(year=tn.year, month=tn.month, day=1) tt = tn - timedelta(hours=1) return tt.day
Returns day number of the last day of the month :param t: datetime :return: int
entailment
def localize_time_range(begin: datetime, end: datetime, tz=None) -> (datetime, datetime): """ Localizes time range. Uses pytz.utc if None provided. :param begin: Begin datetime :param end: End datetime :param tz: pytz timezone or None (default UTC) :return: begin, end """ if not tz: ...
Localizes time range. Uses pytz.utc if None provided. :param begin: Begin datetime :param end: End datetime :param tz: pytz timezone or None (default UTC) :return: begin, end
entailment
def this_week(today: datetime=None, tz=None): """ Returns this week begin (inclusive) and end (exclusive). :param today: Some date (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: today = datetime.ut...
Returns this week begin (inclusive) and end (exclusive). :param today: Some date (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive)
entailment
def this_month(today: datetime=None, tz=None): """ Returns current month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: t...
Returns current month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive)
entailment
def next_month(today: datetime=None, tz=None): """ Returns next month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: toda...
Returns next month begin (inclusive) and end (exclusive). :param today: Some date in the month (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive)
entailment
def last_year(today: datetime=None, tz=None): """ Returns last year begin (inclusive) and end (exclusive). :param today: Some date (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive) """ if today is None: today = datetime.ut...
Returns last year begin (inclusive) and end (exclusive). :param today: Some date (defaults current datetime) :param tz: Timezone (defaults pytz UTC) :return: begin (inclusive), end (exclusive)
entailment
def add_month(t: datetime, n: int=1) -> datetime: """ Adds +- n months to datetime. Clamps to number of days in given month. :param t: datetime :param n: count :return: datetime """ t2 = t for count in range(abs(n)): if n > 0: t2 = datetime(year=t2.year, month=t2....
Adds +- n months to datetime. Clamps to number of days in given month. :param t: datetime :param n: count :return: datetime
entailment
def per_delta(start: datetime, end: datetime, delta: timedelta): """ Iterates over time range in steps specified in delta. :param start: Start of time range (inclusive) :param end: End of time range (exclusive) :param delta: Step interval :return: Iterable collection of [(start+td*0, start+td*...
Iterates over time range in steps specified in delta. :param start: Start of time range (inclusive) :param end: End of time range (exclusive) :param delta: Step interval :return: Iterable collection of [(start+td*0, start+td*1), (start+td*1, start+td*2), ..., end)
entailment
def per_month(start: datetime, end: datetime, n: int=1): """ Iterates over time range in one month steps. Clamps to number of days in given month. :param start: Start of time range (inclusive) :param end: End of time range (exclusive) :param n: Number of months to step. Default is 1. :retu...
Iterates over time range in one month steps. Clamps to number of days in given month. :param start: Start of time range (inclusive) :param end: End of time range (exclusive) :param n: Number of months to step. Default is 1. :return: Iterable collection of [(month+0, month+1), (month+1, month+2), ....
entailment
def get_requirements() -> List[str]: """Return the requirements as a list of string.""" requirements_path = os.path.join( os.path.dirname(__file__), 'requirements.txt' ) with open(requirements_path) as f: return f.read().split()
Return the requirements as a list of string.
entailment
def project_dev_requirements(): """ List requirements for peltak commands configured for the project. This list is dynamic and depends on the commands you have configured in your project's pelconf.yaml. This will be the combined list of packages needed to be installed in order for all the configured co...
List requirements for peltak commands configured for the project. This list is dynamic and depends on the commands you have configured in your project's pelconf.yaml. This will be the combined list of packages needed to be installed in order for all the configured commands to work.
entailment
def get_func_params(method, called_params): """ :type method: function :type called_params: dict :return: """ insp = inspect.getfullargspec(method) if not isinstance(called_params, dict): raise UserWarning() _called_params = called_params.copy() params = {} arg_count = le...
:type method: function :type called_params: dict :return:
entailment
def parse_dsn(dsn, default_port=5432, protocol='http://'): """ Разбирает строку подключения к БД и возвращает список из (host, port, username, password, dbname) :param dsn: Строка подключения. Например: username@localhost:5432/dname :type: str :param default_port: Порт по-умолчанию :type de...
Разбирает строку подключения к БД и возвращает список из (host, port, username, password, dbname) :param dsn: Строка подключения. Например: username@localhost:5432/dname :type: str :param default_port: Порт по-умолчанию :type default_port: int :params protocol :type protocol str :return...
entailment
def build_images(): # type: () -> None """ Build all docker images for the project. """ registry = conf.get('docker.registry') docker_images = conf.get('docker.images', []) for image in docker_images: build_image(registry, image)
Build all docker images for the project.
entailment
def push_images(): # type: () -> None """ Push all project docker images to a remote registry. """ registry = conf.get('docker.registry') docker_images = conf.get('docker.images', []) if registry is None: log.err("You must define docker.registry conf variable to push images") sys.ex...
Push all project docker images to a remote registry.
entailment
def docker_list(registry_pass): # type: (str) -> None """ List docker images stored in the remote registry. Args: registry_pass (str): Remote docker registry password. """ registry = conf.get('docker.registry', None) if registry is None: log.err("You must define doc...
List docker images stored in the remote registry. Args: registry_pass (str): Remote docker registry password.
entailment
def build_image(registry, image): # type: (str, Dict[str, Any]) -> None """ Build docker image. Args: registry (str): The name of the registry this image belongs to. If not given, the resulting image will have a name without the registry. image (dict[str, Any]): ...
Build docker image. Args: registry (str): The name of the registry this image belongs to. If not given, the resulting image will have a name without the registry. image (dict[str, Any]): The dict containing the information about the built image. This is ...
entailment
def push_image(registry, image): # type: (str, Dict[str, Any]) -> None """ Push the given image to selected repository. Args: registry (str): The name of the registry we're pushing to. This is the address of the repository without the protocol specification (no http(s)://) ...
Push the given image to selected repository. Args: registry (str): The name of the registry we're pushing to. This is the address of the repository without the protocol specification (no http(s)://) image (dict[str, Any]): The dict containing the information abou...
entailment
def _build_opr_data(self, data, store): """Returns a well formatted OPR data""" return { "invoice_data": { "invoice": { "total_amount": data.get("total_amount"), "description": data.get("description") }, ...
Returns a well formatted OPR data
entailment
def create(self, data={}, store=None): """Initiazes an OPR First step in the OPR process is to create the OPR request. Returns the OPR token """ _store = store or self.store _data = self._build_opr_data(data, _store) if data else self._opr_data return self._proce...
Initiazes an OPR First step in the OPR process is to create the OPR request. Returns the OPR token
entailment
def charge(self, data): """Second stage of an OPR request""" token = data.get("token", self._response["token"]) data = { "token": token, "confirm_token": data.get("confirm_token") } return self._process('opr/charge', data)
Second stage of an OPR request
entailment
def get_value(self, field, quick): # type: (Field, bool) -> Any """ Ask user the question represented by this instance. Args: field (Field): The field we're asking the user to provide the value for. quick (bool): Enable quick mode. In quic...
Ask user the question represented by this instance. Args: field (Field): The field we're asking the user to provide the value for. quick (bool): Enable quick mode. In quick mode, the form will reduce the number of question asked by using d...
entailment
def update_image(self, ami_id, instance_id): """Replaces an existing AMI ID with an image created from the provided instance ID :param ami_id: (str) ID of the AMI to delete and replace :param instance_id: (str) ID of the instance ID to create an image from :return: None...
Replaces an existing AMI ID with an image created from the provided instance ID :param ami_id: (str) ID of the AMI to delete and replace :param instance_id: (str) ID of the instance ID to create an image from :return: None
entailment
def create_cons3rt_template(self, instance_id, name, description='CONS3RT OS template'): """Created a new CONS3RT-ready template from an instance ID :param instance_id: (str) Instance ID to create the image from :param name: (str) Name of the new image :param description: (str) ...
Created a new CONS3RT-ready template from an instance ID :param instance_id: (str) Instance ID to create the image from :param name: (str) Name of the new image :param description: (str) Description of the new image :return: None
entailment
def copy_cons3rt_template(self, ami_id): """ :param ami_id: :return: """ log = logging.getLogger(self.cls_logger + '.copy_cons3rt_template') # Get the current AMI info try: ami_info = self.ec2.describe_images(DryRun=False, ImageIds=[ami_id],...
:param ami_id: :return:
entailment
def uniorbytes(s, result=str, enc="utf-8", err="strict"): """ This function was made to avoid byte / str type errors received in packages like base64. Accepts all input types and will recursively encode entire lists and dicts. @s: the #bytes or #str item you are attempting to encode or decode @...
This function was made to avoid byte / str type errors received in packages like base64. Accepts all input types and will recursively encode entire lists and dicts. @s: the #bytes or #str item you are attempting to encode or decode @result: the desired output, either #str or #bytes @enc: the desire...
entailment
def recode_unicode(s, encoding='utf-8'): """ Inputs are encoded to utf-8 and then decoded to the desired output encoding @encoding: the desired encoding -> #str with the desired @encoding """ if isinstance(s, str): return s.encode().decode(encoding) return s
Inputs are encoded to utf-8 and then decoded to the desired output encoding @encoding: the desired encoding -> #str with the desired @encoding
entailment
def fix_bad_unicode(text): u"""Copyright: http://blog.luminoso.com/2012/08/20/fix-unicode-mistakes-with-python/ Something you will find all over the place, in real-world text, is text that's mistakenly encoded as utf-8, decoded in some ugly format like latin-1 or even Windows codepage 1252, and...
u"""Copyright: http://blog.luminoso.com/2012/08/20/fix-unicode-mistakes-with-python/ Something you will find all over the place, in real-world text, is text that's mistakenly encoded as utf-8, decoded in some ugly format like latin-1 or even Windows codepage 1252, and encoded as utf-8 again. T...
entailment
def text_badness(text): u''' Look for red flags that text is encoded incorrectly: Obvious problems: - The replacement character \ufffd, indicating a decoding error - Unassigned or private-use Unicode characters Very weird things: - Adjacent letters from two different scripts - Letters ...
u''' Look for red flags that text is encoded incorrectly: Obvious problems: - The replacement character \ufffd, indicating a decoding error - Unassigned or private-use Unicode characters Very weird things: - Adjacent letters from two different scripts - Letters in scripts that are very rar...
entailment
def get_pycons3rt_home_dir(): """Returns the pycons3rt home directory based on OS :return: (str) Full path to pycons3rt home :raises: OSError """ if platform.system() == 'Linux': return os.path.join(os.path.sep, 'etc', 'pycons3rt') elif platform.system() == 'Windows': return os....
Returns the pycons3rt home directory based on OS :return: (str) Full path to pycons3rt home :raises: OSError
entailment
def initialize_pycons3rt_dirs(): """Initializes the pycons3rt directories :return: None :raises: OSError """ for pycons3rt_dir in [get_pycons3rt_home_dir(), get_pycons3rt_user_dir(), get_pycons3rt_conf_dir(), get_pycons3r...
Initializes the pycons3rt directories :return: None :raises: OSError
entailment
def main(): # Create the pycons3rt directories try: initialize_pycons3rt_dirs() except OSError as ex: traceback.print_exc() return 1 # Replace log directory paths log_dir_path = get_pycons3rt_log_dir() + os.path.sep conf_contents = default_logging_conf_file_contents.re...
for line in fileinput.input(logging_config_file_dest, inplace=True): if re.search(replace_str, line): new_line = re.sub(replace_str, log_dir_path, line, count=0) sys.stdout.write(new_line) else: sys.stdout.write(line)
entailment
def add_hooks(): # type: () -> None """ Add git hooks for commit and push to run linting and tests. """ # Detect virtualenv the hooks should use # Detect virtualenv virtual_env = conf.getenv('VIRTUAL_ENV') if virtual_env is None: log.err("You are not inside a virtualenv") confi...
Add git hooks for commit and push to run linting and tests.
entailment
def start(name): # type: (str) -> None """ Start working on a new feature by branching off develop. This will create a new branch off develop called feature/<name>. Args: name (str): The name of the new feature. """ feature_name = 'feature/' + common.to_branch_name(name) ...
Start working on a new feature by branching off develop. This will create a new branch off develop called feature/<name>. Args: name (str): The name of the new feature.
entailment
def update(): # type: () -> None """ Update the feature with updates committed to develop. This will merge current develop into the current branch. """ branch = git.current_branch(refresh=True) develop = conf.get('git.devel_branch', 'develop') common.assert_branch_type('feature') commo...
Update the feature with updates committed to develop. This will merge current develop into the current branch.
entailment
def merged(): # type: () -> None """ Cleanup a remotely merged branch. """ develop = conf.get('git.devel_branch', 'develop') branch = git.current_branch(refresh=True) common.assert_branch_type('feature') # Pull develop with the merged feature common.git_checkout(develop) common.git_pul...
Cleanup a remotely merged branch.
entailment
def clean(exclude): # type: (bool, List[str]) -> None """ Remove all unnecessary files. Args: pretend (bool): If set to **True**, do not delete any files, just show what would be deleted. exclude (list[str]): A list of path patterns to exclude from deleti...
Remove all unnecessary files. Args: pretend (bool): If set to **True**, do not delete any files, just show what would be deleted. exclude (list[str]): A list of path patterns to exclude from deletion.
entailment
def init(quick): # type: () -> None """ Create an empty pelconf.yaml from template """ config_file = 'pelconf.yaml' prompt = "-- <35>{} <32>already exists. Wipe it?<0>".format(config_file) if exists(config_file) and not click.confirm(shell.fmt(prompt)): log.info("Canceled") return ...
Create an empty pelconf.yaml from template
entailment
def tracebacks_from_lines(lines_iter): """Generator that yields tracebacks found in a lines iterator The lines iterator can be: - a file-like object - a list (or deque) of lines. - any other iterable sequence of strings """ tbgrep = TracebackGrep() for line in lines_iter: tb ...
Generator that yields tracebacks found in a lines iterator The lines iterator can be: - a file-like object - a list (or deque) of lines. - any other iterable sequence of strings
entailment
def tracebacks_from_file(fileobj, reverse=False): """Generator that yields tracebacks found in a file object With reverse=True, searches backwards from the end of the file. """ if reverse: lines = deque() for line in BackwardsReader(fileobj): lines.appendleft(line) ...
Generator that yields tracebacks found in a file object With reverse=True, searches backwards from the end of the file.
entailment
def BackwardsReader(file, BLKSIZE = 4096): """Read a file line by line, backwards""" buf = "" file.seek(0, 2) lastchar = file.read(1) trailing_newline = (lastchar == "\n") while 1: newline_pos = buf.rfind("\n") pos = file.tell() if newline_pos != -1: # Foun...
Read a file line by line, backwards
entailment
def inversefunc(func, y_values=None, domain=None, image=None, open_domain=None, args=(), accuracy=2): r"""Obtain the inverse of a function. Returns the numerical inverse of the function `f`. It may return a callable...
r"""Obtain the inverse of a function. Returns the numerical inverse of the function `f`. It may return a callable that can be used to calculate the inverse, or the inverse of certain points depending on the `y_values` argument. In order for the numerical inverse to exist in its domain, the input fu...
entailment
def progressed_bar(count, total=100, status=None, suffix=None, bar_len=10): """render a progressed.io like progress bar""" status = status or '' suffix = suffix or '%' assert isinstance(count, int) count_normalized = count if count <= total else total filled_len = int(round(bar_len * count_norma...
render a progressed.io like progress bar
entailment
def prettify(string): """ replace markup emoji and progressbars with actual things # Example ```python from habitipy.util import prettify print(prettify('Write thesis :book: ![progress](http://progressed.io/bar/0 "progress")')) ``` ``` Write thesis 📖 ██████████0% ``` """ ...
replace markup emoji and progressbars with actual things # Example ```python from habitipy.util import prettify print(prettify('Write thesis :book: ![progress](http://progressed.io/bar/0 "progress")')) ``` ``` Write thesis 📖 ██████████0% ```
entailment
def assert_secure_file(file): """checks if a file is stored securely""" if not is_secure_file(file): msg = """ File {0} can be read by other users. This is not secure. Please run 'chmod 600 "{0}"'""" raise SecurityError(dedent(msg).replace('\n', ' ').format(file)) return True
checks if a file is stored securely
entailment
def get_translation_for(package_name: str) -> gettext.NullTranslations: """find and return gettext translation for package""" localedir = None for localedir in pkg_resources.resource_filename(package_name, 'i18n'), None: localefile = gettext.find(package_name, localedir) # type: ignore if l...
find and return gettext translation for package
entailment
def get_translation_functions(package_name: str, names: Tuple[str, ...] = ('gettext',)): """finds and installs translation functions for package""" translation = get_translation_for(package_name) return [getattr(translation, x) for x in names]
finds and installs translation functions for package
entailment
def escape_keywords(arr): """append _ to all python keywords""" for i in arr: i = i if i not in kwlist else i + '_' i = i if '-' not in i else i.replace('-', '_') yield i
append _ to all python keywords
entailment
def download_api(branch=None) -> str: """download API documentation from _branch_ of Habitica\'s repo on Github""" habitica_github_api = 'https://api.github.com/repos/HabitRPG/habitica' if not branch: branch = requests.get(habitica_github_api + '/releases/latest').json()['tag_name'] curl = local...
download API documentation from _branch_ of Habitica\'s repo on Github
entailment
def save_apidoc(text: str) -> None: """save `text` to apidoc cache""" apidoc_local = local.path(APIDOC_LOCAL_FILE) if not apidoc_local.dirname.exists(): apidoc_local.dirname.mkdir() with open(apidoc_local, 'w') as f: f.write(text)
save `text` to apidoc cache
entailment
def parse_apidoc( file_or_branch, from_github=False, save_github_version=True ) -> List['ApiEndpoint']: """read file and parse apiDoc lines""" apis = [] # type: List[ApiEndpoint] regex = r'(?P<group>\([^)]*\)){0,1} *(?P<type_>{[^}]*}){0,1} *' regex += r'(?P<field>[^ ]*) *(?P<description>.*)...
read file and parse apiDoc lines
entailment