code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
async def run_checks(self):
"""
Run checks on itself and on the FSM
"""
async for check in self.fsm.health_check():
yield check
async for check in self.self_check():
yield check
for check in MiddlewareManager.health_check():
yield ch... | Run checks on itself and on the FSM |
def accepts(*checkers_args, **checkers_kws):
""" Create a decorator for validating function parameters.
Parameters
----------
checkers_args: positional args
Functions to apply to the inputs of the decorated function. The position of the argument
is assumed to match the position of ... | Create a decorator for validating function parameters.
Parameters
----------
checkers_args: positional args
Functions to apply to the inputs of the decorated function. The position of the argument
is assumed to match the position of the function in the decorator.
checkers_kws: keyw... |
def priority(self):
""" Get priority for this Schema.
Used to sort mapping keys
:rtype: int
"""
# Markers have priority set on the class
if self.compiled_type == const.COMPILED_TYPE.MARKER:
return self.compiled.priority
# Other types have static pri... | Get priority for this Schema.
Used to sort mapping keys
:rtype: int |
def write_xyz(self, *args, **kwargs):
"""Deprecated, use :meth:`~chemcoord.Cartesian.to_xyz`
"""
message = 'Will be removed in the future. Please use to_xyz().'
with warnings.catch_warnings():
warnings.simplefilter("always")
warnings.warn(message, DeprecationWarni... | Deprecated, use :meth:`~chemcoord.Cartesian.to_xyz` |
def add_root_book(self, book_id):
"""Adds a root book.
arg: book_id (osid.id.Id): the ``Id`` of a book
raise: AlreadyExists - ``book_id`` is already in hierarchy
raise: NotFound - ``book_id`` is not found
raise: NullArgument - ``book_id`` is ``null``
raise: Operat... | Adds a root book.
arg: book_id (osid.id.Id): the ``Id`` of a book
raise: AlreadyExists - ``book_id`` is already in hierarchy
raise: NotFound - ``book_id`` is not found
raise: NullArgument - ``book_id`` is ``null``
raise: OperationFailed - unable to complete request
... |
def clacks_overhead(fn):
"""
A Django view decorator that will add the `X-Clacks-Overhead` header.
Usage:
@clacks_overhead
def my_view(request):
return my_response
"""
@wraps(fn)
def _wrapped(*args, **kw):
response = fn(*args, **kw)
response['X-Clac... | A Django view decorator that will add the `X-Clacks-Overhead` header.
Usage:
@clacks_overhead
def my_view(request):
return my_response |
def FindTypeInfo(self, name):
"""Search for a type_info instance which describes this key."""
result = self.type_infos.get(name)
if result is None:
# Not found, assume string.
result = type_info.String(name=name, default="")
return result | Search for a type_info instance which describes this key. |
def get_content_type(self):
"""Returns the Content Type to serve from either the extension or the
Accept headers. Uses the :attr:`EXTENSION_MAP` list for all the
configured MIME types.
"""
extension = self.path_params.get('_extension')
for ext, mime in self.EXTENSION_MAP:... | Returns the Content Type to serve from either the extension or the
Accept headers. Uses the :attr:`EXTENSION_MAP` list for all the
configured MIME types. |
def visitPlusCardinality(self, ctx: ShExDocParser.PlusCardinalityContext):
""" '+' """
self.expression.min = 1
self.expression.max = -1 | '+' |
def visit_reference(self, node: docutils.nodes.reference) -> None:
"""Called for "reference" nodes."""
# if len(node.children) != 1 or not isinstance(node.children[0], docutils.nodes.Text) \
# or not all(_ in node.attributes for _ in ('name', 'refuri')):
# return
path... | Called for "reference" nodes. |
def blend_mode(self):
"""BlendMode: The blend mode used for drawing operations."""
blend_mode_ptr = ffi.new('int *')
lib.SDL_GetTextureBlendMode(self._ptr, blend_mode_ptr)
return BlendMode(blend_mode_ptr[0]) | BlendMode: The blend mode used for drawing operations. |
def tee(iterable, n=2):
"""Return n independent iterators from a single iterable.
Once tee() has made a split, the original iterable should not be used
anywhere else; otherwise, the iterable could get advanced without the tee
objects being informed.
This itertool may require significant auxiliary ... | Return n independent iterators from a single iterable.
Once tee() has made a split, the original iterable should not be used
anywhere else; otherwise, the iterable could get advanced without the tee
objects being informed.
This itertool may require significant auxiliary storage (depending on how
m... |
def process_config(raw_path, cache_dir, cache_file, **kwargs):
"""
Read a build configuration and create it, storing the result in a build
cache.
Arguments
raw_path -- path to a build configuration
cache_dir -- the directory where cache should be written
cache_file -- The filename to write ... | Read a build configuration and create it, storing the result in a build
cache.
Arguments
raw_path -- path to a build configuration
cache_dir -- the directory where cache should be written
cache_file -- The filename to write the cache. This will live inside
cache_dir.
**kwargs... |
def talk_back(self, message):
"""that's what she said: Tells you some things she actually said. :)"""
quote = self.get_quote()
if quote:
self.reply("Actually, she said things like this: \n%s" % quote) | that's what she said: Tells you some things she actually said. :) |
def get_average_along_axis(self, ind):
"""
Get the averaged total of the volumetric data a certain axis direction.
For example, useful for visualizing Hartree Potentials from a LOCPOT
file.
Args:
ind (int): Index of axis.
Returns:
Average total a... | Get the averaged total of the volumetric data a certain axis direction.
For example, useful for visualizing Hartree Potentials from a LOCPOT
file.
Args:
ind (int): Index of axis.
Returns:
Average total along axis |
def converge(self, playbook=None, **kwargs):
"""
Executes ``ansible-playbook`` against the converge playbook unless
specified otherwise and returns a string.
:param playbook: An optional string containing an absolute path to a
playbook.
:param kwargs: An optional keywor... | Executes ``ansible-playbook`` against the converge playbook unless
specified otherwise and returns a string.
:param playbook: An optional string containing an absolute path to a
playbook.
:param kwargs: An optional keyword arguments.
:return: str |
def randpath(self):
""" -> a random URI-like #str path """
return '/'.join(
gen_rand_str(3, 10, use=self.random, keyspace=list(self.keyspace))
for _ in range(self.random.randint(0, 3))) | -> a random URI-like #str path |
def _resolve_hostname(name):
"""Returns resolved hostname using the ssh config"""
if env.ssh_config is None:
return name
elif not os.path.exists(os.path.join("nodes", name + ".json")):
resolved_name = env.ssh_config.lookup(name)['hostname']
if os.path.exists(os.path.join("nodes", res... | Returns resolved hostname using the ssh config |
def _consolidate_binds(local_binds, remote_binds):
"""
Fill local_binds with defaults when no value/s were specified,
leaving paramiko to decide in which local port the tunnel will be open
"""
count = len(remote_binds) - len(local_binds)
if count < 0:
raise Va... | Fill local_binds with defaults when no value/s were specified,
leaving paramiko to decide in which local port the tunnel will be open |
def fmt_row(self, columns, dimensions, row, **settings):
"""
Format single table row.
"""
cells = []
i = 0
for column in columns:
cells.append(self.fmt_cell(
row[i],
dimensions[i],
column,
... | Format single table row. |
def _setup_directories(self):
""" Creates data directory structure.
* Raises a ``DirectorySetupFail`` exception if error occurs
while creating directories.
"""
dirs = [self._data_dir]
dirs += [os.path.join(self._data_dir, name) for name
in ... | Creates data directory structure.
* Raises a ``DirectorySetupFail`` exception if error occurs
while creating directories. |
def module_settings(self):
"""
Get Module settings. Uses GET to /settings/modules interface.
:Returns: (dict) Module settings as shown `here <https://cloud.knuverse.com/docs/api/#api-Module_Settings-Get_the_module_settings>`_.
"""
response = self._get(url.settings_modules)
... | Get Module settings. Uses GET to /settings/modules interface.
:Returns: (dict) Module settings as shown `here <https://cloud.knuverse.com/docs/api/#api-Module_Settings-Get_the_module_settings>`_. |
def _to_dict(self, serialize=False):
"""
This method works by copying self.__dict__, and removing everything that should not be serialized.
"""
copy_dict = self.__dict__.copy()
for key, value in vars(self).items():
# We want to send all ids to Zendesk always
... | This method works by copying self.__dict__, and removing everything that should not be serialized. |
def keys(self):
"""return a list of all app_names"""
keys = []
for app_name, __ in self.items():
keys.append(app_name)
return keys | return a list of all app_names |
def run(self, depth=None):
"""
Checks that the paths in the specified path group stay the same over the next
`depth` bytes.
The path group should have a "left" and a "right" stash, each with a single
path.
"""
#pg_history = [ ]
if len(self.simgr.right) !=... | Checks that the paths in the specified path group stay the same over the next
`depth` bytes.
The path group should have a "left" and a "right" stash, each with a single
path. |
def Terminate(self, status=None):
"""Terminates this flow."""
try:
self.queue_manager.DestroyFlowStates(self.session_id)
except queue_manager.MoreDataException:
pass
# This flow might already not be running.
if not self.IsRunning():
return
self._SendTerminationMessage(status=... | Terminates this flow. |
def pull_tasks(self, kill_event):
""" Pulls tasks from the incoming tasks 0mq pipe onto the internal
pending task queue
Parameters:
-----------
kill_event : threading.Event
Event to let the thread know when it is time to die.
"""
logger.info("[TASK ... | Pulls tasks from the incoming tasks 0mq pipe onto the internal
pending task queue
Parameters:
-----------
kill_event : threading.Event
Event to let the thread know when it is time to die. |
def attribute_node(self, name, ns_uri=None):
"""
:param string name: the name of the attribute to return.
:param ns_uri: a URI defining a namespace constraint on the attribute.
:type ns_uri: string or None
:return: this element's attributes that match ``ns_uri`` as
:... | :param string name: the name of the attribute to return.
:param ns_uri: a URI defining a namespace constraint on the attribute.
:type ns_uri: string or None
:return: this element's attributes that match ``ns_uri`` as
:class:`Attribute` nodes. |
def align(s1, s2, gap=' ', eq=operator.eq):
'''aligns two strings
>>> print(*align('pharmacy', 'farmácia', gap='_'), sep='\\n')
pharmac_y
_farmácia
>>> print(*align('advantage', 'vantagem', gap='_'), sep='\\n')
advantage_
__vantagem
'''
# first we compute the dynamic programming t... | aligns two strings
>>> print(*align('pharmacy', 'farmácia', gap='_'), sep='\\n')
pharmac_y
_farmácia
>>> print(*align('advantage', 'vantagem', gap='_'), sep='\\n')
advantage_
__vantagem |
def _output(self):
""" Prompts the creating of image objects.
"""
self.session._out('<</Type /XObject')
self.session._out('/Subtype /Image')
self.session._out('/Width %s' % self.width)
self.session._out('/Height %s' % self.height)
if self.colorspace is 'Indexed'... | Prompts the creating of image objects. |
def get_template_options():
"""
Returns a list of all templates that can be used for CMS pages.
The paths that are returned are relative to TURRENTINE_TEMPLATE_ROOT.
"""
template_root = turrentine_settings.TURRENTINE_TEMPLATE_ROOT
turrentine_dir = turrentine_settings.TURR... | Returns a list of all templates that can be used for CMS pages.
The paths that are returned are relative to TURRENTINE_TEMPLATE_ROOT. |
def id(self) -> typing.Union[str, None]:
"""Identifier for the project."""
return self._project.id if self._project else None | Identifier for the project. |
def get_branch_sha(profile, name):
"""Get the SHA a branch's HEAD points to.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
... | Get the SHA a branch's HEAD points to.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
name
The name of the branch... |
def _handle_xmpp_message(self, xmpp_message: BeautifulSoup):
"""
a XMPP 'message' in the case of Kik is the actual stanza we receive when someone sends us a message
(weather groupchat or not), starts typing, stops typing, reads our message, etc.
Examples: http://slixmpp.readthedocs.io/ap... | a XMPP 'message' in the case of Kik is the actual stanza we receive when someone sends us a message
(weather groupchat or not), starts typing, stops typing, reads our message, etc.
Examples: http://slixmpp.readthedocs.io/api/stanza/message.html
:param xmpp_message: The XMPP 'message' element we ... |
def hil_actuator_controls_encode(self, time_usec, controls, mode, flags):
'''
Sent from autopilot to simulation. Hardware in the loop control
outputs (replacement for HIL_CONTROLS)
time_usec : Timestamp (microseconds since UNIX epoch or mi... | Sent from autopilot to simulation. Hardware in the loop control
outputs (replacement for HIL_CONTROLS)
time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot) (uint64_t)
controls : Control outputs -1 .. 1. ... |
def copy(self):
'''
Copy the container, put an invalidated copy of the condition in the new container
'''
dup = super(Conditional, self).copy()
condition = self._condition.copy()
condition.invalidate(self)
dup._condition = condition
return dup | Copy the container, put an invalidated copy of the condition in the new container |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
assert all(stddev_type in self.DEFINED_FOR_STANDARD_DEVIATION_TYPES
... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. |
def show_hydrophobic(self):
"""Visualizes hydrophobic contacts."""
grp = self.getPseudoBondGroup("Hydrophobic Interactions-%i" % self.tid, associateWith=[self.model])
grp.lineType = self.chimera.Dash
grp.lineWidth = 3
grp.color = self.colorbyname('gray')
for i in self.plc... | Visualizes hydrophobic contacts. |
def getbool(value):
"""
Returns a boolean from any of a range of values. Returns None for
unrecognized values. Numbers other than 0 and 1 are considered
unrecognized.
>>> getbool(True)
True
>>> getbool(1)
True
>>> getbool('1')
True
>>> getbool('t')
True
>>> getbool(2... | Returns a boolean from any of a range of values. Returns None for
unrecognized values. Numbers other than 0 and 1 are considered
unrecognized.
>>> getbool(True)
True
>>> getbool(1)
True
>>> getbool('1')
True
>>> getbool('t')
True
>>> getbool(2)
>>> getbool(0)
False
... |
def _read_from_folder(self, dirname):
"""
Internal folder reader.
:type dirname: str
:param dirname: Folder to read from.
"""
templates = _par_read(dirname=dirname, compressed=False)
t_files = glob.glob(dirname + os.sep + '*.ms')
tribe_cat_file = glob.glo... | Internal folder reader.
:type dirname: str
:param dirname: Folder to read from. |
def get_share_properties(self, share_name, timeout=None):
'''
Returns all user-defined metadata and system properties for the
specified share. The data returned does not include the shares's
list of files or directories.
:param str share_name:
Name of existing share.... | Returns all user-defined metadata and system properties for the
specified share. The data returned does not include the shares's
list of files or directories.
:param str share_name:
Name of existing share.
:param int timeout:
The timeout parameter is expressed in... |
def __replace_names(sentence, counts):
"""Lets find and replace all instances of #NAME
:param _sentence:
:param counts:
"""
if sentence is not None:
while sentence.find('#NAME') != -1:
sentence = sentence.replace('#NAME', str(__get_name(counts)), 1)
if sentence.fin... | Lets find and replace all instances of #NAME
:param _sentence:
:param counts: |
def encode(password, algorithm, salt, iterations):
"""
Encode a Password
:param password: Password
:param algorithm
:param salt: Salt
:param iterations: iterations
:return: PBKDF2 hashed Password
"""
hash = hashlib.pbkdf2_hmac(digest().name, password.encode(), salt.encode(), iteratio... | Encode a Password
:param password: Password
:param algorithm
:param salt: Salt
:param iterations: iterations
:return: PBKDF2 hashed Password |
def drop(connection, skip):
"""Drop all."""
for idx, name, manager in _iterate_managers(connection, skip):
click.secho(f'dropping {name}', fg='cyan', bold=True)
manager.drop_all() | Drop all. |
def ReadMostRecentClientGraphSeries(self, client_label,
report_type
):
"""See db.Database."""
series_with_timestamps = self.ReadAllClientGraphSeries(
client_label, report_type)
if not series_with_timestamps:
return None... | See db.Database. |
def absorptionCoefficient_Doppler(Components=None,SourceTables=None,partitionFunction=PYTIPS,
Environment=None,OmegaRange=None,OmegaStep=None,OmegaWing=None,
IntensityThreshold=DefaultIntensityThreshold,
OmegaWingHW=De... | INPUT PARAMETERS:
Components: list of tuples [(M,I,D)], where
M - HITRAN molecule number,
I - HITRAN isotopologue number,
D - abundance (optional)
SourceTables: list of tables from which to calculate cross-section (optional)
... |
def join(L, keycols=None, nullvals=None, renamer=None,
returnrenaming=False, Names=None):
"""
Combine two or more numpy ndarray with structured dtype on common key
column(s).
Merge a list (or dictionary) of numpy ndarray with structured dtype, given
by `L`, on key columns listed in `keyc... | Combine two or more numpy ndarray with structured dtype on common key
column(s).
Merge a list (or dictionary) of numpy ndarray with structured dtype, given
by `L`, on key columns listed in `keycols`.
This function is actually a wrapper for
:func:`tabular.spreadsheet.strictjoin`.
The ``stric... |
def cleanup(self):
"""
Clean up my temporary files.
"""
all([delete_file_or_tree(f) for f in self.to_delete])
self.to_delete = [] | Clean up my temporary files. |
def success_count(self):
"""
Amount of passed test cases in this list.
:return: integer
"""
return len([i for i, result in enumerate(self.data) if result.success]) | Amount of passed test cases in this list.
:return: integer |
def _addDPFilesToOldEntry(self, *files):
"""callback to add DPs corresponding to files."""
# quiet flag is always true
self.view_entry_dialog.addDataProducts(self.purrer.makeDataProducts(
[(file, True) for file in files], unbanish=True, unignore=True)) | callback to add DPs corresponding to files. |
def spike_times(signal, threshold, fs, absval=True):
"""Detect spikes from a given signal
:param signal: Spike trace recording (vector)
:type signal: numpy array
:param threshold: Threshold value to determine spikes
:type threshold: float
:param absval: Whether to apply absolute value to signal... | Detect spikes from a given signal
:param signal: Spike trace recording (vector)
:type signal: numpy array
:param threshold: Threshold value to determine spikes
:type threshold: float
:param absval: Whether to apply absolute value to signal before thresholding
:type absval: bool
:returns: li... |
def _onError(self, error):
"""
Stop observer, raise exception, then restart. This prevents an infinite ping pong game of exceptions.
"""
self.stop()
self._logModule.err(
error,
"Unhandled error logging exception to %s" % (self.airbrakeURL,))
self.... | Stop observer, raise exception, then restart. This prevents an infinite ping pong game of exceptions. |
def from_inline(cls: Type[IdentityType], version: int, currency: str, inline: str) -> IdentityType:
"""
Return Identity instance from inline Identity string
:param version: Document version number
:param currency: Name of the currency
:param inline: Inline string of the Identity
... | Return Identity instance from inline Identity string
:param version: Document version number
:param currency: Name of the currency
:param inline: Inline string of the Identity
:return: |
def name_backbone(name, rank=None, kingdom=None, phylum=None, clazz=None,
order=None, family=None, genus=None, strict=False, verbose=False,
offset=None, limit=100, **kwargs):
'''
Lookup names in the GBIF backbone taxonomy.
:param name: [str] Full scientific name potentially with authorship (required)
:para... | Lookup names in the GBIF backbone taxonomy.
:param name: [str] Full scientific name potentially with authorship (required)
:param rank: [str] The rank given as our rank enum. (optional)
:param kingdom: [str] If provided default matching will also try to match against this
if no direct match is found for the... |
def configure(root_directory, build_path, cmake_command, only_show):
"""
Main configure function.
"""
default_build_path = os.path.join(root_directory, 'build')
# check that CMake is available, if not stop
check_cmake_exists('cmake')
# deal with build path
if build_path is None:
... | Main configure function. |
def get_proficiency_admin_session(self, proxy):
"""Gets the ``OsidSession`` associated with the proficiency administration service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``ProficiencyAdminSession``
:rtype: ``osid.learning.ProficiencyAdminSession``
... | Gets the ``OsidSession`` associated with the proficiency administration service.
:param proxy: a proxy
:type proxy: ``osid.proxy.Proxy``
:return: a ``ProficiencyAdminSession``
:rtype: ``osid.learning.ProficiencyAdminSession``
:raise: ``NullArgument`` -- ``proxy`` is ``null``
... |
def score_frequency_grid(self, f0, df, N):
"""Compute the score on a frequency grid.
Some models can compute results faster if the inputs are passed in this
manner.
Parameters
----------
f0, df, N : (float, float, int)
parameters describing the frequency gri... | Compute the score on a frequency grid.
Some models can compute results faster if the inputs are passed in this
manner.
Parameters
----------
f0, df, N : (float, float, int)
parameters describing the frequency grid freq = f0 + df * arange(N)
Note that the... |
def orify(event, changed_callback):
'''
Override ``set`` and ``clear`` methods on event to call specified callback
function after performing default behaviour.
Parameters
----------
'''
event.changed = changed_callback
if not hasattr(event, '_set'):
# `set`/`clear` methods have... | Override ``set`` and ``clear`` methods on event to call specified callback
function after performing default behaviour.
Parameters
---------- |
def _read_dictionary_page(file_obj, schema_helper, page_header, column_metadata):
"""Read a page containing dictionary data.
Consumes data using the plain encoding and returns an array of values.
"""
raw_bytes = _read_page(file_obj, page_header, column_metadata)
io_obj = io.BytesIO(raw_bytes)
v... | Read a page containing dictionary data.
Consumes data using the plain encoding and returns an array of values. |
def group_add(self, name, restrict, repos, lces=[], assets=[], queries=[],
policies=[], dashboards=[], credentials=[], description=''):
'''group_add name, restrict, repos
'''
return self.raw_query('group', 'add', data={
'lces': [{'id': i} for i in lces],
... | group_add name, restrict, repos |
def init_word_db(cls, name, text):
"""Initialize a database of words for the maker with the given name"""
# Prep the words
text = text.replace('\n', ' ').replace('\r', ' ')
words = [w.strip() for w in text.split(' ') if w.strip()]
assert len(words) > 2, \
'Databa... | Initialize a database of words for the maker with the given name |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
# pylint: disable=too-many-arguments
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for specification of input and result values.
Implements the following eq... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for specification of input and result values.
Implements the following equations:
Equation (8) on p. 203 for the bedrock ground motion:
``ln(y_br) = c1 + c2*(M - 6) + c3*(M - 6)**2 - lnR - c... |
def uploads(self, option):
"""
Set whether to filter by a user's uploads list. Options available are
user.ONLY, user.NOT, and None; default is None.
"""
params = join_params(self.parameters, {"uploads": option})
return self.__class__(**params) | Set whether to filter by a user's uploads list. Options available are
user.ONLY, user.NOT, and None; default is None. |
def rgb_color_list_to_hex(color_list):
"""
Convert a list of RGBa colors to a list of hexadecimal color codes.
Parameters
----------
color_list : list
the list of RGBa colors
Returns
-------
color_list_hex : list
"""
color_list_rgb = [[int(x*255) for x in c[0:3]] for c ... | Convert a list of RGBa colors to a list of hexadecimal color codes.
Parameters
----------
color_list : list
the list of RGBa colors
Returns
-------
color_list_hex : list |
def process_scheduled_consumption(self, token):
"""Processes a scheduled consumption request that has completed
:type token: RequestToken
:param token: The token associated to the consumption
request that is used to identify the request.
"""
scheduled_retry = self._t... | Processes a scheduled consumption request that has completed
:type token: RequestToken
:param token: The token associated to the consumption
request that is used to identify the request. |
def make_get_request(url, params, headers, connection):
"""
Helper function that makes an HTTP GET request to the given firebase
endpoint. Timeout is 60 seconds.
`url`: The full URL of the firebase endpoint (DSN appended.)
`params`: Python dict that is appended to the URL like a querystring.
`he... | Helper function that makes an HTTP GET request to the given firebase
endpoint. Timeout is 60 seconds.
`url`: The full URL of the firebase endpoint (DSN appended.)
`params`: Python dict that is appended to the URL like a querystring.
`headers`: Python dict. HTTP request headers.
`connection`: Predefi... |
def create_empty_resource(self, name):
"""Create an empty (length-0) resource.
See DAVResource.create_empty_resource()
"""
assert "/" not in name
if self.provider.readonly:
raise DAVError(HTTP_FORBIDDEN)
path = util.join_uri(self.path, name)
fp = self... | Create an empty (length-0) resource.
See DAVResource.create_empty_resource() |
def update(self, uid):
'''
in infor.
'''
postinfo = MPost.get_by_uid(uid)
if postinfo.kind == self.kind:
pass
else:
return False
post_data, ext_dic = self.fetch_post_data()
if 'gcat0' in post_data:
pass
else:
... | in infor. |
def add_castle(self, position):
"""
Adds kingside and queenside castling moves if legal
:type: position: Board
"""
if self.has_moved or self.in_check(position):
return
if self.color == color.white:
rook_rank = 0
else:
rook_ran... | Adds kingside and queenside castling moves if legal
:type: position: Board |
def read_stdout(self):
"""
Reads the standard output of the QEMU process.
Only use when the process has been stopped or has crashed.
"""
output = ""
if self._stdout_file:
try:
with open(self._stdout_file, "rb") as file:
out... | Reads the standard output of the QEMU process.
Only use when the process has been stopped or has crashed. |
def load_libs(self, scripts_paths):
"""
Load script files into the context.\
This can be thought as the HTML script tag.\
The files content must be utf-8 encoded.
This is a shortcut for reading the files\
and pass the content to :py:func:`run_script`
:param list... | Load script files into the context.\
This can be thought as the HTML script tag.\
The files content must be utf-8 encoded.
This is a shortcut for reading the files\
and pass the content to :py:func:`run_script`
:param list scripts_paths: Script file paths.
:raises OSErr... |
def tagscleanupdicts(configuration=None, url=None, keycolumn=5, failchained=True):
# type: (Optional[Configuration], Optional[str], int, bool) -> Tuple[Dict,List]
"""
Get tags cleanup dictionaries
Args:
configuration (Optional[Configuration]): HDX configuration. Defaults to ... | Get tags cleanup dictionaries
Args:
configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration.
url (Optional[str]): Url of tags cleanup spreadsheet. Defaults to None (internal configuration parameter).
keycolumn (int): Column number of tag ... |
def get_rmse(self, data_x=None, data_y=None):
"""
Get Root Mean Square Error using
self.bestfit_func
args:
x_min: scalar, default=min(x)
minimum x value of the line
x_max: scalar, default=max(x)
maximum x value of the line
... | Get Root Mean Square Error using
self.bestfit_func
args:
x_min: scalar, default=min(x)
minimum x value of the line
x_max: scalar, default=max(x)
maximum x value of the line
resolution: int, default=1000
how many steps b... |
def asyncPipeUnion(context=None, _INPUT=None, conf=None, **kwargs):
"""An operator that asynchronously merges multiple source together.
Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred iterable of items)
conf : unused
... | An operator that asynchronously merges multiple source together.
Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred iterable of items)
conf : unused
Keyword arguments
-----------------
_OTHER1 : asyncPipe like objec... |
def send(self, command, message=None):
'''Send a command over the socket with length endcoded'''
if message:
joined = command + constants.NL + util.pack(message)
else:
joined = command + constants.NL
if self._blocking:
for sock in self.socket():
... | Send a command over the socket with length endcoded |
def _validate_arguments(self):
"""
Validates the command line arguments passed to the CLI
Derived classes that override need to call this method before
validating their arguments
"""
if self._email is None:
self.set_error_message("E-mail for the account not pr... | Validates the command line arguments passed to the CLI
Derived classes that override need to call this method before
validating their arguments |
def dates(self, start, end):
'''Internal function which perform pre-conditioning on dates:
:keyword start: start date.
:keyword end: end date.
This function makes sure the *start* and *end* date are consistent.
It *never fails* and always return a two-element tuple
containing *start*, *end* with *star... | Internal function which perform pre-conditioning on dates:
:keyword start: start date.
:keyword end: end date.
This function makes sure the *start* and *end* date are consistent.
It *never fails* and always return a two-element tuple
containing *start*, *end* with *start* less or equal *end*
and *end* never a... |
def round_controlled(cycled_iterable, rounds=1):
"""Return after <rounds> passes through a cycled iterable."""
round_start = None
rounds_completed = 0
for item in cycled_iterable:
if round_start is None:
round_start = item
elif item == round_start:
rounds_complet... | Return after <rounds> passes through a cycled iterable. |
def get_factory_kwargs(self):
"""
Returns the keyword arguments for calling the formset factory
"""
kwargs = {}
kwargs.update({
'can_delete': self.can_delete,
'extra': self.extra,
'exclude': self.exclude,
'fields': self.fields,
... | Returns the keyword arguments for calling the formset factory |
def user_exists(name, host='localhost', **kwargs):
"""
Check if a MySQL user exists.
"""
with settings(hide('running', 'stdout', 'stderr', 'warnings'), warn_only=True):
res = query("""
use mysql;
SELECT COUNT(*) FROM user
WHERE User = '%(name)s' AND Host =... | Check if a MySQL user exists. |
def offer_trades(self, offer_id, cursor=None, order='asc', limit=10):
"""This endpoint represents all trades for a given offer.
`GET /offers/{offer_id}/trades{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/trades-for-offer.html>`_
:param int offer_... | This endpoint represents all trades for a given offer.
`GET /offers/{offer_id}/trades{?cursor,limit,order}
<https://www.stellar.org/developers/horizon/reference/endpoints/trades-for-offer.html>`_
:param int offer_id: The offer ID to get trades on.
:param int cursor: A paging token, spe... |
def is_fully_verified(self):
"""
Determine if this Job is fully verified based on the state of its Errors.
An Error (TextLogError or FailureLine) is considered Verified once its
related TextLogErrorMetadata has best_is_verified set to True. A Job
is then considered Verified onc... | Determine if this Job is fully verified based on the state of its Errors.
An Error (TextLogError or FailureLine) is considered Verified once its
related TextLogErrorMetadata has best_is_verified set to True. A Job
is then considered Verified once all its Errors TextLogErrorMetadata
ins... |
def size(self):
"""Total number of coefficients in the ScalarCoefs structure.
Example::
>>> sz = c.size
>>> N = c.nmax + 1
>>> L = N+ c.mmax * (2 * N - c.mmax - 1);
>>> assert sz == L
"""
N = self.nmax + 1;
NC = N + se... | Total number of coefficients in the ScalarCoefs structure.
Example::
>>> sz = c.size
>>> N = c.nmax + 1
>>> L = N+ c.mmax * (2 * N - c.mmax - 1);
>>> assert sz == L |
def getObjectId(self):
"""
Return the object id for this master, for associating state with the
master.
@returns: ID, via Deferred
"""
# try to get the cached value
if self._object_id is not None:
return defer.succeed(self._object_id)
# faili... | Return the object id for this master, for associating state with the
master.
@returns: ID, via Deferred |
def get_dependencies_from_wheel_cache(ireq):
"""Retrieves dependencies for the given install requirement from the wheel cache.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallReq... | Retrieves dependencies for the given install requirement from the wheel cache.
:param ireq: A single InstallRequirement
:type ireq: :class:`~pip._internal.req.req_install.InstallRequirement`
:return: A set of dependency lines for generating new InstallRequirements.
:rtype: set(str) or None |
def current_index(self):
"""Get the currently selected index in the parent table view."""
i = self._parent.proxy_model.mapToSource(self._parent.currentIndex())
return i | Get the currently selected index in the parent table view. |
def loadFile(self, fileName):
"""
Load and display the PDF file specified by ``fileName``.
"""
# Test if the file exists.
if not QtCore.QFile(fileName).exists():
msg = "File <b>{}</b> does not exist".format(self.qteAppletID())
self.qteLogger.info(msg)
... | Load and display the PDF file specified by ``fileName``. |
def _is_master_running(self):
'''
Perform a lightweight check to see if the master daemon is running
Note, this will return an invalid success if the master crashed or was
not shut down cleanly.
'''
# Windows doesn't have IPC. Assume the master is running.
# At w... | Perform a lightweight check to see if the master daemon is running
Note, this will return an invalid success if the master crashed or was
not shut down cleanly. |
def robot_files(self):
'''Return a list of all folders, and test suite files (.txt, .robot)
'''
result = []
for name in os.listdir(self.path):
fullpath = os.path.join(self.path, name)
if os.path.isdir(fullpath):
result.append(RobotFactory(fullpath,... | Return a list of all folders, and test suite files (.txt, .robot) |
def bbox(self):
"""
The minimal `~photutils.aperture.BoundingBox` for the cutout
region with respect to the original (large) image.
"""
return BoundingBox(self.slices[1].start, self.slices[1].stop,
self.slices[0].start, self.slices[0].stop) | The minimal `~photutils.aperture.BoundingBox` for the cutout
region with respect to the original (large) image. |
def maverage(size):
"""
Moving average
This is the only strategy that uses a ``collections.deque`` object
instead of a ZFilter instance. Fast, but without extra capabilites such
as a frequency response plotting method.
Parameters
----------
size :
Data block window size. Should be an integer.
R... | Moving average
This is the only strategy that uses a ``collections.deque`` object
instead of a ZFilter instance. Fast, but without extra capabilites such
as a frequency response plotting method.
Parameters
----------
size :
Data block window size. Should be an integer.
Returns
-------
A callabl... |
def null_advance_strain(self, blocksize):
""" Advance and insert zeros
Parameters
----------
blocksize: int
The number of seconds to attempt to read from the channel
"""
sample_step = int(blocksize * self.sample_rate)
csize = sample_step + self.corrup... | Advance and insert zeros
Parameters
----------
blocksize: int
The number of seconds to attempt to read from the channel |
def __populate_symbols(self):
"""Get a list of the symbols present in the bfd to populate our
internal list.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
try:
symbols = _bfd.get_symbols(self._ptr)
# Temporary dictionary or... | Get a list of the symbols present in the bfd to populate our
internal list. |
def calc_regenerated(self, lastvotetime):
''' Uses math formula to calculate the amount
of steem power that would have been regenerated
given a certain datetime object
'''
delta = datetime.utcnow() - datetime.strptime(lastvotetime,'%Y-%m-%dT%H:%M:%S')
td = delta.days
... | Uses math formula to calculate the amount
of steem power that would have been regenerated
given a certain datetime object |
def generate_maximum_validator(maximum, exclusiveMaximum=False, **kwargs):
"""
Generator function returning a callable for maximum value validation.
"""
return functools.partial(validate_maximum, maximum=maximum, is_exclusive=exclusiveMaximum) | Generator function returning a callable for maximum value validation. |
def parse_compound_list(path, compounds):
"""Parse a structured list of compounds as obtained from a YAML file
Yields CompoundEntries. Path can be given as a string or a context.
"""
context = FilePathContext(path)
for compound_def in compounds:
if 'include' in compound_def:
f... | Parse a structured list of compounds as obtained from a YAML file
Yields CompoundEntries. Path can be given as a string or a context. |
def geo2apex(self, glat, glon, height):
"""Converts geodetic to modified apex coordinates.
Parameters
==========
glat : array_like
Geodetic latitude
glon : array_like
Geodetic longitude
height : array_like
Altitude in km
Retur... | Converts geodetic to modified apex coordinates.
Parameters
==========
glat : array_like
Geodetic latitude
glon : array_like
Geodetic longitude
height : array_like
Altitude in km
Returns
=======
alat : ndarray or float
... |
def create_item(self, item):
"""
Create a new item in D4S2 service for item at the specified destination.
:param item: D4S2Item data to use for creating a D4S2 item
:return: requests.Response containing the successful result
"""
item_dict = {
'project_id': ite... | Create a new item in D4S2 service for item at the specified destination.
:param item: D4S2Item data to use for creating a D4S2 item
:return: requests.Response containing the successful result |
def update_expression_list(self):
"""Extract a list of expressions from the dictionary of expressions."""
self.expression_list = [] # code arrives in dictionary, but is passed in this list
self.expression_keys = [] # Keep track of the dictionary keys.
self.expression_order = [] # This ma... | Extract a list of expressions from the dictionary of expressions. |
def readDOE(serialize_output=True):
"""
Read csv files of DOE buildings
Sheet 1 = BuildingSummary
Sheet 2 = ZoneSummary
Sheet 3 = LocationSummary
Sheet 4 = Schedules
Note BLD8 & 10 = school
Then make matrix of ref data as nested nested lists [16, 3, 16]:
matrix refDOE = Building ob... | Read csv files of DOE buildings
Sheet 1 = BuildingSummary
Sheet 2 = ZoneSummary
Sheet 3 = LocationSummary
Sheet 4 = Schedules
Note BLD8 & 10 = school
Then make matrix of ref data as nested nested lists [16, 3, 16]:
matrix refDOE = Building objs
matrix Schedule = SchDef objs
matrix ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.