code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _parse_title_url(html_chunk):
"""
Parse title/name of the book and URL of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
tuple: (title, url), both as strings.
"""
url = None
title_tags = html_chunk.match(
["div"... | Parse title/name of the book and URL of the book.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
tuple: (title, url), both as strings. |
def fetch_official_missions(data_dir, start_date, end_date):
"""
:param data_dir: (str) directory in which the output file will be saved
:param start_date: (datetime) first date of the range to be scraped
:param end_date: (datetime) last date of the range to be scraped
"""
official_missions = Of... | :param data_dir: (str) directory in which the output file will be saved
:param start_date: (datetime) first date of the range to be scraped
:param end_date: (datetime) last date of the range to be scraped |
def logstats(self):
"""
Print the node's current statistics to log.
"""
lines = [
"node {} current stats".format(self),
"--------------------------------------------------------",
"node inbox size : {}".format(len(self.nodeInBox)),
... | Print the node's current statistics to log. |
def get(self, collection_id):
"""
Retrieve a single collection.
To view a user’s private collections, the 'read_collections' scope is required.
:param collection_id [string]: The collections’s ID. Required.
:return: [Collection]: The Unsplash Collection.
"""
url ... | Retrieve a single collection.
To view a user’s private collections, the 'read_collections' scope is required.
:param collection_id [string]: The collections’s ID. Required.
:return: [Collection]: The Unsplash Collection. |
def get_open_filenames(self):
"""Get the list of open files in the current stack"""
editorstack = self.editorstacks[0]
filenames = []
filenames += [finfo.filename for finfo in editorstack.data]
return filenames | Get the list of open files in the current stack |
def prompt(text, default=None, show_default=True, invisible=False,
confirm=False, skip=False, type=None, input_function=None):
'''Prompts for input from the user.
'''
t = determine_type(type, default)
input_function = get_input_fn(input_function, invisible)
if default is not None and show_default:
tex... | Prompts for input from the user. |
def compute_uncertainty_reward(logits, predictions):
"""Uncertainty reward based on logits."""
# TODO(rsepassi): Add support for L1/L2 loss models. Current code only
# works for softmax models.
vocab_size = logits.shape[-1]
assert vocab_size > 1
log_probs = common_layers.log_prob_from_logits(logits)
max_l... | Uncertainty reward based on logits. |
def shrink_indexes_in_place(self, triples):
"""Uses a union find to find segment."""
_ent_roots = self.UnionFind(self._ent_id)
_rel_roots = self.UnionFind(self._rel_id)
for t in triples:
_ent_roots.add(t.head)
_ent_roots.add(t.tail)
_rel_roots.add(t.... | Uses a union find to find segment. |
def bitstring_probs_to_z_moments(p):
"""
Convert between bitstring probabilities and joint Z moment expectations.
:param np.array p: An array that enumerates bitstring probabilities. When
flattened out ``p = [p_00...0, p_00...1, ...,p_11...1]``. The total number of elements must
therefore b... | Convert between bitstring probabilities and joint Z moment expectations.
:param np.array p: An array that enumerates bitstring probabilities. When
flattened out ``p = [p_00...0, p_00...1, ...,p_11...1]``. The total number of elements must
therefore be a power of 2. The canonical shape has a separat... |
def _CallEventHandler(self, Event, *Args, **KwArgs):
"""Calls all event handlers defined for given Event, additional parameters
will be passed unchanged to event handlers, all event handlers are fired on
separate threads.
:Parameters:
Event : str
Name of th... | Calls all event handlers defined for given Event, additional parameters
will be passed unchanged to event handlers, all event handlers are fired on
separate threads.
:Parameters:
Event : str
Name of the event.
Args
Positional arguments for the... |
def submit(self):
"""
Try to find element with ID "[FORM_ID]_submit" and click on it. If no
element doesn't exists it will call default behaviour - submiting of
form by pressing enter.
"""
elm_name = '%s_submit' % self.get_attribute('id')
try:
self.cli... | Try to find element with ID "[FORM_ID]_submit" and click on it. If no
element doesn't exists it will call default behaviour - submiting of
form by pressing enter. |
def main(argv=None):
''' Runs the program and handles command line options '''
parser = get_parser()
# Parse arguments and run the function
global args
args = parser.parse_args(argv)
args.func() | Runs the program and handles command line options |
def skip(self):
"""Skip this py-pdb command to avoid attaching within the same loop."""
line = self.line
self.line = ''
# 'line' is the statement line of the previous py-pdb command.
if line in self.lines:
if not self.skipping:
self.skipping = True
... | Skip this py-pdb command to avoid attaching within the same loop. |
def symbol(name: str=None, symbol_type: Type[Symbol]=Symbol) -> 'SymbolWildcard':
"""Create a `SymbolWildcard` that matches a single `Symbol` argument.
Args:
name:
Optional variable name for the wildcard.
symbol_type:
An optional subclass of `Symb... | Create a `SymbolWildcard` that matches a single `Symbol` argument.
Args:
name:
Optional variable name for the wildcard.
symbol_type:
An optional subclass of `Symbol` to further limit which kind of symbols are
matched by the wildcard.
... |
def clips_value(self, dvalue):
"""Convert a Python type into CLIPS."""
try:
return VALUES[type(dvalue)](self._env, dvalue)
except KeyError:
if isinstance(dvalue, (list, tuple)):
return self.list_to_multifield(dvalue)
if isinstance(dvalue, (clip... | Convert a Python type into CLIPS. |
def parametrize(self):
r"""
Reads all data and discretizes it into discrete trajectories.
"""
for element in self._chain:
if not element.is_reader and not element._estimated:
element.estimate(element.data_producer, stride=self.param_stride, chunksize=self.chun... | r"""
Reads all data and discretizes it into discrete trajectories. |
def rename(self, old_file_path, new_file_path, force_replace=False):
"""Renames a FakeFile object at old_file_path to new_file_path,
preserving all properties.
Args:
old_file_path: Path to filesystem object to rename.
new_file_path: Path to where the filesystem object wi... | Renames a FakeFile object at old_file_path to new_file_path,
preserving all properties.
Args:
old_file_path: Path to filesystem object to rename.
new_file_path: Path to where the filesystem object will live
after this call.
force_replace: If set and d... |
def check(self, dsm, **kwargs):
"""
Check if matrix and its mediation matrix are compliant.
It means that number of dependencies for each (line, column) is either
0 if the mediation matrix (line, column) is 0, or >0 if the mediation
matrix (line, column) is 1.
Args:
... | Check if matrix and its mediation matrix are compliant.
It means that number of dependencies for each (line, column) is either
0 if the mediation matrix (line, column) is 0, or >0 if the mediation
matrix (line, column) is 1.
Args:
dsm (:class:`DesignStructureMatrix`): the D... |
def db_exists(name, user=None, password=None, host=None, port=None):
'''
Checks if a database exists in Influxdb
name
Database name to create
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port t... | Checks if a database exists in Influxdb
name
Database name to create
user
The user to connect as
password
The password of the user
host
The host to connect to
port
The port to connect to
CLI Example:
.. code-block:: bash
salt '*' influx... |
def step(self, compute=True):
"""Context manager to gradually build a history row, then commit it at the end.
To reduce the number of conditionals needed, code can check run.history.compute:
with run.history.step(batch_idx % log_interval == 0):
run.history.add({"nice": "ok"})
... | Context manager to gradually build a history row, then commit it at the end.
To reduce the number of conditionals needed, code can check run.history.compute:
with run.history.step(batch_idx % log_interval == 0):
run.history.add({"nice": "ok"})
if run.history.compute:
... |
def save_settings(file_path, record_details, overwrite=False, secret_key=''):
''' a method to save dictionary typed data to a local file
:param file_path: string with path to settings file
:param record_details: dictionary with record details
:param overwrite: [optional] boolean to overwrite exi... | a method to save dictionary typed data to a local file
:param file_path: string with path to settings file
:param record_details: dictionary with record details
:param overwrite: [optional] boolean to overwrite existing file data
:param secret_key: [optional] string with key to decrypt drep file
... |
def get_statements(self):
"""Process reader output to produce INDRA Statements."""
for k, v in self.reader_output.items():
for interaction in v['interactions']:
self._process_interaction(k, interaction, v['text'], self.pmid,
self.extr... | Process reader output to produce INDRA Statements. |
def get_variable_accesses(self, variable, same_name=False):
"""
Get a list of all references to the given variable.
:param SimVariable variable: The variable.
:param bool same_name: Whether to include all variables with the same variable name, or just
... | Get a list of all references to the given variable.
:param SimVariable variable: The variable.
:param bool same_name: Whether to include all variables with the same variable name, or just
based on the variable identifier.
:retur... |
def image_to_string(image, lang=None, boxes=False):
'''
Runs tesseract on the specified image. First, the image is written to disk,
and then the tesseract command is run on the image. Resseract's result is
read, and the temporary files are erased.
'''
input_file_name = '%s.bmp' % tempnam()
... | Runs tesseract on the specified image. First, the image is written to disk,
and then the tesseract command is run on the image. Resseract's result is
read, and the temporary files are erased. |
def get_command(self, ctx, name):
"""Get a callable command object."""
if name not in self.daemon_class.list_actions():
return None
# The context object is a Daemon object
daemon = ctx.obj
def subcommand(debug=False):
"""Call a daemonocle action."""
... | Get a callable command object. |
def get_gradebook_ids_by_grade_system(self, grade_system_id):
"""Gets the list of ``Gradebook`` ``Ids`` mapped to a ``GradeSystem``.
arg: grade_system_id (osid.id.Id): ``Id`` of a
``GradeSystem``
return: (osid.id.IdList) - list of gradebook ``Ids``
raise: NotFound -... | Gets the list of ``Gradebook`` ``Ids`` mapped to a ``GradeSystem``.
arg: grade_system_id (osid.id.Id): ``Id`` of a
``GradeSystem``
return: (osid.id.IdList) - list of gradebook ``Ids``
raise: NotFound - ``grade_system_id`` is not found
raise: NullArgument - ``grade_... |
def power(args):
"""
%prog power
Compare performances of various variant callers on simulated STR datasets.
This compares the power of various evidence types.
"""
p = OptionParser(power.__doc__)
p.add_option('--maxinsert', default=300, type="int",
help="Maximum number of re... | %prog power
Compare performances of various variant callers on simulated STR datasets.
This compares the power of various evidence types. |
def _set_label(self, which, label, **kwargs):
"""Private method for setting labels.
Args:
which (str): The indicator of which part of the plots
to adjust. This currently handles `xlabel`/`ylabel`,
and `title`.
label (str): The label to be added.
... | Private method for setting labels.
Args:
which (str): The indicator of which part of the plots
to adjust. This currently handles `xlabel`/`ylabel`,
and `title`.
label (str): The label to be added.
fontsize (int, optional): Fontsize for associa... |
def rcm_vertex_order(vertices_resources, nets):
"""A generator which iterates over the vertices in Reverse-Cuthill-McKee
order.
For use as a vertex ordering for the sequential placer.
"""
vertices_neighbours = _get_vertices_neighbours(nets)
for subgraph_vertices in _get_connected_subgraphs(vert... | A generator which iterates over the vertices in Reverse-Cuthill-McKee
order.
For use as a vertex ordering for the sequential placer. |
def get_plugins():
"""Gets available plugins by looking into the plugins/ directory"""
if os.path.exists('plugins'):
for filename in sorted([f for f in os.listdir('plugins')
if not os.path.isdir(f) and f.endswith(".py")]):
plugin_name = filename[:-3]
try:
... | Gets available plugins by looking into the plugins/ directory |
def from_project_config(cls, project_dict, packages_dict=None):
"""Create a project from its project and package configuration, as read
by yaml.safe_load().
:param project_dict dict: The dictionary as read from disk
:param packages_dict Optional[dict]: If it exists, the packages file as... | Create a project from its project and package configuration, as read
by yaml.safe_load().
:param project_dict dict: The dictionary as read from disk
:param packages_dict Optional[dict]: If it exists, the packages file as
read from disk.
:raises DbtProjectError: If the projec... |
def q(cls, **kwargs):
''' Creates an iterator over the members of this class that applies the
given filters and returns only the elements matching them '''
redis = cls.get_redis()
return QuerySet(cls, redis.sscan_iter(cls.members_key())) | Creates an iterator over the members of this class that applies the
given filters and returns only the elements matching them |
def loglike(self, y, f, var=None):
r"""
Gaussian log likelihood.
Parameters
----------
y: ndarray
array of 0, 1 valued integers of targets
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
... | r"""
Gaussian log likelihood.
Parameters
----------
y: ndarray
array of 0, 1 valued integers of targets
f: ndarray
latent function from the GLM prior (:math:`\mathbf{f} =
\boldsymbol\Phi \mathbf{w}`)
var: float, ndarray, optional
... |
def sdram_alloc_as_filelike(self, size, tag=0, x=Required, y=Required,
app_id=Required, clear=False):
"""Like :py:meth:`.sdram_alloc` but returns a :py:class:`file-like
object <.MemoryIO>` which allows safe reading and writing to the block
that is allocated.
... | Like :py:meth:`.sdram_alloc` but returns a :py:class:`file-like
object <.MemoryIO>` which allows safe reading and writing to the block
that is allocated.
Returns
-------
:py:class:`.MemoryIO`
File-like object which allows accessing the newly allocated region
... |
def _validate_derived_from(cursor, model):
"""Given a database cursor and model, check the derived-from
value accurately points to content in the archive.
The value can be nothing or must point to existing content.
"""
derived_from_uri = model.metadata.get('derived_from_uri')
if derived_from_uri... | Given a database cursor and model, check the derived-from
value accurately points to content in the archive.
The value can be nothing or must point to existing content. |
def proc_ovrds(**kwargs):
"""
Bloomberg overrides
Args:
**kwargs: overrides
Returns:
list of tuples
Examples:
>>> proc_ovrds(DVD_Start_Dt='20180101')
[('DVD_Start_Dt', '20180101')]
>>> proc_ovrds(DVD_Start_Dt='20180101', cache=True, has_date=True)
[... | Bloomberg overrides
Args:
**kwargs: overrides
Returns:
list of tuples
Examples:
>>> proc_ovrds(DVD_Start_Dt='20180101')
[('DVD_Start_Dt', '20180101')]
>>> proc_ovrds(DVD_Start_Dt='20180101', cache=True, has_date=True)
[('DVD_Start_Dt', '20180101')] |
def get_session(self, token=None, signature=None):
'''
If provided a `token` parameter, tries to retrieve a stored
`rauth.OAuth1Session` instance. Otherwise generates a new session
instance with the :class:`rauth.OAuth1Service.consumer_key` and
:class:`rauth.OAuth1Service.consume... | If provided a `token` parameter, tries to retrieve a stored
`rauth.OAuth1Session` instance. Otherwise generates a new session
instance with the :class:`rauth.OAuth1Service.consumer_key` and
:class:`rauth.OAuth1Service.consumer_secret` stored on the
`rauth.OAuth1Service` instance.
... |
def attention_lm_attention_moe_tiny():
"""Cheap model for debugging.
Returns:
an hparams object.
"""
hparams = attention_lm_moe_small()
hparams.moe_layers = ""
hparams.attention_num_experts = 128
hparams.filter_size = 8192
hparams.attention_type = AttentionType.LOCAL_EXPERTS
return hparams | Cheap model for debugging.
Returns:
an hparams object. |
def is_used(self, regs, i, top=None):
""" Checks whether any of the given regs are required from the given point
to the end or not.
"""
if i < 0:
i = 0
if self.lock:
return True
regs = list(regs) # make a copy
if top is None:
... | Checks whether any of the given regs are required from the given point
to the end or not. |
def get_variable_days(self, year):
"""
Add Late Summer holiday (First Monday of September)
"""
days = super(LateSummer, self).get_variable_days(year)
days.append((
self.get_nth_weekday_in_month(year, 9, MON),
"Late Summer Holiday"
))
return... | Add Late Summer holiday (First Monday of September) |
def create_service(self, *args, **kwargs):
"""Create a service to current scope.
See :class:`pykechain.Client.create_service` for available parameters.
.. versionadded:: 1.13
"""
return self._client.create_service(*args, scope=self.id, **kwargs) | Create a service to current scope.
See :class:`pykechain.Client.create_service` for available parameters.
.. versionadded:: 1.13 |
def items(self):
"""
Returns a list of the items that are linked to this layer.
:return [<XNode> || <XNodeConnection>, ..]
"""
from projexui.widgets.xnodewidget import XNode, XNodeConnection
output = []
for item in self.scene().items():
... | Returns a list of the items that are linked to this layer.
:return [<XNode> || <XNodeConnection>, ..] |
def _serialize(self):
"""
A helper method to build a dict of all mutable Properties of
this object
"""
result = { a: getattr(self, a) for a in type(self).properties
if type(self).properties[a].mutable }
for k, v in result.items():
if isinstance(v,... | A helper method to build a dict of all mutable Properties of
this object |
def make_steam64(id=0, *args, **kwargs):
"""
Returns steam64 from various other representations.
.. code:: python
make_steam64() # invalid steamid
make_steam64(12345) # accountid
make_steam64('12345')
make_steam64(id=12345, type='Invalid', universe='Invalid', instance=0)
... | Returns steam64 from various other representations.
.. code:: python
make_steam64() # invalid steamid
make_steam64(12345) # accountid
make_steam64('12345')
make_steam64(id=12345, type='Invalid', universe='Invalid', instance=0)
make_steam64(103582791429521412) # steam64
... |
def __get_league_object():
"""Returns the xml object corresponding to the league
Only designed for internal use"""
# get data
data = mlbgame.data.get_properties()
# return league object
return etree.parse(data).getroot().find('leagues').find('league') | Returns the xml object corresponding to the league
Only designed for internal use |
def _commit(self):
"""
:return: (dict) Response object content
"""
assert self.uri is not None, Exception("BadArgument: uri property cannot be None")
url = '{}/{}'.format(self.uri, self.__class__.__name__)
serialized_json = jsonpickle.encode(self, unpicklable=False, )
... | :return: (dict) Response object content |
def clean_line(str, delimiter):
"""Split string on given delimiter, remove whitespace from each field."""
return [x.strip() for x in str.strip().split(delimiter) if x != ''] | Split string on given delimiter, remove whitespace from each field. |
def resample(self, section_length):
"""
Resample this line into sections.
The first point in the resampled line corresponds
to the first point in the original line.
Starting from the first point in the original line, a line
segment is defined as the line connecting the ... | Resample this line into sections.
The first point in the resampled line corresponds
to the first point in the original line.
Starting from the first point in the original line, a line
segment is defined as the line connecting the last point in the
resampled line and the next po... |
def expand_hostname_range(line = None):
'''
A helper function that expands a given line that contains a pattern
specified in top docstring, and returns a list that consists of the
expanded version.
The '[' and ']' characters are used to maintain the pseudo-code
appearance. They are replaced in ... | A helper function that expands a given line that contains a pattern
specified in top docstring, and returns a list that consists of the
expanded version.
The '[' and ']' characters are used to maintain the pseudo-code
appearance. They are replaced in this function with '|' to ease
string splitting.... |
def decide_k(airport_code):
"""A function to decide if a leading 'K' is throwing off an airport match and return the correct code."""
if airport_code[:1].upper() == 'K':
try: # if there's a match without the K that's likely what it is.
return Airport.objects.get(location_identifier__iexact=... | A function to decide if a leading 'K' is throwing off an airport match and return the correct code. |
def strip(self, text):
'''Return string with markup tags removed.'''
tags, results = [], []
return self.re_tag.sub(lambda m: self.clear_tag(m, tags, results), text) | Return string with markup tags removed. |
def plot_diagnostics(self, variable=0, lags=10, fig=None, figsize=None):
"""Plot an ARIMA's diagnostics.
Diagnostic plots for standardized residuals of one endogenous variable
Parameters
----------
variable : integer, optional
Index of the endogenous variable for wh... | Plot an ARIMA's diagnostics.
Diagnostic plots for standardized residuals of one endogenous variable
Parameters
----------
variable : integer, optional
Index of the endogenous variable for which the diagnostic plots
should be created. Default is 0.
lags ... |
def clearDevice(self):
"""Remove the current stream
"""
print(self.pre, "clearDevice")
if not self.device:
return
self.filterchain.delViewPort(self.viewport)
self.filterchain = None
self.device = None
self.video.updat... | Remove the current stream |
def members_from_score_range_in(
self, leaderboard_name, minimum_score, maximum_score, **options):
'''
Retrieve members from the named leaderboard within a given score range.
@param leaderboard_name [String] Name of the leaderboard.
@param minimum_score [float] Minimum score... | Retrieve members from the named leaderboard within a given score range.
@param leaderboard_name [String] Name of the leaderboard.
@param minimum_score [float] Minimum score (inclusive).
@param maximum_score [float] Maximum score (inclusive).
@param options [Hash] Options to be used when... |
def set_language(self, language):
""" Set self.language to internal lang. repr. code from str or Language object. """
if isinstance(language, str):
language_obj = languages.getlang(language)
if language_obj:
self.language = language_obj.code
else:
... | Set self.language to internal lang. repr. code from str or Language object. |
def adjust_learning_rate(optimizer, epoch, gammas, schedule):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = args.learning_rate
assert len(gammas) == len(schedule), "length of gammas and schedule should be equal"
for (gamma, step) in zip(gammas, schedule):
if (epoch >= ste... | Sets the learning rate to the initial LR decayed by 10 every 30 epochs |
def remove(self, auto_confirm=False, verbose=False):
"""Remove paths in ``self.paths`` with confirmation (unless
``auto_confirm`` is True)."""
if not self.paths:
logger.info(
"Can't uninstall '%s'. No files were found to uninstall.",
self.dist.project... | Remove paths in ``self.paths`` with confirmation (unless
``auto_confirm`` is True). |
def dict(self):
"""
calls the overridden method and adds provenance and summary data
:return: dictionary representation of the metadata
:rtype: dict
"""
metadata = super(ImpactLayerMetadata, self).dict
metadata['provenance'] = self.provenance
metadata['s... | calls the overridden method and adds provenance and summary data
:return: dictionary representation of the metadata
:rtype: dict |
def process_content(self, content, filename=None, content_type=None):
"""Standard implementation of :meth:`.DepotFileInfo.process_content`
This is the standard depot implementation of files upload, it will
store the file on the default depot and will provide the standard
attributes.
... | Standard implementation of :meth:`.DepotFileInfo.process_content`
This is the standard depot implementation of files upload, it will
store the file on the default depot and will provide the standard
attributes.
Subclasses will need to call this method to ensure the standard
set... |
def parse_parameters(self, parameters):
"""Parses and sets parameters in the model."""
self.parameters = []
for param_name, param_value in parameters.items():
p = Parameter(param_name, param_value)
if p:
self.parameters.append(p) | Parses and sets parameters in the model. |
def output_data(self):
"""Get a buffer of data that needs to be written to the network.
"""
c = self.has_output
if c <= 0:
return None
try:
buf = self._pn_transport.peek(c)
except Exception as e:
self._connection_failed(str(e))
... | Get a buffer of data that needs to be written to the network. |
def cleanUp(self):
""" Delete files that are written by CommandLineApplication from disk
WARNING: after cleanUp() you may still have access to part of
your result data, but you should be aware that if the file
size exceeds the size of the buffer you will only have pa... | Delete files that are written by CommandLineApplication from disk
WARNING: after cleanUp() you may still have access to part of
your result data, but you should be aware that if the file
size exceeds the size of the buffer you will only have part
of the file.... |
def _delete_vlan_profile(self, handle, vlan_id, ucsm_ip):
"""Deletes VLAN Profile from UCS Manager."""
vlan_name = self.make_vlan_name(vlan_id)
vlan_profile_dest = (const.VLAN_PATH + const.VLAN_PROFILE_PATH_PREFIX +
vlan_name)
try:
obj = handle.qu... | Deletes VLAN Profile from UCS Manager. |
async def zrangebylex(self, name, min, max, start=None, num=None):
"""
Return the lexicographical range of values from sorted set ``name``
between ``min`` and ``max``.
If ``start`` and ``num`` are specified, then return a slice of the
range.
"""
if (start is not ... | Return the lexicographical range of values from sorted set ``name``
between ``min`` and ``max``.
If ``start`` and ``num`` are specified, then return a slice of the
range. |
def save(self):
""" Save changes """
if self.__session:
self.session.commit()
else:
self.logger.warning("Save called but no session open.") | Save changes |
def _get_area_rates(self, source, mmin, mmax=np.inf):
"""
Adds the rates from the area source by discretising the source
to a set of point sources
:param source:
Area source as instance of :class:
openquake.hazardlib.source.area.AreaSource
"""
poi... | Adds the rates from the area source by discretising the source
to a set of point sources
:param source:
Area source as instance of :class:
openquake.hazardlib.source.area.AreaSource |
def delete(self):
"""Delete the task.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('Homework')
>>> task = project.add_task('Read Chapter 4')
>>> task.delete()
"""
args = {'ids'... | Delete the task.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'password')
>>> project = user.get_project('Homework')
>>> task = project.add_task('Read Chapter 4')
>>> task.delete() |
def _validate_jp2c(self, boxes):
"""Validate the codestream box in relation to other boxes."""
# jp2c must be preceeded by jp2h
jp2h_lst = [idx for (idx, box) in enumerate(boxes)
if box.box_id == 'jp2h']
jp2h_idx = jp2h_lst[0]
jp2c_lst = [idx for (idx, box) in... | Validate the codestream box in relation to other boxes. |
def print_stream(file, name):
"""Print stream from file to logger."""
logger = logging.getLogger('xenon.{}'.format(name))
for line in file:
logger.info('[{}] {}'.format(name, line.strip())) | Print stream from file to logger. |
def accept_record(self, record):
"""Accept a record for inclusion in the community.
:param record: Record object.
"""
with db.session.begin_nested():
req = InclusionRequest.get(self.id, record.id)
if req is None:
raise InclusionRequestMissingError... | Accept a record for inclusion in the community.
:param record: Record object. |
def add_arg(self,arg, prepend=False):
"""Append an arg to the arg list"""
self.args = [arg_.strip() for arg_ in self.args if arg_.strip()]
if arg.title() not in self.args:
if prepend:
self.args = [arg.title()] + self.args
else:
self.args.... | Append an arg to the arg list |
def _from_sql(self, soql):
"""Create Force.com SOQL tree structure from SOQL"""
# pylint:disable=too-many-branches,too-many-nested-blocks
assert not self.soql, "Don't use _from_sql method directly"
self.soql = soql
soql, self.subqueries = split_subquery(soql)
match_parse ... | Create Force.com SOQL tree structure from SOQL |
def organizer(self):
'''
Since events can be organized for registration in different ways (e.g. by month,
by session, or the interaction of the two), this property is used to make it easy
for templates to include necessary organizing information. Note that this method
has nothin... | Since events can be organized for registration in different ways (e.g. by month,
by session, or the interaction of the two), this property is used to make it easy
for templates to include necessary organizing information. Note that this method
has nothing to do with the sorting of any queryset ... |
def _get_timestamp(dirname_full, remove):
"""
Get the timestamp from the timestamp file.
Optionally mark it for removal if we're going to write another one.
"""
record_filename = os.path.join(dirname_full, RECORD_FILENAME)
if not os.path.exists(record_filename):
return None
mtime ... | Get the timestamp from the timestamp file.
Optionally mark it for removal if we're going to write another one. |
def set_attributes(self, **attributes_dict):
"""
Set the value of multiple attributes.
:param attributes_dict dict: a dictionary containing key-value pairs as attribute names and values to be set
:returns: the resource itself
"""
for attr_name, attr_value in attributes_di... | Set the value of multiple attributes.
:param attributes_dict dict: a dictionary containing key-value pairs as attribute names and values to be set
:returns: the resource itself |
def convert_predict_response(pred, serving_bundle):
"""Converts a PredictResponse to ClassificationResponse or RegressionResponse.
Args:
pred: PredictResponse to convert.
serving_bundle: A `ServingBundle` object that contains the information about
the serving request that the response was generated b... | Converts a PredictResponse to ClassificationResponse or RegressionResponse.
Args:
pred: PredictResponse to convert.
serving_bundle: A `ServingBundle` object that contains the information about
the serving request that the response was generated by.
Returns:
A ClassificationResponse or Regression... |
def cbv_decorator(function_decorator):
"""Allows a function-based decorator to be used on a CBV."""
def class_decorator(View):
View.dispatch = method_decorator(function_decorator)(View.dispatch)
return View
return class_decorator | Allows a function-based decorator to be used on a CBV. |
def delete(self, symbol, date_range=None):
"""
Delete all chunks for a symbol.
Which are, for the moment, fully contained in the passed in
date_range.
Parameters
----------
symbol : `str`
symbol name for the item
date_range : `date.DateRange`... | Delete all chunks for a symbol.
Which are, for the moment, fully contained in the passed in
date_range.
Parameters
----------
symbol : `str`
symbol name for the item
date_range : `date.DateRange`
DateRange to delete ticks in |
def generate_aead(hsm, args, password):
"""
Generate an AEAD using the YubiHSM.
"""
try:
pw = password.ljust(args.min_len, chr(0x0))
return hsm.generate_aead_simple(args.nonce.decode('hex'), args.key_handle, pw)
except pyhsm.exception.YHSM_CommandFailed, e:
if e.status_str ==... | Generate an AEAD using the YubiHSM. |
def get_errors(self):
"""If there were any business errors fetching data for this property,
returns the error messages.
Returns:
string - the error message, or None if there was no error.
"""
return [{cr.component_name: cr.get_error()}
for cr in self... | If there were any business errors fetching data for this property,
returns the error messages.
Returns:
string - the error message, or None if there was no error. |
def attachedimage_form_factory(lang='en', debug=False):
''' Returns ModelForm class to be used in admin.
'lang' is the language for GearsUploader (can be 'en' and 'ru' at the
moment).
'''
yui = '' if debug else '.yui'
class _AttachedImageAdminForm(forms.ModelForm):
caption = for... | Returns ModelForm class to be used in admin.
'lang' is the language for GearsUploader (can be 'en' and 'ru' at the
moment). |
def log_erase_send(self, target_system, target_component, force_mavlink1=False):
'''
Erase all logs
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
'''
return self.send(se... | Erase all logs
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t) |
def _set_distribute_list(self, v, load=False):
"""
Setter method for distribute_list, mapped from YANG variable /bgp_state/neighbor/evpn/distribute_list (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_distribute_list is considered as a private
method. Bac... | Setter method for distribute_list, mapped from YANG variable /bgp_state/neighbor/evpn/distribute_list (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_distribute_list is considered as a private
method. Backends looking to populate this variable should
do so vi... |
def normalize_genotypes(genotypes):
"""Normalize the genotypes.
Args:
genotypes (Genotypes): The genotypes to normalize.
Returns:
numpy.array: The normalized genotypes.
"""
genotypes = genotypes.genotypes
return (genotypes - np.nanmean(genotypes)) / np.nanstd(genotypes) | Normalize the genotypes.
Args:
genotypes (Genotypes): The genotypes to normalize.
Returns:
numpy.array: The normalized genotypes. |
def size(self):
"""Calculate and return the file size in bytes."""
old = self.__file.tell() # old position
self.__file.seek(0, 2) # end of file
n_bytes = self.__file.tell() # file size in bytes
self.__file.seek(old) # back to old position
r... | Calculate and return the file size in bytes. |
def allocate(self):
"""
Arrange for a unique context ID to be allocated and associated with a
route leading to the active context. In masters, the ID is generated
directly, in children it is forwarded to the master via a
:data:`mitogen.core.ALLOCATE_ID` message.
"""
... | Arrange for a unique context ID to be allocated and associated with a
route leading to the active context. In masters, the ID is generated
directly, in children it is forwarded to the master via a
:data:`mitogen.core.ALLOCATE_ID` message. |
def ungettext(self):
"""
Dispatch to the appropriate ngettext method to handle text objects.
Note that under python 3, this uses `ngettext()`, while under python 2,
it uses `ungettext()`. This should not be used with bytestrings.
"""
# pylint: disable=no-member
... | Dispatch to the appropriate ngettext method to handle text objects.
Note that under python 3, this uses `ngettext()`, while under python 2,
it uses `ungettext()`. This should not be used with bytestrings. |
def get_stacked_rnn(config: RNNConfig, prefix: str,
parallel_inputs: bool = False,
layers: Optional[Iterable[int]] = None) -> mx.rnn.SequentialRNNCell:
"""
Returns (stacked) RNN cell given parameters.
:param config: rnn configuration.
:param prefix: Symbol prefix... | Returns (stacked) RNN cell given parameters.
:param config: rnn configuration.
:param prefix: Symbol prefix for RNN.
:param parallel_inputs: Support parallel inputs for the stacked RNN cells.
:param layers: Specify which layers to create as a list of layer indexes.
:return: RNN cell. |
def euler_matrix(ai, aj, ak, axes='sxyz'):
"""Return homogeneous rotation matrix from Euler angles and axis sequence.
ai, aj, ak : Euler's roll, pitch and yaw angles
axes : One of 24 axis sequences as string or encoded tuple
>>> R = euler_matrix(1, 2, 3, 'syxz')
>>> np.allclose(np.sum(R[0]), -1.34... | Return homogeneous rotation matrix from Euler angles and axis sequence.
ai, aj, ak : Euler's roll, pitch and yaw angles
axes : One of 24 axis sequences as string or encoded tuple
>>> R = euler_matrix(1, 2, 3, 'syxz')
>>> np.allclose(np.sum(R[0]), -1.34786452)
True
>>> R = euler_matrix(1, 2, 3,... |
def codeComplete(self, path, line, column, unsaved_files=None,
include_macros=False, include_code_patterns=False,
include_brief_comments=False):
"""
Code complete in this translation unit.
In-memory contents for files can be provided by passing a list o... | Code complete in this translation unit.
In-memory contents for files can be provided by passing a list of pairs
as unsaved_files, the first items should be the filenames to be mapped
and the second should be the contents to be substituted for the
file. The contents may be passed as stri... |
def _wmi_to_ts(self, wmi_ts):
''' Convert a wmi formatted timestamp into an epoch.
'''
year, month, day, hour, minute, second, microsecond, tz = to_time(wmi_ts)
tz_delta = timedelta(minutes=int(tz))
if '+' in wmi_ts:
tz_delta = -tz_delta
dt = (
da... | Convert a wmi formatted timestamp into an epoch. |
def yaml_get_data(filename):
"""Get data from .yml file
"""
with open(filename, 'rb') as fd:
yaml_data = yaml.load(fd)
return yaml_data
return False | Get data from .yml file |
def get_environment_paths(config, env):
"""
Get environment paths from given environment variable.
"""
if env is None:
return config.get(Config.DEFAULTS, 'environment')
# Config option takes precedence over environment key.
if config.has_option(Config.ENVIRONMENTS, env):
... | Get environment paths from given environment variable. |
def memoize(fn):
"""Caches previous calls to the function."""
memo = {}
@wraps(fn)
def wrapper(*args, **kwargs):
if not memoize.disabled:
key = pickle.dumps((args, kwargs))
if key not in memo:
memo[key] = fn(*args, **kwargs)
value = memo[key]
... | Caches previous calls to the function. |
def _cumprod(l):
"""Cumulative product of a list.
Args:
l: a list of integers
Returns:
a list with one more element (starting with 1)
"""
ret = [1]
for item in l:
ret.append(ret[-1] * item)
return ret | Cumulative product of a list.
Args:
l: a list of integers
Returns:
a list with one more element (starting with 1) |
def create_mirror_settings(repo_url):
"""
Creates settings.xml in current working directory, which when used makes Maven use given repo URL as a mirror of all
repositories to look at.
:param repo_url: the repository URL to use
:returns: filepath to the created file
"""
cwd = os.getcwd()
... | Creates settings.xml in current working directory, which when used makes Maven use given repo URL as a mirror of all
repositories to look at.
:param repo_url: the repository URL to use
:returns: filepath to the created file |
def verify(full, dataset_uri):
"""Verify the integrity of a dataset.
"""
dataset = dtoolcore.DataSet.from_uri(dataset_uri)
all_okay = True
generated_manifest = dataset.generate_manifest()
generated_identifiers = set(generated_manifest["items"].keys())
manifest_identifiers = set(dataset.iden... | Verify the integrity of a dataset. |
def sanitize_block(self, block):
"""Santizes the data for the given block.
If block has a matching embed serializer, use the `to_internal_value` method."""
embed_type = block.get('type', None)
data = block.get('data', {})
serializer = self.serializers.get(embed_type, None)
... | Santizes the data for the given block.
If block has a matching embed serializer, use the `to_internal_value` method. |
def wallet_unlock(self, wallet, password):
"""
Unlocks **wallet** using **password**
:param wallet: Wallet to unlock
:type wallet: str
:param password: Password to enter
:type password: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.wallet_unlock... | Unlocks **wallet** using **password**
:param wallet: Wallet to unlock
:type wallet: str
:param password: Password to enter
:type password: str
:raises: :py:exc:`nano.rpc.RPCException`
>>> rpc.wallet_unlock(
... wallet="000D1BAEC8EC208142C99059B393051BAC838... |
def set_option(name, option):
"""
Set the given LLVM "command-line" option.
For example set_option("test", "-debug-pass=Structure") would display
all optimization passes when generating code.
"""
ffi.lib.LLVMPY_SetCommandLine(_encode_string(name),
_encode_strin... | Set the given LLVM "command-line" option.
For example set_option("test", "-debug-pass=Structure") would display
all optimization passes when generating code. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.