text stringlengths 81 112k |
|---|
Given a network name, returns the IP address
:param network_name: (str) Name of the network to search for
:param scenario_role_name: (str) role name to return the IP address for
:return: (str) IP address on the specified network or None
def get_scenario_host_ip_on_network(self, scenario_role_n... |
Given a cons3rt network name, return the network interface name
on this Linux system
:param network_name: (str) Name of the network to search for
:return: (str) name of the network interface device or None
def get_device_for_network_linux(self, network_name):
"""Given a cons3rt network... |
Returns authenticated User.
:param request: HttpRequest
:param exceptions: Raise (NotAuthenticated) exception. Default is True.
:return: User
def require_auth(request: Request, exceptions: bool=True) -> User:
"""
Returns authenticated User.
:param request: HttpRequest
:param exceptions: Rai... |
Add sane defaults rules to the raw and filter tables
def insertSaneDefaults(self):
""" Add sane defaults rules to the raw and filter tables """
self.raw.insert(0, '-A OUTPUT -o lo -j NOTRACK')
self.raw.insert(1, '-A PREROUTING -i lo -j NOTRACK')
self.filters.insert(0, '-A INPUT -i lo -j ACCEPT')
self.filters... |
Add a DROP policy at the end of the rules
def appendDefaultDrop(self):
""" Add a DROP policy at the end of the rules """
self.filters.append('-A INPUT -j DROP')
self.filters.append('-A OUTPUT -j DROP')
self.filters.append('-A FORWARD -j DROP')
return self |
Create a rules file in iptables-restore format
def template(self):
""" Create a rules file in iptables-restore format """
s = Template(self._IPTABLES_TEMPLATE)
return s.substitute(filtertable='\n'.join(self.filters),
rawtable='\n'.join(self.raw),
mangletable='\n'.join(self.mangle),
nattable=... |
Create a rules file in ipset --restore format
def template(self):
""" Create a rules file in ipset --restore format """
s = Template(self._IPSET_TEMPLATE)
return s.substitute(sets='\n'.join(self.sets),
date=datetime.today()) |
wrapper to search_s
def query(self, base, filterstr, attrlist=None):
""" wrapper to search_s """
return self.conn.search_s(base, ldap.SCOPE_SUBTREE, filterstr, attrlist) |
search for a user in LDAP and return its DN and uid
def getUserByNumber(self, base, uidNumber):
""" search for a user in LDAP and return its DN and uid """
res = self.query(base, "uidNumber="+str(uidNumber), ['uid'])
if len(res) > 1:
raise InputError(uidNumber, "Multiple users found. Expecting one.")
return... |
Query LDAP to obtain the network ACLs of a given user,
parse the ACLs, and return the results in a dict of the form
acls[group][cidr] = description
def getACLs(self, base, searchstr):
"""
Query LDAP to obtain the network ACLs of a given user,
parse the ACLs, and return the results in a dict of the form
... |
Splits a comma-separated number sequence into a list (of floats).
def splitValues(textStr):
"""Splits a comma-separated number sequence into a list (of floats).
"""
vals = textStr.split(",")
nums = []
for v in vals:
nums.append(float(v))
return nums |
Expands parameters (presented as tuples of lists and symbolic names)
so that each is returned in a new list where each contains the same number
of values.
Each `arg` is a tuple containing two items: a list of values and a
symbolic name.
def expandParameters(*args):
"""Expands parameters (presented... |
Returns the input list with the length of `count`. If the
list is [1] and the count is 3. [1,1,1] is returned. The list
must be the count length or 1. Normally called from `expandParameters()`
where `name` is the symbolic name of the input.
def expandValues(inputs, count, name):
"""Returns the input li... |
Returns geo IP info or empty dict if geoip query fails at http://ipstack.com.
requires settings.IPSTACK_TOKEN set as valid access token to the API.
Example replies:
{'country_name': 'United States', 'country_code': 'US', 'region_code': 'TX', 'region_name': 'Texas', 'ip': '76.184.236.184', 'latitude': 33.15... |
Returns (ip, country_code, host) tuple of the IP address.
:param ip: IP address
:param exceptions: Raise Exception or not
:param timeout: Timeout in seconds. Note that timeout only affects geo IP part, not getting host name.
:return: (ip, country_code, host)
def get_ip_info(ip: str, exceptions: bool=Fa... |
Determines if this system is on AWS
:return: bool True if this system is running on AWS
def is_aws():
"""Determines if this system is on AWS
:return: bool True if this system is running on AWS
"""
log = logging.getLogger(mod_logger + '.is_aws')
log.info('Querying AWS meta data URL: {u}'.forma... |
Gets the instance ID of this EC2 instance
:return: String instance ID or None
def get_instance_id():
"""Gets the instance ID of this EC2 instance
:return: String instance ID or None
"""
log = logging.getLogger(mod_logger + '.get_instance_id')
# Exit if not running on AWS
if not is_aws():... |
Gets the VPC ID for this EC2 instance
:return: String instance ID or None
def get_vpc_id_from_mac_address():
"""Gets the VPC ID for this EC2 instance
:return: String instance ID or None
"""
log = logging.getLogger(mod_logger + '.get_vpc_id')
# Exit if not running on AWS
if not is_aws():
... |
Gets the AWS Availability Zone ID for this system
:return: (str) Availability Zone ID where this system lives
def get_availability_zone():
"""Gets the AWS Availability Zone ID for this system
:return: (str) Availability Zone ID where this system lives
"""
log = logging.getLogger(mod_logger + '.ge... |
Gets the AWS Region ID for this system
:return: (str) AWS Region ID where this system lives
def get_region():
"""Gets the AWS Region ID for this system
:return: (str) AWS Region ID where this system lives
"""
log = logging.getLogger(mod_logger + '.get_region')
# First get the availability zo... |
Determines the MAC address to use for querying the AWS
meta data service for network related queries
:return: (str) MAC address for the eth0 interface
:raises: AWSMetaDataError
def get_primary_mac_address():
"""Determines the MAC address to use for querying the AWS
meta data service for network re... |
Set the new value for the attribute separator.
When the new value is assigned a new tree is generated.
def attr_sep(self, new_sep: str) -> None:
"""Set the new value for the attribute separator.
When the new value is assigned a new tree is generated.
"""
self._... |
Compares two URLs/paths and returns True if they point to same URI.
For example, querystring parameters can be different order but URLs are still equal.
:param a: URL/path
:param b: URL/path
:return: True if URLs/paths are equal
def url_equals(a: str, b: str) -> bool:
"""
Compares two URLs/path... |
Modifies existing URL by setting/overriding specified query string parameters.
Note: Does not support multiple querystring parameters with identical name.
:param url: Base URL/path to modify
:param new_params: Querystring parameters to set/override (dict)
:return: New URL/path
def url_mod(url: str, new... |
Parses hostname from URL.
:param url: URL
:return: hostname
def url_host(url: str) -> str:
"""
Parses hostname from URL.
:param url: URL
:return: hostname
"""
from urllib.parse import urlparse
res = urlparse(url)
return res.netloc.split(':')[0] if res.netloc else '' |
This gives us a dictionary of nominal values from a dictionary of uncertainties
def ufloatDict_nominal(self, ufloat_dict):
'This gives us a dictionary of nominal values from a dictionary of uncertainties'
return OrderedDict(izip(ufloat_dict.keys(), map(lambda x: x.nominal_value, ufloat_dict.values()))) |
This gives us a dictionary of nominal values from a dictionary of uncertainties
def ufloatDict_stdev(self, ufloat_dict):
'This gives us a dictionary of nominal values from a dictionary of uncertainties'
return OrderedDict(izip(ufloat_dict.keys(), map(lambda x: x.std_dev, ufloat_dict.values()))) |
Build the documentation for the project.
Args:
recreate (bool):
If set to **True**, the build and output directories will be cleared
prior to generating the docs.
gen_index (bool):
If set to **True**, it will generate top-level index file for the
refe... |
Generate reference documentation for the project.
This will use **sphinx-refdoc** to generate the source .rst files for the
reference documentation.
Args:
gen_index (bool):
Set it to **True** if you want to generate the index file with the
list of top-level packages. This i... |
Generate the ID-NAME map dict
:param sdk: CloudGenix API constructor
:param reverse: Generate reverse name-> ID map as well, return tuple with both.
:return: ID Name dictionary
def generate_id_name_map(sdk, reverse=False):
"""
Generate the ID-NAME map dict
:param sdk: CloudGenix API constructor... |
Reverse sorts a #dict by a given key, optionally returning it as a
#tuple. By default, the @dict is sorted by it's value.
@dict: the #dict you wish to sorts
@key: the #sorted key to use
@as_tuple: returns result as a #tuple ((k, v),...)
-> :class:OrderedDict or #tuple
def revr... |
Sorts a #dict by a given key, optionally returning it as a
#tuple. By default, the @dict is sorted by it's value.
@dict: the #dict you wish to sorts
@key: the #sorted key to use
@as_tuple: returns result as a #tuple ((k, v),...)
-> :class:OrderedDict or #tuple
def rank_dict(di... |
Finds a key in @obj via a period-delimited string @name.
@obj: (#dict)
@name: (#str) |.|-separated keys to search @obj in
..
obj = {'foo': {'bar': {'baz': True}}}
getitem_in(obj, 'foo.bar.baz')
..
|True|
def getitem_in(obj, name):
""" Finds a key in @... |
Create a new release.
It will bump the current version number and create a release branch called
`release/<version>` with one new commit (the version bump).
**Example Config**::
\b
version_file: 'src/mypkg/__init__.py'
**Examples**::
\b
$ peltak release start patch ... |
Tag the current commit with as the current version release.
This should be the same commit as the one that's uploaded as the release
(to pypi for example).
**Example Config**::
\b
version_file: 'src/mypkg/__init__.py'
Examples::
$ peltak release tag # Tag the curren... |
This function asks for a location file address from the command terminal
it checks if the file exists before proceeding with the code
"question" is a string that is presented to the user.
"default_address" is the presumed file location.
def query_file_location(question, default_address):
"""
This ... |
This method establishes the output files from pycloudy grids
For these simulations in which we are only want to calculate the emissivities from the hydrogen and helium lines
most of the default files from pycloudy outputs are not required
:return:
def declare_output_files():
"""
This method establ... |
Limits name length to specified length. Tries to keep name as human-readable an natural as possible.
:param first_name: First name
:param last_name: Last name
:param max_length: Maximum length
:return: Full name of shortened version depending on length
def format_full_name(first_name: str, last_name: s... |
Formats timedelta to readable format, e.g. 1h30min.
:param dt: timedelta
:return: str
def format_timedelta(dt: timedelta) -> str:
"""
Formats timedelta to readable format, e.g. 1h30min.
:param dt: timedelta
:return: str
"""
seconds = int(dt.total_seconds())
days, remainder = divmod(... |
Formats XML document as human-readable plain text.
:param xml_str: str (Input XML str)
:param exceptions: Raise exceptions on error
:return: str (Formatted XML str)
def format_xml(xml_str: str, exceptions: bool=False):
"""
Formats XML document as human-readable plain text.
:param xml_str: str (... |
Handler starting the asyncio part.
def worker_allocator(self, async_loop, to_do, **kwargs):
""" Handler starting the asyncio part. """
d = kwargs
threading.Thread(
target=self._asyncio_thread, args=(async_loop, to_do, d)
).start() |
Sends a mail using the configured mail server for Pulsar. See mailgun documentation at
https://documentation.mailgun.com/en/latest/user_manual.html#sending-via-api for specifics.
Args:
form: `dict`. The mail form fields, i.e. 'to', 'from', ...
Returns:
`requests.models.Response` instanc... |
Determines whether the biosample is part of a ChipseqExperiment or SingleCellSorting
Experiment, and if so, returns the associated experiment as a models.Model instance that
is one of those two classes. The biosample is determined to be part of a ChipseqExperiment if the Biosample.chipseq_experiment_id
attr... |
Clean up a multiple-line, potentially multiple-paragraph text
string. This is used to extract the first paragraph of a string
and eliminate line breaks and indentation. Lines will be joined
together by a single space.
:param text: The text string to clean up. It is safe to pass
``No... |
Decorator used to specify the program name for the console script
help message.
:param text: The text to use for the program name.
def prog(text):
"""
Decorator used to specify the program name for the console script
help message.
:param text: The text to use for the program name.
"""
... |
Decorator used to specify a usage string for the console script
help message.
:param text: The text to use for the usage.
def usage(text):
"""
Decorator used to specify a usage string for the console script
help message.
:param text: The text to use for the usage.
"""
def decorator(f... |
Decorator used to specify a short description of the console
script. This can be used to override the default, which is
derived from the docstring of the function.
:param text: The text to use for the description.
def description(text):
"""
Decorator used to specify a short description of the con... |
Decorator used to specify an epilog for the console script help
message.
:param text: The text to use for the epilog.
def epilog(text):
"""
Decorator used to specify an epilog for the console script help
message.
:param text: The text to use for the epilog.
"""
def decorator(func):
... |
Decorator used to specify the formatter class for the console
script.
:param klass: The formatter class to use.
def formatter_class(klass):
"""
Decorator used to specify the formatter class for the console
script.
:param klass: The formatter class to use.
"""
def decorator(func):
... |
Decorator used to specify an argument taken by the console script.
Positional and keyword arguments have the same meaning as those
given to ``argparse.ArgumentParser.add_argument()``.
def argument(*args, **kwargs):
"""
Decorator used to specify an argument taken by the console script.
Positional an... |
Decorator used to specify an argument group. Keyword arguments
have the same meaning as those given to
``argparse.ArgumentParser.add_argument_group()``.
Arguments may be placed in a given argument group by passing the
``group`` keyword argument to @argument().
:param group: The name of the argume... |
Decorator used to specify alternate keyword arguments to pass to
the ``argparse.ArgumentParser.add_subparsers()`` call.
def subparsers(**kwargs):
"""
Decorator used to specify alternate keyword arguments to pass to
the ``argparse.ArgumentParser.add_subparsers()`` call.
"""
def decorator(func):... |
Decorator used to load subcommands from a given ``pkg_resources``
entrypoint group. Each function must be appropriately decorated
with the ``cli_tools`` decorators to be considered an extension.
:param group: The name of the ``pkg_resources`` entrypoint group.
def load_subcommands(group):
"""
Dec... |
Collapse a sub-tree.
def _collapse_subtree(self, name, recursive=True):
"""Collapse a sub-tree."""
oname = name
children = self._db[name]["children"]
data = self._db[name]["data"]
del_list = []
while (len(children) == 1) and (not data):
del_list.append(name)
... |
Create intermediate nodes if hierarchy does not exist.
def _create_intermediate_nodes(self, name):
"""Create intermediate nodes if hierarchy does not exist."""
hierarchy = self._split_node_name(name, self.root_name)
node_tree = [
self.root_name
+ self._node_separator
... |
Create new tree node.
def _create_node(self, name, parent, children, data):
"""Create new tree node."""
self._db[name] = {"parent": parent, "children": children, "data": data} |
Delete subtree private method.
No argument validation and usage of getter/setter private methods is
used for speed
def _delete_subtree(self, nodes):
"""
Delete subtree private method.
No argument validation and usage of getter/setter private methods is
used for speed
... |
Find common prefix between two nodes.
def _find_common_prefix(self, node1, node2):
"""Find common prefix between two nodes."""
tokens1 = [item.strip() for item in node1.split(self.node_separator)]
tokens2 = [item.strip() for item in node2.split(self.node_separator)]
ret = []
for... |
Print a row (leaf) of tree.
:param name: Full node name
:type name: string
:param lparent: Position in full node name of last separator before
node to be printed
:type lparent: integer
:param pre1: Connector next to node name, either a null character ... |
Rename node private method.
No argument validation and usage of getter/setter private methods is
used for speed
def _rename_node(self, name, new_name):
"""
Rename node private method.
No argument validation and usage of getter/setter private methods is
used for speed
... |
Search_tree for nodes that contain a specific hierarchy name.
def _search_tree(self, name):
"""Search_tree for nodes that contain a specific hierarchy name."""
tpl1 = "{sep}{name}{sep}".format(sep=self._node_separator, name=name)
tpl2 = "{sep}{name}".format(sep=self._node_separator, name=name)
... |
Validate NodeName pseudo-type.
def _validate_node_name(self, var_value):
"""Validate NodeName pseudo-type."""
# pylint: disable=R0201
var_values = var_value if isinstance(var_value, list) else [var_value]
for item in var_values:
if (not isinstance(item, str)) or (
... |
Validate NodeWithData pseudo-type.
def _validate_nodes_with_data(self, names):
"""Validate NodeWithData pseudo-type."""
names = names if isinstance(names, list) else [names]
if not names:
raise RuntimeError("Argument `nodes` is not valid")
for ndict in names:
if ... |
r"""
Add nodes to tree.
:param nodes: Node(s) to add with associated data. If there are
several list items in the argument with the same node
name the resulting node data is a list with items
corresponding to the data of each entry in th... |
r"""
Collapse a sub-tree.
Nodes that have a single child and no data are combined with their
child as a single tree node
:param name: Root of the sub-tree to collapse
:type name: :ref:`NodeName`
:param recursive: Flag that indicates whether the collapse operation
... |
r"""
Copy a sub-tree from one sub-node to another.
Data is added if some nodes of the source sub-tree exist in the
destination sub-tree
:param source_name: Root node of the sub-tree to copy from
:type source_name: :ref:`NodeName`
:param dest_name: Root node of the sub... |
r"""
Delete hierarchy levels from all nodes in the tree.
:param nodes: Prefix to delete
:type nodes: :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not a valid prefix)
* RuntimeError (Argument \`name\` is not valid)
For example:
... |
r"""
Delete nodes (and their sub-trees) from the tree.
:param nodes: Node(s) to delete
:type nodes: :ref:`NodeName` or list of :ref:`NodeName`
:raises:
* RuntimeError (Argument \`nodes\` is not valid)
* RuntimeError (Node *[node_name]* not in tree)
Using th... |
r"""
Flatten sub-tree.
Nodes that have children and no data are merged with each child
:param name: Ending hierarchy node whose sub-trees are to be
flattened
:type name: :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
... |
r"""
Get the children node names of a node.
:param name: Parent node name
:type name: :ref:`NodeName`
:rtype: list of :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tree)
def get_children(self,... |
r"""
Get the data associated with a node.
:param name: Node name
:type name: :ref:`NodeName`
:rtype: any type or list of objects of any type
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tree)
def get_data(se... |
r"""
Get the sub-tree leaf node(s).
:param name: Sub-tree root node name
:type name: :ref:`NodeName`
:rtype: list of :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tree)
def get_leafs(self, nam... |
r"""
Get a tree node structure.
The structure is a dictionary with the following keys:
* **parent** (*NodeName*) Parent node name, :code:`''` if the
node is the root node
* **children** (*list of NodeName*) Children node names, an
empty list if node is a leaf
... |
r"""
Get the list of children structures of a node.
See :py:meth:`ptrie.Trie.get_node` for details about the structure
:param name: Parent node name
:type name: :ref:`NodeName`
:rtype: list
:raises:
* RuntimeError (Argument \`name\` is not valid)
*... |
r"""
Get the parent structure of a node.
See :py:meth:`ptrie.Trie.get_node` for details about the structure
:param name: Child node name
:type name: :ref:`NodeName`
:rtype: dictionary
:raises:
* RuntimeError (Argument \`name\` is not valid)
* Runti... |
r"""
Get all node names in a sub-tree.
:param name: Sub-tree root node name
:type name: :ref:`NodeName`
:rtype: list of :ref:`NodeName`
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tree)
Using the sa... |
r"""
Test if a node is in the tree.
:param name: Node name to search for
:type name: :ref:`NodeName`
:rtype: boolean
:raises: RuntimeError (Argument \`name\` is not valid)
def in_tree(self, name):
r"""
Test if a node is in the tree.
:param name: Node... |
r"""
Test if a node is a leaf node (node with no children).
:param name: Node name
:type name: :ref:`NodeName`
:rtype: boolean
:raises:
* RuntimeError (Argument \`name\` is not valid)
* RuntimeError (Node *[name]* not in tree)
def is_leaf(self, name):
... |
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... |
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... |
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... |
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... |
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
... |
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 : ... |
Seaborn color blind
#0072B2 dark blue
#009E73 green
#D55E00 orangish
#CC79A7 pink
#F0E442 yellow
#56B4E9 cyan
#bcbd22 olive #adicional
#7f7f7f grey
#FFB5B8 skin
def define_format(self, plotStyle, plotSize):
#Default sizes for computer
... |
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
--... |
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 ... |
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... |
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... |
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 ... |
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... |
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... |
Return the sample arithmetic mean of data.
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 |
Calculates the population standard deviation.
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 ... |
Calcuates the median value in a @lst
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[inde... |
: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... |
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
... |
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>|
def hashtag_links(uri, s):
""" Turns hashtag-like strings into HTML links
@uri: /uri/ root... |
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>|
def mentions_links(uri, s):
""" Turns mentions-like strings into HTML links,
@uri: /uri/ r... |
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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.