code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def set_colors(self, buf):
"""
DEPRECATED: use self.color_list
Use with extreme caution!
Directly sets the internal buffer and bypasses all brightness and
rotation control buf must also be in the exact format required by the
display type.
"""
deprecated.d... | DEPRECATED: use self.color_list
Use with extreme caution!
Directly sets the internal buffer and bypasses all brightness and
rotation control buf must also be in the exact format required by the
display type. |
def f0Morph(fromWavFN, pitchPath, stepList,
outputName, doPlotPitchSteps, fromPitchData, toPitchData,
outputMinPitch, outputMaxPitch, praatEXE, keepPitchRange=False,
keepAveragePitch=False, sourcePitchDataList=None,
minIntervalLength=0.3):
'''
Resynthesizes the pi... | Resynthesizes the pitch track from a source to a target wav file
fromPitchData and toPitchData should be segmented according to the
portions that you want to morph. The two lists must have the same
number of sublists.
Occurs over a three-step process.
This function can act as a template for how ... |
def is_reconstructed(self, xy_cutoff=0.3, z_cutoff=0.4):
"""Compare initial and final slab configuration
to determine if slab reconstructs during relaxation
xy_cutoff: Allowed xy-movement is determined from
the covalent radii as:
xy_cutoff * np.mean(cradi... | Compare initial and final slab configuration
to determine if slab reconstructs during relaxation
xy_cutoff: Allowed xy-movement is determined from
the covalent radii as:
xy_cutoff * np.mean(cradii)
z_cutoff: Allowed z-movement is determined as
... |
def to_args(self):
"""Return command arguments for this object.
Return a list of the non-default options of this ``SoSOptions``
object in ``sosreport`` command line argument notation:
``["--all-logs", "-vvv"]``
"""
def has_value(name, value):
... | Return command arguments for this object.
Return a list of the non-default options of this ``SoSOptions``
object in ``sosreport`` command line argument notation:
``["--all-logs", "-vvv"]`` |
def _update_tcs_helper_catalogue_tables_info_with_new_tables(
self):
"""update tcs helper catalogue tables info with new tables
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage e... | update tcs helper catalogue tables info with new tables
.. todo ::
- update key arguments values and definitions with defaults
- update return values and definitions
- update usage examples and text
- update docstring text
- check sublime snippet exi... |
def convert_hpdist(self, node):
"""
Convert the given node into a probability mass function for the
hypo depth distribution.
:param node: a hypoDepthDist node
:returns: a :class:`openquake.hazardlib.pmf.PMF` instance
"""
with context(self.fname, node):
... | Convert the given node into a probability mass function for the
hypo depth distribution.
:param node: a hypoDepthDist node
:returns: a :class:`openquake.hazardlib.pmf.PMF` instance |
def info(self, text):
""" Ajout d'un message de log de type INFO """
self.logger.info("{}{}".format(self.message_prefix, text)) | Ajout d'un message de log de type INFO |
def _set_metric(self, metric_name, metric_type, value, tags=None):
"""
Set a metric
"""
if metric_type == self.GAUGE:
self.gauge(metric_name, value, tags=tags)
else:
self.log.error('Metric type "{}" unknown'.format(metric_type)) | Set a metric |
def import_file(self, taskfileinfo):
"""Import the file for the given taskfileinfo
This will also update the status to :data:`Reftrack.IMPORTED`. This will also call
:meth:`fetch_new_children`. Because after the import, we might have new children.
:param taskfileinfo: the taskfileinfo ... | Import the file for the given taskfileinfo
This will also update the status to :data:`Reftrack.IMPORTED`. This will also call
:meth:`fetch_new_children`. Because after the import, we might have new children.
:param taskfileinfo: the taskfileinfo to import. If None is given, try to import
... |
def submit(self, fn, *args, **kwargs):
"""Submit an operation"""
if not self.asynchronous:
return fn(*args, **kwargs)
raise NotImplementedError | Submit an operation |
def unkown_field(self, value=None):
"""Corresponds to IDD Field `unkown_field` Empty field in data.
Args:
value (str): value for IDD Field `unkown_field`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
... | Corresponds to IDD Field `unkown_field` Empty field in data.
Args:
value (str): value for IDD Field `unkown_field`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises:
ValueError: if `va... |
def PublishableBox(publishable, box_type, nodelist, model=None):
"add some content type info of self.target"
if not model:
model = publishable.content_type.model_class()
box_class = model.box_class
if box_class == PublishableBox:
box_class = Box
return box_class(publishable, box_typ... | add some content type info of self.target |
def draw_line(self, x1, y1, x2, y2):
"""Draw a line on the current rendering target.
Args:
x1 (int): The x coordinate of the start point.
y1 (int): The y coordinate of the start point.
x2 (int): The x coordinate of the end point.
y2 (int): The y coordinat... | Draw a line on the current rendering target.
Args:
x1 (int): The x coordinate of the start point.
y1 (int): The y coordinate of the start point.
x2 (int): The x coordinate of the end point.
y2 (int): The y coordinate of the end point.
Raises:
... |
def _combine_ranges(ranges):
"""
This function takes a list of row-ranges (as returned by `_parse_row`)
ordered by rows, and produces a list of distinct rectangular ranges
within this grid.
Within this function we define a 2d-range as a rectangular set of cells
such that:
- there are no e... | This function takes a list of row-ranges (as returned by `_parse_row`)
ordered by rows, and produces a list of distinct rectangular ranges
within this grid.
Within this function we define a 2d-range as a rectangular set of cells
such that:
- there are no empty rows / columns within this rectangle... |
def load_lc_data(filename, indep, dep, indweight=None, mzero=None, dir='./'):
"""
load dictionary with lc data
"""
if '/' in filename:
path, filename = os.path.split(filename)
else:
# TODO: this needs to change to be directory of the .phoebe file
path = dir
load_file = ... | load dictionary with lc data |
def diff_stats(self, ids):
"""Compute diff stats for a set of results.
:param id: Result IDs as int list.
:return: :class:`results.DiffStats <results.DiffStats>` object
:rtype: results.DiffStats
"""
schema = DiffStatsSchema()
resp = self.service.post(self.base, p... | Compute diff stats for a set of results.
:param id: Result IDs as int list.
:return: :class:`results.DiffStats <results.DiffStats>` object
:rtype: results.DiffStats |
def _get_setter_fun(object_type, # type: Type
parameter, # type: Parameter
private_property_name # type: str
):
"""
Utility method to find the overridden setter function for a given property, or generate a new one
:param obj... | Utility method to find the overridden setter function for a given property, or generate a new one
:param object_type:
:param property_name:
:param property_type:
:param private_property_name:
:return: |
def encodeDeltas(self, dx,dy):
"""Return the SDR for dx,dy"""
dxe = self.dxEncoder.encode(dx)
dye = self.dyEncoder.encode(dy)
ex = numpy.outer(dxe,dye)
return ex.flatten().nonzero()[0] | Return the SDR for dx,dy |
async def close(self, timeout=5) -> None:
"""Stop a ffmpeg instance."""
if not self.is_running:
_LOGGER.warning("FFmpeg isn't running!")
return
# Can't use communicate because we attach the output to a streamreader
def _close():
"""Close ffmpeg."""
... | Stop a ffmpeg instance. |
def main(raw_args=None):
"""Run the iotile-emulate script.
Args:
raw_args (list): Optional list of commmand line arguments. If not
passed these are pulled from sys.argv.
"""
if raw_args is None:
raw_args = sys.argv[1:]
parser = build_parser()
args = parser.parse_a... | Run the iotile-emulate script.
Args:
raw_args (list): Optional list of commmand line arguments. If not
passed these are pulled from sys.argv. |
def run(self):
"""Threading callback"""
self.viewing = True
while self.viewing and self._lock.acquire():
try:
line = self._readline()
except:
pass
else:
logger.info(line)
self._lock.release()
... | Threading callback |
def write_yaml(data, out_path, Dumper=yaml.Dumper, **kwds):
'''Write python dictionary to YAML'''
import errno
import os
class OrderedDumper(Dumper):
pass
def _dict_representer(dumper, data):
return dumper.represent_mapping(
yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG... | Write python dictionary to YAML |
def __set_style_sheet(self):
"""
Sets the Widget stylesheet.
"""
colors = map(
lambda x: "rgb({0}, {1}, {2}, {3})".format(x.red(), x.green(), x.blue(), int(self.__opacity * 255)),
(self.__color, self.__background_color, self.__border_color))
self.setStyle... | Sets the Widget stylesheet. |
def GetFileEntryByPathSpec(self, path_spec):
"""Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): a path specification.
Returns:
TSKPartitionFileEntry: a file entry or None of not available.
"""
tsk_vs_part, partition_index = tsk_partition.GetTSKVsPartByPathS... | Retrieves a file entry for a path specification.
Args:
path_spec (PathSpec): a path specification.
Returns:
TSKPartitionFileEntry: a file entry or None of not available. |
def singleton(cls):
"""
单例模式的装饰器: 在需要单例的类定义上加 @singleton 即可
"""
INSTANCES = {}
def _singleton(*args, **kwargs):
if cls not in INSTANCES:
INSTANCES[cls] = cls(*args, **kwargs)
return INSTANCES[cls]
return _singleton | 单例模式的装饰器: 在需要单例的类定义上加 @singleton 即可 |
def _write_triggers(self, fh, triggers, indent=""):
"""Write triggers to a file handle.
Parameters:
fh (file): file object.
triggers (list): list of triggers to write.
indent (str): indentation for each line.
"""
for trig in triggers:
fh.... | Write triggers to a file handle.
Parameters:
fh (file): file object.
triggers (list): list of triggers to write.
indent (str): indentation for each line. |
def canvasPressEvent(self, e):
"""
Handle canvas press events so we know when user is capturing the rect.
:param e: A Qt event object.
:type: QEvent
"""
self.start_point = self.toMapCoordinates(e.pos())
self.end_point = self.start_point
self.is_emitting_p... | Handle canvas press events so we know when user is capturing the rect.
:param e: A Qt event object.
:type: QEvent |
def push(self, message, device=None, title=None, url=None, url_title=None,
priority=None, timestamp=None, sound=None):
"""Pushes the notification, returns the Requests response.
Arguments:
message -- your message
Keyword arguments:
device -- your user's dev... | Pushes the notification, returns the Requests response.
Arguments:
message -- your message
Keyword arguments:
device -- your user's device name to send the message directly to
that device, rather than all of the user's devices
title -- your message's... |
def fetch_max(self, cluster, metric, topology, component, instance, timerange, environ=None):
'''
:param cluster:
:param metric:
:param topology:
:param component:
:param instance:
:param timerange:
:param environ:
:return:
'''
components = [component] if component != "*" els... | :param cluster:
:param metric:
:param topology:
:param component:
:param instance:
:param timerange:
:param environ:
:return: |
def _clear(self):
"""Resets all assigned data for the current message."""
self._finished = False
self._measurement = None
self._message = None
self._message_body = None | Resets all assigned data for the current message. |
def get_resultsets(self, routine, *args):
"""Return a list of lists of dictionaries, for when a query returns
more than one resultset.
"""
(query, replacements) = self.__build_raw_query(routine, args)
# Grab a raw connection from the connection-pool.
connection = mm.db... | Return a list of lists of dictionaries, for when a query returns
more than one resultset. |
def com_google_fonts_check_monospace_max_advancewidth(ttFont, glyph_metrics_stats):
"""Monospace font has hhea.advanceWidthMax equal to each glyph's
advanceWidth?"""
from fontbakery.utils import pretty_print_list
seems_monospaced = glyph_metrics_stats["seems_monospaced"]
if not seems_monospaced:
yield SK... | Monospace font has hhea.advanceWidthMax equal to each glyph's
advanceWidth? |
def init_queue_for(
self,
queue_identifier: QueueIdentifier,
items: List[QueueItem_T],
) -> NotifyingQueue:
""" Create the queue identified by the queue_identifier
and initialize it with `items`.
"""
recipient = queue_identifier.recipient
q... | Create the queue identified by the queue_identifier
and initialize it with `items`. |
def Davis_David(m, x, D, rhol, rhog, Cpl, kl, mul):
r'''Calculates the two-phase non-boiling heat transfer coefficient of a
liquid and gas flowing inside a tube of any inclination, as in [1]_ and
reviewed in [2]_.
.. math::
\frac{h_{TP} D}{k_l} = 0.060\left(\frac{\rho_L}{\rho_G}\right)^{0.28}... | r'''Calculates the two-phase non-boiling heat transfer coefficient of a
liquid and gas flowing inside a tube of any inclination, as in [1]_ and
reviewed in [2]_.
.. math::
\frac{h_{TP} D}{k_l} = 0.060\left(\frac{\rho_L}{\rho_G}\right)^{0.28}
\left(\frac{DG_{TP} x}{\mu_L}\right)^{0.87}
... |
def _set_map_(self, v, load=False):
"""
Setter method for map_, mapped from YANG variable /overlay_gateway/map (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_map_ is considered as a private
method. Backends looking to populate this variable should
do... | Setter method for map_, mapped from YANG variable /overlay_gateway/map (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_map_ is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_map_() directly. |
def _check(user, topic):
"""If the topic has it's export_control set to True then all the teams
under the product team can access to the topic's resources.
:param user:
:param topic:
:return: True if check is ok, False otherwise
"""
# if export_control then check the team is associated to t... | If the topic has it's export_control set to True then all the teams
under the product team can access to the topic's resources.
:param user:
:param topic:
:return: True if check is ok, False otherwise |
def CMOVS(cpu, dest, src):
"""
Conditional move - Sign (negative).
Tests the status flags in the EFLAGS register and moves the source operand
(second operand) to the destination operand (first operand) if the given
test condition is true.
:param cpu: current CPU.
... | Conditional move - Sign (negative).
Tests the status flags in the EFLAGS register and moves the source operand
(second operand) to the destination operand (first operand) if the given
test condition is true.
:param cpu: current CPU.
:param dest: destination operand.
:pa... |
def _cleanup_markers(context_id, task_ids):
"""Delete the FuriousAsyncMarker entities corresponding to ids."""
logging.debug("Cleanup %d markers for Context %s",
len(task_ids), context_id)
# TODO: Handle exceptions and retries here.
delete_entities = [ndb.Key(FuriousAsyncMarker, id) ... | Delete the FuriousAsyncMarker entities corresponding to ids. |
def open(self):
"""
Obtains the lvm handle. Usually you would never need to use this method unless
you are trying to do operations using the ctypes function wrappers in conversion.py
*Raises:*
* HandleError
"""
if not self.handle:
try:
... | Obtains the lvm handle. Usually you would never need to use this method unless
you are trying to do operations using the ctypes function wrappers in conversion.py
*Raises:*
* HandleError |
def get_or_create(self, qualifier, new_parameter, **kwargs):
"""
Get a :class:`Parameter` from the ParameterSet, if it does not exist,
create and attach it.
Note: running this on a ParameterSet that is NOT a
:class:`phoebe.frontend.bundle.Bundle`,
will NOT add the Parame... | Get a :class:`Parameter` from the ParameterSet, if it does not exist,
create and attach it.
Note: running this on a ParameterSet that is NOT a
:class:`phoebe.frontend.bundle.Bundle`,
will NOT add the Parameter to the bundle, but only the temporary
ParameterSet
:paramete... |
def getSoname(filename):
"""
Return the soname of a library.
"""
cmd = ["objdump", "-p", "-j", ".dynamic", filename]
m = re.search(r'\s+SONAME\s+([^\s]+)', compat.exec_command(*cmd))
if m:
return m.group(1) | Return the soname of a library. |
def google_news_search(self,query,category_label,num=50):
'''
Searches Google News.
NOTE: Official Google News API is deprecated https://developers.google.com/news-search/?hl=en
NOTE: Google limits the maximum number of documents per query to 100.
Use multiple related queri... | Searches Google News.
NOTE: Official Google News API is deprecated https://developers.google.com/news-search/?hl=en
NOTE: Google limits the maximum number of documents per query to 100.
Use multiple related queries to get a bigger corpus.
Args:
query (str): The search... |
def openSourceFile(self, fileToOpen):
"""Finds and opens the source file for link target fileToOpen.
When links like [test](test) are clicked, the file test.md is opened.
It has to be located next to the current opened file.
Relative paths like [test](../test) or [test](folder/test) are also possible.
"""
... | Finds and opens the source file for link target fileToOpen.
When links like [test](test) are clicked, the file test.md is opened.
It has to be located next to the current opened file.
Relative paths like [test](../test) or [test](folder/test) are also possible. |
def _set_local_preference(self, v, load=False):
"""
Setter method for local_preference, mapped from YANG variable /routing_system/route_map/content/set/local_preference (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_local_preference is considered as a privat... | Setter method for local_preference, mapped from YANG variable /routing_system/route_map/content/set/local_preference (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_local_preference is considered as a private
method. Backends looking to populate this variable sho... |
def pymmh3_hash128(key: Union[bytes, bytearray],
seed: int = 0,
x64arch: bool = True) -> int:
"""
Implements 128bit murmur3 hash, as per ``pymmh3``.
Args:
key: data to hash
seed: seed
x64arch: is a 64-bit architecture available?
Returns:
... | Implements 128bit murmur3 hash, as per ``pymmh3``.
Args:
key: data to hash
seed: seed
x64arch: is a 64-bit architecture available?
Returns:
integer hash |
def first_visible_line(self, after_scroll_offset=False):
"""
Return the line number (0 based) of the input document that corresponds
with the first visible line.
"""
if after_scroll_offset:
return self.displayed_lines[self.applied_scroll_offsets.top]
else:
... | Return the line number (0 based) of the input document that corresponds
with the first visible line. |
def show(self, view: View, request: Request):
"""Show the welcome page.
Arguments:
view {masonite.view.View} -- The Masonite view class.
Application {config.application} -- The application config module.
Returns:
masonite.view.View -- The Masonite view class... | Show the welcome page.
Arguments:
view {masonite.view.View} -- The Masonite view class.
Application {config.application} -- The application config module.
Returns:
masonite.view.View -- The Masonite view class. |
def get(self, user_id):
"""Returns a specific user"""
user = db.User.find_one(User.user_id == user_id)
roles = db.Role.all()
if not user:
return self.make_response('Unable to find the user requested, might have been removed', HTTP.NOT_FOUND)
return self.make_respons... | Returns a specific user |
def get(self, layout, default=None):
"""
Returns given layout value.
:param layout: Layout name.
:type layout: unicode
:param default: Default value if layout is not found.
:type default: object
:return: Action.
:rtype: QAction
"""
try:
... | Returns given layout value.
:param layout: Layout name.
:type layout: unicode
:param default: Default value if layout is not found.
:type default: object
:return: Action.
:rtype: QAction |
def build_kalman_mean_step(get_transition_matrix_for_timestep,
get_transition_noise_for_timestep,
get_observation_matrix_for_timestep,
get_observation_noise_for_timestep):
"""Build a callable that performs one step of Kalman mean recursi... | Build a callable that performs one step of Kalman mean recursion.
Args:
get_transition_matrix_for_timestep: callable taking a timestep
as an integer `Tensor` argument, and returning a `LinearOperator`
of shape `[latent_size, latent_size]`.
get_transition_noise_for_timestep: callable taking a time... |
def locked_put(self, credentials):
"""Write a Credentials to the Django datastore.
Args:
credentials: Credentials, the credentials to store.
"""
entity, _ = self.model_class.objects.get_or_create(
**{self.key_name: self.key_value})
setattr(entity, self.p... | Write a Credentials to the Django datastore.
Args:
credentials: Credentials, the credentials to store. |
def lattice_from_abivars(cls=None, *args, **kwargs):
"""
Returns a `Lattice` object from a dictionary
with the Abinit variables `acell` and either `rprim` in Bohr or `angdeg`
If acell is not given, the Abinit default is used i.e. [1,1,1] Bohr
Args:
cls: Lattice class to be instantiated. pym... | Returns a `Lattice` object from a dictionary
with the Abinit variables `acell` and either `rprim` in Bohr or `angdeg`
If acell is not given, the Abinit default is used i.e. [1,1,1] Bohr
Args:
cls: Lattice class to be instantiated. pymatgen.core.lattice.Lattice if `cls` is None
Example:
... |
def build(self):
"""Build straight helix along z-axis, starting with CA1 on x-axis"""
ang_per_res = (2 * numpy.pi) / self.residues_per_turn
atom_offsets = _atom_offsets[self.helix_type]
if self.handedness == 'l':
handedness = -1
else:
handedness = 1
... | Build straight helix along z-axis, starting with CA1 on x-axis |
def run_epilogue(self):
"""Run the epilogue script in the current working directory.
raises:
subprocess.CalledProcessError: if the script does not finish with
exit code zero.
"""
logger = logging.getLogger(__name__)
if self.epilogue is not None:
... | Run the epilogue script in the current working directory.
raises:
subprocess.CalledProcessError: if the script does not finish with
exit code zero. |
def get_order(self, order_id):
"""
See more:
http://developer.oanda.com/rest-live/orders/#getInformationForAnOrder
"""
url = "{0}/{1}/accounts/{2}/orders/{3}".format(
self.domain,
self.API_VERSION,
self.account_id,
order_id
... | See more:
http://developer.oanda.com/rest-live/orders/#getInformationForAnOrder |
def Process(self, parser_mediator, root_item=None, **kwargs):
"""Parses a document summary information OLECF item.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
root_item (Optional[pyolecf.item]): root item o... | Parses a document summary information OLECF item.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
root_item (Optional[pyolecf.item]): root item of the OLECF file.
Raises:
ValueError: If the root item is ... |
def _parse_xml(self):
"""Extracts the XML settings into class instances that can operate on
the settings to perform the testing functions.
"""
import xml.etree.ElementTree as ET
from os import path
#This dict has the keys of XML tags that are required in order for the
... | Extracts the XML settings into class instances that can operate on
the settings to perform the testing functions. |
def buy(self, account_id, **params):
"""https://developers.coinbase.com/api/v2#buy-bitcoin"""
if 'amount' not in params and 'total' not in params:
raise ValueError("Missing required parameter: 'amount' or 'total'")
for required in ['currency', 'payment_method']:
if requir... | https://developers.coinbase.com/api/v2#buy-bitcoin |
def decode_array(values):
"""
Decode the values which are bytestrings.
"""
out = []
for val in values:
try:
out.append(val.decode('utf8'))
except AttributeError:
out.append(val)
return out | Decode the values which are bytestrings. |
def to_pickle(obj, path, compression='infer',
protocol=pickle.HIGHEST_PROTOCOL):
"""
Pickle (serialize) object to file.
Parameters
----------
obj : any object
Any python object.
path : str
File path where the pickled object will be stored.
compression : {'infer... | Pickle (serialize) object to file.
Parameters
----------
obj : any object
Any python object.
path : str
File path where the pickled object will be stored.
compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer'
A string representing the compression to use ... |
def dihed_iter(self, g_nums, ats_1, ats_2, ats_3, ats_4, \
invalid_error=False):
""" Iterator over selected dihedral angles.
Angles are in degrees as with :meth:`dihed_single`.
See `above <toc-generators_>`_ for more information on
ca... | Iterator over selected dihedral angles.
Angles are in degrees as with :meth:`dihed_single`.
See `above <toc-generators_>`_ for more information on
calling options.
Parameters
----------
g_nums
|int| or iterable |int| or |None| --
Indices of the... |
def confdate(self):
"""Date range of the conference the abstract belongs to represented
by two tuples in the form (YYYY, MM, DD).
"""
date = self._confevent.get('confdate', {})
if len(date) > 0:
start = {k: int(v) for k, v in date['startdate'].items()}
end... | Date range of the conference the abstract belongs to represented
by two tuples in the form (YYYY, MM, DD). |
def create(self, data, **kwargs):
"""Create a new object.
Args:
data (dict): Parameters to send to the server to create the
resource
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If auth... | Create a new object.
Args:
data (dict): Parameters to send to the server to create the
resource
**kwargs: Extra options to send to the server (e.g. sudo)
Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabC... |
def load(self, id): #pylint:disable=redefined-builtin
"""
Retrieves one object from the pickler with the provided id.
:param id: an ID to use
"""
l.debug("LOAD: %s", id)
try:
l.debug("... trying cached")
return self._object_cache[id]
excep... | Retrieves one object from the pickler with the provided id.
:param id: an ID to use |
def collect(cls, sources):
"""
:param sources: dictionaries with a key 'tectonicRegion'
:returns: an ordered list of SourceGroup instances
"""
source_stats_dict = {}
for src in sources:
trt = src['tectonicRegion']
if trt not in source_stats_dict:
... | :param sources: dictionaries with a key 'tectonicRegion'
:returns: an ordered list of SourceGroup instances |
def to_protobuf(self) -> SaveStateProto:
"""
Create protobuf item.
:return: protobuf structure
:rtype: ~unidown.plugin.protobuf.save_state_pb2.SaveStateProto
"""
result = SaveStateProto()
result.version = str(self.version)
result.last_update.CopyFrom(date... | Create protobuf item.
:return: protobuf structure
:rtype: ~unidown.plugin.protobuf.save_state_pb2.SaveStateProto |
def discover_resources():
"""
Searches for translations files matching [catalog].[lang].[format]
Traverses TRANZ_LOCALE_PATHS:
-
| TRANZ_LOCALE_PATHS
+- messages.fr.yml
| messages.en.yml
And apps paths if TRANZ_SEARCH_LOCALE_IN_APPS is set to True):
-
| app_path
+- TRANZ... | Searches for translations files matching [catalog].[lang].[format]
Traverses TRANZ_LOCALE_PATHS:
-
| TRANZ_LOCALE_PATHS
+- messages.fr.yml
| messages.en.yml
And apps paths if TRANZ_SEARCH_LOCALE_IN_APPS is set to True):
-
| app_path
+- TRANZ_DIR_NAME
+- messages.fr.yml
... |
def stop(self):
"""Stop the daemon."""
pid = None
if os.path.exists(self.pidfile):
with open(self.pidfile, 'r') as fp:
pid = int(fp.read().strip())
if not pid:
msg = 'pidfile (%s) does not exist. Daemon not running?\n'
sys.stderr.write... | Stop the daemon. |
def _get_conda_version(stdout, stderr):
"""Callback for get_conda_version."""
# argparse outputs version to stderr in Python < 3.4.
# http://bugs.python.org/issue18920
pat = re.compile(r'conda:?\s+(\d+\.\d\S+|unknown)')
m = pat.match(stderr.decode().strip())
if m is None:... | Callback for get_conda_version. |
def unpack_post(environ, content_length):
"""
Unpacks a post request query string.
:param environ: whiskey application environment.
:return: A dictionary with parameters.
"""
post_body = environ['wsgi.input'].read(content_length).decode("utf-8")
data = None
if "application/x-www-form-url... | Unpacks a post request query string.
:param environ: whiskey application environment.
:return: A dictionary with parameters. |
def _get_localhost_ssh_port():
"""Something in the VM chain, either VirtualBox or Machine, helpfully
sets up localhost-to-VM forwarding on port 22. We can inspect this
rule to determine the port on localhost which gets forwarded to
22 in the VM."""
for line in _get_vm_config():
if line.start... | Something in the VM chain, either VirtualBox or Machine, helpfully
sets up localhost-to-VM forwarding on port 22. We can inspect this
rule to determine the port on localhost which gets forwarded to
22 in the VM. |
def moderators(self, limit=None):
"""GETs moderators for this subreddit. Calls :meth:`narwal.Reddit.moderators`.
:param limit: max number of items to return
"""
return self._reddit.moderators(self.display_name, limit=limit) | GETs moderators for this subreddit. Calls :meth:`narwal.Reddit.moderators`.
:param limit: max number of items to return |
def _validate_obj_by_schema(self, obj, obj_nex_id, vc):
"""Creates:
errors if `obj` does not contain keys in the schema.ALLOWED_KEY_SET,
warnings if `obj` lacks keys listed in schema.EXPECETED_KEY_SET,
or if `obj` contains keys not listed in schema.ALLOWED_KEY_SET.
... | Creates:
errors if `obj` does not contain keys in the schema.ALLOWED_KEY_SET,
warnings if `obj` lacks keys listed in schema.EXPECETED_KEY_SET,
or if `obj` contains keys not listed in schema.ALLOWED_KEY_SET. |
def basic_retinotopy_data(hemi, retino_type):
'''
basic_retinotopy_data(hemi, t) yields a numpy array of data for the given cortex object hemi
and retinotopy type t; it does this by looking at the properties in hemi and picking out any
combination that is commonly used to denote empirical retinotopy dat... | basic_retinotopy_data(hemi, t) yields a numpy array of data for the given cortex object hemi
and retinotopy type t; it does this by looking at the properties in hemi and picking out any
combination that is commonly used to denote empirical retinotopy data. These common names are
stored in _predicted_retinto... |
def _create_struct(data, session):
"""Create a struct from session data.
"""
out = Struct()
for name in data.dtype.names:
item = data[name]
# Extract values that are cells (they are doubly wrapped).
if isinstance(item, np.ndarray) and item.dtype.kind == 'O':
i... | Create a struct from session data. |
def uploader(func):
"""This method only used for CKEditor under version 4.5, in newer version,
you should use ``upload_success()`` and ``upload_fail()`` instead.
Decorated the view function that handle the file upload. The upload
view must return the uploaded image's url. For example::
... | This method only used for CKEditor under version 4.5, in newer version,
you should use ``upload_success()`` and ``upload_fail()`` instead.
Decorated the view function that handle the file upload. The upload
view must return the uploaded image's url. For example::
from flask import ... |
def on_lock(self, widget, data=None):
"""Locks respective selected core element"""
path_list = None
if self.view is not None:
model, path_list = self.tree_view.get_selection().get_selected_rows()
models = [self.list_store[path][self.MODEL_STORAGE_ID] for path in path_list] if... | Locks respective selected core element |
def prepare_samples(job, patient_dict, univ_options):
"""
Obtain the input files for the patient and write them to the file store.
:param dict patient_dict: The input fastq dict
patient_dict:
|- 'tumor_dna_fastq_[12]' OR 'tumor_dna_bam': str
|- 'tumor_rna_fastq_[12]... | Obtain the input files for the patient and write them to the file store.
:param dict patient_dict: The input fastq dict
patient_dict:
|- 'tumor_dna_fastq_[12]' OR 'tumor_dna_bam': str
|- 'tumor_rna_fastq_[12]' OR 'tumor_rna_bam': str
|- 'normal_dna_fastq_[12]... |
def relatedness_title(tt_pairs, gcube_token=None, lang=DEFAULT_LANG, api=DEFAULT_REL_API):
'''
Get the semantic relatedness among pairs of entities. Entities are indicated by their
Wikipedia ID (an integer).
:param tt_pairs: either one pair or a list of pairs of entity titles.
:param gcube_token: th... | Get the semantic relatedness among pairs of entities. Entities are indicated by their
Wikipedia ID (an integer).
:param tt_pairs: either one pair or a list of pairs of entity titles.
:param gcube_token: the authentication token provided by the D4Science infrastructure.
:param lang: the Wikipedia languag... |
def attachment_md5(self):
'''
Calculate the checksum of the file upload.
For binary files (e.g. PDFs), the MD5 of the file itself is used.
Archives are unpacked and the MD5 is generated from the sanitized textfiles
in the archive. This is done with some smartness... | Calculate the checksum of the file upload.
For binary files (e.g. PDFs), the MD5 of the file itself is used.
Archives are unpacked and the MD5 is generated from the sanitized textfiles
in the archive. This is done with some smartness:
- Whitespace and tabs are removed be... |
def print_tables(xmldoc, output, output_format, tableList = [], columnList = [],
round_floats = True, decimal_places = 2, format_links = True,
title = None, print_table_names = True, unique_rows = False,
row_span_columns = [], rspan_break_columns = []):
"""
Method to print tables in an xml file in o... | Method to print tables in an xml file in other formats.
Input is an xmldoc, output is a file object containing the
tables.
@xmldoc: document to convert
@output: file object to write output to; if None, will write to stdout
@output_format: format to convert to
@tableList: only convert the listed... |
def param_particle_rad(self, ind):
""" Get radius of one or more particles """
ind = self._vps(listify(ind))
return [self._i2p(i, 'a') for i in ind] | Get radius of one or more particles |
def parse(self, raw_content, find_message_cb):
"""Function parses the RAW AS2 MDN, verifies it and extracts the
processing status of the orginal AS2 message.
:param raw_content:
A byte string of the received HTTP headers followed by the body.
:param find_message_cb:
... | Function parses the RAW AS2 MDN, verifies it and extracts the
processing status of the orginal AS2 message.
:param raw_content:
A byte string of the received HTTP headers followed by the body.
:param find_message_cb:
A callback the must returns the original Message Obje... |
def primers(self):
"""
Read in the primer file, and create a properly formatted output file that takes any degenerate bases
into account
"""
with open(self.formattedprimers, 'w') as formatted:
for record in SeqIO.parse(self.primerfile, 'fasta'):
# from... | Read in the primer file, and create a properly formatted output file that takes any degenerate bases
into account |
def get_field_by_showname(self, showname):
"""
Gets a field by its "showname"
(the name that appears in Wireshark's detailed display i.e. in 'User-Agent: Mozilla...', 'User-Agent' is the
showname)
Returns None if not found.
"""
for field in self._get_all_fields... | Gets a field by its "showname"
(the name that appears in Wireshark's detailed display i.e. in 'User-Agent: Mozilla...', 'User-Agent' is the
showname)
Returns None if not found. |
def change_svc_check_timeperiod(self, service, check_timeperiod):
"""Modify service check timeperiod
Format of the line that triggers function call::
CHANGE_SVC_CHECK_TIMEPERIOD;<host_name>;<service_description>;<check_timeperiod>
:param service: service to modify check timeperiod
... | Modify service check timeperiod
Format of the line that triggers function call::
CHANGE_SVC_CHECK_TIMEPERIOD;<host_name>;<service_description>;<check_timeperiod>
:param service: service to modify check timeperiod
:type service: alignak.objects.service.Service
:param check_timep... |
def put_records(self, records, partition_key=None):
"""Add a list of data records to the record queue in the proper format.
Convinience method that calls self.put_record for each element.
Parameters
----------
records : list
Lists of records to send.
partitio... | Add a list of data records to the record queue in the proper format.
Convinience method that calls self.put_record for each element.
Parameters
----------
records : list
Lists of records to send.
partition_key: str
Hash that determines which shard a given... |
def calculate_size(name, entry_processor, keys):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += calculate_size_data(entry_processor)
data_size += INT_SIZE_IN_BYTES
for keys_item in keys:
data_size += calculate_size_data(keys_it... | Calculates the request payload size |
def get_central_wave(wav, resp, weight=1.0):
"""Calculate the central wavelength or the central wavenumber, depending on
which parameters is input. On default the weighting funcion is
f(lambda)=1.0, but it is possible to add a custom weight, e.g. f(lambda) =
1./lambda**4 for Rayleigh scattering calcula... | Calculate the central wavelength or the central wavenumber, depending on
which parameters is input. On default the weighting funcion is
f(lambda)=1.0, but it is possible to add a custom weight, e.g. f(lambda) =
1./lambda**4 for Rayleigh scattering calculations |
def _set_mpls_config(self, v, load=False):
"""
Setter method for mpls_config, mapped from YANG variable /mpls_config (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mpls_config is considered as a private
method. Backends looking to populate this variable ... | Setter method for mpls_config, mapped from YANG variable /mpls_config (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mpls_config is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_mpls_config()... |
def _create_add_petabencana_layer_action(self):
"""Create action for import OSM Dialog."""
icon = resources_path('img', 'icons', 'add-petabencana-layer.svg')
self.action_add_petabencana_layer = QAction(
QIcon(icon),
self.tr('Add PetaBencana Flood Layer'),
self... | Create action for import OSM Dialog. |
def execute(self, output_options=None, sampling=None, context=None, query_params=None):
""" Initiate the query and return a QueryJob.
Args:
output_options: a QueryOutput object describing how to execute the query
sampling: sampling function to use. No sampling is done if None. See bigquery.Sampling... | Initiate the query and return a QueryJob.
Args:
output_options: a QueryOutput object describing how to execute the query
sampling: sampling function to use. No sampling is done if None. See bigquery.Sampling
context: an optional Context object providing project_id and credentials. If a specific
... |
def predict(self, X, lengths=None):
"""Find most likely state sequence corresponding to ``X``.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Feature matrix of individual samples.
lengths : array-like of integers, shape (n_sequences, ), optional... | Find most likely state sequence corresponding to ``X``.
Parameters
----------
X : array-like, shape (n_samples, n_features)
Feature matrix of individual samples.
lengths : array-like of integers, shape (n_sequences, ), optional
Lengths of the individual sequence... |
def shift_ordering_up(self, parent_id, position, db_session=None, *args, **kwargs):
"""
Shifts ordering to "open a gap" for node insertion,
begins the shift from given position
:param parent_id:
:param position:
:param db_session:
:return:
"""
ret... | Shifts ordering to "open a gap" for node insertion,
begins the shift from given position
:param parent_id:
:param position:
:param db_session:
:return: |
def set_variable(section, value, create):
"""
Set value of a variable in an environment file for the given section.
If the variable is already defined, its value is replaced, otherwise, it is added to the end of the file.
The value is given as "ENV_VAR_NAME=env_var_value", e.g.:
s3conf set test ENV... | Set value of a variable in an environment file for the given section.
If the variable is already defined, its value is replaced, otherwise, it is added to the end of the file.
The value is given as "ENV_VAR_NAME=env_var_value", e.g.:
s3conf set test ENV_VAR_NAME=env_var_value |
def get_ssl(self, host_and_port=None):
"""
Get SSL params for the given host.
:param (str,int) host_and_port: the host/port pair we want SSL params for, default current_host_and_port
"""
if not host_and_port:
host_and_port = self.current_host_and_port
return... | Get SSL params for the given host.
:param (str,int) host_and_port: the host/port pair we want SSL params for, default current_host_and_port |
def contribution_maps_1d_from_hyper_images_and_galaxies(hyper_model_image_1d, hyper_galaxy_images_1d, hyper_galaxies,
hyper_minimum_values):
"""For a fitting hyper_galaxy_image, hyper_galaxy model image, list of hyper galaxies images and model hyper galaxies, ... | For a fitting hyper_galaxy_image, hyper_galaxy model image, list of hyper galaxies images and model hyper galaxies, compute
their contribution maps, which are used to compute a scaled-noise_map map. All quantities are masked 1D arrays.
The reason this is separate from the *contributions_from_fitting_hyper_imag... |
def HHIPreFilter(config={}):
"""HHI pre-interlace filter.
A widely used prefilter to prevent line twitter when converting
sequential images to interlace.
Coefficients taken from: 'Specification of a Generic Format
Converter', S. Pigeon, L. Vandendorpe, L. Cuvelier and B. Maison,
CEC RACE/HAMLE... | HHI pre-interlace filter.
A widely used prefilter to prevent line twitter when converting
sequential images to interlace.
Coefficients taken from: 'Specification of a Generic Format
Converter', S. Pigeon, L. Vandendorpe, L. Cuvelier and B. Maison,
CEC RACE/HAMLET Deliverable no R2110/WP2/DS/S/006/... |
def run_forecast(self):
"""
Updates card & runs for RAPID to GSSHA & LSM to GSSHA
"""
# ----------------------------------------------------------------------
# LSM to GSSHA
# ----------------------------------------------------------------------
self.prepare_hme... | Updates card & runs for RAPID to GSSHA & LSM to GSSHA |
def correlation_linear(
values_1,
values_2,
printout = None
):
"""
This function calculates the Pearson product-moment correlation coefficient.
This is a measure of the linear collelation of two variables. The value can
be between +1 and -1 inclusive, where 1 is total positive correlati... | This function calculates the Pearson product-moment correlation coefficient.
This is a measure of the linear collelation of two variables. The value can
be between +1 and -1 inclusive, where 1 is total positive correlation, 0 is
no correlation and -1 is total negative correlation. It is a measure of the
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.