code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def list_networks(full_ids=False):
"""
Lists networks on the Docker remote host, similar to ``docker network ls``.
:param full_ids: Shows the full network ids. When ``False`` (default) only shows the first 12 characters.
:type full_ids: bool
"""
networks = docker_fabric().networks()
_format... | Lists networks on the Docker remote host, similar to ``docker network ls``.
:param full_ids: Shows the full network ids. When ``False`` (default) only shows the first 12 characters.
:type full_ids: bool |
def get_ssl_context(private_key, certificate):
"""Get ssl context from private key and certificate paths.
The return value is used when calling Flask.
i.e. app.run(ssl_context=get_ssl_context(,,,))
"""
if (
certificate
and os.path.isfile(certificate)
and private_key
a... | Get ssl context from private key and certificate paths.
The return value is used when calling Flask.
i.e. app.run(ssl_context=get_ssl_context(,,,)) |
def stop(self):
"""
Stop the interface
:rtype: None
"""
should_sleep = self._is_running
super(Sensor, self).stop()
if should_sleep:
# Make sure everything has enough time to exit
time.sleep(max(self._select_timeout, self._retransmit_timeou... | Stop the interface
:rtype: None |
def check_frequencies(pfeed, *, as_df=False, include_warnings=False):
"""
Check that ``pfeed.frequency`` follows the ProtoFeed spec.
Return a list of problems of the form described in
:func:`gt.check_table`;
the list will be empty if no problems are found.
"""
table = 'frequencies'
probl... | Check that ``pfeed.frequency`` follows the ProtoFeed spec.
Return a list of problems of the form described in
:func:`gt.check_table`;
the list will be empty if no problems are found. |
def get_changesets(self, start=None, end=None, start_date=None,
end_date=None, branch_name=None, reverse=False):
"""
Returns iterator of ``MercurialChangeset`` objects from start to end
(both are inclusive)
:param start: None, str, int or mercurial lookup format
... | Returns iterator of ``MercurialChangeset`` objects from start to end
(both are inclusive)
:param start: None, str, int or mercurial lookup format
:param end: None, str, int or mercurial lookup format
:param start_date:
:param end_date:
:param branch_name:
:param... |
def _prepare_hiveconf(d):
"""
This function prepares a list of hiveconf params
from a dictionary of key value pairs.
:param d:
:type d: dict
>>> hh = HiveCliHook()
>>> hive_conf = {"hive.exec.dynamic.partition": "true",
... "hive.exec.dynamic.partition.m... | This function prepares a list of hiveconf params
from a dictionary of key value pairs.
:param d:
:type d: dict
>>> hh = HiveCliHook()
>>> hive_conf = {"hive.exec.dynamic.partition": "true",
... "hive.exec.dynamic.partition.mode": "nonstrict"}
>>> hh._prepare_hiv... |
def main():
"""
NAME
vgp_di.py
DESCRIPTION
converts site latitude, longitude and pole latitude, longitude to declination, inclination
SYNTAX
vgp_di.py [-h] [-i] [-f FILE] [< filename]
OPTIONS
-h prints help message and quits
-i interactive data entry
... | NAME
vgp_di.py
DESCRIPTION
converts site latitude, longitude and pole latitude, longitude to declination, inclination
SYNTAX
vgp_di.py [-h] [-i] [-f FILE] [< filename]
OPTIONS
-h prints help message and quits
-i interactive data entry
-f FILE to specif... |
def get_load(jid):
'''
Return the load data that marks a specified jid
'''
jid_dir = salt.utils.jid.jid_dir(jid, _job_dir(), __opts__['hash_type'])
load_fn = os.path.join(jid_dir, LOAD_P)
if not os.path.exists(jid_dir) or not os.path.exists(load_fn):
return {}
serial = salt.payload.S... | Return the load data that marks a specified jid |
def get_timeout(self):
"setup a timeout for waiting for a proposal"
if self.timeout_time is not None or self.proposal:
return
now = self.cm.chainservice.now
round_timeout = ConsensusManager.round_timeout
round_timeout_factor = ConsensusManager.round_timeout_factor
... | setup a timeout for waiting for a proposal |
def write_temp_file(self, content, filename=None, mode='w'):
"""Write content to a temporary file.
Args:
content (bytes|str): The file content. If passing binary data the mode needs to be set
to 'wb'.
filename (str, optional): The filename to use when writing the... | Write content to a temporary file.
Args:
content (bytes|str): The file content. If passing binary data the mode needs to be set
to 'wb'.
filename (str, optional): The filename to use when writing the file.
mode (str, optional): The file write mode which could... |
def all_notebook_jobs(self):
"""
Similar to notebook_jobs,
but uses the default manager to return archived experiments as well.
"""
from db.models.notebooks import NotebookJob
return NotebookJob.all.filter(project=self) | Similar to notebook_jobs,
but uses the default manager to return archived experiments as well. |
def simxGetArrayParameter(clientID, paramIdentifier, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
paramValues = (ct.c_float*3)()
ret = c_GetArrayParameter(clientID, paramIdentifier, paramValues, operationMode)
arr = []
for i in... | Please have a look at the function description/documentation in the V-REP user manual |
def get_notifications(self, startDate, endDate, loadBalancerID, loadBalancerRuleID):
"""
Get the load balancer notifications for a specific rule within a specifying window time frame
:type startDate: datetime
:type endDate: datetime
:type loadBalancerID: int
:type loadBal... | Get the load balancer notifications for a specific rule within a specifying window time frame
:type startDate: datetime
:type endDate: datetime
:type loadBalancerID: int
:type loadBalancerRuleID: int
:param startDate: From Date
:param endDate: To Date
:param loadB... |
def merge_with(self, other, multiset_op, other_op=None):
'''Merge this feature collection with another.
Merges two feature collections using the given ``multiset_op``
on each corresponding multiset and returns a new
:class:`FeatureCollection`. The contents of the two original
fe... | Merge this feature collection with another.
Merges two feature collections using the given ``multiset_op``
on each corresponding multiset and returns a new
:class:`FeatureCollection`. The contents of the two original
feature collections are not modified.
For each feature name i... |
def convergence_from_grid(self, grid):
""" Calculate the projected convergence at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the surface density is computed on.
"""
s... | Calculate the projected convergence at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the surface density is computed on. |
def load_isd_daily_temp_data(
self, start, end, read_from_cache=True, write_to_cache=True
):
""" Load resampled daily ISD temperature data from start date to end date (inclusive).
This is the primary convenience method for loading resampled daily ISD temperature data.
Parameters
... | Load resampled daily ISD temperature data from start date to end date (inclusive).
This is the primary convenience method for loading resampled daily ISD temperature data.
Parameters
----------
start : datetime.datetime
The earliest date from which to load data.
end... |
def export_to_dicts(table, *args, **kwargs):
"""Export a `rows.Table` to a list of dicts"""
field_names = table.field_names
return [{key: getattr(row, key) for key in field_names} for row in table] | Export a `rows.Table` to a list of dicts |
def handle_selected_page(self):
"""
Open the subscription and submission pages subwindows, but close the
current page if any other type of page is selected.
"""
if not self.selected_page:
pass
if self.selected_page.name in ('subscription', 'submission'):
... | Open the subscription and submission pages subwindows, but close the
current page if any other type of page is selected. |
def delete_ec2_nodes(
instance_id_list,
client=None
):
"""This deletes EC2 nodes and terminates the instances.
Parameters
----------
instance_id_list : list of str
A list of EC2 instance IDs to terminate.
client : boto3.Client or None
If None, this function will in... | This deletes EC2 nodes and terminates the instances.
Parameters
----------
instance_id_list : list of str
A list of EC2 instance IDs to terminate.
client : boto3.Client or None
If None, this function will instantiate a new `boto3.Client` object to
use in its operations. Altern... |
def _make_repr_table_from_sframe(X):
"""
Serializes an SFrame to a list of strings, that, when printed, creates a well-formatted table.
"""
assert isinstance(X, _SFrame)
column_names = X.column_names()
out_data = [ [None]*len(column_names) for i in range(X.num_rows())]
column_sizes = [le... | Serializes an SFrame to a list of strings, that, when printed, creates a well-formatted table. |
def state(self):
"""Get the Document's state"""
state = self._resource.get('state', self.default_state)
if state in State:
return state
else:
return getattr(State, state) | Get the Document's state |
def _check_connection(self):
"""Check if connection is alive every reconnect_timeout seconds."""
try:
super()._check_connection()
except OSError as exc:
_LOGGER.error(exc)
self.protocol.transport.close()
self.protocol.conn_lost_callback()
... | Check if connection is alive every reconnect_timeout seconds. |
def __create_coordinates(self, lat, lon, elev):
"""
GeoJSON standard:
Use to determine 2-point or 4-point coordinates
:param list lat:
:param list lon:
:return dict:
"""
# Sort lat an lon in numerical order
lat.sort()
lon.sort()
geo... | GeoJSON standard:
Use to determine 2-point or 4-point coordinates
:param list lat:
:param list lon:
:return dict: |
def predict(self):
""" predict the value of the fixed effect """
RV = np.zeros((self.N,self.P))
for term_i in range(self.n_terms):
RV+=np.dot(self.Fstar()[term_i],np.dot(self.B()[term_i],self.Astar()[term_i]))
return RV | predict the value of the fixed effect |
def relative_datetime(self):
"""Return human-readable relative time string."""
now = datetime.now(timezone.utc)
tense = "from now" if self.created_at > now else "ago"
return "{0} {1}".format(humanize.naturaldelta(now - self.created_at), tense) | Return human-readable relative time string. |
def plot_evec(fignum, Vs, symsize, title):
"""
plots eigenvector directions of S vectors
Paramters
________
fignum : matplotlib figure number
Vs : nested list of eigenvectors
symsize : size in pts for symbol
title : title for plot
"""
#
plt.figure(num=fignum)
plt.text(-1.1, ... | plots eigenvector directions of S vectors
Paramters
________
fignum : matplotlib figure number
Vs : nested list of eigenvectors
symsize : size in pts for symbol
title : title for plot |
def generate_ppi_network(
ppi_graph_path: str,
dge_list: List[Gene],
max_adj_p: float,
max_log2_fold_change: float,
min_log2_fold_change: float,
ppi_edge_min_confidence: Optional[float] = None,
current_disease_ids_path: Optional[str] = None,
disease_associ... | Generate the protein-protein interaction network.
:return Network: Protein-protein interaction network with information on differential expression. |
def get_authorization_user(self, **kwargs):
"""Gets the user the authorization object is for."""
if self.authorization_user is not None:
return self.authorization_user
self.authorization_user = self.request.user
return self.request.user | Gets the user the authorization object is for. |
def load_schema(schema_path):
"""Load the JSON schema at the given path as a Python object.
Args:
schema_path: A filename for a JSON schema.
Returns:
A Python object representation of the schema.
"""
try:
with open(schema_path) as schema_file:
schema = json.loa... | Load the JSON schema at the given path as a Python object.
Args:
schema_path: A filename for a JSON schema.
Returns:
A Python object representation of the schema. |
def _gzip_open_filename(handle):
"""Hide Python 2 vs. 3 differences in gzip.open()"""
import gzip
if sys.version_info[0] > 2:
handle = gzip.open(handle, mode='rt', encoding="UTF-8")
else:
handle = gzip.open(handle)
return handle | Hide Python 2 vs. 3 differences in gzip.open() |
def get_as_bytes(self, s3_path):
"""
Get the contents of an object stored in S3 as bytes
:param s3_path: URL for target S3 location
:return: File contents as pure bytes
"""
(bucket, key) = self._path_to_bucket_and_key(s3_path)
obj = self.s3.Object(bucket, key)
... | Get the contents of an object stored in S3 as bytes
:param s3_path: URL for target S3 location
:return: File contents as pure bytes |
def _set_url(self, url):
"""
Set a new URL for the data server. If we're unable to contact
the given url, then the original url is kept.
"""
original_url = self._url
try:
self._update_index(url)
except:
self._url = original_url
raise | Set a new URL for the data server. If we're unable to contact
the given url, then the original url is kept. |
def playURI(self, uri):
"""Play a Spotify uri, for example spotify:track:5Yn8WCB4Dqm8snemB5Mu4K
:param uri: Playlist, Artist, Album, or Song Uri
"""
url: str = get_url("/remote/play.json")
params = {
"oauth": self._oauth_token,
"csrf": self._csrf_token,
... | Play a Spotify uri, for example spotify:track:5Yn8WCB4Dqm8snemB5Mu4K
:param uri: Playlist, Artist, Album, or Song Uri |
def _op_msg_no_header(flags, command, identifier, docs, check_keys, opts):
"""Get a OP_MSG message.
Note: this method handles multiple documents in a type one payload but
it does not perform batch splitting and the total message size is
only checked *after* generating the entire message.
"""
# ... | Get a OP_MSG message.
Note: this method handles multiple documents in a type one payload but
it does not perform batch splitting and the total message size is
only checked *after* generating the entire message. |
def get_item_with_id(self, uid):
"""
Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found.
"""
for item in self.get_items():
... | Returns item for defined UID.
>>> book.get_item_with_id('image_001')
:Args:
- uid: UID for the item
:Returns:
Returns item object. Returns None if nothing was found. |
def compare_and_set(self, expect, update):
'''
Atomically sets the value to `update` if the current value is equal to
`expect`.
:param expect: The expected current value.
:param update: The value to set if and only if `expect` equals the
current value.
'''
... | Atomically sets the value to `update` if the current value is equal to
`expect`.
:param expect: The expected current value.
:param update: The value to set if and only if `expect` equals the
current value. |
def convert_sequence_to_motor_units(cycles, unit_converter):
""" Converts a move sequence to motor units.
Converts a move sequence to motor units using the provied converter.
Parameters
----------
cycles : iterable of dicts
The iterable of cycles of motion to do one after another. See
... | Converts a move sequence to motor units.
Converts a move sequence to motor units using the provied converter.
Parameters
----------
cycles : iterable of dicts
The iterable of cycles of motion to do one after another. See
``compile_sequence`` for format.
unit_converter : UnitConvert... |
def run_step(context):
"""Wipe the entire context.
Args:
Context is a dictionary or dictionary-like.
Does not require any specific keys in context.
"""
logger.debug("started")
context.clear()
logger.info(f"Context wiped. New context size: {len(context)}")
logger.debug("don... | Wipe the entire context.
Args:
Context is a dictionary or dictionary-like.
Does not require any specific keys in context. |
def hash(self):
"""
Return a value that's used to uniquely identify an entry in a date so we can regroup all entries that share the
same hash.
"""
return u''.join([
self.alias,
self.description,
str(self.ignored),
str(self.flags),
... | Return a value that's used to uniquely identify an entry in a date so we can regroup all entries that share the
same hash. |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
# pylint: disable=too-many-arguments
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for specification of input and result values.
Implements the correction f... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for specification of input and result values.
Implements the correction factor for the upper crust, equation (12) on
p. 484:
``P' = P x Correction_factor`` |
def _truncated_power_method(self, A, x0, k, max_iter=10000, thresh=1e-8):
'''
given a matrix A, an initial guess x0, and a maximum cardinality k,
find the best k-sparse approximation to its dominant eigenvector
References
----------
[1] Yuan, X-T. and Zhang, T. "Truncate... | given a matrix A, an initial guess x0, and a maximum cardinality k,
find the best k-sparse approximation to its dominant eigenvector
References
----------
[1] Yuan, X-T. and Zhang, T. "Truncated Power Method for Sparse Eigenvalue Problems."
Journal of Machine Learning Research. ... |
def api_request(*args, **kwargs):
"""
Wrapper which converts a requests.Response into our custom APIResponse
object
:param args:
:param kwargs:
:return:
"""
r = requests.request(*args, **kwargs)
return APIResponse(r) | Wrapper which converts a requests.Response into our custom APIResponse
object
:param args:
:param kwargs:
:return: |
def reftrack_element_data(rt, role):
"""Return the data for the element (e.g. the Asset or Shot)
:param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data
:type rt: :class:`jukeboxcore.reftrack.Reftrack`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data fo... | Return the data for the element (e.g. the Asset or Shot)
:param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data
:type rt: :class:`jukeboxcore.reftrack.Reftrack`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the element
:rtype: depending on role
... |
def list_tables(self):
"""
Runs the ``\\dt`` command and returns a list of column values with
information about all tables in the database.
"""
lines = output_lines(self.exec_psql('\\dt'))
return [line.split('|') for line in lines] | Runs the ``\\dt`` command and returns a list of column values with
information about all tables in the database. |
def fetch_next(self):
"""A Future used with `gen.coroutine`_ to asynchronously retrieve the
next document in the result set, fetching a batch of documents from the
server if necessary. Resolves to ``False`` if there are no more
documents, otherwise :meth:`next_object` is guaranteed to re... | A Future used with `gen.coroutine`_ to asynchronously retrieve the
next document in the result set, fetching a batch of documents from the
server if necessary. Resolves to ``False`` if there are no more
documents, otherwise :meth:`next_object` is guaranteed to return a
document.
... |
def attach_event_handler(canvas, handler=close_on_esc_or_middlemouse):
"""
Attach a handler function to the ProcessedEvent slot, defaulting to
closing when middle mouse is clicked or escape is pressed
Note that escape only works if the pad has focus, which in ROOT-land means
the mouse has to be ove... | Attach a handler function to the ProcessedEvent slot, defaulting to
closing when middle mouse is clicked or escape is pressed
Note that escape only works if the pad has focus, which in ROOT-land means
the mouse has to be over the canvas area. |
def visit_AsyncFunctionDef(self, node):
"""Visit an async function node."""
node = self.get_function_node(node)
if node is not None:
node._async = True | Visit an async function node. |
def _load_isd_station_metadata(download_path):
""" Collect metadata for US isd stations.
"""
from shapely.geometry import Point
# load ISD history which contains metadata
isd_history = pd.read_csv(
os.path.join(download_path, "isd-history.csv"),
dtype=str,
parse_dates=["BEGI... | Collect metadata for US isd stations. |
def QA_SU_save_stock_list(client=DATABASE, ui_log=None, ui_progress=None):
"""save stock_list
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE})
"""
client.drop_collection('stock_list')
coll = client.stock_list
coll.create_index('code')
try:
# 🛠todo ... | save stock_list
Keyword Arguments:
client {[type]} -- [description] (default: {DATABASE}) |
def upsert(manager, defaults=None, updates=None, **kwargs):
"""
Performs an update on an object or an insert if the object does not exist.
:type defaults: dict
:param defaults: These values are set when the object is created, but are irrelevant
when the object already exists. This field sho... | Performs an update on an object or an insert if the object does not exist.
:type defaults: dict
:param defaults: These values are set when the object is created, but are irrelevant
when the object already exists. This field should only be used when values only need to
be set during crea... |
def printPre(self, *args):
"""
get/set the str_pre string.
"""
if len(args):
self.b_printPre = args[0]
else:
return self.b_printPre | get/set the str_pre string. |
def to_volume(self):
"""Return a 3D volume of the data"""
if hasattr(self.header.definitions, "Lattice"):
X, Y, Z = self.header.definitions.Lattice
else:
raise ValueError("Unable to determine data size")
volume = self.decoded_data.reshape(Z, Y, X)
... | Return a 3D volume of the data |
def get(self, key, value):
"""Gets an element from an index under a given
key-value pair
@params key: Index key string
@params value: Index value string
@returns A generator of Vertex or Edge objects"""
for element in self.neoindex[key][value]:
if self.indexCl... | Gets an element from an index under a given
key-value pair
@params key: Index key string
@params value: Index value string
@returns A generator of Vertex or Edge objects |
def sized_imap(func, iterable, strict=False):
'''
Return an iterable whose elements are the result of applying the callable `func`
to each element of `iterable`. If `iterable` has a `len()`, then the iterable returned
by this function will have the same `len()`. Otherwise calling `len()` on the
retu... | Return an iterable whose elements are the result of applying the callable `func`
to each element of `iterable`. If `iterable` has a `len()`, then the iterable returned
by this function will have the same `len()`. Otherwise calling `len()` on the
returned iterable will raise `TypeError`.
:param func: Th... |
def ingest_user(self):
'''Username responsible for ingesting this object into the repository,
as recorded in the :attr:`audit_trail`, if available.'''
# if there is an audit trail and it has records and the first
# action is ingest, return the user
if self.audit_trail and self.au... | Username responsible for ingesting this object into the repository,
as recorded in the :attr:`audit_trail`, if available. |
def XYZ100_to_CIECAM02(self, XYZ100, on_negative_A="raise"):
"""Computes CIECAM02 appearance correlates for the given tristimulus
value(s) XYZ (normalized to be on the 0-100 scale).
Example: ``vc.XYZ100_to_CIECAM02([30.0, 45.5, 21.0])``
:param XYZ100: An array-like of tristimulus value... | Computes CIECAM02 appearance correlates for the given tristimulus
value(s) XYZ (normalized to be on the 0-100 scale).
Example: ``vc.XYZ100_to_CIECAM02([30.0, 45.5, 21.0])``
:param XYZ100: An array-like of tristimulus values. These should be
given on the 0-100 scale, not the 0-1 scale... |
def _iterate_uniqueness_keys(self, field):
"""Iterates over the keys marked as "unique"
in the specified field.
Arguments:
field:
The field of which key's to
iterate over.
"""
uniqueness = getattr(field, 'uniqueness', None)
if... | Iterates over the keys marked as "unique"
in the specified field.
Arguments:
field:
The field of which key's to
iterate over. |
def get_homes(self, query=None, gps_lat=None, gps_lng=None, offset=0, items_per_grid=8):
"""
Search listings with
* Query (e.g. query="Lisbon, Portugal") or
* Location (e.g. gps_lat=55.6123352&gps_lng=37.7117917)
"""
params = {
'is_guided_search': 'tru... | Search listings with
* Query (e.g. query="Lisbon, Portugal") or
* Location (e.g. gps_lat=55.6123352&gps_lng=37.7117917) |
def require_perms(view_func, required):
"""Enforces permission-based access controls.
:param list required: A tuple of permission names, all of which the request
user must possess in order access the decorated view.
Example usage::
from horizon.decorators import require_... | Enforces permission-based access controls.
:param list required: A tuple of permission names, all of which the request
user must possess in order access the decorated view.
Example usage::
from horizon.decorators import require_perms
@require_perms(['foo.admin', 'f... |
def case_comments(self):
"""Return only comments made on the case."""
comments = (comment for comment in self.comments if
comment.variant_id is None)
return comments | Return only comments made on the case. |
def export_olx(self, tarball, root_path):
"""if sequestered, only export the assets"""
def append_asset_to_soup_and_export(asset_):
if isinstance(asset_, Item):
try:
unique_url = asset_.export_olx(tarball, root_path)
except AttributeError:
... | if sequestered, only export the assets |
def getDescendants(self, all_descendants=False):
"""Returns the descendant Analysis Requests
:param all_descendants: recursively include all descendants
"""
# N.B. full objects returned here from
# `Products.Archetypes.Referenceable.getBRefs`
# -> don't add th... | Returns the descendant Analysis Requests
:param all_descendants: recursively include all descendants |
def write_oplog_progress(self):
""" Writes oplog progress to file provided by user
"""
if self.oplog_checkpoint is None:
return None
with self.oplog_progress as oplog_prog:
oplog_dict = oplog_prog.get_dict()
items = [[name, util.bson_ts_to_long(oplog_dic... | Writes oplog progress to file provided by user |
def execute(self, sources, target):
"""
:type sources: list[DFAdapter]
:type target: DFAdapter
"""
fields = self._get_fields_list_from_eps(sources)
ret_fields = fields[0]
if self.clear_feature:
ret_fields = list(self._remove_field_roles(ret_fields, set... | :type sources: list[DFAdapter]
:type target: DFAdapter |
def to_excess_returns(returns, rf, nperiods=None):
"""
Given a series of returns, it will return the excess returns over rf.
Args:
* returns (Series, DataFrame): Returns
* rf (float, Series): `Risk-Free rate(s) <https://www.investopedia.com/terms/r/risk-freerate.asp>`_ expressed in annualiz... | Given a series of returns, it will return the excess returns over rf.
Args:
* returns (Series, DataFrame): Returns
* rf (float, Series): `Risk-Free rate(s) <https://www.investopedia.com/terms/r/risk-freerate.asp>`_ expressed in annualized term or return series
* nperiods (int): Optional. If... |
def create_environment_vip(self):
"""Get an instance of environment_vip services facade."""
return EnvironmentVIP(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | Get an instance of environment_vip services facade. |
def list(self, all_my_agents=False, limit=500, offset=0):
"""List `all` the things created by this client on this or all your agents
Returns QAPI list function payload
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
if there is a communications pr... | List `all` the things created by this client on this or all your agents
Returns QAPI list function payload
Raises [LinkException](../Core/AmqpLink.m.html#IoticAgent.Core.AmqpLink.LinkException)
if there is a communications problem between you and the infrastructure
`all_my_agents` (op... |
def method(self, returns, **parameter_types):
"""Syntactic sugar for registering a method
Example:
>>> registry = Registry()
>>> @registry.method(returns=int, x=int, y=int)
... def add(x, y):
... return x + y
:param returns: The method's ret... | Syntactic sugar for registering a method
Example:
>>> registry = Registry()
>>> @registry.method(returns=int, x=int, y=int)
... def add(x, y):
... return x + y
:param returns: The method's return type
:type returns: type
:param param... |
def register_callback_reassigned(self, func, serialised=True):
"""
Register a callback for resource reassignment. This will be called when any resource
is reassigned to or from your agent.
If `serialised` is not set, the callbacks might arrive in a different order to they were requested... | Register a callback for resource reassignment. This will be called when any resource
is reassigned to or from your agent.
If `serialised` is not set, the callbacks might arrive in a different order to they were requested.
The payload passed to your callback is an OrderedDict with the following... |
def get_reset_data(self, data):
""" Returns the user info to reset """
error = False
reset = None
msg = ""
user = self.database.users.find_one({"reset": data["reset"]})
if user is None:
error = True
msg = "Invalid reset hash."
else:
... | Returns the user info to reset |
def i2s_frameid(x):
""" Get representation name of a pnio frame ID
:param x: a key of the PNIO_FRAME_IDS dictionary
:returns: str
"""
try:
return PNIO_FRAME_IDS[x]
except KeyError:
pass
if 0x0100 <= x < 0x1000:
return "RT_CLASS_3 (%4x)" % x
if 0x8000 <= x < 0xC00... | Get representation name of a pnio frame ID
:param x: a key of the PNIO_FRAME_IDS dictionary
:returns: str |
def do_work_spec(self, args):
'''dump the contents of an existing work spec'''
work_spec_name = self._get_work_spec_name(args)
spec = self.task_master.get_work_spec(work_spec_name)
if args.json:
self.stdout.write(json.dumps(spec, indent=4, sort_keys=True) +
... | dump the contents of an existing work spec |
def start_capture(self, adapter_number, output_file):
"""
Starts a packet capture.
:param adapter_number: adapter number
:param output_file: PCAP destination file for the capture
"""
try:
adapter = self._ethernet_adapters[adapter_number]
except KeyEr... | Starts a packet capture.
:param adapter_number: adapter number
:param output_file: PCAP destination file for the capture |
def _set_get_stp_brief_info(self, v, load=False):
"""
Setter method for get_stp_brief_info, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_stp_brief_info is considered as a private
method. ... | Setter method for get_stp_brief_info, mapped from YANG variable /brocade_xstp_ext_rpc/get_stp_brief_info (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_stp_brief_info is considered as a private
method. Backends looking to populate this variable should
do so vi... |
def getScriptLocation():
"""Helper function to get the location of a Python file."""
location = os.path.abspath("./")
if __file__.rfind("/") != -1:
location = __file__[:__file__.rfind("/")]
return location | Helper function to get the location of a Python file. |
def _expand_prefix_spec(self, spec, prefix = ''):
""" Expand prefix specification to SQL.
"""
# sanity checks
if type(spec) is not dict:
raise NipapInputError('invalid prefix specification')
for key in spec.keys():
if key not in _prefix_spec:
... | Expand prefix specification to SQL. |
def build(self, endpoint, values=None, method=None, force_external=False,
append_unknown=True):
"""Building URLs works pretty much the other way round. Instead of
`match` you call `build` and pass it the endpoint and a dict of
arguments for the placeholders.
The `build` f... | Building URLs works pretty much the other way round. Instead of
`match` you call `build` and pass it the endpoint and a dict of
arguments for the placeholders.
The `build` function also accepts an argument called `force_external`
which, if you set it to `True` will force external URLs.... |
def notify(self, msg, color='green', notify='true', message_format='text'):
"""Send notification to specified HipChat room"""
self.message_dict = {
'message': msg,
'color': color,
'notify': notify,
'message_format': message_format,
}
if not... | Send notification to specified HipChat room |
def possible_version_evaluation(self):
"""Evaluate the possible range of versions for each target, yielding the output analysis."""
only_broken = self.get_options().only_broken
ranges = self._ranges
yield 'Allowable JVM platform ranges (* = anything):'
for target in sorted(filter(self._is_relevant, ... | Evaluate the possible range of versions for each target, yielding the output analysis. |
def load_schema(schema):
"""
Load a schema file with path +schema+ into the database. Assumes that
there exists an active database connection.
"""
with repo.Repo.db:
repo.Repo.db.executescript(schema) | Load a schema file with path +schema+ into the database. Assumes that
there exists an active database connection. |
def dead(self):
"""Whether the callback no longer exists.
If the callback is maintained via a weak reference, and that
weak reference has been collected, this will be true
instead of false.
"""
if not self._weak:
return False
cb = self._callback()
... | Whether the callback no longer exists.
If the callback is maintained via a weak reference, and that
weak reference has been collected, this will be true
instead of false. |
async def _process_latching(self, key, latching_entry):
"""
This is a private utility method.
This method process latching events and either returns them via
callback or stores them in the latch map
:param key: Encoded pin
:param latching_entry: a latch table entry
... | This is a private utility method.
This method process latching events and either returns them via
callback or stores them in the latch map
:param key: Encoded pin
:param latching_entry: a latch table entry
:returns: Callback or store data in latch map |
def compute_laplacian(self, lap_type='combinatorial'):
r"""Compute a graph Laplacian.
For undirected graphs, the combinatorial Laplacian is defined as
.. math:: L = D - W,
where :math:`W` is the weighted adjacency matrix and :math:`D` the
weighted degree matrix. The normalized... | r"""Compute a graph Laplacian.
For undirected graphs, the combinatorial Laplacian is defined as
.. math:: L = D - W,
where :math:`W` is the weighted adjacency matrix and :math:`D` the
weighted degree matrix. The normalized Laplacian is defined as
.. math:: L = I - D^{-1/2} W ... |
def register_languages():
"""Register all supported languages to ensure compatibility."""
for language in set(SUPPORTED_LANGUAGES) - {"en"}:
language_stemmer = partial(nltk_stemmer, get_language_stemmer(language))
Pipeline.register_function(language_stemmer, "stemmer-{}".format(language)) | Register all supported languages to ensure compatibility. |
def _process_image_msg(self, msg):
""" Process an image message and return a numpy array with the image data
Returns
-------
:obj:`numpy.ndarray` containing the image in the image message
Raises
------
CvBridgeError
If the bridge is not able to conver... | Process an image message and return a numpy array with the image data
Returns
-------
:obj:`numpy.ndarray` containing the image in the image message
Raises
------
CvBridgeError
If the bridge is not able to convert the image |
def gen_unordered(self):
"""Generate batches of operations, batched by type of
operation, in arbitrary order.
"""
operations = [_Run(_INSERT), _Run(_UPDATE), _Run(_DELETE)]
for idx, (op_type, operation) in enumerate(self.ops):
operations[op_type].add(idx, operation)
... | Generate batches of operations, batched by type of
operation, in arbitrary order. |
def calculate_request_digest(method, partial_digest, digest_response=None,
uri=None, nonce=None, nonce_count=None, client_nonce=None):
'''
Calculates a value for the 'response' value of the client authentication request.
Requires the 'partial_digest' calculated from the realm, u... | Calculates a value for the 'response' value of the client authentication request.
Requires the 'partial_digest' calculated from the realm, username, and password.
Either call it with a digest_response to use the values from an authentication request,
or pass the individual parameters (i.e. to generate an a... |
def load(cls, path_to_file):
"""
Loads the image data from a file on disk and tries to guess the image MIME type
:param path_to_file: path to the source file
:type path_to_file: str
:return: a `pyowm.image.Image` instance
"""
import mimetypes
mimetypes.in... | Loads the image data from a file on disk and tries to guess the image MIME type
:param path_to_file: path to the source file
:type path_to_file: str
:return: a `pyowm.image.Image` instance |
def run_preassembly_related(preassembler, beliefengine, **kwargs):
"""Run related stage of preassembly on a list of statements.
Parameters
----------
preassembler : indra.preassembler.Preassembler
A Preassembler instance which already has a set of unique statements
internally.
belie... | Run related stage of preassembly on a list of statements.
Parameters
----------
preassembler : indra.preassembler.Preassembler
A Preassembler instance which already has a set of unique statements
internally.
beliefengine : indra.belief.BeliefEngine
A BeliefEngine instance.
r... |
def visible(self, visible):
"""When visible changed, do setup or unwatch and call visible_callback"""
self._visible = visible
if visible and len(self.panel.objects) == 0:
self.setup()
self.select.visible = True
self.control_panel.extend(self.controls)
... | When visible changed, do setup or unwatch and call visible_callback |
def eval(self, expression, args=None, *,
timeout=-1.0, push_subscribe=False) -> _MethodRet:
"""
Eval request coroutine.
Examples:
.. code-block:: pycon
>>> await conn.eval('return 42')
<Response sync=3 rowcount=1 data=[42]>
... | Eval request coroutine.
Examples:
.. code-block:: pycon
>>> await conn.eval('return 42')
<Response sync=3 rowcount=1 data=[42]>
>>> await conn.eval('return box.info.version')
<Response sync=3 rowcount=1 data=['2.1.1-7-gd381a45b... |
def run(configobj, wcsmap=None):
"""
Initial example by Nadia ran MD with configobj EPAR using:
It can be run in one of two ways:
from stsci.tools import teal
1. Passing a config object to teal
teal.teal('drizzlepac/pars/astrodrizzle.cfg')
2. Passing a task name:
... | Initial example by Nadia ran MD with configobj EPAR using:
It can be run in one of two ways:
from stsci.tools import teal
1. Passing a config object to teal
teal.teal('drizzlepac/pars/astrodrizzle.cfg')
2. Passing a task name:
teal.teal('astrodrizzle')
The exa... |
def _check_minions_directories(pki_dir):
'''
Return the minion keys directory paths.
This function is a copy of salt.key.Key._check_minions_directories.
'''
minions_accepted = os.path.join(pki_dir, salt.key.Key.ACC)
minions_pre = os.path.join(pki_dir, salt.key.Key.PEND)
minions_rejected = o... | Return the minion keys directory paths.
This function is a copy of salt.key.Key._check_minions_directories. |
def write(self, filename, type_='obo'): #FIXME this is bugged
""" Write file, will not overwrite files with the same name
outputs to obo by default but can also output to ttl if
passed type_='ttl' when called.
"""
if os.path.exists(filename):
name, ext = file... | Write file, will not overwrite files with the same name
outputs to obo by default but can also output to ttl if
passed type_='ttl' when called. |
def parsebool(el):
"""
Parse a ``BeautifulSoup`` element as a bool
"""
txt = text(el)
up = txt.upper()
if up == "OUI":
return True
if up == "NON":
return False
return bool(parseint(el)) | Parse a ``BeautifulSoup`` element as a bool |
def namedb_history_save( cur, opcode, history_id, creator_address, value_hash, block_id, vtxindex, txid, accepted_rec, history_snapshot=False ):
"""
Insert data into the state engine's history.
It must be for a never-before-seen (txid,block_id,vtxindex) set.
@history_id is either the name or namespace I... | Insert data into the state engine's history.
It must be for a never-before-seen (txid,block_id,vtxindex) set.
@history_id is either the name or namespace ID
Return True on success
Raise an Exception on error |
def record_serializer(self):
"""Github Release API class."""
imp = current_app.config['GITHUB_RECORD_SERIALIZER']
if isinstance(imp, string_types):
return import_string(imp)
return imp | Github Release API class. |
def run(self):
'''
Execute the salt command line
'''
import salt.client
self.parse_args()
if self.config['log_level'] not in ('quiet', ):
# Setup file logging!
self.setup_logfile_logger()
verify_log(self.config)
try:
... | Execute the salt command line |
def fig16():
"""The network shown in Figure 5B of the 2014 IIT 3.0 paper."""
tpm = np.array([
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 1, 0, 0],
[1, 0, 0, 0, 0, 0, 0],
[1, 0, 1, 0, 1, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
... | The network shown in Figure 5B of the 2014 IIT 3.0 paper. |
def sanitize_type(raw_type):
"""Sanitize the raw type string."""
cleaned = get_printable(raw_type).strip()
for bad in [
r'__drv_aliasesMem', r'__drv_freesMem',
r'__drv_strictTypeMatch\(\w+\)',
r'__out_data_source\(\w+\)',
r'_In_NLS_string_\(\w+\)',
... | Sanitize the raw type string. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.