code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _refresh(self, session, stopping=False):
'''Get this task's current state.
This must be called under the registry's lock. It updates
the :attr:`finished` and :attr:`failed` flags and the
:attr:`data` dictionary based on the current state in the
registry.
In the nor... | Get this task's current state.
This must be called under the registry's lock. It updates
the :attr:`finished` and :attr:`failed` flags and the
:attr:`data` dictionary based on the current state in the
registry.
In the normal case, nothing will change and this function
... |
def this_week_day(base_date, weekday):
"""
Finds coming weekday
"""
day_of_week = base_date.weekday()
# If today is Tuesday and the query is `this monday`
# We should output the next_week monday
if day_of_week > weekday:
return next_week_day(base_date, weekday)
start_of_this_week... | Finds coming weekday |
def clear_vdp_vsi(self, port_uuid):
"""Stores the vNIC specific info for VDP Refresh.
:param uuid: vNIC UUID
"""
try:
LOG.debug("Clearing VDP VSI MAC %(mac)s UUID %(uuid)s",
{'mac': self.vdp_vif_map[port_uuid].get('mac'),
'uuid': ... | Stores the vNIC specific info for VDP Refresh.
:param uuid: vNIC UUID |
def verify_jwt_in_request_optional():
"""
Optionally check if this request has a valid access token. If an access
token in present in the request, :func:`~flask_jwt_extended.get_jwt_identity`
will return the identity of the access token. If no access token is
present in the request, this simply re... | Optionally check if this request has a valid access token. If an access
token in present in the request, :func:`~flask_jwt_extended.get_jwt_identity`
will return the identity of the access token. If no access token is
present in the request, this simply returns, and
:func:`~flask_jwt_extended.get_jwt_... |
def info(self, category_id, store_view=None, attributes=None):
"""
Retrieve Category details
:param category_id: ID of category to retrieve
:param store_view: Store view ID or code
:param attributes: Return the fields specified
:return: Dictionary of data
"""
... | Retrieve Category details
:param category_id: ID of category to retrieve
:param store_view: Store view ID or code
:param attributes: Return the fields specified
:return: Dictionary of data |
def process_delivery(message, notification):
"""Function to process a delivery notification"""
mail = message['mail']
delivery = message['delivery']
if 'timestamp' in delivery:
delivered_datetime = clean_time(delivery['timestamp'])
else:
delivered_datetime = None
deliveries = [... | Function to process a delivery notification |
def _ns_query(self, session):
"""
Return a SQLAlchemy query that is already namespaced by the app and namespace given to this backend
during initialization.
Returns: a SQLAlchemy query object
"""
return session.query(ORMJob).filter(ORMJob.app == self.app,
... | Return a SQLAlchemy query that is already namespaced by the app and namespace given to this backend
during initialization.
Returns: a SQLAlchemy query object |
def parse_alert(output):
"""
Parses the supplied output and yields any alerts.
Example alert format:
01/28/14-22:26:04.885446 [**] [1:1917:11] INDICATOR-SCAN UPnP service discover attempt [**] [Classification: Detection of a Network Scan] [Priority: 3] {UDP} 10.1.1.132:58650 -> 239.255.255.250:1900
... | Parses the supplied output and yields any alerts.
Example alert format:
01/28/14-22:26:04.885446 [**] [1:1917:11] INDICATOR-SCAN UPnP service discover attempt [**] [Classification: Detection of a Network Scan] [Priority: 3] {UDP} 10.1.1.132:58650 -> 239.255.255.250:1900
:param output: A string containing... |
def ping(self):
"""
Check server is alive over HTTP
"""
status, _, body = self._request('GET', self.ping_path())
return(status is not None) and (bytes_to_str(body) == 'OK') | Check server is alive over HTTP |
def CompleteHuntIfExpirationTimeReached(hunt_obj):
"""Marks the hunt as complete if it's past its expiry time."""
# TODO(hanuszczak): This should not set the hunt state to `COMPLETED` but we
# should have a sparate `EXPIRED` state instead and set that.
if (hunt_obj.hunt_state not in [
rdf_hunt_objects.Hun... | Marks the hunt as complete if it's past its expiry time. |
def parse(self, data):
"""
Converts a CNML structure to a NetworkX Graph object
which is then returned.
"""
graph = self._init_graph()
# loop over links and create networkx graph
# Add only working nodes with working links
for link in data.get_inner_links(... | Converts a CNML structure to a NetworkX Graph object
which is then returned. |
def authorize(self, email, permission_type='read', cloud=None, api_key=None, version=None, **kwargs):
"""
This API endpoint allows you to authorize another user to access your model in a read or write capacity.
Before calling authorize, you must first make sure your model has been registered.
... | This API endpoint allows you to authorize another user to access your model in a read or write capacity.
Before calling authorize, you must first make sure your model has been registered.
Inputs:
email - String: The email of the user you would like to share access with.
permission_type ... |
def keyEvent(self, key, down=1):
"""For most ordinary keys, the "keysym" is the same as the corresponding ASCII value.
Other common keys are shown in the KEY_ constants."""
self.transport.write(pack("!BBxxI", 4, down, key)) | For most ordinary keys, the "keysym" is the same as the corresponding ASCII value.
Other common keys are shown in the KEY_ constants. |
def roc_curve(roc_objs, obj_labels, colors, markers, filename, figsize=(8, 8),
xlabel="Probability of False Detection",
ylabel="Probability of Detection",
title="ROC Curve", ticks=np.arange(0, 1.1, 0.1), dpi=300,
legend_params=None, bootstrap_sets=None, ci=(2.5, 9... | Plots a set receiver/relative operating characteristic (ROC) curves from DistributedROC objects.
The ROC curve shows how well a forecast discriminates between two outcomes over a series of thresholds. It
features Probability of Detection (True Positive Rate) on the y-axis and Probability of False Detection
... |
def should_expand(self, tag):
"""Return whether the specified tag should be expanded."""
return self.indentation is not None and tag and (
not self.previous_indent or (
tag.serializer == 'list'
and tag.subtype.serializer in ('array', 'list', 'compound')
... | Return whether the specified tag should be expanded. |
def get_undefined_namespace_names(graph: BELGraph, namespace: str) -> Set[str]:
"""Get the names from a namespace that wasn't actually defined.
:return: The set of all names from the undefined namespace
"""
return {
exc.name
for _, exc, _ in graph.warnings
if isinstance(exc, Und... | Get the names from a namespace that wasn't actually defined.
:return: The set of all names from the undefined namespace |
def _train_lbfgs(self, X_feat_train, X_seq_train, y_train,
X_feat_valid, X_seq_valid, y_valid,
graph, var, other_var,
early_stop_patience=None,
n_cores=3):
"""
Train the model actual model
Updates weights / vari... | Train the model actual model
Updates weights / variables, computes and returns the training and validation accuracy |
def get_cutout(self, resource, resolution, x_range, y_range, z_range, time_range=None, id_list=[], no_cache=None, access_mode=CacheMode.no_cache, **kwargs):
"""Get a cutout from the volume service.
Note that access_mode=no_cache is desirable when reading large amounts of
data at onc... | Get a cutout from the volume service.
Note that access_mode=no_cache is desirable when reading large amounts of
data at once. In these cases, the data is not first read into the
cache, but instead, is sent directly from the data store to the
requester.
Args... |
def label_position(self):
'''
Find the largest region and position the label in that.
'''
reg_sizes = [(r.size(), r) for r in self.pieces]
reg_sizes.sort()
return reg_sizes[-1][1].label_position() | Find the largest region and position the label in that. |
def get_function_for_cognito_trigger(self, trigger):
"""
Get the associated function to execute for a cognito trigger
"""
print("get_function_for_cognito_trigger", self.settings.COGNITO_TRIGGER_MAPPING, trigger, self.settings.COGNITO_TRIGGER_MAPPING.get(trigger))
return self.sett... | Get the associated function to execute for a cognito trigger |
def add_job(self, idx):
"""Called after self.targets[idx] just got the job with header.
Override with subclasses. The default ordering is simple LRU.
The default loads are the number of outstanding jobs."""
self.loads[idx] += 1
for lis in (self.targets, self.loads):
... | Called after self.targets[idx] just got the job with header.
Override with subclasses. The default ordering is simple LRU.
The default loads are the number of outstanding jobs. |
def read(self, source = None, **options):
'''
Reads and optionally parses a single message.
:Parameters:
- `source` - optional data buffer to be read, if not specified data is
read from the wrapped stream
:Options:
- `raw` (`boolean`) - indicates wh... | Reads and optionally parses a single message.
:Parameters:
- `source` - optional data buffer to be read, if not specified data is
read from the wrapped stream
:Options:
- `raw` (`boolean`) - indicates whether read data should parsed or
returned in raw b... |
def dbg_print_irsb(self, irsb_addr, project=None):
"""
Pretty-print an IRSB with whitelist information
"""
if project is None:
project = self._project
if project is None:
raise Exception("Dict addr_to_run is empty. " + \
"Give... | Pretty-print an IRSB with whitelist information |
def pass_to_pipeline_if_article(
self,
response,
source_domain,
original_url,
rss_title=None
):
"""
Responsible for passing a NewscrawlerItem to the pipeline if the
response contains an article.
:param obj response: the scr... | Responsible for passing a NewscrawlerItem to the pipeline if the
response contains an article.
:param obj response: the scrapy response to work on
:param str source_domain: the response's domain as set for the crawler
:param str original_url: the url set in the json file
:param ... |
def plot_correlated_groups(self, group=None, n_genes=5, **kwargs):
"""Plots orthogonal expression patterns.
In the default mode, plots orthogonal gene expression patterns. A
specific correlated group of genes can be specified to plot gene
expression patterns within that group.
... | Plots orthogonal expression patterns.
In the default mode, plots orthogonal gene expression patterns. A
specific correlated group of genes can be specified to plot gene
expression patterns within that group.
Parameters
----------
group - int, optional, default None
... |
def _should_retry(exc):
"""Predicate for determining when to retry.
We retry if and only if the 'reason' is 'backendError'
or 'rateLimitExceeded'.
"""
if not hasattr(exc, "errors"):
return False
if len(exc.errors) == 0:
# Check for unstructured error returns, e.g. from GFE
... | Predicate for determining when to retry.
We retry if and only if the 'reason' is 'backendError'
or 'rateLimitExceeded'. |
def scp_file(dest_path, contents=None, kwargs=None, local_file=None):
'''
Use scp or sftp to copy a file to a server
'''
file_to_upload = None
try:
if contents is not None:
try:
tmpfd, file_to_upload = tempfile.mkstemp()
os.write(tmpfd, contents)
... | Use scp or sftp to copy a file to a server |
def iter_multi_items(mapping):
"""Iterates over the items of a mapping yielding keys and values
without dropping any from more complex structures.
"""
if isinstance(mapping, MultiDict):
for item in iteritems(mapping, multi=True):
yield item
elif isinstance(mapping, dict):
... | Iterates over the items of a mapping yielding keys and values
without dropping any from more complex structures. |
def save(self, fname, compression='blosc'):
"""
Save method for the Egg object
The data will be saved as a 'egg' file, which is a dictionary containing
the elements of a Egg saved in the hd5 format using
`deepdish`.
Parameters
----------
fname : str
... | Save method for the Egg object
The data will be saved as a 'egg' file, which is a dictionary containing
the elements of a Egg saved in the hd5 format using
`deepdish`.
Parameters
----------
fname : str
A name for the file. If the file extension (.egg) is n... |
def build(self, construct):
"""Build a single construct in CLIPS.
The Python equivalent of the CLIPS build command.
"""
if lib.EnvBuild(self._env, construct.encode()) != 1:
raise CLIPSError(self._env) | Build a single construct in CLIPS.
The Python equivalent of the CLIPS build command. |
def rename(self, newpath):
"Move folder to a new name, possibly a whole new path"
# POST https://www.jottacloud.com/jfs/**USERNAME**/Jotta/Sync/Ny%20mappe?mvDir=/**USERNAME**/Jotta/Sync/testFolder
#url = '%s?mvDir=/%s%s' % (self.path, self.jfs.username, newpath)
params = {'mvDir':'/%s%s'... | Move folder to a new name, possibly a whole new path |
def make_energy_funnel_data(self, cores=1):
"""Compares models created during the minimisation to the best model.
Returns
-------
energy_rmsd_gen: [(float, float, int)]
A list of triples containing the BUFF score, RMSD to the
top model and generation of a model g... | Compares models created during the minimisation to the best model.
Returns
-------
energy_rmsd_gen: [(float, float, int)]
A list of triples containing the BUFF score, RMSD to the
top model and generation of a model generated during the
minimisation. |
def precmd(self, line):
"""Handle alias expansion and ';;' separator."""
if not line.strip():
return line
args = line.split()
while args[0] in self.aliases:
line = self.aliases[args[0]]
ii = 1
for tmpArg in args[1:]:
line = ... | Handle alias expansion and ';;' separator. |
def getCandScoresMap(self, profile):
"""
Returns a dictionary that associates integer representations of each candidate with their
Copeland score.
:ivar Profile profile: A Profile object that represents an election profile.
"""
# Currently, we expect the profile to cont... | Returns a dictionary that associates integer representations of each candidate with their
Copeland score.
:ivar Profile profile: A Profile object that represents an election profile. |
def part_sum(x, i=0):
"""All subsetsums from x[i:]
:param x: table of values
:param int i: index defining suffix of x to be considered
:iterates: over all values, in arbitrary order
:complexity: :math:`O(2^{len(x)-i})`
"""
if i == len(x):
yield 0
else:
for s in part_sum(... | All subsetsums from x[i:]
:param x: table of values
:param int i: index defining suffix of x to be considered
:iterates: over all values, in arbitrary order
:complexity: :math:`O(2^{len(x)-i})` |
def iter_auth_hashes(user, purpose, minutes_valid):
"""
Generate auth tokens tied to user and specified purpose.
The hash expires at midnight on the minute of now + minutes_valid, such
that when minutes_valid=1 you get *at least* 1 minute to use the token.
"""
now = timezone.now().replace(micro... | Generate auth tokens tied to user and specified purpose.
The hash expires at midnight on the minute of now + minutes_valid, such
that when minutes_valid=1 you get *at least* 1 minute to use the token. |
def remove(self, safe=None):
"""Removes the document itself from database.
The optional ``safe`` argument is a boolean that specifies if the
remove method should wait for the operation to complete.
"""
self._session.remove(self, safe=None)
self._session.flush() | Removes the document itself from database.
The optional ``safe`` argument is a boolean that specifies if the
remove method should wait for the operation to complete. |
def images(self):
'''
a method to list the local docker images
:return: list of dictionaries with available image fields
[ {
'CREATED': '7 days ago',
'TAG': 'latest',
'IMAGE ID': '2298fbaac143',
'VIRTUAL SIZE':... | a method to list the local docker images
:return: list of dictionaries with available image fields
[ {
'CREATED': '7 days ago',
'TAG': 'latest',
'IMAGE ID': '2298fbaac143',
'VIRTUAL SIZE': '302.7 MB',
'REPOSITORY': 'test1... |
def start_notebook(self, name, context: dict, fg=False):
"""Start new IPython Notebook daemon.
:param name: The owner of the Notebook will be *name*. He/she gets a new Notebook content folder created where all files are placed.
:param context: Extra context information passed to the started No... | Start new IPython Notebook daemon.
:param name: The owner of the Notebook will be *name*. He/she gets a new Notebook content folder created where all files are placed.
:param context: Extra context information passed to the started Notebook. This must contain {context_hash:int} parameter used to ident... |
def dafopw(fname):
"""
Open a DAF for subsequent write requests.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafopw_c.html
:param fname: Name of DAF to be opened.
:type fname: str
:return: Handle assigned to DAF.
:rtype: int
"""
fname = stypes.stringToCharP(fname)
h... | Open a DAF for subsequent write requests.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dafopw_c.html
:param fname: Name of DAF to be opened.
:type fname: str
:return: Handle assigned to DAF.
:rtype: int |
def visit_attribute(self, node):
"""check if the getattr is an access to a class member
if so, register it. Also check for access to protected
class member from outside its class (but ignore __special__
methods)
"""
# Check self
if self._uses_mandatory_method_para... | check if the getattr is an access to a class member
if so, register it. Also check for access to protected
class member from outside its class (but ignore __special__
methods) |
def get_logger(name=None, level=logging.DEBUG, stream=None):
"""returns a colorized logger. This function can be used just like
:py:func:`logging.getLogger` except you can set the level right
away."""
logger = logging.getLogger(name)
colored = colorize_logger(logger, stream=stream, level=level)
... | returns a colorized logger. This function can be used just like
:py:func:`logging.getLogger` except you can set the level right
away. |
def __reorganize_chron_header(line):
"""
Reorganize the list of variables. If there are units given, log them.
:param str line:
:return dict: key: variable, val: units (optional)
"""
d = {}
# Header variables should be tab-delimited. Use regex to split by tabs
... | Reorganize the list of variables. If there are units given, log them.
:param str line:
:return dict: key: variable, val: units (optional) |
def is_special_string(obj):
"""Is special string."""
import bs4
return isinstance(obj, (bs4.Comment, bs4.Declaration, bs4.CData, bs4.ProcessingInstruction)) | Is special string. |
def _set_row_label(self, value):
"Set the row label format string (empty to hide)"
if not value:
self.wx_obj.SetRowLabelSize(0)
else:
self.wx_obj._table._row_label = value | Set the row label format string (empty to hide) |
def get_body(self):
"""Get the body value from the response.
:return: a future contains the deserialized value of body
"""
raw_body = yield get_arg(self, 2)
if not self.serializer:
raise tornado.gen.Return(raw_body)
else:
body = self.serializer.d... | Get the body value from the response.
:return: a future contains the deserialized value of body |
def potential_cloud_layer(self, pcp, water, tlow, land_cloud_prob, land_threshold,
water_cloud_prob, water_threshold=0.5):
"""Final step of determining potential cloud layer
Equation 18 (Zhu and Woodcock, 2012)
Saturation (green or red) test is not in the algorithm
... | Final step of determining potential cloud layer
Equation 18 (Zhu and Woodcock, 2012)
Saturation (green or red) test is not in the algorithm
Parameters
----------
pcps: ndarray
potential cloud pixels
water: ndarray
water mask
... |
def highlight_multiline_block(self, block, start_pattern, end_pattern, state, format):
"""
Highlights given multiline text block.
:param block: Text block.
:type block: QString
:param pattern: Start regex pattern.
:type pattern: QRegExp
:param pattern: End regex ... | Highlights given multiline text block.
:param block: Text block.
:type block: QString
:param pattern: Start regex pattern.
:type pattern: QRegExp
:param pattern: End regex pattern.
:type pattern: QRegExp
:param format: Format.
:type format: QTextCharForma... |
def _set_default_configuration_options(app):
"""
Sets the default configuration options used by this extension
"""
# Where to look for the JWT. Available options are cookies or headers
app.config.setdefault('JWT_TOKEN_LOCATION', ('headers',))
# Options for JWTs when the ... | Sets the default configuration options used by this extension |
def get_registration(self, path):
"""
Returns registration item for specified path.
If an email template is not registered, this will raise NotRegistered.
"""
if not self.is_registered(path):
raise NotRegistered("Email template not registered")
return self._r... | Returns registration item for specified path.
If an email template is not registered, this will raise NotRegistered. |
def get_pixel(framebuf, x, y):
"""Get the color of a given pixel"""
index = (y >> 3) * framebuf.stride + x
offset = y & 0x07
return (framebuf.buf[index] >> offset) & 0x01 | Get the color of a given pixel |
def create_CreateProcessWarnMultiproc(original_name):
"""
CreateProcess(*args, **kwargs)
"""
def new_CreateProcess(*args):
try:
import _subprocess
except ImportError:
import _winapi as _subprocess
warn_multiproc()
return getattr(_subprocess, origi... | CreateProcess(*args, **kwargs) |
def length_range(string, minimum, maximum):
""" Requires values' length to be in a certain range.
:param string: Value to validate
:param minimum: Minimum length to accept
:param maximum: Maximum length to accept
:type string: str
:type minimum: int
:type maximum: int
"""
int_range(... | Requires values' length to be in a certain range.
:param string: Value to validate
:param minimum: Minimum length to accept
:param maximum: Maximum length to accept
:type string: str
:type minimum: int
:type maximum: int |
def check_oscntab(oscntab, ccdamp, xsize, ysize, leading, trailing):
"""Check if the supplied parameters are in the
``OSCNTAB`` reference file.
.. note:: Even if an entry does not exist in ``OSCNTAB``,
as long as the subarray does not have any overscan,
it should not be a proble... | Check if the supplied parameters are in the
``OSCNTAB`` reference file.
.. note:: Even if an entry does not exist in ``OSCNTAB``,
as long as the subarray does not have any overscan,
it should not be a problem for CALACS.
.. note:: This function does not check the virtual bias r... |
def get_playlists(self, search, start=0, max_items=100):
"""Search for playlists.
See get_music_service_information for details on the arguments.
Note:
Un-intuitively this method returns MSAlbumList items. See
note in class doc string for details.
"""
r... | Search for playlists.
See get_music_service_information for details on the arguments.
Note:
Un-intuitively this method returns MSAlbumList items. See
note in class doc string for details. |
def filter_and_save(raw, symbol_ids, destination_path):
"""
Parameters
----------
raw : dict
with key 'handwriting_datasets'
symbol_ids : dict
Maps LaTeX to write-math.com id
destination_path : str
Path where the filtered dict 'raw' will be saved
"""
logging.info(... | Parameters
----------
raw : dict
with key 'handwriting_datasets'
symbol_ids : dict
Maps LaTeX to write-math.com id
destination_path : str
Path where the filtered dict 'raw' will be saved |
def get_source(self, source_id=None, source_name=None):
"""Returns a dict with keys ['id', 'name', 'description'] or None if
no match. The ``id`` field is guaranteed to be an int that
exists in table source. Requires exactly one of ``source_id``
or ``source_name``. A new source correspon... | Returns a dict with keys ['id', 'name', 'description'] or None if
no match. The ``id`` field is guaranteed to be an int that
exists in table source. Requires exactly one of ``source_id``
or ``source_name``. A new source corresponding to
``source_name`` is created if necessary. |
def remove_all_timers(self):
"""Remove all waiting timers and terminate any blocking threads."""
with self.lock:
if self.rtimer is not None:
self.rtimer.cancel()
self.timers = {}
self.heap = []
self.rtimer = None
self.expiring ... | Remove all waiting timers and terminate any blocking threads. |
def conversations_setTopic(
self, *, channel: str, topic: str, **kwargs
) -> SlackResponse:
"""Sets the topic for a conversation.
Args:
channel (str): The channel id. e.g. 'C1234567890'
topic (str): The new topic for the channel. e.g. 'My Topic'
"""
k... | Sets the topic for a conversation.
Args:
channel (str): The channel id. e.g. 'C1234567890'
topic (str): The new topic for the channel. e.g. 'My Topic' |
def rm_eltorito(self):
# type: () -> None
'''
Remove the El Torito boot record (and Boot Catalog) from the ISO.
Parameters:
None.
Returns:
Nothing.
'''
if not self._initialized:
raise pycdlibexception.PyCdlibInvalidInput('This object... | Remove the El Torito boot record (and Boot Catalog) from the ISO.
Parameters:
None.
Returns:
Nothing. |
def ping(self, endpoint=''):
"""
Ping the server to make sure that you can access the base URL.
Arguments:
None
Returns:
`boolean` Successful access of server (or status code)
"""
r = requests.get(self.url() + "/" + endpoint)
return r.stat... | Ping the server to make sure that you can access the base URL.
Arguments:
None
Returns:
`boolean` Successful access of server (or status code) |
def respond_to_contact_info(self, message):
"""contact info: Show everyone's emergency contact info."""
contacts = self.load("contact_info", {})
context = {
"contacts": contacts,
}
contact_html = rendered_template("contact_info.html", context)
self.say(contact... | contact info: Show everyone's emergency contact info. |
def path(self):
"""The path attribute returns a stringified, concise representation of
the MultiFieldSelector. It can be reversed by the ``from_path``
constructor.
"""
if len(self.heads) == 1:
return _fmt_mfs_path(self.heads.keys()[0], self.heads.values()[0])
... | The path attribute returns a stringified, concise representation of
the MultiFieldSelector. It can be reversed by the ``from_path``
constructor. |
def detrend(x, deg=1):
"""
remove polynomial from data.
used by autocorr_noise_id()
Parameters
----------
x: numpy.array
time-series
deg: int
degree of polynomial to remove from x
Returns
-------
x_detrended: numpy.array
detrended time-series... | remove polynomial from data.
used by autocorr_noise_id()
Parameters
----------
x: numpy.array
time-series
deg: int
degree of polynomial to remove from x
Returns
-------
x_detrended: numpy.array
detrended time-series |
def _find_executables(self):
"""Finds the list of executables that pass the requirements necessary to have
a wrapper created for them.
"""
if len(self.needs) > 0:
return
for execname, executable in list(self.module.executables.items()):
skip = Fal... | Finds the list of executables that pass the requirements necessary to have
a wrapper created for them. |
def _setup_chassis(self):
"""
Sets up the router with the corresponding chassis
(create slots and insert default adapters).
"""
self._create_slots(2)
self._slots[0] = self.integrated_adapters[self._chassis]() | Sets up the router with the corresponding chassis
(create slots and insert default adapters). |
async def get_chat(self):
"""
Returns `chat`, but will make an API call to find the
chat unless it's already cached.
"""
# See `get_sender` for information about 'min'.
if (self._chat is None or getattr(self._chat, 'min', None))\
and await self.get_input_c... | Returns `chat`, but will make an API call to find the
chat unless it's already cached. |
def unindent(self):
"""
Performs an un-indentation
"""
if self.tab_always_indent:
cursor = self.editor.textCursor()
if not cursor.hasSelection():
cursor.select(cursor.LineUnderCursor)
self.unindent_selection(cursor)
else:
... | Performs an un-indentation |
def addContainer(self, query):
"""
Creates a new query container widget object and slides it into
the frame.
:return <XOrbQueryContainer>
"""
self.setUpdatesEnabled(False)
self.blockSignals(True)
container = XOrbQueryContainer(self)
... | Creates a new query container widget object and slides it into
the frame.
:return <XOrbQueryContainer> |
def dlopen(ffi, *names):
"""Try various names for the same library, for different platforms."""
for name in names:
for lib_name in (name, 'lib' + name):
try:
path = ctypes.util.find_library(lib_name)
lib = ffi.dlopen(path or lib_name)
if lib:
... | Try various names for the same library, for different platforms. |
def autocommit(data_access):
"""Make statements autocommit.
:param data_access: a DataAccess instance
"""
if not data_access.autocommit:
data_access.commit()
old_autocommit = data_access.autocommit
data_access.autocommit = True
try:
yield data_access
finally:
data_access.autocommit = old_au... | Make statements autocommit.
:param data_access: a DataAccess instance |
def match_replace(cls, ops, kwargs):
"""Match and replace a full operand specification to a function that
provides a replacement for the whole expression
or raises a :exc:`.CannotSimplify` exception.
E.g.
First define an operation::
>>> class Invert(Operation):
... _rules = Ord... | Match and replace a full operand specification to a function that
provides a replacement for the whole expression
or raises a :exc:`.CannotSimplify` exception.
E.g.
First define an operation::
>>> class Invert(Operation):
... _rules = OrderedDict()
... simplifications =... |
def handle_modifier_up(self, modifier):
"""
Updates the state of the given modifier key to 'released'.
"""
_logger.debug("%s released", modifier)
# Caps and num lock are handled on key down only
if modifier not in (Key.CAPSLOCK, Key.NUMLOCK):
self.modifiers[mo... | Updates the state of the given modifier key to 'released'. |
def estimate(self, X, **params):
"""
Parameters
----------
X : tuple of (ttrajs, dtrajs, btrajs)
Simulation trajectories. ttrajs contain the indices of the thermodynamic state, dtrajs
contains the indices of the configurational states and btrajs contain the biases... | Parameters
----------
X : tuple of (ttrajs, dtrajs, btrajs)
Simulation trajectories. ttrajs contain the indices of the thermodynamic state, dtrajs
contains the indices of the configurational states and btrajs contain the biases.
ttrajs : list of numpy.ndarray(X_i, dt... |
def edge_tuple(self, vertex0_id, vertex1_id):
"""To avoid duplicate edges where the vertex ids are reversed,
we maintain that the vertex ids are ordered so that the corresponding
pathway names are alphabetical.
Parameters
-----------
vertex0_id : int
one vertex... | To avoid duplicate edges where the vertex ids are reversed,
we maintain that the vertex ids are ordered so that the corresponding
pathway names are alphabetical.
Parameters
-----------
vertex0_id : int
one vertex in the edge
vertex1_id : int
the other... |
def add(self, key, value):
"""Add an entry to a list preference
Add `value` to the list of entries for the `key` preference.
"""
if not key in self.prefs:
self.prefs[key] = []
self.prefs[key].append(value) | Add an entry to a list preference
Add `value` to the list of entries for the `key` preference. |
def interpret(self, config_dict):
"""
Converts the config_parser output into the proper type,
supplies defaults if available and needed, and checks for some errors.
"""
value = config_dict.get(self.name)
if value is None:
if self.default is None:
... | Converts the config_parser output into the proper type,
supplies defaults if available and needed, and checks for some errors. |
def all(user, groupby='week', summary='default', network=False,
split_week=False, split_day=False, filter_empty=True, attributes=True,
flatten=False):
"""
Returns a dictionary containing all bandicoot indicators for the user,
as well as reporting variables.
Relevant indicators are defin... | Returns a dictionary containing all bandicoot indicators for the user,
as well as reporting variables.
Relevant indicators are defined in the 'individual', and 'spatial' modules.
=================================== =======================================================================
Reporting varia... |
def comments(self):
"""
Iterator of :class:`stravalib.model.ActivityComment` objects for this activity.
"""
if self._comments is None:
self.assert_bind_client()
if self.comment_count > 0:
self._comments = self.bind_client.get_activity_comments(self... | Iterator of :class:`stravalib.model.ActivityComment` objects for this activity. |
def fftlog(fEM, time, freq, ftarg):
r"""Fourier Transform using FFTLog.
FFTLog is the logarithmic analogue to the Fast Fourier Transform FFT.
FFTLog was presented in Appendix B of [Hami00]_ and published at
<http://casa.colorado.edu/~ajsh/FFTLog>.
This function uses a simplified version of ``pyfft... | r"""Fourier Transform using FFTLog.
FFTLog is the logarithmic analogue to the Fast Fourier Transform FFT.
FFTLog was presented in Appendix B of [Hami00]_ and published at
<http://casa.colorado.edu/~ajsh/FFTLog>.
This function uses a simplified version of ``pyfftlog``, which is a
python-version of ... |
def update_service(self, stack, service, args):
"""更新服务
更新指定名称服务的配置如容器镜像等参数,容器被重新部署后生效。
如果指定manualUpdate参数,则需要额外调用 部署服务 接口并指定参数进行部署;处于人工升级模式的服务禁止执行其他修改操作。
如果不指定manualUpdate参数,平台会自动完成部署。
Args:
- stack: 服务所属的服务组名称
- service: 服务名
- args: ... | 更新服务
更新指定名称服务的配置如容器镜像等参数,容器被重新部署后生效。
如果指定manualUpdate参数,则需要额外调用 部署服务 接口并指定参数进行部署;处于人工升级模式的服务禁止执行其他修改操作。
如果不指定manualUpdate参数,平台会自动完成部署。
Args:
- stack: 服务所属的服务组名称
- service: 服务名
- args: 服务具体描述请求参数(json),参考 http://kirk-docs.qiniu.com/apidocs/
... |
def insert_instance(self, block):
"""Insert a fetched instance into embed block."""
embed_type = block.get('type', None)
data = block.get('data', {})
serializer = self.serializers.get(embed_type, None)
if serializer is None:
return block
try:
in... | Insert a fetched instance into embed block. |
def radialvelocity(self, rf='', v0='0m/s', off=None):
"""Defines a radialvelocity measure. It has to specify a reference
code, radialvelocity quantity value (see introduction for the action
on a scalar quantity with either a vector or scalar value, and when
a vector of quantities is give... | Defines a radialvelocity measure. It has to specify a reference
code, radialvelocity quantity value (see introduction for the action
on a scalar quantity with either a vector or scalar value, and when
a vector of quantities is given), and optionally it can specify an
offset, which in its... |
def save(self):
"""Save this object to the database. Behaves very similarly to
whatever collection.save(document) would, ie. does upserts on _id
presence. If methods ``pre_save`` or ``post_save`` are defined, those
are called. If there is a spec document, then the document is
... | Save this object to the database. Behaves very similarly to
whatever collection.save(document) would, ie. does upserts on _id
presence. If methods ``pre_save`` or ``post_save`` are defined, those
are called. If there is a spec document, then the document is
validated against it after ... |
def _construct_version(self, function, intrinsics_resolver):
"""Constructs a Lambda Version resource that will be auto-published when CodeUri of the function changes.
Old versions will not be deleted without a direct reference from the CloudFormation template.
:param model.lambda_.LambdaFunctio... | Constructs a Lambda Version resource that will be auto-published when CodeUri of the function changes.
Old versions will not be deleted without a direct reference from the CloudFormation template.
:param model.lambda_.LambdaFunction function: Lambda function object that is being connected to a version
... |
def parse_prototype(prototype):
'''Returns a :attr:`FunctionSpec` instance from the input.
'''
val = ' '.join(prototype.splitlines())
f = match(func_pat, val) # match the whole function
if f is None:
raise Exception('Cannot parse function prototype "{}"'.format(val))
ftp, pointer... | Returns a :attr:`FunctionSpec` instance from the input. |
def get_config():
"""
Reads the music download filepath from scdl.cfg
"""
global token
config = configparser.ConfigParser()
config.read(os.path.join(os.path.expanduser('~'), '.config/scdl/scdl.cfg'))
try:
token = config['scdl']['auth_token']
path = config['scdl']['path']
... | Reads the music download filepath from scdl.cfg |
def validate_lang(ctx, param, lang):
"""Validation callback for the <lang> option.
Ensures <lang> is a supported language unless the <nocheck> flag is set
"""
if ctx.params['nocheck']:
return lang
try:
if lang not in tts_langs():
raise click.UsageError(
"... | Validation callback for the <lang> option.
Ensures <lang> is a supported language unless the <nocheck> flag is set |
def compute(cls, observation, prediction):
"""Compute a z-score from an observation and a prediction."""
assert isinstance(observation, dict)
try:
p_value = prediction['mean'] # Use the prediction's mean.
except (TypeError, KeyError, IndexError): # If there isn't one...
... | Compute a z-score from an observation and a prediction. |
def parse_raml(self):
"""
Parse RAML file
"""
if utils.is_url(self.ramlfile):
raml = utils.download_file(self.ramlfile)
else:
with codecs.open(self.ramlfile, "rb", encoding="utf-8") as raml_f:
raml = raml_f.read()
loader = raml... | Parse RAML file |
def main(args):
of = sys.stdout
if args.output and args.output[-4:] == '.bam':
cmd = 'samtools view -Sb - -o '+args.output
pof = Popen(cmd.split(),stdin=PIPE)
of = pof.stdin
elif args.output:
of = open(args.output,'w')
"""Use the valid input file to get the header information."""
header = Non... | Use the valid input file to get the header information. |
def process_into(self, node, obj):
"""
Process a BeautifulSoup node and fill its elements into a pyth
base object.
"""
if isinstance(node, BeautifulSoup.NavigableString):
text = self.process_text(node)
if text:
obj.append(text)
... | Process a BeautifulSoup node and fill its elements into a pyth
base object. |
def dump_image_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
"""Dump image data object to vtkjs"""
if root is None:
root = {}
root['vtkClass'] = 'vtkImageData'
container = root
container['spacing'] = dataset.GetSpacing()
container['origin'] = dataset.... | Dump image data object to vtkjs |
def afterglow(self, src=None, event=None, dst=None, **kargs):
"""Experimental clone attempt of http://sourceforge.net/projects/afterglow
each datum is reduced as src -> event -> dst and the data are graphed.
by default we have IP.src -> IP.dport -> IP.dst"""
if src is None:
s... | Experimental clone attempt of http://sourceforge.net/projects/afterglow
each datum is reduced as src -> event -> dst and the data are graphed.
by default we have IP.src -> IP.dport -> IP.dst |
def get_stp_mst_detail_output_cist_migrate_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
cist = ... | Auto Generated Code |
def get_ccle_mutations():
"""Get CCLE mutations
returns the amino acid changes for a given list of genes and cell lines
"""
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
gene_list = body.get('gene_list')
cell_... | Get CCLE mutations
returns the amino acid changes for a given list of genes and cell lines |
def get_mean(self, col, row):
"""
Returns the mean at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:return: the mean
:rtype: float
"""
return javabr... | Returns the mean at this location (if valid location).
:param col: the 0-based column index
:type col: int
:param row: the 0-based row index
:type row: int
:return: the mean
:rtype: float |
def gen_textfiles_from_filenames(
filenames: Iterable[str]) -> Generator[TextIO, None, None]:
"""
Generates file-like objects from a list of filenames.
Args:
filenames: iterable of filenames
Yields:
each file as a :class:`TextIO` object
"""
for filename in filenames:
... | Generates file-like objects from a list of filenames.
Args:
filenames: iterable of filenames
Yields:
each file as a :class:`TextIO` object |
def subdomain(self, index, value=None):
"""
Return a subdomain or set a new value and return a new :class:`URL`
instance.
:param integer index: 0-indexed subdomain
:param string value: New subdomain
"""
if value is not None:
subdomains = self.subdomai... | Return a subdomain or set a new value and return a new :class:`URL`
instance.
:param integer index: 0-indexed subdomain
:param string value: New subdomain |
def find_stack_elements(self, module, module_name="", _visited_modules=None):
"""
This function goes through the given container and returns the stack elements. Each stack
element is represented by a tuple:
( container_name, element_name, stack_element)
The tuples are returne... | This function goes through the given container and returns the stack elements. Each stack
element is represented by a tuple:
( container_name, element_name, stack_element)
The tuples are returned in an array |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.