code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_tagged(self, event):
"""Return a list of tagged objects for a schema"""
self.log("Tagged objects request for", event.data, "from",
event.user, lvl=debug)
if event.data in self.tags:
tagged = self._get_tagged(event.data)
response = {
... | Return a list of tagged objects for a schema |
def set_isotopic_ratio(self, compound='', element='', list_ratio=[]):
"""defines the new set of ratio of the compound/element and trigger the calculation to update the density
Parameters:
===========
compound: string (default is ''). Name of compound
element: string (default is ... | defines the new set of ratio of the compound/element and trigger the calculation to update the density
Parameters:
===========
compound: string (default is ''). Name of compound
element: string (default is ''). Name of element
list_ratio: list (default is []). list of new stoich... |
def calc_fwhm_gaussian(self, arr1d, medv=None, gauss_fn=None):
"""FWHM calculation on a 1D array by using least square fitting of
a gaussian function on the data. arr1d is a 1D array cut in either
X or Y direction on the object.
"""
if gauss_fn is None:
gauss_fn = se... | FWHM calculation on a 1D array by using least square fitting of
a gaussian function on the data. arr1d is a 1D array cut in either
X or Y direction on the object. |
def convert_data_to_ndarray(self):
"""Converts the data from dataframe to ndarray format. Assumption: df-columns are ndarray-layers (3rd dim.)"""
if self._data_structure != "DataFrame":
raise Exception(f"Data is not a DataFrame but {self._data_structure}.")
self._data = self._convert... | Converts the data from dataframe to ndarray format. Assumption: df-columns are ndarray-layers (3rd dim.) |
def duplicate(self, host):
# pylint: disable=too-many-locals
"""For a given host, look for all copy we must create for for_each property
:param host: alignak host object
:type host: alignak.objects.host.Host
:return: list
:rtype: list
"""
duplicates = []... | For a given host, look for all copy we must create for for_each property
:param host: alignak host object
:type host: alignak.objects.host.Host
:return: list
:rtype: list |
def getLeader(self, vehID, dist=0.):
"""getLeader(string, double) -> (string, double)
Return the leading vehicle id together with the distance. The distance
is measured from the front + minGap to the back of the leader, so it does not include the
minGap of the vehicle.
The dist ... | getLeader(string, double) -> (string, double)
Return the leading vehicle id together with the distance. The distance
is measured from the front + minGap to the back of the leader, so it does not include the
minGap of the vehicle.
The dist parameter defines the maximum lookahead, 0 calcu... |
def allow(self, ctx, acls):
'''Allow access to any ACL members that was equal to the user name.
That is, some user u is considered a member of group u and no other.
'''
for acl in acls:
if self._identity == acl:
return True
return False | Allow access to any ACL members that was equal to the user name.
That is, some user u is considered a member of group u and no other. |
def _check_tcpdump():
"""
Return True if the tcpdump command can be started
"""
with open(os.devnull, 'wb') as devnull:
try:
proc = subprocess.Popen([conf.prog.tcpdump, "--version"],
stdout=devnull, stderr=subprocess.STDOUT)
except OSError:... | Return True if the tcpdump command can be started |
def _do_synchronise_jobs(walltime, machines):
""" This returns a common reservation date for all the jobs.
This reservation date is really only a hint and will be supplied to each
oar server. Without this *common* reservation_date, one oar server can
decide to postpone the start of the job while the ot... | This returns a common reservation date for all the jobs.
This reservation date is really only a hint and will be supplied to each
oar server. Without this *common* reservation_date, one oar server can
decide to postpone the start of the job while the other are already
running. But this doens't prevent ... |
def _validate_message(self, message):
"""Validate XML response from iLO.
This function validates the XML response to see
if the exit status is 0 or not in the response.
If the status is non-zero it raises exception.
"""
if message.tag != 'RIBCL':
# the true c... | Validate XML response from iLO.
This function validates the XML response to see
if the exit status is 0 or not in the response.
If the status is non-zero it raises exception. |
def clip_or_fit_solutions(self, pop, idx):
"""make sure that solutions fit to sample distribution, this interface will probably change.
In particular the frequency of long vectors appearing in pop[idx] - self.mean is limited.
"""
for k in idx:
self.repair_genotype(pop[k]) | make sure that solutions fit to sample distribution, this interface will probably change.
In particular the frequency of long vectors appearing in pop[idx] - self.mean is limited. |
async def deserialize(data: dict):
"""
Builds a Proof object with defined attributes.
Attributes are provided by a previous call to the serialize function.
:param data:
Example:
name = "proof name"
requested_attrs = [{"name": "age", "restrictions": [{"schema_id": ... | Builds a Proof object with defined attributes.
Attributes are provided by a previous call to the serialize function.
:param data:
Example:
name = "proof name"
requested_attrs = [{"name": "age", "restrictions": [{"schema_id": "6XFh8yBzrpJQmNyZzgoTqB:2:schema_name:0.0.11", "schema_... |
def start_heron_tools(masters, cl_args):
'''
Start Heron tracker and UI
'''
single_master = list(masters)[0]
wait_for_master_to_start(single_master)
cmd = "%s run %s >> /tmp/heron_tools_start.log 2>&1 &" \
% (get_nomad_path(cl_args), get_heron_tools_job_file(cl_args))
Log.info("Starting Heron Too... | Start Heron tracker and UI |
def _request(self, method, uri_relative, request_bytes, params,
custom_headers):
"""
:type method: str
:type uri_relative: str
:type request_bytes: bytes
:type params: dict[str, str]
:type custom_headers: dict[str, str]
:return: BunqResponseRaw
... | :type method: str
:type uri_relative: str
:type request_bytes: bytes
:type params: dict[str, str]
:type custom_headers: dict[str, str]
:return: BunqResponseRaw |
def learnObject(self,
objectDescription,
randomLocation=False,
useNoise=False,
noisyTrainingTime=1):
"""
Train the network to recognize the specified object. Move the sensor to one of
its features and activate a random location represen... | Train the network to recognize the specified object. Move the sensor to one of
its features and activate a random location representation in the location
layer. Move the sensor over the object, updating the location representation
through path integration. At each point on the object, form reciprocal
co... |
def get_instance(self):
"""
Returns the singleton instance. Upon its first call, it creates a
new instance of the decorated class and calls its `__init__` method.
On all subsequent calls, the already created instance is returned.
"""
try:
return self._instance... | Returns the singleton instance. Upon its first call, it creates a
new instance of the decorated class and calls its `__init__` method.
On all subsequent calls, the already created instance is returned. |
def _dK_dR(self, R):
"""Return numpy array of dK/dR from K1 up to and including Kn."""
return -self._ns * self._N / R**2 / self._sin_alpha | Return numpy array of dK/dR from K1 up to and including Kn. |
def run(self, file_list):
"""
Runs pylint on the list of files and return a dictionary:
{<filename>: [list of pylint errors],
'total': <int> - Total number of pylint messages,
'errors': <int> - Number of pylint errors,
'scores': (<filename>, score) - Individual sco... | Runs pylint on the list of files and return a dictionary:
{<filename>: [list of pylint errors],
'total': <int> - Total number of pylint messages,
'errors': <int> - Number of pylint errors,
'scores': (<filename>, score) - Individual score for each file.}
:param file_list:
... |
def _interpolationFunctionFactory(self, spline_order=None, cval=None):
"""Returns a function F(x,y,z) that interpolates any values on the grid.
_interpolationFunctionFactory(self,spline_order=3,cval=None) --> F
*cval* is set to :meth:`Grid.grid.min`. *cval* cannot be chosen too
large o... | Returns a function F(x,y,z) that interpolates any values on the grid.
_interpolationFunctionFactory(self,spline_order=3,cval=None) --> F
*cval* is set to :meth:`Grid.grid.min`. *cval* cannot be chosen too
large or too small or NaN because otherwise the spline interpolation
breaks down ... |
def _group_and_publish_tasks_statistics(self, result):
"""This function group statistics of same tasks by adding them.
It also add 'instances_count' statistic to get information about
how many instances is running on the server
Args:
result: result of mesos query. List of di... | This function group statistics of same tasks by adding them.
It also add 'instances_count' statistic to get information about
how many instances is running on the server
Args:
result: result of mesos query. List of dictionaries with
'executor_id', 'framework_id' as a str... |
def restore_geometry_on_layout_change(self, value):
"""
Setter for **self.__restore_geometry_on_layout_change** attribute.
:param value: Attribute value.
:type value: bool
"""
if value is not None:
assert type(value) is bool, "'{0}' attribute: '{1}' type is ... | Setter for **self.__restore_geometry_on_layout_change** attribute.
:param value: Attribute value.
:type value: bool |
def wet_bulb_from_db_rh(db_temp, rh, b_press=101325):
"""Wet Bulb Temperature (C) at db_temp (C),
Relative Humidity rh (%), and Pressure b_press (Pa).
Note:
[1] J. Sullivan and L. D. Sanders. "Method for obtaining wet-bulb temperatures by
modifying the psychrometric formula." Center for Exp... | Wet Bulb Temperature (C) at db_temp (C),
Relative Humidity rh (%), and Pressure b_press (Pa).
Note:
[1] J. Sullivan and L. D. Sanders. "Method for obtaining wet-bulb temperatures by
modifying the psychrometric formula." Center for Experiment Design and Data
Analysis. NOAA - National Oce... |
def leaf_sections(h):
"""
Returns a list of all sections that have no children.
"""
leaves = []
for section in h.allsec():
sref = h.SectionRef(sec=section)
# nchild returns a float... cast to bool
if sref.nchild() < 0.9:
leaves.append(section)
return leaves | Returns a list of all sections that have no children. |
def activate_user(self, user):
"""Activates a specified user. Returns `True` if a change was made.
:param user: The user to activate
"""
if not user.active:
user.active = True
return True
return False | Activates a specified user. Returns `True` if a change was made.
:param user: The user to activate |
def apply_palette(img, palette, options):
'''Apply the pallete to the given image. The first step is to set all
background pixels to the background color; then, nearest-neighbor
matching is used to map each foreground color to the closest one in
the palette.
'''
if not options.quiet:
print(' app... | Apply the pallete to the given image. The first step is to set all
background pixels to the background color; then, nearest-neighbor
matching is used to map each foreground color to the closest one in
the palette. |
def download_interim_for_gssha(main_directory,
start_datetime,
end_datetime,
leftlon=-180,
rightlon=180,
toplat=90,
bottomlat=-90,
... | Function to download ERA5 data for GSSHA
.. note:: https://software.ecmwf.int/wiki/display/WEBAPI/Access+ECMWF+Public+Datasets
Args:
main_directory(:obj:`str`): Location of the output for the forecast data.
start_datetime(:obj:`str`): Datetime for download start.
end_datetime(:obj:`str... |
def reporter(self):
"""
Creates a report of the results
"""
# Create the path in which the reports are stored
make_path(self.reportpath)
logging.info('Creating {} report'.format(self.analysistype))
# Initialise the header and data strings
header = 'Strain,... | Creates a report of the results |
def getClassAllSubs(self, aURI):
"""
note: requires SPARQL 1.1
2015-06-04: currenlty not used, inferred from above
"""
aURI = aURI
try:
qres = self.rdfgraph.query(
"""SELECT DISTINCT ?x
WHERE {
{ ... | note: requires SPARQL 1.1
2015-06-04: currenlty not used, inferred from above |
async def async_input(prompt):
"""
Python's ``input()`` is blocking, which means the event loop we set
above can't be running while we're blocking there. This method will
let the loop run while we wait for input.
"""
print(prompt, end='', flush=True)
return (await loop.run_in_executor(None, ... | Python's ``input()`` is blocking, which means the event loop we set
above can't be running while we're blocking there. This method will
let the loop run while we wait for input. |
def loads(string):
"""Loads the filters dictionary given a string."""
d = _loads(string)
for k, v in d.items():
FILTERS[dr.get_component(k) or k] = set(v) | Loads the filters dictionary given a string. |
def get_location(conn, vm_):
'''
Return the location object to use
'''
locations = conn.list_locations()
vm_location = config.get_cloud_config_value('location', vm_, __opts__)
if not six.PY3:
vm_location = vm_location.encode(
'ascii', 'salt-cloud-force-ascii'
)
f... | Return the location object to use |
def find_one(self, id_, raw=True, recovery_name=True):
"""Find one record.
Ref: http://helpdesk.knackhq.com/support/solutions/articles/5000446111-api-reference-root-access#retrieve
:param id_: record id_
:param using_name: if you are using field name in filter and sort_... | Find one record.
Ref: http://helpdesk.knackhq.com/support/solutions/articles/5000446111-api-reference-root-access#retrieve
:param id_: record id_
:param using_name: if you are using field name in filter and sort_field,
please set using_name = True (it's the default),... |
def to_message(self, keywords=None, show_header=True):
"""Format keywords as a message object.
.. versionadded:: 3.2
.. versionchanged:: 3.3 - default keywords to None
The message object can then be rendered to html, plain text etc.
:param keywords: Keywords to be converted t... | Format keywords as a message object.
.. versionadded:: 3.2
.. versionchanged:: 3.3 - default keywords to None
The message object can then be rendered to html, plain text etc.
:param keywords: Keywords to be converted to a message. Optional. If
not passed then we will atte... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'classifier_id') and self.classifier_id is not None:
_dict['classifier_id'] = self.classifier_id
if hasattr(self, 'url') and self.url is not None:
_dict['url'] ... | Return a json dictionary representing this model. |
def load_wmt_en_fr_dataset(path='data'):
"""Load WMT'15 English-to-French translation dataset.
It will download the data from the WMT'15 Website (10^9-French-English corpus), and the 2013 news test from the same site as development set.
Returns the directories of training data and test data.
Parameter... | Load WMT'15 English-to-French translation dataset.
It will download the data from the WMT'15 Website (10^9-French-English corpus), and the 2013 news test from the same site as development set.
Returns the directories of training data and test data.
Parameters
----------
path : str
The path... |
def envelope(self, header, body):
"""
Build the B{<Envelope/>} for a SOAP outbound message.
@param header: The SOAP message B{header}.
@type header: L{Element}
@param body: The SOAP message B{body}.
@type body: L{Element}
@return: The SOAP envelope containing the... | Build the B{<Envelope/>} for a SOAP outbound message.
@param header: The SOAP message B{header}.
@type header: L{Element}
@param body: The SOAP message B{body}.
@type body: L{Element}
@return: The SOAP envelope containing the body and header.
@rtype: L{Element} |
def read_config(self, filename):
"""
Returns data found in config file (as dict), or raises exception if file not found
"""
if not os.path.exists(filename):
raise Exception("Configuration file cannot be found: %s" % filename)
with io.open(filename, encoding='UTF-8') a... | Returns data found in config file (as dict), or raises exception if file not found |
def save_uca(self, rootpath, raw=False, as_int=False):
""" Saves the upstream contributing area to a file
"""
self.save_array(self.uca, None, 'uca', rootpath, raw, as_int=as_int) | Saves the upstream contributing area to a file |
def add(self, *args):
"""
This function adds strings to the keyboard, while not exceeding row_width.
E.g. ReplyKeyboardMarkup#add("A", "B", "C") yields the json result {keyboard: [["A"], ["B"], ["C"]]}
when row_width is set to 1.
When row_width is set to 2, the following is the r... | This function adds strings to the keyboard, while not exceeding row_width.
E.g. ReplyKeyboardMarkup#add("A", "B", "C") yields the json result {keyboard: [["A"], ["B"], ["C"]]}
when row_width is set to 1.
When row_width is set to 2, the following is the result of this function: {keyboard: [["A", ... |
def addfield(self, pkt, s, i):
"""
There is a hack with the _ExtensionsField.i2len. It works only because
we expect _ExtensionsField.i2m to return a string of the same size (if
not of the same value) upon successive calls (e.g. through i2len here,
then i2m when directly building ... | There is a hack with the _ExtensionsField.i2len. It works only because
we expect _ExtensionsField.i2m to return a string of the same size (if
not of the same value) upon successive calls (e.g. through i2len here,
then i2m when directly building the _ExtensionsField).
XXX A proper way to... |
async def track_event(event, state, service_name):
"""
Store state of events in memory
:param event: Event object
:param state: EventState object
:param service_name: Name of service name
"""
redis = await aioredis.create_redis(
(EVENT_TRACKING_HOST, 6379), loop=loop)
now = date... | Store state of events in memory
:param event: Event object
:param state: EventState object
:param service_name: Name of service name |
def quantile(y, k=4):
"""
Calculates the quantiles for an array
Parameters
----------
y : array
(n,1), values to classify
k : int
number of quantiles
Returns
-------
q : array
(n,1), quantile values
Examples
--------
>>> import n... | Calculates the quantiles for an array
Parameters
----------
y : array
(n,1), values to classify
k : int
number of quantiles
Returns
-------
q : array
(n,1), quantile values
Examples
--------
>>> import numpy as np
>>> import mapclass... |
def set_ccc(ctx, management_key, pin):
"""
Generate and set a CCC on the YubiKey.
"""
controller = ctx.obj['controller']
_ensure_authenticated(ctx, controller, pin, management_key)
controller.update_ccc() | Generate and set a CCC on the YubiKey. |
def working_yesterday(self, date_from=None, date_format=None):
"""
Retourne la date d'hier depuis maintenant ou depuis une date fournie
seulement sur les jours ouvrableq.
Ainsi lundi devient samedi et samedi devient vendredi
:param: :date_from date de référence
:return datetime
"""
# date d'hier que su... | Retourne la date d'hier depuis maintenant ou depuis une date fournie
seulement sur les jours ouvrableq.
Ainsi lundi devient samedi et samedi devient vendredi
:param: :date_from date de référence
:return datetime |
def __RetrieveContent(host, port, adapter, version, path, keyFile, certFile,
thumbprint, sslContext, connectionPoolTimeout=CONNECTION_POOL_IDLE_TIMEOUT_SEC):
"""
Retrieve service instance for connection.
@param host: Which host to connect to.
@type host: string
@param port: Port
... | Retrieve service instance for connection.
@param host: Which host to connect to.
@type host: string
@param port: Port
@type port: int
@param adapter: Adapter
@type adapter: string
@param version: Version
@type version: string
@param path: Path
@type path: string
@param keyFile: ssl... |
def run(self, root):
"""Searches for <div class="math"> that are children in <p> tags and corrects
the invalid HTML that results"""
math_tag_class = self.pelican_mathjax_extension.getConfig('math_tag_class')
for parent in root:
div_math = []
children = list(pare... | Searches for <div class="math"> that are children in <p> tags and corrects
the invalid HTML that results |
async def invoke(self, *args, **kwargs):
r"""|coro|
Calls a command with the arguments given.
This is useful if you want to just call the callback that a
:class:`.Command` holds internally.
Note
------
You do not pass in the context as it is done for you.
... | r"""|coro|
Calls a command with the arguments given.
This is useful if you want to just call the callback that a
:class:`.Command` holds internally.
Note
------
You do not pass in the context as it is done for you.
Warning
---------
The first p... |
def show_data(self, item):
""" show data key-value in ListCtrl for tree item
"""
child, cookie = self.mainview_tree.GetFirstChild(item)
child_list = []
while child.IsOk():
child_list.append(child)
child, cookie = self.mainview_tree.GetNextChild(item, cooki... | show data key-value in ListCtrl for tree item |
def fit_model(ts, sc=None):
"""
Fits a GARCH(1, 1) model to the given time series.
Parameters
----------
ts:
the time series to which we want to fit a GARCH model as a Numpy array
Returns a GARCH model
"""
assert sc != None, "Missing SparkContext"
jvm = sc.... | Fits a GARCH(1, 1) model to the given time series.
Parameters
----------
ts:
the time series to which we want to fit a GARCH model as a Numpy array
Returns a GARCH model |
def update_vlan(self, name, vid, vni):
"""Adds a new vlan to vni mapping for the interface
EosVersion:
4.13.7M
Args:
vlan (str, int): The vlan id to map to the vni
vni (str, int): The vni value to use
Returns:
True if the command complet... | Adds a new vlan to vni mapping for the interface
EosVersion:
4.13.7M
Args:
vlan (str, int): The vlan id to map to the vni
vni (str, int): The vni value to use
Returns:
True if the command completes successfully |
def plot(cg):
"""
Plot the call graph using matplotlib
For larger graphs, this should not be used, as it is very slow
and probably you can not see anything on it.
:param cg: A networkx call graph to plot
"""
from androguard.core.analysis.analysis import ExternalMethod
import matplotlib.... | Plot the call graph using matplotlib
For larger graphs, this should not be used, as it is very slow
and probably you can not see anything on it.
:param cg: A networkx call graph to plot |
def _on_timeout(self, _attempts=0):
"""
Called when the request associated with this ResponseFuture times out.
This function may reschedule itself. The ``_attempts`` parameter tracks
the number of times this has happened. This parameter should only be
set in those cases, where `... | Called when the request associated with this ResponseFuture times out.
This function may reschedule itself. The ``_attempts`` parameter tracks
the number of times this has happened. This parameter should only be
set in those cases, where ``_on_timeout`` reschedules itself. |
def _get_paths():
"""Generate paths to test data. Done in a function to protect namespace a bit."""
import os
base_path = os.path.dirname(os.path.abspath(__file__))
test_data_dir = os.path.join(base_path, 'tests', 'data', 'Plate01')
test_data_file = os.path.join(test_data_dir, 'RFP_Well_A3.fcs')
... | Generate paths to test data. Done in a function to protect namespace a bit. |
def disqus_sso_script(context):
"""
Provides a generic context variable which adds single-sign-on
support to DISQUS if ``COMMENTS_DISQUS_API_PUBLIC_KEY`` and
``COMMENTS_DISQUS_API_SECRET_KEY`` are specified.
"""
settings = context["settings"]
public_key = getattr(settings, "COMMENTS_DISQUS_A... | Provides a generic context variable which adds single-sign-on
support to DISQUS if ``COMMENTS_DISQUS_API_PUBLIC_KEY`` and
``COMMENTS_DISQUS_API_SECRET_KEY`` are specified. |
def resetPassword(self, email=True):
"""
resets a users password for an account. The password will be randomly
generated and emailed by the system.
Input:
email - boolean that an email password will be sent to the
user's profile email address. The default... | resets a users password for an account. The password will be randomly
generated and emailed by the system.
Input:
email - boolean that an email password will be sent to the
user's profile email address. The default is True. |
def file_needs_update(target_file, source_file):
"""Checks if target_file is not existing or differing from source_file
:param target_file: File target for a copy action
:param source_file: File to be copied
:return: True, if target_file not existing or differing from source_file, else False
:rtype... | Checks if target_file is not existing or differing from source_file
:param target_file: File target for a copy action
:param source_file: File to be copied
:return: True, if target_file not existing or differing from source_file, else False
:rtype: False |
def build(self, pre=None, shortest=False):
"""Build the ``Ref`` instance by fetching the rule from
the GramFuzzer instance and building it
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should... | Build the ``Ref`` instance by fetching the rule from
the GramFuzzer instance and building it
:param list pre: The prerequisites list
:param bool shortest: Whether or not the shortest reference-chain (most minimal) version of the field should be generated. |
def to_dict(self, fields=_all_fields, labels=None):
"""
Encode the node as a dictionary suitable for JSON serialization.
Args:
fields: if given, this is a whitelist of fields to include
on nodes (`daughters` and `form` are always shown)
labels: optional l... | Encode the node as a dictionary suitable for JSON serialization.
Args:
fields: if given, this is a whitelist of fields to include
on nodes (`daughters` and `form` are always shown)
labels: optional label annotations to embed in the
derivation dict; the va... |
def split_unquoted_newlines(stmt):
"""Split a string on all unquoted newlines.
Unlike str.splitlines(), this will ignore CR/LF/CR+LF if the requisite
character is inside of a string."""
text = text_type(stmt)
lines = SPLIT_REGEX.split(text)
outputlines = ['']
for line in lines:
if n... | Split a string on all unquoted newlines.
Unlike str.splitlines(), this will ignore CR/LF/CR+LF if the requisite
character is inside of a string. |
def load_backends(self):
"""
Loads all the backends setup in settings.py.
"""
for name, backend_settings in settings.storage.iteritems():
backend_path = backend_settings['backend']
backend_module, backend_cls = backend_path.rsplit('.', 1)
backend_module = import_module(backend_module)
... | Loads all the backends setup in settings.py. |
def pattern_to_regex(cls, pattern):
"""
Convert the pattern into a regular expression.
*pattern* (:class:`unicode` or :class:`bytes`) is the pattern to
convert into a regular expression.
Returns the uncompiled regular expression (:class:`unicode`, :class:`bytes`,
or :data:`None`), and whether matched file... | Convert the pattern into a regular expression.
*pattern* (:class:`unicode` or :class:`bytes`) is the pattern to
convert into a regular expression.
Returns the uncompiled regular expression (:class:`unicode`, :class:`bytes`,
or :data:`None`), and whether matched files should be included
(:data:`True`), exclu... |
def get_list(self, id, name=None):
'''
Get a list
Returns:
List: The list with the given `id`
'''
return self.create_list(dict(id=id, name=name)) | Get a list
Returns:
List: The list with the given `id` |
def preprocessing_declaration(job, config):
"""
Declare jobs related to preprocessing
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace config: Argparse Namespace object containing argument inputs
"""
if config.preprocessing:
job.fileStore.logToMaster('Ran... | Declare jobs related to preprocessing
:param JobFunctionWrappingJob job: passed automatically by Toil
:param Namespace config: Argparse Namespace object containing argument inputs |
def add_transformers(line):
'''Extract the transformers names from a line of code of the form
from __experimental__ import transformer1 [,...]
and adds them to the globally known dict
'''
assert FROM_EXPERIMENTAL.match(line)
line = FROM_EXPERIMENTAL.sub(' ', line)
# we now have: " tra... | Extract the transformers names from a line of code of the form
from __experimental__ import transformer1 [,...]
and adds them to the globally known dict |
async def send(self, message: Union[str, bytes],
binary: bool=False,
compress: Optional[int]=None) -> None:
"""Send a frame over the websocket with message as its payload."""
if isinstance(message, str):
message = message.encode('utf-8')
if binar... | Send a frame over the websocket with message as its payload. |
def initialize(self, training_info, model, environment, device):
""" Initialize policy gradient from reinforcer settings """
if self.trust_region:
self.average_model = self.model_factory.instantiate(action_space=environment.action_space).to(device)
self.average_model.load_state_d... | Initialize policy gradient from reinforcer settings |
def _prepare_sample(data, run_folder):
"""Extract passed keywords from input LIMS information.
"""
want = set(["description", "files", "genome_build", "name", "analysis", "upload", "algorithm"])
out = {}
for k, v in data.items():
if k in want:
out[k] = _relative_paths(v, run_fold... | Extract passed keywords from input LIMS information. |
def check_privatenet(self):
"""
Check if privatenet is running, and if container is same as the current Chains/privnet database.
Raises:
PrivnetConnectionError: if the private net couldn't be reached or the nonce does not match
"""
rpc_settings.setup(self.RPC_LIST)
... | Check if privatenet is running, and if container is same as the current Chains/privnet database.
Raises:
PrivnetConnectionError: if the private net couldn't be reached or the nonce does not match |
def pilot_PLL(xr,fq,fs,loop_type,Bn,zeta):
"""
theta, phi_error = pilot_PLL(xr,fq,fs,loop_type,Bn,zeta)
Mark Wickert, April 2014
"""
T = 1/float(fs)
# Set the VCO gain in Hz/V
Kv = 1.0
# Design a lowpass filter to remove the double freq term
Norder = 5
b_lp,a_lp... | theta, phi_error = pilot_PLL(xr,fq,fs,loop_type,Bn,zeta)
Mark Wickert, April 2014 |
def create_context_menu(self, event, shape):
'''
Parameters
----------
event : gtk.gdk.Event
GTK mouse click event.
shape : str
Electrode shape identifier (e.g., `"electrode028"`).
Returns
-------
gtk.Menu
Context menu.... | Parameters
----------
event : gtk.gdk.Event
GTK mouse click event.
shape : str
Electrode shape identifier (e.g., `"electrode028"`).
Returns
-------
gtk.Menu
Context menu.
.. versionchanged:: 0.13
- Deprecate hard-... |
def delete_fastqs(job, patient_dict):
"""
Delete the fastqs from the job Store once their purpose has been achieved (i.e. after all
mapping steps)
:param dict patient_dict: Dict of list of input fastqs
"""
for key in patient_dict.keys():
if 'fastq' not in key:
continue
... | Delete the fastqs from the job Store once their purpose has been achieved (i.e. after all
mapping steps)
:param dict patient_dict: Dict of list of input fastqs |
async def update_template_context(self, context: dict) -> None:
"""Update the provided template context.
This adds additional context from the various template context
processors.
Arguments:
context: The context to update (mutate).
"""
processors = self.temp... | Update the provided template context.
This adds additional context from the various template context
processors.
Arguments:
context: The context to update (mutate). |
def tangent_approx(f: SYM, x: SYM, a: SYM = None, assert_linear: bool = False) -> Dict[str, SYM]:
"""
Create a tangent approximation of a non-linear function f(x) about point a
using a block lower triangular solver
0 = f(x) = f(a) + J*x # taylor series about a (if f(x) linear in x, then globally vali... | Create a tangent approximation of a non-linear function f(x) about point a
using a block lower triangular solver
0 = f(x) = f(a) + J*x # taylor series about a (if f(x) linear in x, then globally valid)
J*x = -f(a) # solve for x
x = -J^{-1}f(a) # but inverse is slow, so we use solv... |
def parse(self):
""" parse data """
url = self.config.get('url')
self.cnml = CNMLParser(url)
self.parsed_data = self.cnml.getNodes() | parse data |
def get_qtls_from_mapqtl_data(matrix, threshold, inputfile):
"""Extract the QTLs found by MapQTL reading its file.
This assume that there is only one QTL per linkage group.
:arg matrix, the MapQTL file read in memory
:arg threshold, threshold used to determine if a given LOD value is
reflective... | Extract the QTLs found by MapQTL reading its file.
This assume that there is only one QTL per linkage group.
:arg matrix, the MapQTL file read in memory
:arg threshold, threshold used to determine if a given LOD value is
reflective the presence of a QTL.
:arg inputfile, name of the inputfile in... |
def get_importable_modules(folder):
"""Find all module files in the given folder that end with '.py' and
don't start with an underscore.
@return module names
@rtype: iterator of string
"""
for fname in os.listdir(folder):
if fname.endswith('.py') and not fname.startswith('_'):
... | Find all module files in the given folder that end with '.py' and
don't start with an underscore.
@return module names
@rtype: iterator of string |
def _cleanup_label(label):
"""
Reformat the ALL CAPS OMIM labels to something more pleasant to read.
This will:
1. remove the abbreviation suffixes
2. convert the roman numerals to integer numbers
3. make the text title case,
except for suplied conjunctions... | Reformat the ALL CAPS OMIM labels to something more pleasant to read.
This will:
1. remove the abbreviation suffixes
2. convert the roman numerals to integer numbers
3. make the text title case,
except for suplied conjunctions/prepositions/articles
:param label:
... |
def prefix_dict_keys(d: Dict[str, Any], prefix: str) -> Dict[str, Any]:
"""
Returns a dictionary that's a copy of as ``d`` but with ``prefix``
prepended to its keys.
"""
result = {} # type: Dict[str, Any]
for k, v in d.items():
result[prefix + k] = v
return result | Returns a dictionary that's a copy of as ``d`` but with ``prefix``
prepended to its keys. |
def delete(self):
""" Remove this file """
self.room.check_owner()
self.conn.make_call("deleteFiles", [self.fid]) | Remove this file |
def get(self, request, *args, **kwargs):
"""
Do the login and password protection.
"""
response = super(EntryProtectionMixin, self).get(
request, *args, **kwargs)
if self.object.login_required and not request.user.is_authenticated:
return self.login()
... | Do the login and password protection. |
def makeNetwork(self):
"""Makes graph object from .gdf loaded data"""
if "weight" in self.data_friendships.keys():
self.G=G=x.DiGraph()
else:
self.G=G=x.Graph()
F=self.data_friends
for friendn in range(self.n_friends):
if "posts" in F.keys():
... | Makes graph object from .gdf loaded data |
def get_or_create_head(root):
"""Ensures that `root` contains a <head> element and returns it.
"""
head = _create_cssselector("head")(root)
if not head:
head = etree.Element("head")
body = _create_cssselector("body")(root)[0]
body.getparent().insert(0, head)
return head
... | Ensures that `root` contains a <head> element and returns it. |
def search(self, text, lookup=None):
'''Returns a new :class:`Query` for :attr:`Manager.model` with
a full text search value.'''
return self.query().search(text, lookup=lookup) | Returns a new :class:`Query` for :attr:`Manager.model` with
a full text search value. |
def revoke_token(self, token, headers=None, **kwargs):
"""
Revoke an access token
"""
self._check_configuration("site", "revoke_uri")
url = "%s%s" % (self.site, quote(self.revoke_url))
data = {'token': token}
data.update(kwargs)
return self._make_request(... | Revoke an access token |
def __call_api(self, path, params=None, api_url=FORECAST_URL):
"""
Call the datapoint api using the requests module
"""
if not params:
params = dict()
payload = {'key': self.api_key}
payload.update(params)
url = "%s/%s" % (api_url, path)
# Ad... | Call the datapoint api using the requests module |
def plot_3d_dist(Z, X, Y, N=1000, AxisOffset=0, Angle=-40, LowLim=None, HighLim=None, show_fig=True):
"""
Plots Z, X and Y as a 3d scatter plot with heatmaps of each axis pair.
Parameters
----------
Z : ndarray
Array of Z positions with time
X : ndarray
Array of X positions with... | Plots Z, X and Y as a 3d scatter plot with heatmaps of each axis pair.
Parameters
----------
Z : ndarray
Array of Z positions with time
X : ndarray
Array of X positions with time
Y : ndarray
Array of Y positions with time
N : optional, int
Number of time points t... |
def trade_signals_handler(self, signals):
'''
Process buy and sell signals from the simulation
'''
alloc = {}
if signals['buy'] or signals['sell']:
# Compute the optimal portfolio allocation,
# Using user defined function
try:
... | Process buy and sell signals from the simulation |
def _kwarg(self, kwargs, kwname, default=None):
"""
Resolves keyword arguments from constructor or :doc:`config`.
.. note::
The keyword arguments take this order of precedence:
1. Arguments passed to constructor through the
:func:`authomatic.login`.
... | Resolves keyword arguments from constructor or :doc:`config`.
.. note::
The keyword arguments take this order of precedence:
1. Arguments passed to constructor through the
:func:`authomatic.login`.
2. Provider specific arguments from :doc:`config`.
... |
def to_csv(weekmatrices, filename, digits=5):
"""
Exports a list of week-matrices to a specified filename in the CSV format.
Parameters
----------
weekmatrices : list
The week-matrices to export.
filename : string
Path for the exported CSV file.
"""
with open(filename, ... | Exports a list of week-matrices to a specified filename in the CSV format.
Parameters
----------
weekmatrices : list
The week-matrices to export.
filename : string
Path for the exported CSV file. |
def plot_clock_diagrams(self, colormap="summer"):
"""
Ploting clock diagrams - one or more rings around residue name and id (and chain id).
The rings show the fraction of simulation time this residue has spent in the vicinity of the
ligand - characterised by distance.
"""
... | Ploting clock diagrams - one or more rings around residue name and id (and chain id).
The rings show the fraction of simulation time this residue has spent in the vicinity of the
ligand - characterised by distance. |
def get_attribute_values(self, att_name):
"""
Returns the values of attribute "att_name" of CPE Name.
By default a only element in each part.
:param string att_name: Attribute name to get
:returns: List of attribute values
:rtype: list
:exception: ValueError - in... | Returns the values of attribute "att_name" of CPE Name.
By default a only element in each part.
:param string att_name: Attribute name to get
:returns: List of attribute values
:rtype: list
:exception: ValueError - invalid attribute name |
def list_vms_sub(access_token, subscription_id):
'''List VMs in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of a list of VM model views.
'''
endpoint = ''.join(... | List VMs in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of a list of VM model views. |
def send_async(self, transaction, headers=None):
"""Submit a transaction to the Federation with the mode `async`.
Args:
transaction (dict): the transaction to be sent
to the Federation node(s).
headers (dict): Optional headers to pass to the request.
Ret... | Submit a transaction to the Federation with the mode `async`.
Args:
transaction (dict): the transaction to be sent
to the Federation node(s).
headers (dict): Optional headers to pass to the request.
Returns:
dict: The transaction sent to the Federati... |
def collection_keys(coll, sep='.'):
"""Get a list of all (including nested) keys in a collection.
Examines the first document in the collection.
:param sep: Separator for nested keys
:return: List of str
"""
def _keys(x, pre=''):
for k in x:
yield (pre + k)
if is... | Get a list of all (including nested) keys in a collection.
Examines the first document in the collection.
:param sep: Separator for nested keys
:return: List of str |
def extract(args):
"""
%prog extract [--options] ace_file
Extract contigs from ace file and if necessary reformat header with
a pipe(|) separated list of constituent reads.
"""
p = OptionParser(extract.__doc__)
p.add_option("--format", default=False, action="store_true",
help="e... | %prog extract [--options] ace_file
Extract contigs from ace file and if necessary reformat header with
a pipe(|) separated list of constituent reads. |
def list_storage_accounts_rg(access_token, subscription_id, rgname):
'''List the storage accounts in the specified resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
Re... | List the storage accounts in the specified resource group.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
rgname (str): Azure resource group name.
Returns:
HTTP response. JSON body list of storage accounts. |
def display_monthly_returns(self):
"""
Display a table containing monthly returns and ytd returns
for every year in range.
"""
data = [['Year', 'Jan', 'Feb', 'Mar', 'Apr', 'May',
'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', 'YTD']]
for k in self.retur... | Display a table containing monthly returns and ytd returns
for every year in range. |
def _get_rest_doc(self, request, start_response):
"""Sends back HTTP response with API directory.
This calls start_response and returns the response body. It will return
the discovery doc for the requested api/version.
Args:
request: An ApiRequest, the transformed request sent to the Discovery ... | Sends back HTTP response with API directory.
This calls start_response and returns the response body. It will return
the discovery doc for the requested api/version.
Args:
request: An ApiRequest, the transformed request sent to the Discovery API.
start_response: A function with semantics defi... |
def _run_hooks(self, name, module):
"""
Run all hooks for a module.
"""
hooks = self.post_load_hooks.pop(name, [])
for hook in hooks:
hook(module) | Run all hooks for a module. |
def RemoveObject(self, identifier):
"""Removes a cached object based on the identifier.
This method ignores the cache value reference count.
Args:
identifier (str): VFS object identifier.
Raises:
KeyError: if the VFS object is not found in the cache.
"""
if identifier not in self.... | Removes a cached object based on the identifier.
This method ignores the cache value reference count.
Args:
identifier (str): VFS object identifier.
Raises:
KeyError: if the VFS object is not found in the cache. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.