code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _cumsum(group_idx, a, size, fill_value=None, dtype=None):
"""
N to N aggregate operation of cumsum. Perform cumulative sum for each group.
group_idx = np.array([4, 3, 3, 4, 4, 1, 1, 1, 7, 8, 7, 4, 3, 3, 1, 1])
a = np.array([3, 4, 1, 3, 9, 9, 6, 7, 7, 0, 8, 2, 1, 8, 9, 8])
_cumsum(group_idx, a, ... | N to N aggregate operation of cumsum. Perform cumulative sum for each group.
group_idx = np.array([4, 3, 3, 4, 4, 1, 1, 1, 7, 8, 7, 4, 3, 3, 1, 1])
a = np.array([3, 4, 1, 3, 9, 9, 6, 7, 7, 0, 8, 2, 1, 8, 9, 8])
_cumsum(group_idx, a, np.max(group_idx) + 1)
>>> array([ 3, 4, 5, 6, 15, 9, 15, 22, 7, ... |
def get(self, sid):
"""
Constructs a VerificationContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.verify.v2.service.verification.VerificationContext
:rtype: twilio.rest.verify.v2.service.verification.VerificationContext
"""
... | Constructs a VerificationContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.verify.v2.service.verification.VerificationContext
:rtype: twilio.rest.verify.v2.service.verification.VerificationContext |
def is_possible_type(
self, abstract_type: GraphQLAbstractType, possible_type: GraphQLObjectType
) -> bool:
"""Check whether a concrete type is possible for an abstract type."""
possible_type_map = self._possible_type_map
try:
possible_type_names = possible_type_map[abstr... | Check whether a concrete type is possible for an abstract type. |
def setup_random_seed(seed):
"""Setup the random seed. If the input seed is -1, the code will use a random seed for every run. If it is \
positive, that seed is used for all runs, thereby giving reproducible results.
Parameters
----------
seed : int
The seed of the random number generator.
... | Setup the random seed. If the input seed is -1, the code will use a random seed for every run. If it is \
positive, that seed is used for all runs, thereby giving reproducible results.
Parameters
----------
seed : int
The seed of the random number generator. |
def pickle_dict(items):
'''Returns a new dictionary where values which aren't instances of
basestring are pickled. Also, a new key '_pickled' contains a comma
separated list of keys corresponding to the pickled values.
'''
ret = {}
pickled_keys = []
for key, val in items.items():
if ... | Returns a new dictionary where values which aren't instances of
basestring are pickled. Also, a new key '_pickled' contains a comma
separated list of keys corresponding to the pickled values. |
def parse_string(self, string):
"""Parse ASCII output of JPrintMeta"""
self.log.info("Parsing ASCII data")
if not string:
self.log.warning("Empty metadata")
return
lines = string.splitlines()
application_data = []
application = lines[0].split()[... | Parse ASCII output of JPrintMeta |
def execute(self, method, *args, **kargs):
result = None
'''
max 10 rechecks
'''
for i in range(0, 10):
try:
method_map = {
'get_lead_by_id': self.get_lead_by_id,
'get_multiple_leads_by_filter_type': self.g... | max 10 rechecks |
async def search_participant(self, name, force_update=False):
""" search a participant by (display) name
|methcoro|
Args:
name: display name of the participant
force_update (dfault=False): True to force an update to the Challonge API
Returns:
Partic... | search a participant by (display) name
|methcoro|
Args:
name: display name of the participant
force_update (dfault=False): True to force an update to the Challonge API
Returns:
Participant: None if not found
Raises:
APIException |
def shape(self):
"""Returns a tuple of row, column, (band count if multidimensional)."""
shp = (self.ds.RasterYSize, self.ds.RasterXSize, self.ds.RasterCount)
return shp[:2] if shp[2] <= 1 else shp | Returns a tuple of row, column, (band count if multidimensional). |
def default_start():
"""
Use `sys.argv` for starting parameters. This is the entry-point of `vlcp-start`
"""
(config, daemon, pidfile, startup, fork) = parsearg()
if config is None:
if os.path.isfile('/etc/vlcp.conf'):
config = '/etc/vlcp.conf'
else:
print('/e... | Use `sys.argv` for starting parameters. This is the entry-point of `vlcp-start` |
def follow(ctx, nick, url, force):
"""Add a new source to your followings."""
source = Source(nick, url)
sources = ctx.obj['conf'].following
if not force:
if source.nick in (source.nick for source in sources):
click.confirm("➤ You’re already following {0}. Overwrite?".format(
... | Add a new source to your followings. |
def fetchall(self, mode=5, after=0, parent='any', order_by='id',
limit=100, page=0, asc=1):
"""
Return comments for admin with :param:`mode`.
"""
fields_comments = ['tid', 'id', 'parent', 'created', 'modified',
'mode', 'remote_addr', 'text', 'a... | Return comments for admin with :param:`mode`. |
def type_validator(validator, types, instance, schema):
"""Swagger 1.2 supports parameters of 'type': 'File'. Skip validation of
the 'type' field in this case.
"""
if schema.get('type') == 'File':
return []
return _validators.type_draft3(validator, types, instance, schema) | Swagger 1.2 supports parameters of 'type': 'File'. Skip validation of
the 'type' field in this case. |
def get_fallback_resolution(self):
"""Returns the previous fallback resolution
set by :meth:`set_fallback_resolution`,
or default fallback resolution if never set.
:returns: ``(x_pixels_per_inch, y_pixels_per_inch)``
"""
ppi = ffi.new('double[2]')
cairo.cairo_su... | Returns the previous fallback resolution
set by :meth:`set_fallback_resolution`,
or default fallback resolution if never set.
:returns: ``(x_pixels_per_inch, y_pixels_per_inch)`` |
def as_xml_index(self, basename="/tmp/sitemap.xml"):
"""Return a string of the index for a large list that is split.
All we need to do is determine the number of component sitemaps will
be is and generate their URIs based on a pattern.
Q - should there be a flag to select generation of... | Return a string of the index for a large list that is split.
All we need to do is determine the number of component sitemaps will
be is and generate their URIs based on a pattern.
Q - should there be a flag to select generation of each component sitemap
in order to calculate the md5sum... |
def find():
"""Find a local spark installation.
Will first check the SPARK_HOME env variable, and otherwise
search common installation locations, e.g. from homebrew
"""
spark_home = os.environ.get('SPARK_HOME', None)
if not spark_home:
for path in [
'/usr/local/opt/apache-s... | Find a local spark installation.
Will first check the SPARK_HOME env variable, and otherwise
search common installation locations, e.g. from homebrew |
def parse_timespan_value(s):
"""Parse a string that contains a time span, optionally with a unit like s.
@return the number of seconds encoded by the string
"""
number, unit = split_number_and_unit(s)
if not unit or unit == "s":
return number
elif unit == "min":
return number * 6... | Parse a string that contains a time span, optionally with a unit like s.
@return the number of seconds encoded by the string |
def adjustPoolSize(self, newsize):
"""
Change the target pool size. If we have too many connections already,
ask some to finish what they're doing and die (preferring to kill
connections to the node that already has the most connections). If
we have too few, create more.
... | Change the target pool size. If we have too many connections already,
ask some to finish what they're doing and die (preferring to kill
connections to the node that already has the most connections). If
we have too few, create more. |
def parse_segment(text, version=None, encoding_chars=None, validation_level=None, reference=None):
"""
Parse the given ER7-encoded segment and return an instance of :class:`Segment <hl7apy.core.Segment>`.
:type text: ``str``
:param text: the ER7-encoded string containing the segment to be parsed
:... | Parse the given ER7-encoded segment and return an instance of :class:`Segment <hl7apy.core.Segment>`.
:type text: ``str``
:param text: the ER7-encoded string containing the segment to be parsed
:type version: ``str``
:param version: the HL7 version (e.g. "2.5"), or ``None`` to use the default
... |
def depth_profile(list_, max_depth=None, compress_homogenous=True, compress_consecutive=False, new_depth=False):
r"""
Returns a nested list corresponding the shape of the nested structures
lists represent depth, tuples represent shape. The values of the items do
not matter. only the lengths.
Args:
... | r"""
Returns a nested list corresponding the shape of the nested structures
lists represent depth, tuples represent shape. The values of the items do
not matter. only the lengths.
Args:
list_ (list):
max_depth (None):
compress_homogenous (bool):
compress_consecutive (boo... |
def bs_values_df(run_list, estimator_list, estimator_names, n_simulate,
**kwargs):
"""Computes a data frame of bootstrap resampled values.
Parameters
----------
run_list: list of dicts
List of nested sampling run dicts.
estimator_list: list of functions
Estimators t... | Computes a data frame of bootstrap resampled values.
Parameters
----------
run_list: list of dicts
List of nested sampling run dicts.
estimator_list: list of functions
Estimators to apply to runs.
estimator_names: list of strs
Name of each func in estimator_list.
n_simul... |
def find_modules_with_decorators(path,decorator_module,decorator_name):
'''
Finds all the modules decorated with the specified decorator in the path, file or module specified.
Args :
path : All modules in the directory and its sub-directories will be scanned.
decorato... | Finds all the modules decorated with the specified decorator in the path, file or module specified.
Args :
path : All modules in the directory and its sub-directories will be scanned.
decorator_module : Then full name of the module defining the decorator.
decorator... |
def cumulative_distance(lat, lon,dist_int=None):
'''
;+
; CUMULATIVE_DISTANCE : permet de calculer la distance le long d'une ligne.
;
; @Author : Renaud DUSSURGET, LEGOS/CTOH
; @History :
; - Feb. 2009 : First release (adapted from calcul_distance)
;-
'''
# Defin... | ;+
; CUMULATIVE_DISTANCE : permet de calculer la distance le long d'une ligne.
;
; @Author : Renaud DUSSURGET, LEGOS/CTOH
; @History :
; - Feb. 2009 : First release (adapted from calcul_distance)
;- |
def receive_message(self, message, data):
""" Currently not doing anything with received messages. """
if data['type'] == TYPE_RESPONSE_STATUS:
self.is_launched = True
return True | Currently not doing anything with received messages. |
def show_proportions(adata):
"""Fraction of spliced/unspliced/ambiguous abundances
Arguments
---------
adata: :class:`~anndata.AnnData`
Annotated data matrix.
Returns
-------
Prints the fractions of abundances.
"""
layers_keys = [key for key in ['spliced', 'unspliced', 'amb... | Fraction of spliced/unspliced/ambiguous abundances
Arguments
---------
adata: :class:`~anndata.AnnData`
Annotated data matrix.
Returns
-------
Prints the fractions of abundances. |
def _lexical_chains(self, doc, term_concept_map):
"""
Builds lexical chains, as an adjacency matrix,
using a disambiguated term-concept map.
"""
concepts = list({c for c in term_concept_map.values()})
# Build an adjacency matrix for the graph
# Using the encoding... | Builds lexical chains, as an adjacency matrix,
using a disambiguated term-concept map. |
def charge(self):
"""Species charge"""
if self._reader._level == 3:
# Look for FBC charge
for ns in (FBC_V2, FBC_V1):
charge = self._root.get(_tag('charge', ns))
if charge is not None:
return self._parse_charge_string(charge)
... | Species charge |
def _mom(self, kloc, cache, **kwargs):
"""
Example:
>>> dist = chaospy.J(chaospy.Uniform(), chaospy.Normal())
>>> print(numpy.around(dist.mom([[0, 0, 1], [0, 1, 1]]), 4))
[1. 0. 0.]
>>> d0 = chaospy.Uniform()
>>> dist = chaospy.J(d0, d0+chaospy... | Example:
>>> dist = chaospy.J(chaospy.Uniform(), chaospy.Normal())
>>> print(numpy.around(dist.mom([[0, 0, 1], [0, 1, 1]]), 4))
[1. 0. 0.]
>>> d0 = chaospy.Uniform()
>>> dist = chaospy.J(d0, d0+chaospy.Uniform())
>>> print(numpy.around(dist.mom([1,... |
def parse(self,DXfield):
"""Parse the dx file and construct a DX field object with component classes.
A :class:`field` instance *DXfield* must be provided to be
filled by the parser::
DXfield_object = OpenDX.field(*args)
parse(DXfield_object)
A tokenizer turns th... | Parse the dx file and construct a DX field object with component classes.
A :class:`field` instance *DXfield* must be provided to be
filled by the parser::
DXfield_object = OpenDX.field(*args)
parse(DXfield_object)
A tokenizer turns the dx file into a stream of tokens. A... |
def custom_to_pmrapmdec(pmphi1,pmphi2,phi1,phi2,T=None,degree=False):
"""
NAME:
custom_to_pmrapmdec
PURPOSE:
rotate proper motions in a custom set of sky coordinates (phi1,phi2) to ICRS (ra,dec)
INPUT:
pmphi1 - proper motion in custom (multplied with cos(phi2)) [mas/yr]
... | NAME:
custom_to_pmrapmdec
PURPOSE:
rotate proper motions in a custom set of sky coordinates (phi1,phi2) to ICRS (ra,dec)
INPUT:
pmphi1 - proper motion in custom (multplied with cos(phi2)) [mas/yr]
pmphi2 - proper motion in phi2 [mas/yr]
phi1 - custom longitude
p... |
def coarsen_all_traces(level=2, exponential=False, axes="all", figure=None):
"""
This function does nearest-neighbor coarsening of the data. See
spinmob.fun.coarsen_data for more information.
Parameters
----------
level=2
How strongly to coarsen.
exponential=False
If Tr... | This function does nearest-neighbor coarsening of the data. See
spinmob.fun.coarsen_data for more information.
Parameters
----------
level=2
How strongly to coarsen.
exponential=False
If True, use the exponential method (great for log-x plots).
axes="all"
Which axes... |
def set_grade(
self,
assignment_id,
student_id,
grade_value,
gradebook_id='',
**kwargs
):
"""Set numerical grade for student and assignment.
Set a numerical grade for for a student and assignment. Additional
options
... | Set numerical grade for student and assignment.
Set a numerical grade for for a student and assignment. Additional
options
for grade ``mode`` are: OVERALL_GRADE = ``1``, REGULAR_GRADE = ``2``
To set 'excused' as the grade, enter ``None`` for letter and
numeric grade values,
... |
def CopyToDateTimeString(self):
"""Copies the APFS timestamp to a date and time string.
Returns:
str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#########" or
None if the timestamp is missing or invalid.
"""
if (self._timestamp is None or self._timestamp < self._INT64_MIN or... | Copies the APFS timestamp to a date and time string.
Returns:
str: date and time value formatted as: "YYYY-MM-DD hh:mm:ss.#########" or
None if the timestamp is missing or invalid. |
def chunk(self, regex):
'''FIXME:
'''
chunks = []
for component in self._content:
chunks.extend(
StringComponent(component.placeholder, s) for s in
regex.split(str(component)))
for i, (chunk1, chunk2) in enumerate(
zip(c... | FIXME: |
def switch_to_app(self, package):
"""
activates an app that is specified by package. Selects the first
app it finds in the app list
:param package: name of package/app
:type package: str
:return: None
:rtype: None
"""
log.debug("switching to app '... | activates an app that is specified by package. Selects the first
app it finds in the app list
:param package: name of package/app
:type package: str
:return: None
:rtype: None |
def list_js_files(dir):
"""
Generator for all JavaScript files in the directory, recursively
>>> 'examples/module.js' in list(list_js_files('examples'))
True
"""
for dirpath, dirnames, filenames in os.walk(dir):
for filename in filenames:
if is_js_file(filename):
... | Generator for all JavaScript files in the directory, recursively
>>> 'examples/module.js' in list(list_js_files('examples'))
True |
def merge_dictionaries(a, b):
"""Merge two dictionaries; duplicate keys get value from b."""
res = {}
for k in a:
res[k] = a[k]
for k in b:
res[k] = b[k]
return res | Merge two dictionaries; duplicate keys get value from b. |
def normalized(self):
""":obj:`DualQuaternion`: This quaternion with qr normalized.
"""
qr = self.qr /1./ np.linalg.norm(self.qr)
return DualQuaternion(qr, self.qd, True) | :obj:`DualQuaternion`: This quaternion with qr normalized. |
def from_directory(cls, directory):
"""Create a security object from a directory.
Relies on standard names for each file (``skein.crt`` and
``skein.pem``)."""
cert_path = os.path.join(directory, 'skein.crt')
key_path = os.path.join(directory, 'skein.pem')
for path, name ... | Create a security object from a directory.
Relies on standard names for each file (``skein.crt`` and
``skein.pem``). |
def find_raw_devices(vendor=None, product=None, serial_number=None,
custom_match=None, **kwargs):
"""Find connected USB RAW devices. See usbutil.find_devices for more info.
"""
def is_usbraw(dev):
if custom_match and not custom_match(dev):
return False
return... | Find connected USB RAW devices. See usbutil.find_devices for more info. |
def log(self, n=None, template=None):
"""
Run the repository log command
Returns:
str: output of log command (``bzr log -l <n>``)
"""
cmd = ['bzr', 'log']
if n:
cmd.append('-l%d' % n)
return self.sh(cmd, shell=False) | Run the repository log command
Returns:
str: output of log command (``bzr log -l <n>``) |
def readSTATION0(path, stations):
"""
Read a Seisan STATION0.HYP file on the path given.
Outputs the information, and writes to station.dat file.
:type path: str
:param path: Path to the STATION0.HYP file
:type stations: list
:param stations: Stations to look for
:returns: List of tup... | Read a Seisan STATION0.HYP file on the path given.
Outputs the information, and writes to station.dat file.
:type path: str
:param path: Path to the STATION0.HYP file
:type stations: list
:param stations: Stations to look for
:returns: List of tuples of station, lat, long, elevation
:rtyp... |
def sg_int(tensor, opt):
r"""Casts a tensor to intx.
See `tf.cast()` in tensorflow.
Args:
tensor: A `Tensor` or `SparseTensor` (automatically given by chain).
opt:
name: If provided, it replaces current tensor's name.
Returns:
A `Tensor` or `SparseTensor` with same shape... | r"""Casts a tensor to intx.
See `tf.cast()` in tensorflow.
Args:
tensor: A `Tensor` or `SparseTensor` (automatically given by chain).
opt:
name: If provided, it replaces current tensor's name.
Returns:
A `Tensor` or `SparseTensor` with same shape as `tensor`. |
def write_squonk_datasetmetadata(outputBase, thinOutput, valueClassMappings, datasetMetaProps, fieldMetaProps):
"""This is a temp hack to write the minimal metadata that Squonk needs.
Will needs to be replaced with something that allows something more complete to be written.
:param outputBase: Base name fo... | This is a temp hack to write the minimal metadata that Squonk needs.
Will needs to be replaced with something that allows something more complete to be written.
:param outputBase: Base name for the file to write to
:param thinOutput: Write only new data, not structures. Result type will be BasicObject
... |
def convert(credentials):
"""Convert oauth2client credentials to google-auth credentials.
This class converts:
- :class:`oauth2client.client.OAuth2Credentials` to
:class:`google.oauth2.credentials.Credentials`.
- :class:`oauth2client.client.GoogleCredentials` to
:class:`google.oauth2.crede... | Convert oauth2client credentials to google-auth credentials.
This class converts:
- :class:`oauth2client.client.OAuth2Credentials` to
:class:`google.oauth2.credentials.Credentials`.
- :class:`oauth2client.client.GoogleCredentials` to
:class:`google.oauth2.credentials.Credentials`.
- :class... |
def split_into(iterable, sizes):
"""Yield a list of sequential items from *iterable* of length 'n' for each
integer 'n' in *sizes*.
>>> list(split_into([1,2,3,4,5,6], [1,2,3]))
[[1], [2, 3], [4, 5, 6]]
If the sum of *sizes* is smaller than the length of *iterable*, then the
remaining i... | Yield a list of sequential items from *iterable* of length 'n' for each
integer 'n' in *sizes*.
>>> list(split_into([1,2,3,4,5,6], [1,2,3]))
[[1], [2, 3], [4, 5, 6]]
If the sum of *sizes* is smaller than the length of *iterable*, then the
remaining items of *iterable* will not be returned.... |
def ls(args):
"""
List S3 buckets. See also "aws s3 ls". Use "aws s3 ls NAME" to list bucket contents.
"""
table = []
for bucket in filter_collection(resources.s3.buckets, args):
bucket.LocationConstraint = clients.s3.get_bucket_location(Bucket=bucket.name)["LocationConstraint"]
clou... | List S3 buckets. See also "aws s3 ls". Use "aws s3 ls NAME" to list bucket contents. |
def write_peps(self, peps, reverse_seqs):
"""Writes peps to db. We can reverse to be able to look up
peptides that have some amino acids missing at the N-terminal.
This way we can still use the index.
"""
if reverse_seqs:
peps = [(x[0][::-1],) for x in peps]
c... | Writes peps to db. We can reverse to be able to look up
peptides that have some amino acids missing at the N-terminal.
This way we can still use the index. |
def merge(self, data, clean=False, validate=False):
""" Merge a dict with the model
This is needed because schematics doesn't auto cast
values when assigned. This method allows us to ensure
incoming data & existing data on a model are always
coerced properly.
We create ... | Merge a dict with the model
This is needed because schematics doesn't auto cast
values when assigned. This method allows us to ensure
incoming data & existing data on a model are always
coerced properly.
We create a temporary model instance with just the new
data so all... |
def image_list(auth=None, **kwargs):
'''
List images
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_list
salt '*' glanceng.image_list
'''
cloud = get_operator_cloud(auth)
kwargs = _clean_kwargs(**kwargs)
return cloud.list_images(**kwargs) | List images
CLI Example:
.. code-block:: bash
salt '*' glanceng.image_list
salt '*' glanceng.image_list |
def _init(self):
"""Given GO ids and GOTerm objects, create mini GO dag."""
for goid in self.godag.go_sources:
goobj = self.godag.go2obj[goid]
self.godag.go2obj[goid] = goobj
# Traverse up parents
if self.traverse_parent and goid not in self.seen_cids:
... | Given GO ids and GOTerm objects, create mini GO dag. |
def f1_score(y_true, y_pred, average='micro', suffix=False):
"""Compute the F1 score.
The F1 score can be interpreted as a weighted average of the precision and
recall, where an F1 score reaches its best value at 1 and worst score at 0.
The relative contribution of precision and recall to the F1 score ... | Compute the F1 score.
The F1 score can be interpreted as a weighted average of the precision and
recall, where an F1 score reaches its best value at 1 and worst score at 0.
The relative contribution of precision and recall to the F1 score are
equal. The formula for the F1 score is::
F1 = 2 * (... |
def _parse_memory_embedded_health(self, data):
"""Parse the get_host_health_data() for essential properties
:param data: the output returned by get_host_health_data()
:returns: memory size in MB.
:raises IloError, if unable to get the memory details.
"""
memory_mb = 0
... | Parse the get_host_health_data() for essential properties
:param data: the output returned by get_host_health_data()
:returns: memory size in MB.
:raises IloError, if unable to get the memory details. |
def is_ipv6_ok(soft_fail=False):
"""
Check if IPv6 support is present and ip6tables functional
:param soft_fail: If set to True and IPv6 support is broken, then reports
that the host doesn't have IPv6 support, otherwise a
UFWIPv6Error exception is raised.
:re... | Check if IPv6 support is present and ip6tables functional
:param soft_fail: If set to True and IPv6 support is broken, then reports
that the host doesn't have IPv6 support, otherwise a
UFWIPv6Error exception is raised.
:returns: True if IPv6 is working, False otherwi... |
def rowsBeforeValue(self, value, count):
"""
Retrieve display data for rows with sort-column values less than the
given value.
@type value: Some type compatible with the current sort column.
@param value: Starting value in the index for the current sort column
at which t... | Retrieve display data for rows with sort-column values less than the
given value.
@type value: Some type compatible with the current sort column.
@param value: Starting value in the index for the current sort column
at which to start returning results. Rows with a column value for the
... |
def set_wrappable_term(self, v, term):
"""Set the Root.Description, possibly splitting long descriptions across multiple terms. """
import textwrap
for t in self['Root'].find(term):
self.remove_term(t)
for l in textwrap.wrap(v, 80):
self['Root'].new_term(term, ... | Set the Root.Description, possibly splitting long descriptions across multiple terms. |
def _arburg2(X, order):
"""This version is 10 times faster than arburg, but the output rho is not correct.
returns [1 a0,a1, an-1]
"""
x = np.array(X)
N = len(x)
if order <= 0.:
raise ValueError("order must be > 0")
# Initialisation
# ------ rho, den
rho = sum(abs(x)**2.... | This version is 10 times faster than arburg, but the output rho is not correct.
returns [1 a0,a1, an-1] |
def join_state_collections( collection_a, collection_b):
"""
Warning: This is a very naive join. Only use it when measures and groups will remain entirely within each subcollection.
For example: if each collection has states grouped by date and both include the same date, then the new collection
w... | Warning: This is a very naive join. Only use it when measures and groups will remain entirely within each subcollection.
For example: if each collection has states grouped by date and both include the same date, then the new collection
would have both of those groups, likely causing problems for group mea... |
def RAMON(typ):
"""
Takes str or int, returns class type
"""
if six.PY2:
lookup = [str, unicode]
elif six.PY3:
lookup = [str]
if type(typ) is int:
return _ramon_types[typ]
elif type(typ) in lookup:
return _ramon_typ... | Takes str or int, returns class type |
def serach_path():
"""Return potential locations of IACA installation."""
operating_system = get_os()
# 1st choice: in ~/.kerncraft/iaca-{}
# 2nd choice: in package directory / iaca-{}
return [os.path.expanduser("~/.kerncraft/iaca/{}/".format(operating_system)),
os.path.abspath(os.path.d... | Return potential locations of IACA installation. |
def subscribe_topic(self, topics=[], pattern=None):
"""Subscribe to a list of topics, or a topic regex pattern.
- ``topics`` (list): List of topics for subscription.
- ``pattern`` (str): Pattern to match available topics. You must provide either topics or pattern,
but not both... | Subscribe to a list of topics, or a topic regex pattern.
- ``topics`` (list): List of topics for subscription.
- ``pattern`` (str): Pattern to match available topics. You must provide either topics or pattern,
but not both. |
def dispatch(self, receiver):
''' Dispatch handling of this event to a receiver.
This method will invoke ``receiver._session_callback_added`` if
it exists.
'''
super(SessionCallbackAdded, self).dispatch(receiver)
if hasattr(receiver, '_session_callback_added'):
... | Dispatch handling of this event to a receiver.
This method will invoke ``receiver._session_callback_added`` if
it exists. |
def get_all_scores(self, motifs, dbmotifs, match, metric, combine,
pval=False, parallel=True, trim=None, ncpus=None):
"""Pairwise comparison of a set of motifs compared to reference motifs.
Parameters
----------
motifs : list
List of Motif instan... | Pairwise comparison of a set of motifs compared to reference motifs.
Parameters
----------
motifs : list
List of Motif instances.
dbmotifs : list
List of Motif instances.
match : str
Match can be "partial", "subtotal" or "total". Not all met... |
def xml_findall(xpath):
"""Find a list of XML elements via xpath."""
def xpath_findall(value):
validate(ET.iselement, value)
return value.findall(xpath)
return transform(xpath_findall) | Find a list of XML elements via xpath. |
def data(self):
"""Data for packet creation."""
header = struct.pack('>BLB',
4, # version
self.created, # creation
self.algo_id) # public key algorithm ID
oid = util.prefix_len('>B', self.curve_i... | Data for packet creation. |
def add_log_type(name, display, color, bcolor):
"""
name : call name (A-Z and '_')
display : display message in [-]
color : text color (see bashutils.colors)
bcolor : background color (see bashutils.colors)
"""
global MESSAGE_LOG
v_name = name.replace(" ", "_").upper()
val = 0
lk... | name : call name (A-Z and '_')
display : display message in [-]
color : text color (see bashutils.colors)
bcolor : background color (see bashutils.colors) |
def do_macro_arg(parser, token):
""" Function taking a parsed template tag
to a MacroArgNode.
"""
# macro_arg takes no arguments, so we don't
# need to split the token/do validation.
nodelist = parser.parse(('endmacro_arg',))
parser.delete_first_token()
# simply save the contents to a Ma... | Function taking a parsed template tag
to a MacroArgNode. |
def has_abiext(self, ext, single_file=True):
"""
Returns the absolute path of the ABINIT file with extension ext.
Support both Fortran files and netcdf files. In the later case,
we check whether a file with extension ext + ".nc" is present
in the directory. Returns empty string i... | Returns the absolute path of the ABINIT file with extension ext.
Support both Fortran files and netcdf files. In the later case,
we check whether a file with extension ext + ".nc" is present
in the directory. Returns empty string is file is not present.
Raises:
`ValueError` ... |
def largest_graph(mol):
"""Return a molecule which has largest graph in the compound
Passing single molecule object will results as same as molutil.clone
"""
mol.require("Valence")
mol.require("Topology")
m = clone(mol) # Avoid modification of original object
if m.isolated:
for k in... | Return a molecule which has largest graph in the compound
Passing single molecule object will results as same as molutil.clone |
def _pushMessages(self):
""" Internal callback used to make sure the msg list keeps moving. """
# This continues to get itself called until no msgs are left in list.
self.showStatus('')
if len(self._statusMsgsToShow) > 0:
self.top.after(200, self._pushMessages) | Internal callback used to make sure the msg list keeps moving. |
def copy(self):
"""
Copy the selected text to the clipboard. If no text was selected, the
entire line is copied (this feature can be turned off by
setting :attr:`select_line_on_copy_empty` to False.
"""
if self.select_line_on_copy_empty and not self.textCursor().hasSelect... | Copy the selected text to the clipboard. If no text was selected, the
entire line is copied (this feature can be turned off by
setting :attr:`select_line_on_copy_empty` to False. |
def _compute_ymean(self, **kwargs):
"""Compute the (weighted) mean of the y data"""
y = np.asarray(kwargs.get('y', self.y))
dy = np.asarray(kwargs.get('dy', self.dy))
if dy.size == 1:
return np.mean(y)
else:
return np.average(y, weights=1 / dy ** 2) | Compute the (weighted) mean of the y data |
async def processClaims(self, allClaims: Dict[ID, Claims]):
"""
Processes and saves received Claims.
:param claims: claims to be processed and saved for each claim
definition.
"""
res = []
for schemaId, (claim_signature, claim_attributes) in allClaims.items():
... | Processes and saves received Claims.
:param claims: claims to be processed and saved for each claim
definition. |
def initiate_close(self):
"""Start closing the sender (won't complete until all data is sent)."""
self._running = False
self._accumulator.close()
self.wakeup() | Start closing the sender (won't complete until all data is sent). |
def list_ctx(self):
"""Returns a list of contexts this parameter is initialized on."""
if self._data is None:
if self._deferred_init:
return self._deferred_init[1]
raise RuntimeError("Parameter '%s' has not been initialized"%self.name)
return self._ctx_lis... | Returns a list of contexts this parameter is initialized on. |
def create_user(self, user_name, path='/'):
"""
Create a user.
:type user_name: string
:param user_name: The name of the new user
:type path: string
:param path: The path in which the user will be created.
Defaults to /.
"""
params ... | Create a user.
:type user_name: string
:param user_name: The name of the new user
:type path: string
:param path: The path in which the user will be created.
Defaults to /. |
def _render(self, template, context, is_file, at_paths=None,
at_encoding=ENCODING, **kwargs):
"""
Render given template string and return the result.
:param template: Template content
:param context: A dict or dict-like object to instantiate given
template fi... | Render given template string and return the result.
:param template: Template content
:param context: A dict or dict-like object to instantiate given
template file
:param is_file: True if given `template` is a filename
:param at_paths: Template search paths
:param at... |
def get_all_instances(self, instance_ids=None, filters=None):
"""
Retrieve all the instances associated with your account.
:type instance_ids: list
:param instance_ids: A list of strings of instance IDs
:type filters: dict
:param filters: Optional filters that can be us... | Retrieve all the instances associated with your account.
:type instance_ids: list
:param instance_ids: A list of strings of instance IDs
:type filters: dict
:param filters: Optional filters that can be used to limit
the results returned. Filters are provided
... |
def predict(self, x):
"""
Predict values for a single data point or an RDD of points
using the model trained.
"""
if isinstance(x, RDD):
return x.map(lambda v: self.predict(v))
x = _convert_to_vector(x)
if self.numClasses == 2:
margin = se... | Predict values for a single data point or an RDD of points
using the model trained. |
def load(filename):
"""
Load the state from the given file, moving to the file's directory during
load (temporarily, moving back after loaded)
Parameters
----------
filename : string
name of the file to open, should be a .pkl file
"""
path, name = os.path.split(filename)
pat... | Load the state from the given file, moving to the file's directory during
load (temporarily, moving back after loaded)
Parameters
----------
filename : string
name of the file to open, should be a .pkl file |
def get_form(self, request, obj=None, **kwargs):
"""Get a :class:`Page <pages.admin.forms.PageForm>` for the
:class:`Page <pages.models.Page>` and modify its fields depending on
the request."""
template = get_template_from_request(request, obj)
#model = create_page_model(get_pl... | Get a :class:`Page <pages.admin.forms.PageForm>` for the
:class:`Page <pages.models.Page>` and modify its fields depending on
the request. |
def abort_copy_file(self, share_name, directory_name, file_name, copy_id, timeout=None):
'''
Aborts a pending copy_file operation, and leaves a destination file
with zero length and full metadata.
:param str share_name:
Name of destination share.
:param str direct... | Aborts a pending copy_file operation, and leaves a destination file
with zero length and full metadata.
:param str share_name:
Name of destination share.
:param str directory_name:
The path to the directory.
:param str file_name:
Name of destinatio... |
def reconstructed_pixelization_from_solution_vector(self, solution_vector):
"""Given the solution vector of an inversion (see *inversions.Inversion*), determine the reconstructed \
pixelization of the rectangular pixelization by using the mapper."""
recon = mapping_util.map_unmasked_1d_array_to_... | Given the solution vector of an inversion (see *inversions.Inversion*), determine the reconstructed \
pixelization of the rectangular pixelization by using the mapper. |
def handle_exception(exc_info=None, source_hint=None, tb_override=_NO):
"""Exception handling helper. This is used internally to either raise
rewritten exceptions or return a rendered traceback for the template.
"""
global _make_traceback
if exc_info is None: # pragma: no cover
exc_info =... | Exception handling helper. This is used internally to either raise
rewritten exceptions or return a rendered traceback for the template. |
def traverse_layout(root, callback):
"""
Tree walker and invokes the callback as it
traverse pdf object tree
"""
callback(root)
if isinstance(root, collections.Iterable):
for child in root:
traverse_layout(child, callback) | Tree walker and invokes the callback as it
traverse pdf object tree |
def _check_file(self):
"""
Check if the file exists and has the expected password reference.
"""
if not os.path.exists(self.file_path):
return False
self._migrate()
config = configparser.RawConfigParser()
config.read(self.file_path)
try:
... | Check if the file exists and has the expected password reference. |
def deregister(self, reg_data, retry=True, interval=1, timeout=3):
"""
Deregister model/view of this bundle
"""
Retry(target=self.publish.direct.delete,
args=("/controller/registration", reg_data,),
kwargs={"timeout": timeout},
options={"retry": ... | Deregister model/view of this bundle |
def metadata(self):
"""return a cp:metadata element with the metadata in the document"""
md = self.xml(src="docProps/core.xml")
if md is None:
md = XML(root=etree.Element("{%(cp)s}metadata" % self.NS))
return md.root | return a cp:metadata element with the metadata in the document |
def _add_sub_elements_from_dict(parent, sub_dict):
"""
Add SubElements to the parent element.
:param parent: ElementTree.Element: The parent element for the newly created SubElement.
:param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema`
method docstring for more information. e.g.:
{"e... | Add SubElements to the parent element.
:param parent: ElementTree.Element: The parent element for the newly created SubElement.
:param sub_dict: dict: Used to create a new SubElement. See `dict_to_xml_schema`
method docstring for more information. e.g.:
{"example": {
"attrs": {
"key1": "value1",
...
... |
def recarrayequalspairs(X,Y,weak=True):
"""
Indices of elements in a sorted numpy recarray (or ndarray with
structured dtype) equal to those in another.
Record array version of func:`tabular.fast.equalspairs`, but slightly
different because the concept of being sorted is less well-defined for a
... | Indices of elements in a sorted numpy recarray (or ndarray with
structured dtype) equal to those in another.
Record array version of func:`tabular.fast.equalspairs`, but slightly
different because the concept of being sorted is less well-defined for a
record array.
Given numpy recarray `X` and ... |
def replica_lag(self, **kwargs):
"""
Returns the current replication lag in seconds between the master and replica databases.
:returns: float
"""
if not self._use_replica():
return 0
try:
kwargs['stack'] = self.stack_mark(inspect.stack())
... | Returns the current replication lag in seconds between the master and replica databases.
:returns: float |
def disk_pick_polar(n=1, rng=None):
"""Return vectors uniformly picked on the unit disk.
The unit disk is the space enclosed by the unit circle.
Vectors are in a polar representation.
Parameters
----------
n: integer
Number of points to return.
Returns
-------
r: array, sha... | Return vectors uniformly picked on the unit disk.
The unit disk is the space enclosed by the unit circle.
Vectors are in a polar representation.
Parameters
----------
n: integer
Number of points to return.
Returns
-------
r: array, shape (n, 2)
Sample vectors. |
def assert_dict_eq(expected, actual, number_tolerance=None, dict_path=[]):
"""Asserts that two dictionaries are equal, producing a custom message if they are not."""
assert_is_instance(expected, dict)
assert_is_instance(actual, dict)
expected_keys = set(expected.keys())
actual_keys = set(actual.key... | Asserts that two dictionaries are equal, producing a custom message if they are not. |
def _unascii(s):
"""Unpack `\\uNNNN` escapes in 's' and encode the result as UTF-8
This method takes the output of the JSONEncoder and expands any \\uNNNN
escapes it finds (except for \\u0000 to \\u001F, which are converted to
\\xNN escapes).
For performance, it assumes that the input is valid JSO... | Unpack `\\uNNNN` escapes in 's' and encode the result as UTF-8
This method takes the output of the JSONEncoder and expands any \\uNNNN
escapes it finds (except for \\u0000 to \\u001F, which are converted to
\\xNN escapes).
For performance, it assumes that the input is valid JSON, and performs few
... |
def cat(ctx, archive_name, version):
'''
Echo the contents of an archive
'''
_generate_api(ctx)
var = ctx.obj.api.get_archive(archive_name)
with var.open('r', version=version) as f:
for chunk in iter(lambda: f.read(1024 * 1024), ''):
click.echo(chunk) | Echo the contents of an archive |
def metadata_converter_help_content():
"""Helper method that returns just the content in extent mode.
This method was added so that the text could be reused in the
wizard.
:returns: A message object without brand element.
:rtype: safe.messaging.message.Message
"""
message = m.Message()
... | Helper method that returns just the content in extent mode.
This method was added so that the text could be reused in the
wizard.
:returns: A message object without brand element.
:rtype: safe.messaging.message.Message |
def dumps(data): # type: (_TOMLDocument) -> str
"""
Dumps a TOMLDocument into a string.
"""
if not isinstance(data, _TOMLDocument) and isinstance(data, dict):
data = item(data)
return data.as_string() | Dumps a TOMLDocument into a string. |
def _get_table_data(self):
"""Return clipboard processed as data"""
data = self._simplify_shape(
self.table_widget.get_data())
if self.table_widget.array_btn.isChecked():
return array(data)
elif pd and self.table_widget.df_btn.isChecked():
i... | Return clipboard processed as data |
def beam_search(self, text:str, n_words:int, no_unk:bool=True, top_k:int=10, beam_sz:int=1000, temperature:float=1.,
sep:str=' ', decoder=decode_spec_tokens):
"Return the `n_words` that come after `text` using beam search."
ds = self.data.single_dl.dataset
self.model.reset()
... | Return the `n_words` that come after `text` using beam search. |
def set_access_port(self, port_number, vlan_id):
"""
Sets the specified port as an ACCESS port.
:param port_number: allocated port number
:param vlan_id: VLAN number membership
"""
if port_number not in self._nios:
raise DynamipsError("Port {} is not allocat... | Sets the specified port as an ACCESS port.
:param port_number: allocated port number
:param vlan_id: VLAN number membership |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.