code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _expectation(p, mean, none, kern, feat, nghp=None):
"""
Compute the expectation:
expectation[n] = <x_n K_{x_n, Z}>_p(x_n)
- K_{.,} :: Linear kernel
or the equivalent for MarkovGaussian
:return: NxDxM
"""
return tf.matrix_transpose(expectation(p, (kern, feat), mean)) | Compute the expectation:
expectation[n] = <x_n K_{x_n, Z}>_p(x_n)
- K_{.,} :: Linear kernel
or the equivalent for MarkovGaussian
:return: NxDxM |
def load(self, typedef, value, **kwargs):
"""
Return the result of the bound load method for a typedef
Looks up the load function that was bound to the engine for a typedef,
and return the result of passing the given `value` and any `context`
to that function.
Parameter... | Return the result of the bound load method for a typedef
Looks up the load function that was bound to the engine for a typedef,
and return the result of passing the given `value` and any `context`
to that function.
Parameters
----------
typedef : :class:`~TypeDefinition... |
def dispatch(self, *args, **kwargs):
'''
Entry point for this class, here we decide basic stuff
'''
# Get if this class is working as only a base render and List funcionality shouldn't be enabled
onlybase = getattr(self, "onlybase", False)
# REST not available when only... | Entry point for this class, here we decide basic stuff |
def get(self):
"""
*get the cone_search object*
**Return:**
- ``results`` -- the results of the conesearch
"""
self.log.info('starting the ``get`` method')
# sort results by angular separation
from operator import itemgetter
results = list(s... | *get the cone_search object*
**Return:**
- ``results`` -- the results of the conesearch |
def __find_index(alig_file_pth, idx_extensions):
"""
Find an index file for a genome alignment file in the same directory.
:param alig_file_path: path to the alignment file.
:param idx_extensions: check for index files with these extensions
:return: path to first index file that matches the name of the align... | Find an index file for a genome alignment file in the same directory.
:param alig_file_path: path to the alignment file.
:param idx_extensions: check for index files with these extensions
:return: path to first index file that matches the name of the alignment file
and has one of the specified extensi... |
def tabulate(self, restricted_predicted_column_indices = [], restricted_predicted_column_names = [], dataset_name = None):
'''Returns summary analysis from the dataframe as a DataTable object.
DataTables are wrapped pandas dataframes which can be combined if the have the same width. This is useful fo... | Returns summary analysis from the dataframe as a DataTable object.
DataTables are wrapped pandas dataframes which can be combined if the have the same width. This is useful for combining multiple analyses.
DataTables can be printed to terminal as a tabular string using their representation functio... |
def validate_config(config):
"""
Validates the extractor configuration file. Ensures that there are no duplicate field names, etc.
:param config: The configuration file that contains the specification of the extractor
:return: True if config is valid, else raises a exception that specifies the correcti... | Validates the extractor configuration file. Ensures that there are no duplicate field names, etc.
:param config: The configuration file that contains the specification of the extractor
:return: True if config is valid, else raises a exception that specifies the correction to be made |
def run_download_media(filename=None):
"""
Downloads the media dump from the server into your local machine.
In order to import the downloaded media dump, run ``fab import_media``
Usage::
fab prod run_download_media
fab prod run_download_media:filename=foobar.tar.gz
"""
if no... | Downloads the media dump from the server into your local machine.
In order to import the downloaded media dump, run ``fab import_media``
Usage::
fab prod run_download_media
fab prod run_download_media:filename=foobar.tar.gz |
def parse(self,tolerance=0,downsample=None,evidence=2,use_gene_names=False):
"""Divide out the transcripts. allow junction tolerance if wanted"""
g = Graph()
nodes = [Node(x) for x in self._transcripts]
for n in nodes: g.add_node(n)
for i in range(0,len(nodes)):
for j in range(0,... | Divide out the transcripts. allow junction tolerance if wanted |
def compute_bin_edges(features, num_bins, edge_range, trim_outliers, trim_percentile, use_orig_distr=False):
"Compute the edges for the histogram bins to keep it the same for all nodes."
if use_orig_distr:
print('Using original distribution (without histogram) to compute edge weights!')
edges=N... | Compute the edges for the histogram bins to keep it the same for all nodes. |
def iter_prio_dict(prio_dict):
"""
Iterate over a priority dictionary. A priority dictionary is a
dictionary keyed by integer priority, with the values being lists
of objects. This generator will iterate over the dictionary in
priority order (from lowest integer value to highest integer
value)... | Iterate over a priority dictionary. A priority dictionary is a
dictionary keyed by integer priority, with the values being lists
of objects. This generator will iterate over the dictionary in
priority order (from lowest integer value to highest integer
value), yielding each object in the lists in turn... |
def save(self, filething=None, padding=None):
"""save(filething=None, padding=None)
Save a tag to a file.
If no filename is given, the one most recently loaded is used.
Args:
filething (filething)
padding (:obj:`mutagen.PaddingFunction`)
Raises:
... | save(filething=None, padding=None)
Save a tag to a file.
If no filename is given, the one most recently loaded is used.
Args:
filething (filething)
padding (:obj:`mutagen.PaddingFunction`)
Raises:
mutagen.MutagenError |
def features_node_edge_graph(obj):
"""
Transform the features into a more graph-like structure by
appropriately splitting LineString features into two-point
"edges" that connect Point "nodes".
"""
points = {}
features = obj['features']
for feature in tqdm(obj['features']):
for (l... | Transform the features into a more graph-like structure by
appropriately splitting LineString features into two-point
"edges" that connect Point "nodes". |
def most_by_mask(self, mask, y, mult):
""" Extracts the first 4 most correct/incorrect indexes from the ordered list of probabilities
Arguments:
mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contain... | Extracts the first 4 most correct/incorrect indexes from the ordered list of probabilities
Arguments:
mask (numpy.ndarray): the mask of probabilities specific to the selected class; a boolean array with shape (num_of_samples,) which contains True where class==selected_class, and False every... |
def get_form(self, request, obj=None, **kwargs):
"""
Returns a Form class for use in the admin add view. This is used by
add_view and change_view.
"""
parent_id = request.GET.get('parent_id', None)
if not parent_id:
parent_id = request.POST.get('parent_id', No... | Returns a Form class for use in the admin add view. This is used by
add_view and change_view. |
def reset(self):
"""
Reset all internal storage to initial status
Returns
-------
None
"""
self.solved = False
self.niter = 0
self.iter_mis = []
self.F = None
self.system.dae.factorize = True | Reset all internal storage to initial status
Returns
-------
None |
def gfrepi(window, begmss, endmss):
"""
This entry point initializes a search progress report.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfrepi_c.html
:param window: A window over which a job is to be performed.
:type window: spiceypy.utils.support_types.SpiceCell
:param begmss: ... | This entry point initializes a search progress report.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/gfrepi_c.html
:param window: A window over which a job is to be performed.
:type window: spiceypy.utils.support_types.SpiceCell
:param begmss: Beginning of the text portion of the output mess... |
def parse_value(named_reg_value):
"""
Convert the value returned from EnumValue to a (name, value) tuple using the value classes.
"""
name, value, value_type = named_reg_value
value_class = REG_VALUE_TYPE_MAP[value_type]
return name, value_class(value) | Convert the value returned from EnumValue to a (name, value) tuple using the value classes. |
def _getModelPosterior(self,min):
"""
USES LAPLACE APPROXIMATION TO CALCULATE THE BAYESIAN MODEL POSTERIOR
"""
Sigma = self._getLaplaceCovar(min)
n_params = self.vd.getNumberScales()
ModCompl = 0.5*n_params*sp.log(2*sp.pi)+0.5*sp.log(sp.linalg.det(Sigma))
RV = min... | USES LAPLACE APPROXIMATION TO CALCULATE THE BAYESIAN MODEL POSTERIOR |
def row_wise_rescale(matrix):
"""
Row-wise rescale of a given matrix.
For fMRI data (num_voxels x num_time_points), this would translate to voxel-wise normalization over time.
Parameters
----------
matrix : ndarray
Input rectangular matrix, typically a carpet of size num_voxels x num_... | Row-wise rescale of a given matrix.
For fMRI data (num_voxels x num_time_points), this would translate to voxel-wise normalization over time.
Parameters
----------
matrix : ndarray
Input rectangular matrix, typically a carpet of size num_voxels x num_4th_dim, 4th_dim could be time points or g... |
def batch_insert(self, records, typecast=False):
"""
Calls :any:`insert` repetitively, following set API Rate Limit (5/sec)
To change the rate limit use ``airtable.API_LIMIT = 0.2``
(5 per second)
>>> records = [{'Name': 'John'}, {'Name': 'Marc'}]
>>> airtable.bat... | Calls :any:`insert` repetitively, following set API Rate Limit (5/sec)
To change the rate limit use ``airtable.API_LIMIT = 0.2``
(5 per second)
>>> records = [{'Name': 'John'}, {'Name': 'Marc'}]
>>> airtable.batch_insert(records)
Args:
records(``list``): Rec... |
def to_graph_decomposition(H):
"""Returns an UndirectedHypergraph object that has the same nodes (and
corresponding attributes) as the given H, except that for all
hyperedges in the given H, each node in the hyperedge is pairwise
connected to every other node also in that hyperedge in the new H.
Sai... | Returns an UndirectedHypergraph object that has the same nodes (and
corresponding attributes) as the given H, except that for all
hyperedges in the given H, each node in the hyperedge is pairwise
connected to every other node also in that hyperedge in the new H.
Said another way, each of the original hy... |
def saved(name,
source='running',
user=None,
group=None,
mode=None,
attrs=None,
makedirs=False,
dir_mode=None,
replace=True,
backup='',
show_changes=True,
create=True,
tmp_dir='',
tmp_ext=''... | .. versionadded:: 2019.2.0
Save the configuration to a file on the local file system.
name
Absolute path to file where to save the configuration.
To push the files to the Master, use
:mod:`cp.push <salt.modules.cp.push>` Execution function.
source: ``running``
The configur... |
def CI_calc(mean, SE, CV=1.96):
"""
Calculate confidence interval.
:param mean: mean of data
:type mean : float
:param SE: standard error of data
:type SE : float
:param CV: critical value
:type CV:float
:return: confidence interval as tuple
"""
try:
CI_down = mean -... | Calculate confidence interval.
:param mean: mean of data
:type mean : float
:param SE: standard error of data
:type SE : float
:param CV: critical value
:type CV:float
:return: confidence interval as tuple |
def initSchd_1_to_4(self):
""" Initialize first tariff schedule :class:`~ekmmeters.SerialBlock`. """
self.m_schd_1_to_4["reserved_40"] = [6, FieldType.Hex, ScaleType.No, "", 0, False, False]
self.m_schd_1_to_4["Schedule_1_Period_1_Hour"] = [2, FieldType.Int, ScaleType.No, "", 0, False, True]
... | Initialize first tariff schedule :class:`~ekmmeters.SerialBlock`. |
def get_current_future_chain(self, continuous_future, dt):
"""
Retrieves the future chain for the contract at the given `dt` according
the `continuous_future` specification.
Returns
-------
future_chain : list[Future]
A list of active futures, where the firs... | Retrieves the future chain for the contract at the given `dt` according
the `continuous_future` specification.
Returns
-------
future_chain : list[Future]
A list of active futures, where the first index is the current
contract specified by the continuous future ... |
def line(x_fn, y_fn, *, options={}, **interact_params):
"""
Generates an interactive line chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for x-coordinates.... | Generates an interactive line chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for x-coordinates.
If function, must take parameters to interact with and... |
def _apply_theme(self):
"""
Apply theme attributes to Matplotlib objects
"""
self.theme.apply_axs(self.axs)
self.theme.apply_figure(self.figure) | Apply theme attributes to Matplotlib objects |
def unblock_username(username, pipe=None):
""" unblock the given Username """
do_commit = False
if not pipe:
pipe = REDIS_SERVER.pipeline()
do_commit = True
if username:
pipe.delete(get_username_attempt_cache_key(username))
pipe.delete(get_username_blocked_cache_key(usern... | unblock the given Username |
def sources_remove(source_uri, ruby=None, runas=None, gem_bin=None):
'''
Remove a gem source.
:param source_uri: string
The source URI to remove.
:param gem_bin: string : None
Full path to ``gem`` binary to use.
:param ruby: string : None
If RVM or rbenv are installed, the r... | Remove a gem source.
:param source_uri: string
The source URI to remove.
:param gem_bin: string : None
Full path to ``gem`` binary to use.
:param ruby: string : None
If RVM or rbenv are installed, the ruby version and gemset to use.
Ignored if ``gem_bin`` is specified.
:... |
def map_lazy(
self,
target: Callable,
map_iter: Sequence[Any] = None,
*,
map_args: Sequence[Sequence[Any]] = None,
args: Sequence = None,
map_kwargs: Sequence[Mapping[str, Any]] = None,
kwargs: Mapping = None,
pass_state: bool = False,
num_... | r"""
Functional equivalent of ``map()`` in-built function,
but executed in a parallel fashion.
Distributes the iterables,
provided in the ``map_*`` arguments to ``num_chunks`` no of worker nodes.
The idea is to:
1. Split the the iterables provided in the ``map_*`` a... |
def bin(args):
"""
%prog bin data.tsv
Conver tsv to binary format.
"""
p = OptionParser(bin.__doc__)
p.add_option("--dtype", choices=("float32", "int32"),
help="dtype of the matrix")
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help()... | %prog bin data.tsv
Conver tsv to binary format. |
def remove_bucket(self, bucket_name):
"""
Remove a bucket.
:param bucket_name: Bucket to remove
"""
is_valid_bucket_name(bucket_name)
self._url_open('DELETE', bucket_name=bucket_name)
# Make sure to purge bucket_name from region cache.
self._delete_bucke... | Remove a bucket.
:param bucket_name: Bucket to remove |
def raise_301(instance, location):
"""Abort the current request with a 301 (Moved Permanently) response code.
Sets the Location header correctly. If the location does not start with a
slash, the path of the current request is prepended.
:param instance: Resource instance (used to access the response)
... | Abort the current request with a 301 (Moved Permanently) response code.
Sets the Location header correctly. If the location does not start with a
slash, the path of the current request is prepended.
:param instance: Resource instance (used to access the response)
:type instance: :class:`webob.resource.... |
def startup_config_content(self, startup_config):
"""
Update the startup config
:param startup_config: content of the startup configuration file
"""
try:
startup_config_path = os.path.join(self.working_dir, "startup-config.cfg")
if startup_config is Non... | Update the startup config
:param startup_config: content of the startup configuration file |
def querytime(self, value):
"""
Sets self._querytime as well as self.query.querytime.
:param value: None or datetime
:return:
"""
self._querytime = value
self.query.querytime = value | Sets self._querytime as well as self.query.querytime.
:param value: None or datetime
:return: |
def weighted_axioms(self, x, y, xg):
"""
return a tuple (sub,sup,equiv,other) indicating estimated prior probabilities for an interpretation of a mapping
between x and y.
See kboom paper
"""
# TODO: allow additional weighting
# weights are log odds w=log(p/(1-p))... | return a tuple (sub,sup,equiv,other) indicating estimated prior probabilities for an interpretation of a mapping
between x and y.
See kboom paper |
def obfn_fvar(self, i):
r"""Variable to be evaluated in computing :math:`f_i(\cdot)`,
depending on the ``fEvalX`` option value.
"""
return self.X[..., i] if self.opt['fEvalX'] else self.Y | r"""Variable to be evaluated in computing :math:`f_i(\cdot)`,
depending on the ``fEvalX`` option value. |
def set_node_as_int(self, dst, src):
"""
Set a node to a value captured from another node
example::
R = [
In : node #setcapture(_, node)
]
"""
dst.value = self.value(src)
return True | Set a node to a value captured from another node
example::
R = [
In : node #setcapture(_, node)
] |
def citation_count(doi, url = "http://www.crossref.org/openurl/",
key = "[email protected]", **kwargs):
'''
Get a citation count with a DOI
:param doi: [String] DOI, digital object identifier
:param url: [String] the API url for the function (should be left to default)
:param keyc: [String]... | Get a citation count with a DOI
:param doi: [String] DOI, digital object identifier
:param url: [String] the API url for the function (should be left to default)
:param keyc: [String] your API key
See http://labs.crossref.org/openurl/ for more info on this Crossref API service.
Usage::
f... |
def readline(self, size=-1):
"Ignore the `size` since a complete line must be processed."
while True:
try:
record = next(self.reader)
except StopIteration:
break
# Ensure this is a valid record
if checks.record_is_valid(rec... | Ignore the `size` since a complete line must be processed. |
def inline(args):
"""
Parse input file with the specified parser and post messages based on lint output
:param args: Contains the following
interface: How are we going to post comments?
owner: Username of repo owner
repo: Repository name
pr: Pull request ID
token: Au... | Parse input file with the specified parser and post messages based on lint output
:param args: Contains the following
interface: How are we going to post comments?
owner: Username of repo owner
repo: Repository name
pr: Pull request ID
token: Authentication for repository
... |
def _run_pre_command(self, pre_cmd):
'''
Run a pre command to get external args for a command
'''
logger.debug('Executing pre-command: %s', pre_cmd)
try:
pre_proc = Popen(pre_cmd, stdout=PIPE, stderr=STDOUT, shell=True)
except OSError as err:
if er... | Run a pre command to get external args for a command |
def list(self, log=values.unset, message_date_before=values.unset,
message_date=values.unset, message_date_after=values.unset, limit=None,
page_size=None):
"""
Lists NotificationInstance records from the API as a list.
Unlike stream(), this operation is eager and will l... | Lists NotificationInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param unicode log: Filter by log level
:param date message_date_before: Filter by date
:param date message_date: Filte... |
def main():
'''main routine'''
# create parser
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('--vmssname', '-s', required=True,
action='store', help='VM Scale Set name')
arg_parser.add_argument('--resourcegroup', '-r', required=True,
... | main routine |
def list(self, request, *args, **kwargs):
"""
To get a list of SSH keys, run **GET** against */api/keys/* as authenticated user.
A new SSH key can be created by any active users. Example of a valid request:
.. code-block:: http
POST /api/keys/ HTTP/1.1
Content-... | To get a list of SSH keys, run **GET** against */api/keys/* as authenticated user.
A new SSH key can be created by any active users. Example of a valid request:
.. code-block:: http
POST /api/keys/ HTTP/1.1
Content-Type: application/json
Accept: application/json
... |
def moderate_model(ParentModel, publication_date_field=None, enable_comments_field=None):
"""
Register a parent model (e.g. ``Blog`` or ``Article``) that should receive comment moderation.
:param ParentModel: The parent model, e.g. a ``Blog`` or ``Article`` model.
:param publication_date_field: The fie... | Register a parent model (e.g. ``Blog`` or ``Article``) that should receive comment moderation.
:param ParentModel: The parent model, e.g. a ``Blog`` or ``Article`` model.
:param publication_date_field: The field name of a :class:`~django.db.models.DateTimeField` in the parent model which stores the publication... |
def sign(self, msg, key):
"""
Create a signature over a message as defined in RFC7515 using an
RSA key
:param msg: the message.
:type msg: bytes
:returns: bytes, the signature of data.
:rtype: bytes
"""
if not isinstance(key, rsa.RSAPrivateKey):
... | Create a signature over a message as defined in RFC7515 using an
RSA key
:param msg: the message.
:type msg: bytes
:returns: bytes, the signature of data.
:rtype: bytes |
def ngettext(*args, **kwargs):
"""
Like :func:`gettext`, except it supports pluralization.
"""
is_plural = args[2] > 1
if not is_plural:
key = args[0]
key_match = TRANSLATION_KEY_RE.match(key)
else:
key = args[1]
key_match = PLURAL_TRANSLATION_KEY_RE.match(key)
... | Like :func:`gettext`, except it supports pluralization. |
def _get_module_filename(module):
"""
Return the filename of `module` if it can be imported.
If `module` is a package, its directory will be returned.
If it cannot be imported ``None`` is returned.
If the ``__file__`` attribute is missing, or the module or package is a
compiled egg, then an :... | Return the filename of `module` if it can be imported.
If `module` is a package, its directory will be returned.
If it cannot be imported ``None`` is returned.
If the ``__file__`` attribute is missing, or the module or package is a
compiled egg, then an :class:`Unparseable` instance is returned, sinc... |
def mask_plane(data, wcs, region, negate=False):
"""
Mask a 2d image (data) such that pixels within 'region' are set to nan.
Parameters
----------
data : 2d-array
Image array.
wcs : astropy.wcs.WCS
WCS for the image in question.
region : :class:`AegeanTools.regions.Region`... | Mask a 2d image (data) such that pixels within 'region' are set to nan.
Parameters
----------
data : 2d-array
Image array.
wcs : astropy.wcs.WCS
WCS for the image in question.
region : :class:`AegeanTools.regions.Region`
A region within which the image pixels will be maske... |
def _dimension_keys(self):
"""
Helper for __mul__ that returns the list of keys together with
the dimension labels.
"""
return [tuple(zip([d.name for d in self.kdims], [k] if self.ndims == 1 else k))
for k in self.keys()] | Helper for __mul__ that returns the list of keys together with
the dimension labels. |
def validate_query_params(self, strict=True):
"""Check if the request is valid and can be sent, raise ValueError if
not.
`strict` is a boolean argument that defaults to True which means an
exception is raised on every invalid query parameter, if set to False
an e... | Check if the request is valid and can be sent, raise ValueError if
not.
`strict` is a boolean argument that defaults to True which means an
exception is raised on every invalid query parameter, if set to False
an exception is raised only when the search request cannot be ... |
def prepare_state_m_for_insert_as(state_m_to_insert, previous_state_size):
"""Prepares and scales the meta data to fit into actual size of the state."""
# TODO check how much code is duplicated or could be reused for library fit functionality meta data helper
# TODO DO REFACTORING !!! and move maybe the hol... | Prepares and scales the meta data to fit into actual size of the state. |
def from_xdr_object(cls, op_xdr_object):
"""Creates a :class:`Payment` object from an XDR Operation
object.
"""
if not op_xdr_object.sourceAccount:
source = None
else:
source = encode_check(
'account', op_xdr_object.sourceAccount[0].ed2551... | Creates a :class:`Payment` object from an XDR Operation
object. |
def _unrecognised(achr):
""" Handle unrecognised characters. """
if options['handleUnrecognised'] == UNRECOGNISED_ECHO:
return achr
elif options['handleUnrecognised'] == UNRECOGNISED_SUBSTITUTE:
return options['substituteChar']
else:
raise KeyError(achr) | Handle unrecognised characters. |
def execute_pool_txns(self, three_pc_batch) -> List:
"""
Execute a transaction that involves consensus pool management, like
adding a node, client or a steward.
:param ppTime: PrePrepare request time
:param reqs_keys: requests keys to be committed
"""
committed_t... | Execute a transaction that involves consensus pool management, like
adding a node, client or a steward.
:param ppTime: PrePrepare request time
:param reqs_keys: requests keys to be committed |
def _get_app_auth_headers(self):
"""Set the correct auth headers to authenticate against GitHub."""
now = datetime.now(timezone.utc)
expiry = now + timedelta(minutes=5)
data = {"iat": now, "exp": expiry, "iss": self.app_id}
app_token = jwt.encode(data, self.app_key, algorithm="R... | Set the correct auth headers to authenticate against GitHub. |
def _resolve_model(obj):
"""
Resolve supplied `obj` to a Django model class.
`obj` must be a Django model class itself, or a string
representation of one. Useful in situations like GH #1225 where
Django may not have resolved a string-based reference to a model in
another model's foreign key de... | Resolve supplied `obj` to a Django model class.
`obj` must be a Django model class itself, or a string
representation of one. Useful in situations like GH #1225 where
Django may not have resolved a string-based reference to a model in
another model's foreign key definition.
String representations... |
def delete(self, using=None):
""" Deletes the post instance. """
if self.is_alone:
# The default way of operating is to trigger the deletion of the associated topic
# only if the considered post is the only post embedded in the topic
self.topic.delete()
else:
... | Deletes the post instance. |
def dir(self, filetype, **kwargs):
"""Return the directory containing a file of a given type.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
dir : str
Directory containing the file.
"""
full = k... | Return the directory containing a file of a given type.
Parameters
----------
filetype : str
File type parameter.
Returns
-------
dir : str
Directory containing the file. |
def get_objective(self, objective_id=None):
"""Gets the Objective specified by its Id.
In plenary mode, the exact Id is found or a NotFound results.
Otherwise, the returned Objective may have a different Id than
requested, such as the case where a duplicate Id was assigned to
an ... | Gets the Objective specified by its Id.
In plenary mode, the exact Id is found or a NotFound results.
Otherwise, the returned Objective may have a different Id than
requested, such as the case where a duplicate Id was assigned to
an Objective and retained for compatibility.
arg: ... |
def cast_to_subclass(self):
"""
Load the bundle file from the database to get the derived bundle class,
then return a new bundle built on that class
:return:
"""
self.import_lib()
self.load_requirements()
try:
self.commit() # To ensure the r... | Load the bundle file from the database to get the derived bundle class,
then return a new bundle built on that class
:return: |
def cloud_front_origin_access_identity_exists(Id, region=None, key=None, keyid=None, profile=None):
'''
Return True if a CloudFront origin access identity exists with the given Resource ID or False
otherwise.
Id
Resource ID of the CloudFront origin access identity.
region
Region to... | Return True if a CloudFront origin access identity exists with the given Resource ID or False
otherwise.
Id
Resource ID of the CloudFront origin access identity.
region
Region to connect to.
key
Secret key to use.
keyid
Access key to use.
profile
Dict... |
def makeFigFromFile(filename,*args,**kwargs):
"""
Renders an image in a matplotlib figure, so it can be added to reports
args and kwargs are passed to plt.subplots
"""
import matplotlib.pyplot as plt
img = plt.imread(filename)
fig,ax = plt.subplots(*args,**kwargs)
ax.axis('off')
ax.... | Renders an image in a matplotlib figure, so it can be added to reports
args and kwargs are passed to plt.subplots |
def t_ID(self, t):
r'[a-z][a-zA-Z0-9_]*'
t.type = self.reserved.get(t.value, 'ID')
if t.type == 'ID':
t.value = node.Id(t.value, self.lineno, self.filename)
return t | r'[a-z][a-zA-Z0-9_]* |
def resource(resource_id):
"""Show a resource."""
resource_obj = app.db.resource(resource_id)
if 'raw' in request.args:
return send_from_directory(os.path.dirname(resource_obj.path),
os.path.basename(resource_obj.path))
return render_template('resource.html',... | Show a resource. |
def global_set_option(self, opt, value):
"""set option on the correct option provider"""
self._all_options[opt].set_option(opt, value) | set option on the correct option provider |
def get_urls(self):
"""
Appends the custom will_not_clone url to the admin site
"""
not_clone_url = [url(r'^(.+)/will_not_clone/$',
admin.site.admin_view(self.will_not_clone))]
restore_url = [
url(r'^(.+)/restore/$', admin.site.admin_view(... | Appends the custom will_not_clone url to the admin site |
def get_color_label(self):
"""Text for colorbar label
"""
if self.args.norm:
return 'Normalized to {}'.format(self.args.norm)
if len(self.units) == 1 and self.usetex:
return r'ASD $\left({0}\right)$'.format(
self.units[0].to_string('latex').strip('... | Text for colorbar label |
def load_plug_in(self, name):
"""Loads a DBGF plug-in.
in name of type str
The plug-in name or DLL. Special name 'all' loads all installed plug-ins.
return plug_in_name of type str
The name of the loaded plug-in.
"""
if not isinstance(name, basestring):... | Loads a DBGF plug-in.
in name of type str
The plug-in name or DLL. Special name 'all' loads all installed plug-ins.
return plug_in_name of type str
The name of the loaded plug-in. |
def represent_datetime(self, d):
"""
turns a given datetime obj into a string representation.
This will:
1) look if a fixed 'timestamp_format' is given in the config
2) check if a 'timestamp_format' hook is defined
3) use :func:`~alot.helper.pretty_datetime` as fallback
... | turns a given datetime obj into a string representation.
This will:
1) look if a fixed 'timestamp_format' is given in the config
2) check if a 'timestamp_format' hook is defined
3) use :func:`~alot.helper.pretty_datetime` as fallback |
def _command(self, event, command, *args, **kwargs):
"""
Context state controller.
Check whether the transition is possible or not, it executes it and
triggers the Hooks with the pre_* and post_* events.
@param event: (str) event generated by the command.
@param command... | Context state controller.
Check whether the transition is possible or not, it executes it and
triggers the Hooks with the pre_* and post_* events.
@param event: (str) event generated by the command.
@param command: (virDomain.method) state transition to impose.
@raise: RuntimeE... |
def encipher(self,string):
"""Encipher string using Delastelle cipher according to initialised key.
Example::
ciphertext = Delastelle('APCZ WRLFBDKOTYUQGENHXMIVS').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. The cipherte... | Encipher string using Delastelle cipher according to initialised key.
Example::
ciphertext = Delastelle('APCZ WRLFBDKOTYUQGENHXMIVS').encipher(plaintext)
:param string: The string to encipher.
:returns: The enciphered string. The ciphertext will be 3 times the length of the p... |
def _do_connection(self, wgt, sig, func):
"""
Make a connection between a GUI widget and a callable.
wgt and sig are strings with widget and signal name
func is a callable for that signal
"""
#new style (we use this)
#self.btn_name.clicked.connect(self.on_btn_na... | Make a connection between a GUI widget and a callable.
wgt and sig are strings with widget and signal name
func is a callable for that signal |
def set_child_value(self, name, value):
"""Set the text value of the (nameless) plain-text child of a named
child node."""
return XMLElement(lib.lsl_set_child_value(self.e,
str.encode(name),
str.... | Set the text value of the (nameless) plain-text child of a named
child node. |
def predict(self, X):
"""Predict target values for X.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
Returns
-------
y : array of shape = [n_samples]
The predicted target value.
"""
... | Predict target values for X.
Parameters
----------
X : array-like of shape = [n_samples, n_features]
The input samples.
Returns
-------
y : array of shape = [n_samples]
The predicted target value. |
def put(self, key):
"""Put and return the only unique identifier possible, its path
"""
self.client.write(self._key_path(key['name']), **key)
return self._key_path(key['name']) | Put and return the only unique identifier possible, its path |
def vtrees(self):
"""
Get list of VTrees from ScaleIO cluster
:return: List of VTree objects - Can be empty of no VTrees exist
:rtype: VTree object
"""
self.connection._check_login()
response = self.connection._do_get("{}/{}".format(self.connection._api_url, "type... | Get list of VTrees from ScaleIO cluster
:return: List of VTree objects - Can be empty of no VTrees exist
:rtype: VTree object |
def nodes(self):
"""
Returns an (n,2) list of nodes, or vertices on the path.
Note that this generic class function assumes that all of the
reference points are on the path which is true for lines and
three point arcs.
If you were to define another class where that wasn'... | Returns an (n,2) list of nodes, or vertices on the path.
Note that this generic class function assumes that all of the
reference points are on the path which is true for lines and
three point arcs.
If you were to define another class where that wasn't the case
(for example, the ... |
def line_segment(X0, X1):
r"""
Calculate the voxel coordinates of a straight line between the two given
end points
Parameters
----------
X0 and X1 : array_like
The [x, y] or [x, y, z] coordinates of the start and end points of
the line.
Returns
-------
coords : list... | r"""
Calculate the voxel coordinates of a straight line between the two given
end points
Parameters
----------
X0 and X1 : array_like
The [x, y] or [x, y, z] coordinates of the start and end points of
the line.
Returns
-------
coords : list of lists
A list of li... |
def selenol_params(**kwargs):
"""Decorate request parameters to transform them into Selenol objects."""
def params_decorator(func):
"""Param decorator.
:param f: Function to decorate, typically on_request.
"""
def service_function_wrapper(service, message):
"""Wrap f... | Decorate request parameters to transform them into Selenol objects. |
def load_grammar(self, path):
"""Load a grammar file (python file containing grammar definitions) by
file path. When loaded, the global variable ``GRAMFUZZER`` will be set
within the module. This is not always needed, but can be useful.
:param str path: The path to the grammar file
... | Load a grammar file (python file containing grammar definitions) by
file path. When loaded, the global variable ``GRAMFUZZER`` will be set
within the module. This is not always needed, but can be useful.
:param str path: The path to the grammar file |
def get_text(node, strategy):
"""
Get the most confident text results, either those with @index = 1 or the first text results or empty string.
"""
textEquivs = node.get_TextEquiv()
if not textEquivs:
log.debug("No text results on %s %s", node, node.id)
return ''
# elif strategy ... | Get the most confident text results, either those with @index = 1 or the first text results or empty string. |
def get_file_to_path(self, share_name, directory_name, file_name, file_path,
open_mode='wb', start_range=None, end_range=None,
range_get_content_md5=None, progress_callback=None,
max_connections=1, max_retries=5, retry_wait=1.0, timeout=None):
... | Downloads a file to a file path, with automatic chunking and progress
notifications. Returns an instance of File with properties and metadata.
:param str share_name:
Name of existing share.
:param str directory_name:
The path to the directory.
:param str file_nam... |
def do_prune(self):
"""
Return True if prune_table, prune_column, and prune_date are implemented.
If only a subset of prune variables are override, an exception is raised to remind the user to implement all or none.
Prune (data newer than prune_date deleted) before copying new data in.
... | Return True if prune_table, prune_column, and prune_date are implemented.
If only a subset of prune variables are override, an exception is raised to remind the user to implement all or none.
Prune (data newer than prune_date deleted) before copying new data in. |
async def get_source_list(self, scheme: str = "") -> List[Source]:
"""Return available sources for playback."""
res = await self.services["avContent"]["getSourceList"](scheme=scheme)
return [Source.make(**x) for x in res] | Return available sources for playback. |
def normalize_docroot(app, root):
"""Creates a package-list URL and a link base from a docroot element.
Args:
app: the global app object
root: the docroot element [string or dictionary]
"""
srcdir = app.env.srcdir
default_version = app.config.javalink_default_version
if isinst... | Creates a package-list URL and a link base from a docroot element.
Args:
app: the global app object
root: the docroot element [string or dictionary] |
def lock(self):
"""
This method sets a cache variable to mark current job as "already running".
"""
if self.cache.get(self.lock_name):
return False
else:
self.cache.set(self.lock_name, timezone.now(), self.timeout)
return True | This method sets a cache variable to mark current job as "already running". |
def _eval_target_jumptable(state, ip, limit):
"""
A *very* fast method to evaluate symbolic jump targets if they are a) concrete targets, or b) targets coming
from jump tables.
:param state: A SimState instance.
:param ip: The AST of the instruction pointer to evaluate.
... | A *very* fast method to evaluate symbolic jump targets if they are a) concrete targets, or b) targets coming
from jump tables.
:param state: A SimState instance.
:param ip: The AST of the instruction pointer to evaluate.
:param limit: The maximum number of concrete IPs.
... |
def hook_point(self, hook_name, handle=None):
"""Used to call module function that may define a hook function for hook_name
Available hook points:
- `tick`, called on each daemon loop turn
- `save_retention`; called by the scheduler when live state
saving is to be done
... | Used to call module function that may define a hook function for hook_name
Available hook points:
- `tick`, called on each daemon loop turn
- `save_retention`; called by the scheduler when live state
saving is to be done
- `load_retention`; called by the scheduler when live ... |
def eval(self, code, mode='single'):
"""Evaluate code in the context of the frame."""
if isinstance(code, str):
if isinstance(code, str):
code = UTF8_COOKIE + code.encode('utf-8')
code = compile(code, '<interactive>', mode)
if mode != 'exec':
r... | Evaluate code in the context of the frame. |
def imported_targets(self):
"""
:returns: target instances for specs referenced by imported_target_specs.
:rtype: list of Target
"""
libs = []
for spec in self.imported_target_specs(payload=self.payload):
resolved_target = self._build_graph.get_target_from_spec(spec,
... | :returns: target instances for specs referenced by imported_target_specs.
:rtype: list of Target |
def add_fields(self, field_dict):
"""Add a mapping of field names to PayloadField instances.
:API: public
"""
for key, field in field_dict.items():
self.add_field(key, field) | Add a mapping of field names to PayloadField instances.
:API: public |
def opens_platforms(self, tag=None, fromdate=None, todate=None):
"""
Gets an overview of the platforms used to open your emails.
This is only recorded when open tracking is enabled for that email.
"""
return self.call("GET", "/stats/outbound/opens/platforms", tag=tag, fromdate=fr... | Gets an overview of the platforms used to open your emails.
This is only recorded when open tracking is enabled for that email. |
def ps_ball(radius):
r"""
Creates spherical ball structuring element for morphological operations
Parameters
----------
radius : float or int
The desired radius of the structuring element
Returns
-------
strel : 3D-array
A 3D numpy array of the structuring element
"... | r"""
Creates spherical ball structuring element for morphological operations
Parameters
----------
radius : float or int
The desired radius of the structuring element
Returns
-------
strel : 3D-array
A 3D numpy array of the structuring element |
def global_config(cls, key, *args):
''' This reads or sets the global settings stored in class.settings. '''
if args:
cls.settings[key] = args[0]
else:
return cls.settings[key] | This reads or sets the global settings stored in class.settings. |
def decode_base64(data):
"""
Decodes a base64 string, with padding being optional
Args:
data: A base64 encoded string
Returns:
bytes: The decoded bytes
"""
data = bytes(data, encoding="ascii")
missing_padding = len(data) % 4
if missing_padding != 0:
data += b'=... | Decodes a base64 string, with padding being optional
Args:
data: A base64 encoded string
Returns:
bytes: The decoded bytes |
def get_teams():
"""
:return: all knows teams
"""
LOGGER.debug("TeamService.get_teams")
args = {'http_operation': 'GET', 'operation_path': ''}
response = TeamService.requester.call(args)
ret = None
if response.rc == 0:
ret = []
for ... | :return: all knows teams |
def CountFlowLogEntries(self, client_id, flow_id):
"""Returns number of flow log entries of a given flow."""
return len(self.ReadFlowLogEntries(client_id, flow_id, 0, sys.maxsize)) | Returns number of flow log entries of a given flow. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.