code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _expand_scheduledict(scheduledict):
"""Converts a dict of items, some of which are scalar and some of which are
lists, to a list of dicts with scalar items."""
result = []
def f(d):
nonlocal result
#print(d)
d2 = {}
for k,v in d.items():
if isinstance(v, s... | Converts a dict of items, some of which are scalar and some of which are
lists, to a list of dicts with scalar items. |
def get_ecf_props(ep_id, ep_id_ns, rsvc_id=None, ep_ts=None):
"""
Prepares the ECF properties
:param ep_id: Endpoint ID
:param ep_id_ns: Namespace of the Endpoint ID
:param rsvc_id: Remote service ID
:param ep_ts: Timestamp of the endpoint
:return: A dictionary of ECF properties
"""
... | Prepares the ECF properties
:param ep_id: Endpoint ID
:param ep_id_ns: Namespace of the Endpoint ID
:param rsvc_id: Remote service ID
:param ep_ts: Timestamp of the endpoint
:return: A dictionary of ECF properties |
def inspect(self, tab_width=2, ident_char='-'):
"""
Inspects a project file structure based based on the instance folder property.
:param tab_width: width size for subfolders and files.
:param ident_char: char to be used to show identation level
Returns
A string containing the project struct... | Inspects a project file structure based based on the instance folder property.
:param tab_width: width size for subfolders and files.
:param ident_char: char to be used to show identation level
Returns
A string containing the project structure. |
def hclust_linearize(U):
"""Sorts the rows of a matrix by hierarchical clustering.
Parameters:
U (ndarray) : matrix of data
Returns:
prm (ndarray) : permutation of the rows
"""
from scipy.cluster import hierarchy
Z = hierarchy.ward(U)
return hierarchy.leaves_list(hierarchy... | Sorts the rows of a matrix by hierarchical clustering.
Parameters:
U (ndarray) : matrix of data
Returns:
prm (ndarray) : permutation of the rows |
def calc_surfdist(surface, labels, annot, reg, origin, target):
import nibabel as nib
import numpy as np
import os
from surfdist import load, utils, surfdist
import csv
""" inputs:
surface - surface file (e.g. lh.pial, with full path)
labels - label file (e.g. lh.cortex.label, with full path)
annot -... | inputs:
surface - surface file (e.g. lh.pial, with full path)
labels - label file (e.g. lh.cortex.label, with full path)
annot - annot file (e.g. lh.aparc.a2009s.annot, with full path)
reg - registration file (lh.sphere.reg)
origin - the label from which we calculate distances
target - target surface (e.g. ... |
def signOp(self,
op: Dict,
identifier: Identifier=None) -> Request:
"""
Signs the message if a signer is configured
:param identifier: signing identifier; if not supplied the default for
the wallet is used.
:param op: Operation to be signed
... | Signs the message if a signer is configured
:param identifier: signing identifier; if not supplied the default for
the wallet is used.
:param op: Operation to be signed
:return: a signed Request object |
def add_wic(self, old_wic, wic):
"""
Convert the old style WIC slot to a new style WIC slot and add the WIC
to the node properties
:param str old_wic: Old WIC slot
:param str wic: WIC name
"""
new_wic = 'wic' + old_wic[-1]
self.node['properties'][new_wic]... | Convert the old style WIC slot to a new style WIC slot and add the WIC
to the node properties
:param str old_wic: Old WIC slot
:param str wic: WIC name |
def ckchol(M):
"""
CKCHOL
This function computes the Cholesky decomposition of the matrix if it's
positive-definite; else it returns the identity matrix. It was written
to handle the "matrix must be positive definite" error in linalg.cholesky.
Version: 2011may03
"""
from numpy ... | CKCHOL
This function computes the Cholesky decomposition of the matrix if it's
positive-definite; else it returns the identity matrix. It was written
to handle the "matrix must be positive definite" error in linalg.cholesky.
Version: 2011may03 |
def set_monitoring_transaction_name(name, group=None, priority=None):
"""
Sets the transaction name for monitoring.
This is not cached, and only support reporting to New Relic.
"""
if not newrelic:
return
newrelic.agent.set_transaction_name(name, group, priority) | Sets the transaction name for monitoring.
This is not cached, and only support reporting to New Relic. |
def spoolable(*, pre_condition=True, body_params=()):
"""
Decorates a function to make it spoolable using uWSGI, but if no spooling mechanism is available,
the function is called synchronously. All decorated function arguments must be picklable and
the first annotated with `Context` will receive an obje... | Decorates a function to make it spoolable using uWSGI, but if no spooling mechanism is available,
the function is called synchronously. All decorated function arguments must be picklable and
the first annotated with `Context` will receive an object that defines the current execution state.
Return values are... |
def _advance_window(self):
"""Update values in current window and the current window means and variances."""
x_to_remove, y_to_remove = self._x_in_window[0], self._y_in_window[0]
self._window_bound_lower += 1
self._update_values_in_window()
x_to_add, y_to_add = self._x_in_window... | Update values in current window and the current window means and variances. |
def add_stack_frame(self, stack_frame):
"""Add StackFrame to frames list."""
if len(self.stack_frames) >= MAX_FRAMES:
self.dropped_frames_count += 1
else:
self.stack_frames.append(stack_frame.format_stack_frame_json()) | Add StackFrame to frames list. |
def get_insertions(aln_df):
"""Get a list of tuples indicating the first and last residues of a insertion region, as well as the length of the insertion.
If the first tuple is:
(-1, 1) that means the insertion is at the beginning of the original protein
(X, Inf) where X is the length of the ori... | Get a list of tuples indicating the first and last residues of a insertion region, as well as the length of the insertion.
If the first tuple is:
(-1, 1) that means the insertion is at the beginning of the original protein
(X, Inf) where X is the length of the original protein, that means the inser... |
def on_update(self, value, *args, **kwargs):
"""
Inform the parent of progress.
:param value: The value of this subprogresscallback
:param args: Extra positional arguments
:param kwargs: Extra keyword arguments
"""
parent_value = self._parent_min
if self._... | Inform the parent of progress.
:param value: The value of this subprogresscallback
:param args: Extra positional arguments
:param kwargs: Extra keyword arguments |
def getExperimentDescriptionInterfaceFromModule(module):
"""
:param module: imported description.py module
:returns: (:class:`nupic.frameworks.opf.exp_description_api.DescriptionIface`)
represents the experiment description
"""
result = module.descriptionInterface
assert isinstance(result, exp_... | :param module: imported description.py module
:returns: (:class:`nupic.frameworks.opf.exp_description_api.DescriptionIface`)
represents the experiment description |
def colorize(text='', opts=(), **kwargs):
"""
Returns your text, enclosed in ANSI graphics codes.
Depends on the keyword arguments 'fg' and 'bg', and the contents of
the opts tuple/list.
Returns the RESET code if no parameters are given.
Valid colors:
'black', 'red', 'green', 'yellow'... | Returns your text, enclosed in ANSI graphics codes.
Depends on the keyword arguments 'fg' and 'bg', and the contents of
the opts tuple/list.
Returns the RESET code if no parameters are given.
Valid colors:
'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white'
Valid option... |
def import_patch(self, patch_name, new_name=None):
""" Import patch into the patch queue
The patch is inserted as the next unapplied patch.
"""
if new_name:
dir_name = os.path.dirname(new_name)
name = os.path.basename(new_name)
dest_dir = self.quilt_pa... | Import patch into the patch queue
The patch is inserted as the next unapplied patch. |
def print_hex(self, value, justify_right=True):
"""Print a numeric value in hexadecimal. Value should be from 0 to FFFF.
"""
if value < 0 or value > 0xFFFF:
# Ignore out of range values.
return
self.print_str('{0:X}'.format(value), justify_right) | Print a numeric value in hexadecimal. Value should be from 0 to FFFF. |
def interp(mapping, x):
"""Compute the piecewise linear interpolation given by mapping for input x.
>>> interp(((1, 1), (2, 4)), 1.5)
2.5
"""
mapping = sorted(mapping)
if len(mapping) == 1:
xa, ya = mapping[0]
if xa == x:
return ya
return x
for (xa, ya), ... | Compute the piecewise linear interpolation given by mapping for input x.
>>> interp(((1, 1), (2, 4)), 1.5)
2.5 |
def append_sibling_field(self, linenum, indent, field_name, field_value):
"""
:param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param path:
:type path: Path
:param field_n... | :param linenum: The line number of the frame.
:type linenum: int
:param indent: The indentation level of the frame.
:type indent: int
:param path:
:type path: Path
:param field_name:
:type field_name: str
:param field_value:
:type field_value: str |
def create_external_table(self,
external_project_dataset_table,
schema_fields,
source_uris,
source_format='CSV',
autodetect=False,
compressi... | Creates a new external table in the dataset with the data in Google
Cloud Storage. See here:
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables#resource
for more details about these parameters.
:param external_project_dataset_table:
The dotted ``(<project>.|<p... |
def get_notebook_status(self, name):
"""Get the running named Notebook status.
:return: None if no notebook is running, otherwise context dictionary
"""
context = comm.get_context(self.get_pid(name))
if not context:
return None
return context | Get the running named Notebook status.
:return: None if no notebook is running, otherwise context dictionary |
def fit(self, X, y=None, **fit_params):
"""Fits the inverse covariance model according to the given training
data and parameters.
Parameters
-----------
X : 2D ndarray, shape (n_features, n_features)
Input data.
Returns
-------
self
"... | Fits the inverse covariance model according to the given training
data and parameters.
Parameters
-----------
X : 2D ndarray, shape (n_features, n_features)
Input data.
Returns
-------
self |
def save_config(self):
"""
Save configuration: opened projects & tree widget state.
Also save whether dock widget is visible if a project is open.
"""
self.set_option('recent_projects', self.recent_projects)
self.set_option('expanded_state',
... | Save configuration: opened projects & tree widget state.
Also save whether dock widget is visible if a project is open. |
def task(ft):
"""
to create loading progress bar
"""
ft.pack(expand = True, fill = BOTH, side = TOP)
pb_hD = ttk.Progressbar(ft, orient = 'horizontal', mode = 'indeterminate')
pb_hD.pack(expand = True, fill = BOTH, side = TOP)
pb_hD.start(50)
ft.mainloop() | to create loading progress bar |
def saml_provider_absent(name, region=None, key=None, keyid=None, profile=None):
'''
.. versionadded:: 2016.11.0
Ensure the SAML provider with the specified name is absent.
name (string)
The name of the SAML provider.
saml_metadata_document (string)
The xml document of the SAML pr... | .. versionadded:: 2016.11.0
Ensure the SAML provider with the specified name is absent.
name (string)
The name of the SAML provider.
saml_metadata_document (string)
The xml document of the SAML provider.
region (string)
Region to connect to.
key (string)
Secret k... |
def start(self):
"""
Starts the upload.
:raises SbgError: If upload is not in PREPARING state.
"""
if self._status == TransferState.PREPARING:
super(Upload, self).start()
else:
raise SbgError(
'Unable to start. Upload not in PREPARI... | Starts the upload.
:raises SbgError: If upload is not in PREPARING state. |
async def create(self, query, *, dc=None):
"""Creates a new prepared query
Parameters:
Query (Object): Query definition
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
Returns:
Object: New query ... | Creates a new prepared query
Parameters:
Query (Object): Query definition
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
Returns:
Object: New query ID
The create operation expects a body that d... |
def Set(self, interface_name, property_name, value, *args, **kwargs):
'''Standard D-Bus API for setting a property value'''
self.log('Set %s.%s%s' % (interface_name,
property_name,
self.format_args((value,))))
try:
... | Standard D-Bus API for setting a property value |
def poke(self, context):
"""
Check for message on subscribed channels and write to xcom the message with key ``message``
An example of message ``{'type': 'message', 'pattern': None, 'channel': b'test', 'data': b'hello'}``
:param context: the context object
:type context: dict
... | Check for message on subscribed channels and write to xcom the message with key ``message``
An example of message ``{'type': 'message', 'pattern': None, 'channel': b'test', 'data': b'hello'}``
:param context: the context object
:type context: dict
:return: ``True`` if message (with typ... |
def parse_plotProfile(self):
"""Find plotProfile output"""
self.deeptools_plotProfile = dict()
for f in self.find_log_files('deeptools/plotProfile', filehandles=False):
parsed_data, bin_labels, converted_bin_labels = self.parsePlotProfileData(f)
for k, v in parsed_data.it... | Find plotProfile output |
def Policy(self, data=None, subset=None):
"""{dynamic_docstring}"""
return self.factory.get_object(jssobjects.Policy, data, subset) | {dynamic_docstring} |
def make_sentences(self, stream_item):
'assemble Sentence and Token objects'
self.make_label_index(stream_item)
sentences = []
token_num = 0
new_mention_id = 0
for sent_start, sent_end, sent_str in self._sentences(
stream_item.body.clean_visible):
... | assemble Sentence and Token objects |
def uppercase(self, value):
"""Validate and set the uppercase flag."""
if not isinstance(value, bool):
raise TypeError('uppercase attribute must be a logical type.')
self._uppercase = value | Validate and set the uppercase flag. |
def _parse_current_network_settings():
'''
Parse /etc/default/networking and return current configuration
'''
opts = salt.utils.odict.OrderedDict()
opts['networking'] = ''
if os.path.isfile(_DEB_NETWORKING_FILE):
with salt.utils.files.fopen(_DEB_NETWORKING_FILE) as contents:
... | Parse /etc/default/networking and return current configuration |
def get_semester_title(self, node: BaseNode):
"""
get the semester of a node
"""
log.debug("Getting Semester Title for %s" % node.course.id)
return self._get_semester_from_id(node.course.semester) | get the semester of a node |
def read(self):
"Read and interpret data from the daemon."
status = gpscommon.read(self)
if status <= 0:
return status
if self.response.startswith("{") and self.response.endswith("}\r\n"):
self.unpack(self.response)
self.__oldstyle_shim()
s... | Read and interpret data from the daemon. |
def get_concept(self, conceptId, lang='en'):
""" Fetch the concept from the Knowledge base
Args:
id (str): The concept id to be fetched, it can be Wikipedia
page id or Wikiedata id.
Returns:
dict, int: A dict containing the concept information; an inte... | Fetch the concept from the Knowledge base
Args:
id (str): The concept id to be fetched, it can be Wikipedia
page id or Wikiedata id.
Returns:
dict, int: A dict containing the concept information; an integer
representing the response code. |
def _double_centered_imp(a, out=None):
"""
Real implementation of :func:`double_centered`.
This function is used to make parameter ``out`` keyword-only in
Python 2.
"""
out = _float_copy_to_out(out, a)
dim = np.size(a, 0)
mu = np.sum(a) / (dim * dim)
sum_cols = np.sum(a, 0, keepd... | Real implementation of :func:`double_centered`.
This function is used to make parameter ``out`` keyword-only in
Python 2. |
def ReadAllFlowObjects(
self,
client_id = None,
min_create_time = None,
max_create_time = None,
include_child_flows = True,
):
"""Returns all flow objects."""
res = []
for flow in itervalues(self.flows):
if ((client_id is None or flow.client_id == client_id) and
... | Returns all flow objects. |
def languages(self, key, value):
"""Populate the ``languages`` key."""
languages = self.get('languages', [])
values = force_list(value.get('a'))
for value in values:
for language in RE_LANGUAGE.split(value):
try:
name = language.strip().capitalize()
l... | Populate the ``languages`` key. |
def res_from_en(pst,enfile):
"""load ensemble file for residual into a pandas.DataFrame
Parameters
----------
enfile : str
ensemble file name
Returns
-------
pandas.DataFrame : pandas.DataFrame
"""
converters = {"name": str_con, "group": str... | load ensemble file for residual into a pandas.DataFrame
Parameters
----------
enfile : str
ensemble file name
Returns
-------
pandas.DataFrame : pandas.DataFrame |
def change_execution_time(self, job, date_time):
"""
Change a job's execution time.
"""
with self.connection.pipeline() as pipe:
while 1:
try:
pipe.watch(self.scheduled_jobs_key)
if pipe.zscore(self.scheduled_jobs_key, j... | Change a job's execution time. |
def media_new(self, mrl, *options):
"""Create a new Media instance.
If mrl contains a colon (:) preceded by more than 1 letter, it
will be treated as a URL. Else, it will be considered as a
local path. If you need more control, directly use
media_new_location/media_new_path meth... | Create a new Media instance.
If mrl contains a colon (:) preceded by more than 1 letter, it
will be treated as a URL. Else, it will be considered as a
local path. If you need more control, directly use
media_new_location/media_new_path methods.
Options can be specified as suppl... |
def url(self):
"""URL to the affiliation's profile page."""
url = self.xml.find('coredata/link[@rel="scopus-affiliation"]')
if url is not None:
url = url.get('href')
return url | URL to the affiliation's profile page. |
def add_jira_status(test_key, test_status, test_comment):
"""Save test status and comments to update Jira later
:param test_key: test case key in Jira
:param test_status: test case status
:param test_comment: test case comments
"""
global attachments
if test_key and enabled:
if test... | Save test status and comments to update Jira later
:param test_key: test case key in Jira
:param test_status: test case status
:param test_comment: test case comments |
def get_inverses(self, keys):
"""
Returns
-------
Tuple of inverse indices
"""
return tuple([as_index(k, axis=0).inverse for k in keys]) | Returns
-------
Tuple of inverse indices |
def get_jids():
'''
Return all job data from all returners
'''
ret = {}
for returner_ in __opts__[CONFIG_KEY]:
ret.update(_mminion().returners['{0}.get_jids'.format(returner_)]())
return ret | Return all job data from all returners |
def delete_sp_template_for_vlan(self, vlan_id):
"""Deletes SP Template for a vlan_id if it exists."""
with self.session.begin(subtransactions=True):
try:
self.session.query(
ucsm_model.ServiceProfileTemplate).filter_by(
vlan_id=vlan_id)... | Deletes SP Template for a vlan_id if it exists. |
def visit_raise(self, node):
"""Visit a raise statement and check for raising
strings or old-raise-syntax.
"""
# Ignore empty raise.
if node.exc is None:
return
expr = node.exc
if self._check_raise_value(node, expr):
return
try:
... | Visit a raise statement and check for raising
strings or old-raise-syntax. |
def get_details(self):
"""
:rtype list[VmDataField]
"""
data = []
if self.deployment == 'vCenter Clone VM From VM':
data.append(VmDetailsProperty(key='Cloned VM Name',value= self.dep_attributes.get('vCenter VM','')))
if self.deployment == 'VCenter De... | :rtype list[VmDataField] |
def save_model(self, request, obj, form, change):
"""
Set the ID of the parent page if passed in via querystring, and
make sure the new slug propagates to all descendant pages.
"""
if change and obj._old_slug != obj.slug:
# _old_slug was set in PageAdminForm.clean_slu... | Set the ID of the parent page if passed in via querystring, and
make sure the new slug propagates to all descendant pages. |
def rsdl(self):
"""Compute fixed point residual."""
return np.linalg.norm((self.X - self.Yprv).ravel()) | Compute fixed point residual. |
def to_bqstorage(self):
"""Construct a BigQuery Storage API representation of this table.
Install the ``google-cloud-bigquery-storage`` package to use this
feature.
If the ``table_id`` contains a partition identifier (e.g.
``my_table$201812``) or a snapshot identifier (e.g.
... | Construct a BigQuery Storage API representation of this table.
Install the ``google-cloud-bigquery-storage`` package to use this
feature.
If the ``table_id`` contains a partition identifier (e.g.
``my_table$201812``) or a snapshot identifier (e.g.
``mytable@1234567890``), it is... |
def _make_single_subvolume(self, only_one=True, **args):
"""Creates a subvolume, adds it to this class, sets the volume index to 0 and returns it.
:param bool only_one: if this volume system already has at least one volume, it is returned instead.
"""
if only_one and self.volumes:
... | Creates a subvolume, adds it to this class, sets the volume index to 0 and returns it.
:param bool only_one: if this volume system already has at least one volume, it is returned instead. |
def get_message(self, timeout=0.5):
"""
Attempts to retrieve the latest message received by the instance. If no message is
available it blocks for given timeout or until a message is received, or else
returns None (whichever is shorter). This method does not block after
:meth:`ca... | Attempts to retrieve the latest message received by the instance. If no message is
available it blocks for given timeout or until a message is received, or else
returns None (whichever is shorter). This method does not block after
:meth:`can.BufferedReader.stop` has been called.
:param ... |
def dice(edge=15, fn=32):
""" dice
"""
edge = float(edge)
# dice
c = ops.Cube(edge, center=True)
s = ops.Sphere(edge * 3 / 4, center=True)
dice = c & s
# points
c = ops.Circle(edge / 12, _fn=fn)
h = 0.7
point = c.linear_extrude(heig... | dice |
def gather(obj):
"""Retrieve objects that have been distributed, making them local again"""
if hasattr(obj, '__distob_gather__'):
return obj.__distob_gather__()
elif (isinstance(obj, collections.Sequence) and
not isinstance(obj, string_types)):
return [gather(subobj) for subobj ... | Retrieve objects that have been distributed, making them local again |
def to_xml(self):
"""Convert to XML message."""
element = etree.Element(self._tag_name)
struct_to_xml(element, [
{"author": self.handle},
{"target_guid": self.target_guid},
{"target_type": DiasporaRetraction.entity_type_to_remote(self.entity_type)},
])... | Convert to XML message. |
async def play_url(self, url, position=0):
"""Play media from an URL on the device."""
headers = {'User-Agent': 'MediaControl/1.0',
'Content-Type': 'application/x-apple-binary-plist'}
body = {'Content-Location': url, 'Start-Position': position}
address = self._url(sel... | Play media from an URL on the device. |
def lazy_reverse_binmap(f, xs):
"""
Same as lazy_binmap, except the parameters are flipped for the binary function
"""
return (f(y, x) for x, y in zip(xs, xs[1:])) | Same as lazy_binmap, except the parameters are flipped for the binary function |
def exists(self, regex):
"""
See what :meth:`skip_until` would return without advancing the pointer.
>>> s = Scanner("test string")
>>> s.exists(' ')
5
>>> s.pos
0
Returns the number of characters matched if it does exist, or ``None``... | See what :meth:`skip_until` would return without advancing the pointer.
>>> s = Scanner("test string")
>>> s.exists(' ')
5
>>> s.pos
0
Returns the number of characters matched if it does exist, or ``None``
otherwise. |
def _dialect(self, filepath):
"""returns detected dialect of filepath and sets self.has_header
if not passed in __init__ kwargs
Arguments:
filepath (str): filepath of target csv file
"""
with open(filepath, self.read_mode) as csvfile:
sample = csvfile.read... | returns detected dialect of filepath and sets self.has_header
if not passed in __init__ kwargs
Arguments:
filepath (str): filepath of target csv file |
def _defineVariables(self):
"""
Helper funtion to define pertinent variables from catalog data.
ADW (20170627): This has largely been replaced by properties.
"""
logger.info('Catalog contains %i objects'%(len(self.data)))
mc_source_id_field = self.config['catalog']['mc_... | Helper funtion to define pertinent variables from catalog data.
ADW (20170627): This has largely been replaced by properties. |
def libvlc_vlm_add_vod(p_instance, psz_name, psz_input, i_options, ppsz_options, b_enabled, psz_mux):
'''Add a vod, with one input.
@param p_instance: the instance.
@param psz_name: the name of the new vod media.
@param psz_input: the input MRL.
@param i_options: number of additional options.
@p... | Add a vod, with one input.
@param p_instance: the instance.
@param psz_name: the name of the new vod media.
@param psz_input: the input MRL.
@param i_options: number of additional options.
@param ppsz_options: additional options.
@param b_enabled: boolean for enabling the new vod.
@param psz... |
def close(self):
"""Close the canvas
Notes
-----
This will usually destroy the GL context. For Qt, the context
(and widget) will be destroyed only if the widget is top-level.
To avoid having the widget destroyed (more like standard Qt
behavior), consider making t... | Close the canvas
Notes
-----
This will usually destroy the GL context. For Qt, the context
(and widget) will be destroyed only if the widget is top-level.
To avoid having the widget destroyed (more like standard Qt
behavior), consider making the widget a sub-widget. |
def from_any(cls, obj, bucket):
"""
Ensure the current object is an index. Always returns a new object
:param obj: string or IndexInfo object
:param bucket: The bucket name
:return: A new IndexInfo object
"""
if isinstance(obj, cls):
return cls(obj.raw... | Ensure the current object is an index. Always returns a new object
:param obj: string or IndexInfo object
:param bucket: The bucket name
:return: A new IndexInfo object |
def running(self):
"""
Returns true if job still in running state
:return:
"""
r = self._client._redis
flag = '{}:flag'.format(self._queue)
if bool(r.exists(flag)):
return r.ttl(flag) is None
return False | Returns true if job still in running state
:return: |
def read(self, line, f, data):
"""See :meth:`PunchParser.read`"""
line = f.readline()
assert(line == " $HESS\n")
while line != " $END\n":
line = f.readline() | See :meth:`PunchParser.read` |
def _arm_thumb_filter_jump_successors(self, addr, size, successors, get_ins_addr, get_exit_stmt_idx):
"""
Filter successors for THUMB mode basic blocks, and remove those successors that won't be taken normally.
:param int addr: Address of the basic block / SimIRSB.
:param int size: Size... | Filter successors for THUMB mode basic blocks, and remove those successors that won't be taken normally.
:param int addr: Address of the basic block / SimIRSB.
:param int size: Size of the basic block.
:param list successors: A list of successors.
:param func get_ins_addr: A callable th... |
def father(self):
"""Parent of this individual"""
if self._father == []:
self._father = self.sub_tag("FAMC/HUSB")
return self._father | Parent of this individual |
def match(pattern):
"""
Validates that a field value matches the regex given to this validator.
"""
regex = re.compile(pattern)
def validate(value):
if not regex.match(value):
return e("{} does not match the pattern {}", value, pattern)
return validate | Validates that a field value matches the regex given to this validator. |
def generic_http_header_parser_for(header_name):
"""
A parser factory to extract the request id from an HTTP header
:return: A parser that can be used to extract the request id from the current request context
:rtype: ()->str|None
"""
def parser():
request_id = request.headers.get(heade... | A parser factory to extract the request id from an HTTP header
:return: A parser that can be used to extract the request id from the current request context
:rtype: ()->str|None |
def copy_and_verify(path, source_path, sha256):
"""
Copy a file to a given path from a given path, if it does not exist.
After copying it, verify it integrity by checking the SHA-256 hash.
Parameters
----------
path: str
The (destination) path of the file on the local filesystem
sou... | Copy a file to a given path from a given path, if it does not exist.
After copying it, verify it integrity by checking the SHA-256 hash.
Parameters
----------
path: str
The (destination) path of the file on the local filesystem
source_path: str
The path from which to copy the file
... |
def plot(self, vertices, show=False):
"""
Plot the text using matplotlib.
Parameters
--------------
vertices : (n, 2) float
Vertices in space
show : bool
If True, call plt.show()
"""
if vertices.shape[1] != 2:
raise ValueEr... | Plot the text using matplotlib.
Parameters
--------------
vertices : (n, 2) float
Vertices in space
show : bool
If True, call plt.show() |
def run(self, *args, **kwargs):
""" Queue a first item to execute, then wait for the queue to
be empty before returning. This should be the default way of
starting any scraper.
"""
if self._source is not None:
return self._source.run(*args, **kwargs)
else:
... | Queue a first item to execute, then wait for the queue to
be empty before returning. This should be the default way of
starting any scraper. |
def isconnected(mask):
""" Checks that all nodes are reachable from the first node - i.e. that the
graph is fully connected. """
nodes_to_check = list((np.where(mask[0, :])[0])[1:])
seen = [True] + [False] * (len(mask) - 1)
while nodes_to_check and not all(seen):
node = nodes_to_check.pop()... | Checks that all nodes are reachable from the first node - i.e. that the
graph is fully connected. |
def _shared_features(adense, bdense):
"""
Number of features in ``adense`` that are also in ``bdense``.
"""
a_indices = set(nonzero(adense))
b_indices = set(nonzero(bdense))
shared = list(a_indices & b_indices)
diff = list(a_indices - b_indices)
Ndiff = len(diff)
return Ndiff | Number of features in ``adense`` that are also in ``bdense``. |
def _log_prob_with_logsf_and_logcdf(self, y):
"""Compute log_prob(y) using log survival_function and cdf together."""
# There are two options that would be equal if we had infinite precision:
# Log[ sf(y - 1) - sf(y) ]
# = Log[ exp{logsf(y - 1)} - exp{logsf(y)} ]
# Log[ cdf(y) - cdf(y - 1) ]
#... | Compute log_prob(y) using log survival_function and cdf together. |
def getAPIKey(self, keyID=None):
"""
Retrieve the NS1 API Key for the given keyID
:param str keyID: optional keyID to retrieve, or current if not passed
:return: API Key for the given keyID
"""
kcfg = self.getKeyConfig(keyID)
if 'key' not in kcfg:
rai... | Retrieve the NS1 API Key for the given keyID
:param str keyID: optional keyID to retrieve, or current if not passed
:return: API Key for the given keyID |
def rollback(self):
"""Implementation of NAPALM method rollback."""
commands = []
commands.append('configure replace flash:rollback-0')
commands.append('write memory')
self.device.run_commands(commands) | Implementation of NAPALM method rollback. |
def set_user_password(environment, parameter, password):
"""
Sets a user's password in the keyring storage
"""
username = '%s:%s' % (environment, parameter)
return password_set(username, password) | Sets a user's password in the keyring storage |
def flush_job(self, job_id, body=None, params=None):
"""
`<http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-flush-job.html>`_
:arg job_id: The name of the job to flush
:arg body: Flush parameters
:arg advance_time: Advances time to the given value generating res... | `<http://www.elastic.co/guide/en/elasticsearch/reference/current/ml-flush-job.html>`_
:arg job_id: The name of the job to flush
:arg body: Flush parameters
:arg advance_time: Advances time to the given value generating results
and updating the model for the advanced interval
... |
def create_channel(current):
"""
Create a public channel. Can be a broadcast channel or normal chat room.
Chat room and broadcast distinction will be made at user subscription phase.
.. code-block:: python
# request:
{
'view':'_zops_create_chan... | Create a public channel. Can be a broadcast channel or normal chat room.
Chat room and broadcast distinction will be made at user subscription phase.
.. code-block:: python
# request:
{
'view':'_zops_create_channel',
'name': string,
... |
def get_conn(self):
"""
Returns an SFTP connection object
"""
if self.conn is None:
cnopts = pysftp.CnOpts()
if self.no_host_key_check:
cnopts.hostkeys = None
cnopts.compression = self.compress
conn_params = {
... | Returns an SFTP connection object |
def weighted_pixel_signals_from_images(pixels, signal_scale, regular_to_pix, galaxy_image):
"""Compute the (scaled) signal in each pixel, where the signal is the sum of its datas_-pixel fluxes. \
These pixel-signals are used to compute the effective regularization weight of each pixel.
The pixel signals ar... | Compute the (scaled) signal in each pixel, where the signal is the sum of its datas_-pixel fluxes. \
These pixel-signals are used to compute the effective regularization weight of each pixel.
The pixel signals are scaled in the following ways:
1) Divided by the number of datas_-pixels in the pixel, to ens... |
def odinweb_node_formatter(path_node):
# type: (PathParam) -> str
"""
Format a node to be consumable by the `UrlPath.parse`.
"""
args = [path_node.name]
if path_node.type:
args.append(path_node.type.name)
if path_node.type_args:
args.append... | Format a node to be consumable by the `UrlPath.parse`. |
def get_storyline(self, timezone_offset, first_date, start=0.0, end=0.0, track_points=False):
''' a method to retrieve storyline details for a period of time
NOTE: start and end must be no more than 30 days, 1 second apart
NOTE: if track_points=True, start and end must be no more than 6... | a method to retrieve storyline details for a period of time
NOTE: start and end must be no more than 30 days, 1 second apart
NOTE: if track_points=True, start and end must be no more than 6 days, 1 second apart
:param timezone_offset: integer with timezone offset from user profile detai... |
def check_proxy_setting():
"""
If the environmental variable 'HTTP_PROXY' is set, it will most likely be
in one of these forms:
proxyhost:8080
http://proxyhost:8080
urlllib2 requires the proxy URL to start with 'http://'
This routine does that, and returns the transport for xml... | If the environmental variable 'HTTP_PROXY' is set, it will most likely be
in one of these forms:
proxyhost:8080
http://proxyhost:8080
urlllib2 requires the proxy URL to start with 'http://'
This routine does that, and returns the transport for xmlrpc. |
def convert_nonParametricSeismicSource(self, node):
"""
Convert the given node into a non parametric source object.
:param node:
a node with tag areaGeometry
:returns:
a :class:`openquake.hazardlib.source.NonParametricSeismicSource`
instance
"... | Convert the given node into a non parametric source object.
:param node:
a node with tag areaGeometry
:returns:
a :class:`openquake.hazardlib.source.NonParametricSeismicSource`
instance |
def check_meta_tag(domain, prefix, code):
"""
Validates a domain by checking the existance of a <meta name="{prefix}" content="{code}">
tag in the <head> of the home page of the domain using either HTTP or HTTPs protocols.
Returns true if verification suceeded.
"""
url = '://{}'.format(domain)
... | Validates a domain by checking the existance of a <meta name="{prefix}" content="{code}">
tag in the <head> of the home page of the domain using either HTTP or HTTPs protocols.
Returns true if verification suceeded. |
def _create_PmtInf_node(self):
"""
Method to create the blank payment information nodes as a dict.
"""
ED = dict() # ED is element dict
ED['PmtInfNode'] = ET.Element("PmtInf")
ED['PmtInfIdNode'] = ET.Element("PmtInfId")
ED['PmtMtdNode'] = ET.Element("PmtMtd")
... | Method to create the blank payment information nodes as a dict. |
def validate(self, instance, value):
"""Check shape and dtype of vector
validate also coerces the vector from valid strings (these
include ZERO, X, Y, -X, -Y, EAST, WEST, NORTH, and SOUTH) and
scales it to the given length.
"""
if isinstance(value, string_types):
... | Check shape and dtype of vector
validate also coerces the vector from valid strings (these
include ZERO, X, Y, -X, -Y, EAST, WEST, NORTH, and SOUTH) and
scales it to the given length. |
def _rdsignal(fp, file_size, header_size, n_sig, bit_width, is_signed, cut_end):
"""
Read the signal
Parameters
----------
cut_end : bool, optional
If True, enables reading the end of files which appear to terminate
with the incorrect number of samples (ie. sample not present for al... | Read the signal
Parameters
----------
cut_end : bool, optional
If True, enables reading the end of files which appear to terminate
with the incorrect number of samples (ie. sample not present for all channels),
by checking and skipping the reading the end of such files.
Chec... |
def lock(self, lease_time=-1):
"""
Acquires the lock. If a lease time is specified, lock will be released after this lease time.
If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies
dormant until the lock has been acquired.
:... | Acquires the lock. If a lease time is specified, lock will be released after this lease time.
If the lock is not available, the current thread becomes disabled for thread scheduling purposes and lies
dormant until the lock has been acquired.
:param lease_time: (long), time to wait before relea... |
def distance(p0, p1):
r"""Return the distance between two points.
Parameters
----------
p0: (X,Y) ndarray
Starting coordinate
p1: (X,Y) ndarray
Ending coordinate
Returns
-------
d: float
distance
See Also
--------
dist_2
"""
return math.sqr... | r"""Return the distance between two points.
Parameters
----------
p0: (X,Y) ndarray
Starting coordinate
p1: (X,Y) ndarray
Ending coordinate
Returns
-------
d: float
distance
See Also
--------
dist_2 |
def plot_spikes(spikes, view=False, filename=None, title=None):
""" Plots the trains for a single spiking neuron. """
t_values = [t for t, I, v, u, f in spikes]
v_values = [v for t, I, v, u, f in spikes]
u_values = [u for t, I, v, u, f in spikes]
I_values = [I for t, I, v, u, f in spikes]
f_valu... | Plots the trains for a single spiking neuron. |
def _fix_review_dates(self, item):
"""Convert dates so ES detect them"""
for date_field in ['timestamp', 'createdOn', 'lastUpdated']:
if date_field in item.keys():
date_ts = item[date_field]
item[date_field] = unixtime_to_datetime(date_ts).isoformat()
... | Convert dates so ES detect them |
def add_module_definition(self, module_definition):
"""
Add a ModuleDefinition to the document
"""
if module_definition.identity not in self._module_definitions.keys():
self._module_definitions[module_definition.identity] = module_definition
else:
raise Va... | Add a ModuleDefinition to the document |
def lookup_field_orderable(self, field):
"""
Returns whether the passed in field is sortable or not, by default all 'raw' fields, that
is fields that are part of the model are sortable.
"""
try:
self.model._meta.get_field_by_name(field)
return True
... | Returns whether the passed in field is sortable or not, by default all 'raw' fields, that
is fields that are part of the model are sortable. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.