code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def write_point(self, **kw):
"""
Write a task point to the file::
with writer.write_point(type=PointType.TURN):
writer.write_waypoint(...)
writer.write_observation_zone(...)
# <Point type="Turn"> ... </Point>
Inside the with clause the
... | Write a task point to the file::
with writer.write_point(type=PointType.TURN):
writer.write_waypoint(...)
writer.write_observation_zone(...)
# <Point type="Turn"> ... </Point>
Inside the with clause the
:meth:`~aerofiles.xcsoar.Writer.write_wayp... |
def getColor(rgb=None, hsv=None):
"""
Convert a color or list of colors to (r,g,b) format from many input formats.
:param bool hsv: if set to `True`, rgb is assumed as (hue, saturation, value).
Example:
- RGB = (255, 255, 255), corresponds to white
- rgb = (1,1,1) is white
... | Convert a color or list of colors to (r,g,b) format from many input formats.
:param bool hsv: if set to `True`, rgb is assumed as (hue, saturation, value).
Example:
- RGB = (255, 255, 255), corresponds to white
- rgb = (1,1,1) is white
- hex = #FFFF00 is yellow
- s... |
def _get_scope_highlight_color(self):
"""
Gets the base scope highlight color (derivated from the editor
background)
For lighter themes will be a darker color,
and for darker ones will be a lighter color
"""
color = self.editor.sideareas_color
if color.l... | Gets the base scope highlight color (derivated from the editor
background)
For lighter themes will be a darker color,
and for darker ones will be a lighter color |
def do_macro_block(parser, token):
""" Function taking parsed template tag
to a MacroBlockNode.
"""
tag_name, macro_name, args, kwargs = parse_macro_params(token)
# could add extra validation on the macro_name tag
# here, but probably don't need to since we're checking
# if there's a macro b... | Function taking parsed template tag
to a MacroBlockNode. |
def __setup_taskset(self, affinity, pid=None, args=None):
""" if pid specified: set process w/ pid `pid` CPU affinity to specified `affinity` core(s)
if args specified: modify list of args for Popen to start w/ taskset w/ affinity `affinity`
"""
self.taskset_path = self.get_option(se... | if pid specified: set process w/ pid `pid` CPU affinity to specified `affinity` core(s)
if args specified: modify list of args for Popen to start w/ taskset w/ affinity `affinity` |
def case_name_parts(self):
"""
Convert all the parts of the name to the proper case... carefully!
"""
if not self.is_mixed_case():
self.honorific = self.honorific.title() if self.honorific else None
self.nick = self.nick.title() if self.nick else None
... | Convert all the parts of the name to the proper case... carefully! |
def locator_to_latlong (locator):
"""converts Maidenhead locator in the corresponding WGS84 coordinates
Args:
locator (string): Locator, either 4 or 6 characters
Returns:
tuple (float, float): Latitude, Longitude
Raises:
ValueError: When called with wro... | converts Maidenhead locator in the corresponding WGS84 coordinates
Args:
locator (string): Locator, either 4 or 6 characters
Returns:
tuple (float, float): Latitude, Longitude
Raises:
ValueError: When called with wrong or invalid input arg
TypeE... |
def _reset_server(self, address):
"""Clear our pool for a server and mark it Unknown.
Hold the lock when calling this. Does *not* request an immediate check.
"""
server = self._servers.get(address)
# "server" is None if another thread removed it from the topology.
if se... | Clear our pool for a server and mark it Unknown.
Hold the lock when calling this. Does *not* request an immediate check. |
def get_charset(request):
""" Extract charset from the content type
"""
content_type = request.META.get('CONTENT_TYPE', None)
if content_type:
return extract_charset(content_type) if content_type else None
else:
return None | Extract charset from the content type |
def create_hooks(use_tfdbg=False,
use_dbgprofile=False,
dbgprofile_kwargs=None,
use_validation_monitor=False,
validation_monitor_kwargs=None,
use_early_stopping=False,
early_stopping_kwargs=None):
"""Create train and... | Create train and eval hooks for Experiment. |
def add_node(self, binary_descriptor):
"""Add a node to the sensor_graph using a binary node descriptor.
Args:
binary_descriptor (bytes): An encoded binary node descriptor.
Returns:
int: A packed error code.
"""
try:
node_string = parse_bina... | Add a node to the sensor_graph using a binary node descriptor.
Args:
binary_descriptor (bytes): An encoded binary node descriptor.
Returns:
int: A packed error code. |
def flash(message, category='message'):
"""Flashes a message to the next request. In order to remove the
flashed message from the session and to display it to the user,
the template has to call :func:`get_flashed_messages`.
.. versionchanged:: 0.3
`category` parameter added.
:param message... | Flashes a message to the next request. In order to remove the
flashed message from the session and to display it to the user,
the template has to call :func:`get_flashed_messages`.
.. versionchanged:: 0.3
`category` parameter added.
:param message: the message to be flashed.
:param categor... |
def artist_related_artists(self, spotify_id):
"""Get related artists for an artist by their ID.
Parameters
----------
spotify_id : str
The spotify_id to search by.
"""
route = Route('GET', '/artists/{spotify_id}/related-artists', spotify_id=spotify_id)
... | Get related artists for an artist by their ID.
Parameters
----------
spotify_id : str
The spotify_id to search by. |
def find_non_contiguous(all_items):
"""Find any items that have slots that aren't contiguous"""
non_contiguous = []
for item in all_items:
if item.slots.count() < 2:
# No point in checking
continue
last_slot = None
for slot in item.slots.all().order_by('end_ti... | Find any items that have slots that aren't contiguous |
def get(self, queue='', no_ack=False, to_dict=False, auto_decode=True):
"""Fetch a single message.
:param str queue: Queue name
:param bool no_ack: No acknowledgement needed
:param bool to_dict: Should incoming messages be converted to a
dictionary before delivery.
... | Fetch a single message.
:param str queue: Queue name
:param bool no_ack: No acknowledgement needed
:param bool to_dict: Should incoming messages be converted to a
dictionary before delivery.
:param bool auto_decode: Auto-decode strings when possible.
:raises... |
def addcomment(self, comment, private=False):
"""
Add the given comment to this bug. Set private to True to mark this
comment as private.
"""
# Note: fedora bodhi uses this function
vals = self.bugzilla.build_update(comment=comment,
... | Add the given comment to this bug. Set private to True to mark this
comment as private. |
def _receive_data(self):
"""Gets data from queue"""
result = self.queue.get(block=True)
if hasattr(self.queue, 'task_done'):
self.queue.task_done()
return result | Gets data from queue |
def fcontext_add_or_delete_policy(action, name, filetype=None, sel_type=None, sel_user=None, sel_level=None):
'''
.. versionadded:: 2017.7.0
Adds or deletes the SELinux policy for a given filespec and other optional parameters.
Returns the result of the call to semanage.
Note that you don't have ... | .. versionadded:: 2017.7.0
Adds or deletes the SELinux policy for a given filespec and other optional parameters.
Returns the result of the call to semanage.
Note that you don't have to remove an entry before setting a new
one for a given filespec and filetype, as adding one with semanage
automat... |
def _pys_assert_version(self, line):
"""Asserts pys file version"""
if float(line.strip()) > 1.0:
# Abort if file version not supported
msg = _("File version {version} unsupported (>1.0).").format(
version=line.strip())
raise ValueError(msg) | Asserts pys file version |
def _from_dict(cls, _dict):
"""Initialize a SentimentResult object from a json dictionary."""
args = {}
if 'document' in _dict:
args['document'] = DocumentSentimentResults._from_dict(
_dict.get('document'))
if 'targets' in _dict:
args['targets'] = ... | Initialize a SentimentResult object from a json dictionary. |
def update_username(
self,
username: Union[str, None]
) -> bool:
"""Use this method to update your own username.
This method only works for users, not bots. Bot usernames must be changed via Bot Support or by recreating
them from scratch using BotFather. To update a ... | Use this method to update your own username.
This method only works for users, not bots. Bot usernames must be changed via Bot Support or by recreating
them from scratch using BotFather. To update a channel or supergroup username you can use
:meth:`update_chat_username`.
Args:
... |
def pass_rate(self, include_skips=False, include_inconclusive=False, include_retries=True):
"""
Calculate pass rate for tests in this list.
:param include_skips: Boolean, if True skipped tc:s will be included. Default is False
:param include_inconclusive: Boolean, if True inconclusive t... | Calculate pass rate for tests in this list.
:param include_skips: Boolean, if True skipped tc:s will be included. Default is False
:param include_inconclusive: Boolean, if True inconclusive tc:s will be included.
Default is False.
:param include_retries: Boolean, if True retried tc:s wi... |
def get_object_methods(obj):
"""
Returns all methods belonging to an object instance specified in by the
__dir__ function
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_inspect import * # NOQA
>>> import utool as ut
>>> obj = ut.NiceRepr()
>>> methods1 = ut.... | Returns all methods belonging to an object instance specified in by the
__dir__ function
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_inspect import * # NOQA
>>> import utool as ut
>>> obj = ut.NiceRepr()
>>> methods1 = ut.get_object_methods()
>>> ut.injec... |
def delete(self):
'''
delete - Delete all objects in this list.
@return <int> - Number of objects deleted
'''
if len(self) == 0:
return 0
mdl = self.getModel()
return mdl.deleter.deleteMultiple(self) | delete - Delete all objects in this list.
@return <int> - Number of objects deleted |
def is_muted(what):
"""
Checks if a logged event is to be muted for debugging purposes.
Also goes through the solo list - only items in there will be logged!
:param what:
:return:
"""
state = False
for item in solo:
if item not in what:
state = True
else:
... | Checks if a logged event is to be muted for debugging purposes.
Also goes through the solo list - only items in there will be logged!
:param what:
:return: |
def get_email(self, email_id):
"""
Get a specific email
"""
connection = Connection(self.token)
connection.set_url(self.production, self.EMAILS_ID_URL % email_id)
return connection.get_request() | Get a specific email |
def colstack(seq, mode='abort',returnnaming=False):
"""
Horizontally stack a sequence of numpy ndarrays with structured dtypes
Analog of numpy.hstack for recarrays.
Implemented by the tabarray method
:func:`tabular.tab.tabarray.colstack` which uses
:func:`tabular.tabarray.tab_colstack`.
... | Horizontally stack a sequence of numpy ndarrays with structured dtypes
Analog of numpy.hstack for recarrays.
Implemented by the tabarray method
:func:`tabular.tab.tabarray.colstack` which uses
:func:`tabular.tabarray.tab_colstack`.
**Parameters**
**seq** : sequence of numpy ndarra... |
def get_weld_obj_id(weld_obj, data):
"""Helper method to update WeldObject with some data.
Parameters
----------
weld_obj : WeldObject
WeldObject to update.
data : numpy.ndarray or WeldObject or str
Data for which to get an id. If str, it is a placeholder or 'str' literal.
Retu... | Helper method to update WeldObject with some data.
Parameters
----------
weld_obj : WeldObject
WeldObject to update.
data : numpy.ndarray or WeldObject or str
Data for which to get an id. If str, it is a placeholder or 'str' literal.
Returns
-------
str
The id of th... |
def add_extension_if_needed(filepath, ext, check_if_exists=False):
"""Add the extension ext to fpath if it doesn't have it.
Parameters
----------
filepath: str
File name or path
ext: str
File extension
check_if_exists: bool
Returns
-------
File name or path with extension... | Add the extension ext to fpath if it doesn't have it.
Parameters
----------
filepath: str
File name or path
ext: str
File extension
check_if_exists: bool
Returns
-------
File name or path with extension added, if needed. |
def get_mesures(self, mes, debut=None, fin=None, freq='H', format=None,
dayfirst=False, brut=False):
"""
Récupération des données de mesure.
Paramètres:
mes: Un nom de mesure ou plusieurs séparées par des virgules, une liste
(list, tuple, pandas.Series) d... | Récupération des données de mesure.
Paramètres:
mes: Un nom de mesure ou plusieurs séparées par des virgules, une liste
(list, tuple, pandas.Series) de noms
debut: Chaine de caractère ou objet datetime décrivant la date de début.
Défaut=date du jour
fin: Chaine d... |
def infer_trading_calendar(factor_idx, prices_idx):
"""
Infer the trading calendar from factor and price information.
Parameters
----------
factor_idx : pd.DatetimeIndex
The factor datetimes for which we are computing the forward returns
prices_idx : pd.DatetimeIndex
The prices ... | Infer the trading calendar from factor and price information.
Parameters
----------
factor_idx : pd.DatetimeIndex
The factor datetimes for which we are computing the forward returns
prices_idx : pd.DatetimeIndex
The prices datetimes associated withthe factor data
Returns
------... |
def optimisation_plot(d, overlay_alpha=0.5, **kwargs):
"""
Plot the result of signal_optimise.
`signal_optimiser` must be run first, and the output
stored in the `opt` attribute of the latools.D object.
Parameters
----------
d : latools.D object
A latools data object.
overlay_a... | Plot the result of signal_optimise.
`signal_optimiser` must be run first, and the output
stored in the `opt` attribute of the latools.D object.
Parameters
----------
d : latools.D object
A latools data object.
overlay_alpha : float
The opacity of the threshold overlays. Between... |
def _set_sharing_keys(self, keys):
"""
Set the keys to share or unshare
Parameters
----------
keys: string or iterable of strings
The iterable may contain formatoptions that shall be shared (or
unshared), or group names of formatoptions to share all
... | Set the keys to share or unshare
Parameters
----------
keys: string or iterable of strings
The iterable may contain formatoptions that shall be shared (or
unshared), or group names of formatoptions to share all
formatoptions of that group (see the :attr:`fmt_... |
def _valcache_lookup(self, cache, branch, turn, tick):
"""Return the value at the given time in ``cache``"""
if branch in cache:
branc = cache[branch]
try:
if turn in branc and branc[turn].rev_gettable(tick):
return branc[turn][tick]
... | Return the value at the given time in ``cache`` |
def class_method(cls, f):
"""Decorator which dynamically binds class methods to the model for later use."""
setattr(cls, f.__name__, classmethod(f))
return f | Decorator which dynamically binds class methods to the model for later use. |
def monitor(result_queue, broker=None):
"""
Gets finished tasks from the result queue and saves them to Django
:type result_queue: multiprocessing.Queue
"""
if not broker:
broker = get_broker()
name = current_process().name
logger.info(_("{} monitoring at {}").format(name, current_pr... | Gets finished tasks from the result queue and saves them to Django
:type result_queue: multiprocessing.Queue |
def push_plugin(self, name):
"""
Push a plugin to the registry.
Args:
name (string): Name of the plugin to upload. The ``:latest``
tag is optional, and is the default if omitted.
Returns:
``True`` if successful
"""... | Push a plugin to the registry.
Args:
name (string): Name of the plugin to upload. The ``:latest``
tag is optional, and is the default if omitted.
Returns:
``True`` if successful |
def preprocess_incoming_content(content, encrypt_func, max_size_bytes):
"""
Apply preprocessing steps to file/notebook content that we're going to
write to the database.
Applies ``encrypt_func`` to ``content`` and checks that the result is
smaller than ``max_size_bytes``.
"""
encrypted = en... | Apply preprocessing steps to file/notebook content that we're going to
write to the database.
Applies ``encrypt_func`` to ``content`` and checks that the result is
smaller than ``max_size_bytes``. |
def write_short_ascii(s):
"""
Encode a Kafka short string which represents text.
:param str s:
Text string (`str` on Python 3, `str` or `unicode` on Python 2) or
``None``. The string will be ASCII-encoded.
:returns: length-prefixed `bytes`
:raises:
`struct.error` for string... | Encode a Kafka short string which represents text.
:param str s:
Text string (`str` on Python 3, `str` or `unicode` on Python 2) or
``None``. The string will be ASCII-encoded.
:returns: length-prefixed `bytes`
:raises:
`struct.error` for strings longer than 32767 characters |
def addEqLink(self, link):
'''Appends EqLink
'''
if isinstance(link, EqLink):
self.eqLinks.append(link)
else:
raise TypeError(
'link Type should be InternalLink, not %s' % type(link)) | Appends EqLink |
def retrieve_value(self, name, default_value=None):
"""Retrieve a value from DB"""
value = self.spine.send_query("retrieveSetting", self.group, name, processes=["kervi-main"])
if value is None:
return default_value
elif isinstance(value, list) and len(value) == 0:
... | Retrieve a value from DB |
def set_yaxis(self, param, unit=None, label=None):
""" Sets the value of use on the yaxis
:param param: value to use on the yaxis, should be a variable or function of the objects in objectList. ie 'R'
for the radius variable and 'calcDensity()' for the calcDensity function
:param unit: ... | Sets the value of use on the yaxis
:param param: value to use on the yaxis, should be a variable or function of the objects in objectList. ie 'R'
for the radius variable and 'calcDensity()' for the calcDensity function
:param unit: the unit to scale the values to
:type unit: quantities ... |
def head(self, n=None):
"""Returns the first ``n`` rows.
.. note:: This method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
:param n: int, default 1. Number of rows to return.
:return: If n is greate... | Returns the first ``n`` rows.
.. note:: This method should only be used if the resulting array is expected
to be small, as all the data is loaded into the driver's memory.
:param n: int, default 1. Number of rows to return.
:return: If n is greater than 1, return a list of :class:`... |
def __get_nondirect_init(self, init):
"""
return the non-direct init if the direct algorithm has been selected.
"""
crc = init
for i in range(self.Width):
bit = crc & 0x01
if bit:
crc^= self.Poly
crc >>= 1
if bit:
... | return the non-direct init if the direct algorithm has been selected. |
def process_quote(self, data):
"""报价推送"""
for ix, row in data.iterrows():
symbol = row['code']
tick = self._tick_dict.get(symbol, None)
if not tick:
tick = TinyQuoteData()
tick.symbol = symbol
self._tick_dict[symbol] = ... | 报价推送 |
def call_remoteckan(self, *args, **kwargs):
# type: (Any, Any) -> Dict
"""
Calls the remote CKAN
Args:
*args: Arguments to pass to remote CKAN call_action method
**kwargs: Keyword arguments to pass to remote CKAN call_action method
Returns:
D... | Calls the remote CKAN
Args:
*args: Arguments to pass to remote CKAN call_action method
**kwargs: Keyword arguments to pass to remote CKAN call_action method
Returns:
Dict: The response from the remote CKAN call_action method |
def copy(self, graph):
""" Returns a copy of the event handler, remembering the last node clicked.
"""
e = events(graph, self._ctx)
e.clicked = self.clicked
return e | Returns a copy of the event handler, remembering the last node clicked. |
def stop(self):
"""
Stops this VirtualBox VM.
"""
self._hw_virtualization = False
yield from self._stop_ubridge()
yield from self._stop_remote_console()
vm_state = yield from self._get_vm_state()
if vm_state == "running" or vm_state == "paused" or vm_stat... | Stops this VirtualBox VM. |
def tool(self):
"""The tool that was in use during this event.
If the caller keeps a reference to a tool, the tool object will
compare equal to the previously obtained tool object.
Note:
Physical tool tracking requires hardware support. If unavailable,
libinput creates one tool per type per tablet. See
... | The tool that was in use during this event.
If the caller keeps a reference to a tool, the tool object will
compare equal to the previously obtained tool object.
Note:
Physical tool tracking requires hardware support. If unavailable,
libinput creates one tool per type per tablet. See
`Tracking unique t... |
def _sample_batch():
"""Determine if a batch should be processed and if not, pop off all of
the pending metrics for that batch.
:rtype: bool
"""
if _sample_probability == 1.0 or random.random() < _sample_probability:
return True
# Pop off all the metrics for the batch
for database... | Determine if a batch should be processed and if not, pop off all of
the pending metrics for that batch.
:rtype: bool |
def return_markers(self, state='MicromedCode'):
"""Return all the markers (also called triggers or events).
Returns
-------
list of dict
where each dict contains 'name' as str, 'start' and 'end' as float
in seconds from the start of the recordings, and 'chan' as ... | Return all the markers (also called triggers or events).
Returns
-------
list of dict
where each dict contains 'name' as str, 'start' and 'end' as float
in seconds from the start of the recordings, and 'chan' as list of
str with the channels involved (if not ... |
def from_Composition(composition):
"""Return the LilyPond equivalent of a Composition in a string."""
# warning Throw exception
if not hasattr(composition, 'tracks'):
return False
result = '\\header { title = "%s" composer = "%s" opus = "%s" } '\
% (composition.title, composition.author... | Return the LilyPond equivalent of a Composition in a string. |
def dict_factory(cursor, row):
"""
Converts the cursor information from a SQLite query to a dictionary.
:param cursor | <sqlite3.Cursor>
row | <sqlite3.Row>
:return {<str> column: <variant> value, ..}
"""
out = {}
for i, col in enumerate(cursor.description):
... | Converts the cursor information from a SQLite query to a dictionary.
:param cursor | <sqlite3.Cursor>
row | <sqlite3.Row>
:return {<str> column: <variant> value, ..} |
def _render_select(selections):
"""Render the selection part of a query.
Parameters
----------
selections : dict
Selections for a table
Returns
-------
str
A string for the "select" part of a query
See Also
--------
render_query : Further clarification of `sele... | Render the selection part of a query.
Parameters
----------
selections : dict
Selections for a table
Returns
-------
str
A string for the "select" part of a query
See Also
--------
render_query : Further clarification of `selections` dict formatting |
def entrance_beveled(Di, l, angle, method='Rennels'):
r'''Returns loss coefficient for a beveled or chamfered entrance to a pipe
flush with the wall of a reservoir. This calculation has two methods
available.
The 'Rennels' and 'Idelchik' methods have similar trends, but the 'Rennels'
formulatio... | r'''Returns loss coefficient for a beveled or chamfered entrance to a pipe
flush with the wall of a reservoir. This calculation has two methods
available.
The 'Rennels' and 'Idelchik' methods have similar trends, but the 'Rennels'
formulation is centered around a straight loss coefficient of 0.57, ... |
def main(
output_file: str,
entry_point: Optional[str],
console_script: Optional[str],
python: Optional[str],
site_packages: Optional[str],
compressed: bool,
compile_pyc: bool,
extend_pythonpath: bool,
pip_args: List[str],
) -> None:
"""
Shiv is a command line utility for bui... | Shiv is a command line utility for building fully self-contained Python zipapps
as outlined in PEP 441, but with all their dependencies included! |
def _update_rr_ce_entry(self, rec):
# type: (dr.DirectoryRecord) -> int
'''
An internal method to update the Rock Ridge CE entry for the given
record.
Parameters:
rec - The record to update the Rock Ridge CE entry for (if it exists).
Returns:
The number... | An internal method to update the Rock Ridge CE entry for the given
record.
Parameters:
rec - The record to update the Rock Ridge CE entry for (if it exists).
Returns:
The number of additional bytes needed for this Rock Ridge CE entry. |
def str_strip(arr, to_strip=None, side='both'):
"""
Strip whitespace (including newlines) from each string in the
Series/Index.
Parameters
----------
to_strip : str or unicode
side : {'left', 'right', 'both'}, default 'both'
Returns
-------
Series or Index
"""
if side =... | Strip whitespace (including newlines) from each string in the
Series/Index.
Parameters
----------
to_strip : str or unicode
side : {'left', 'right', 'both'}, default 'both'
Returns
-------
Series or Index |
def _build(self, build_method):
"""
build image from provided build_args
:return: BuildResults
"""
logger.info("building image '%s'", self.image)
self.ensure_not_built()
self.temp_dir = tempfile.mkdtemp()
temp_path = os.path.join(self.temp_dir, BUILD_JSON... | build image from provided build_args
:return: BuildResults |
def continue_login(self, login_token, **params):
"""
Continues a login that requires an additional step. This is common
for when login requires completing a captcha or supplying a two-factor
authentication token.
:Parameters:
login_token : `str`
A lo... | Continues a login that requires an additional step. This is common
for when login requires completing a captcha or supplying a two-factor
authentication token.
:Parameters:
login_token : `str`
A login token generated by the MediaWiki API (and used in a
... |
def get_requirements():
"""Extract the list of requirements from our requirements.txt.
:rtype: 2-tuple
:returns: Two lists, the first is a list of requirements in the form of
pkgname==version. The second is a list of URIs or VCS checkout strings
which specify the dependency links for obtain... | Extract the list of requirements from our requirements.txt.
:rtype: 2-tuple
:returns: Two lists, the first is a list of requirements in the form of
pkgname==version. The second is a list of URIs or VCS checkout strings
which specify the dependency links for obtaining a copy of the
requi... |
def ask_captcha(length=4):
"""Prompts the user for a random string."""
captcha = "".join(random.choice(string.ascii_lowercase) for _ in range(length))
ask_str('Enter the following letters, "%s"' % (captcha), vld=[captcha, captcha.upper()], blk=False) | Prompts the user for a random string. |
def get_activities(self, before=None, after=None, limit=None):
"""
Get activities for authenticated user sorted by newest first.
http://strava.github.io/api/v3/activities/
:param before: Result will start with activities whose start date is
before specified date... | Get activities for authenticated user sorted by newest first.
http://strava.github.io/api/v3/activities/
:param before: Result will start with activities whose start date is
before specified date. (UTC)
:type before: datetime.datetime or str or None
:param afte... |
def id(self, value):
"""Split into server_and_prefix and identifier."""
i = value.rfind('/')
if (i > 0):
self.server_and_prefix = value[:i]
self.identifier = value[(i + 1):]
elif (i == 0):
self.server_and_prefix = ''
self.identifier = value... | Split into server_and_prefix and identifier. |
def FindModuleDefiningFlag(self, flagname, default=None):
"""Return the name of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The name of the module which re... | Return the name of the module defining this flag, or default.
Args:
flagname: Name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The name of the module which registered the flag with this name.
If no such module exists ... |
def import_data_to_restful_server(args, content):
'''call restful server to import data to the experiment'''
nni_config = Config(get_config_filename(args))
rest_port = nni_config.get_config('restServerPort')
running, _ = check_rest_server_quick(rest_port)
if running:
response = rest_post(imp... | call restful server to import data to the experiment |
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
engine = engine_from_config(
winchester_config['database'],
prefix='',
poolclass=pool.NullPool)
connection = e... | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. |
def timing(self, stat, value, tags=None):
"""Measure a timing for statistical distribution.
Note: timing is a special case of histogram.
"""
self.histogram(stat, value, tags) | Measure a timing for statistical distribution.
Note: timing is a special case of histogram. |
def start(self):
"""Activate a patch, returning any created mock."""
result = self.__enter__()
self._active_patches.append(self)
return result | Activate a patch, returning any created mock. |
def _get_flavor():
"""
Download flavor from github
"""
target = op.join("seqcluster", "flavor")
url = "https://github.com/lpantano/seqcluster.git"
if not os.path.exists(target):
# shutil.rmtree("seqcluster")
subprocess.check_call(["git", "clone","-b", "flavor", "--single-branch", u... | Download flavor from github |
def getService(self, name, auto_execute=True):
"""
Returns a L{ServiceProxy} for the supplied name. Sets up an object that
can have method calls made to it that build the AMF requests.
@rtype: L{ServiceProxy}
"""
if not isinstance(name, basestring):
raise Typ... | Returns a L{ServiceProxy} for the supplied name. Sets up an object that
can have method calls made to it that build the AMF requests.
@rtype: L{ServiceProxy} |
def _find_match(self, position):
""" Given a valid position in the text document, try to find the
position of the matching bracket. Returns -1 if unsuccessful.
"""
# Decide what character to search for and what direction to search in.
document = self._text_edit.document()
... | Given a valid position in the text document, try to find the
position of the matching bracket. Returns -1 if unsuccessful. |
def _split_generators(self, dl_manager):
"""Returns SplitGenerators from the folder names."""
# At data creation time, parse the folder to deduce number of splits,
# labels, image size,
# The splits correspond to the high level folders
split_names = list_folders(dl_manager.manual_dir)
# Extrac... | Returns SplitGenerators from the folder names. |
def register(self, event_type, callback,
args=None, kwargs=None, details_filter=None,
weak=False):
"""Register a callback to be called when event of a given type occurs.
Callback will be called with provided ``args`` and ``kwargs`` and
when event type occurs (o... | Register a callback to be called when event of a given type occurs.
Callback will be called with provided ``args`` and ``kwargs`` and
when event type occurs (or on any event if ``event_type`` equals to
:attr:`.ANY`). It will also get additional keyword argument,
``details``, that will h... |
def notify_program_learners(cls, enterprise_customer, program_details, users):
"""
Notify learners about a program in which they've been enrolled.
Args:
enterprise_customer: The EnterpriseCustomer being linked to
program_details: Details about the specific program the le... | Notify learners about a program in which they've been enrolled.
Args:
enterprise_customer: The EnterpriseCustomer being linked to
program_details: Details about the specific program the learners were enrolled in
users: An iterable of the users or pending users who were enrol... |
def tm(seq, dna_conc=50, salt_conc=50, parameters='cloning'):
'''Calculate nearest-neighbor melting temperature (Tm).
:param seq: Sequence for which to calculate the tm.
:type seq: coral.DNA
:param dna_conc: DNA concentration in nM.
:type dna_conc: float
:param salt_conc: Salt concentration in ... | Calculate nearest-neighbor melting temperature (Tm).
:param seq: Sequence for which to calculate the tm.
:type seq: coral.DNA
:param dna_conc: DNA concentration in nM.
:type dna_conc: float
:param salt_conc: Salt concentration in mM.
:type salt_conc: float
:param parameters: Nearest-neighbo... |
def on_mouse_wheel(self, event):
'''handle mouse wheel zoom changes'''
rotation = event.GetWheelRotation() / event.GetWheelDelta()
if rotation > 0:
zoom = 1.0/(1.1 * rotation)
elif rotation < 0:
zoom = 1.1 * (-rotation)
self.change_zoom(zoom)
self.... | handle mouse wheel zoom changes |
def del_repo(repo, root=None):
'''
Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias
'''
repos_cfg = _get_configured_repos(root=root)
for alias in repos_cfg.sections():
if alias == repo:
... | Delete a repo.
root
operate on a different root directory.
CLI Examples:
.. code-block:: bash
salt '*' pkg.del_repo alias |
def update_anomalous_score(self):
"""Update anomalous score.
New anomalous score is a weighted average of differences
between current summary and reviews. The weights come from credibilities.
Therefore, the new anomalous score of reviewer :math:`p` is as
.. math::
... | Update anomalous score.
New anomalous score is a weighted average of differences
between current summary and reviews. The weights come from credibilities.
Therefore, the new anomalous score of reviewer :math:`p` is as
.. math::
{\\rm anomalous}(r) = \\frac{
\\... |
def write(self, more):
"""Append the Unicode representation of `s` to our output."""
if more:
self.output += str(more).upper()
self.output += '\n' | Append the Unicode representation of `s` to our output. |
def get_lbaas_agent_hosting_loadbalancer(self, loadbalancer, **_params):
"""Fetches a loadbalancer agent hosting a loadbalancer."""
return self.get((self.lbaas_loadbalancer_path +
self.LOADBALANCER_HOSTING_AGENT) % loadbalancer,
params=_params) | Fetches a loadbalancer agent hosting a loadbalancer. |
def draw_identity_line(ax=None, dynamic=True, **kwargs):
"""
Draws a 45 degree identity line such that y=x for all points within the
given axes x and y limits. This function also registeres a callback so
that as the figure is modified, the axes are updated and the line remains
drawn correctly.
... | Draws a 45 degree identity line such that y=x for all points within the
given axes x and y limits. This function also registeres a callback so
that as the figure is modified, the axes are updated and the line remains
drawn correctly.
Parameters
----------
ax : matplotlib Axes, default: None
... |
def get_form_language(self, request, obj=None):
"""
Return the current language for the currently displayed object fields.
"""
if self._has_translatable_parent_model():
return super(TranslatableInlineModelAdmin, self).get_form_language(request, obj=obj)
else:
... | Return the current language for the currently displayed object fields. |
def _pname_and_metadata(in_file):
"""Retrieve metadata and project name from the input metadata CSV file.
Uses the input file name for the project name and for back compatibility,
accepts the project name as an input, providing no metadata.
"""
if os.path.isfile(in_file):
with open(in_file)... | Retrieve metadata and project name from the input metadata CSV file.
Uses the input file name for the project name and for back compatibility,
accepts the project name as an input, providing no metadata. |
def from_response(raw_response):
"""The Yelp Fusion API returns error messages with a json body
like:
{
'error': {
'code': 'ALL_CAPS_CODE',
'description': 'Human readable description.'
}
}
Some errors may have additional fi... | The Yelp Fusion API returns error messages with a json body
like:
{
'error': {
'code': 'ALL_CAPS_CODE',
'description': 'Human readable description.'
}
}
Some errors may have additional fields. For example, a
validation erro... |
def affine(self, func:AffineFunc, *args, **kwargs)->'Image':
"Equivalent to `image.affine_mat = image.affine_mat @ func()`."
m = tensor(func(*args, **kwargs)).to(self.device)
self.affine_mat = self.affine_mat @ m
return self | Equivalent to `image.affine_mat = image.affine_mat @ func()`. |
def _fasta_slice(fasta, seqid, start, stop, strand):
"""
Return slice of fasta, given (seqid, start, stop, strand)
"""
_strand = 1 if strand == '+' else -1
return fasta.sequence({'chr': seqid, 'start': start, 'stop': stop, \
'strand': _strand}) | Return slice of fasta, given (seqid, start, stop, strand) |
def demacronize(string_matrix: List[List[str]]) -> List[List[str]]:
"""
Transform macronized vowels into normal vowels
:param string_matrix: a data matrix: a list wrapping a list of strings, with each sublist being a sentence.
:return: string_matrix
>>> demacronize([['ōdī', 'et', 'amō',]])
[['od... | Transform macronized vowels into normal vowels
:param string_matrix: a data matrix: a list wrapping a list of strings, with each sublist being a sentence.
:return: string_matrix
>>> demacronize([['ōdī', 'et', 'amō',]])
[['odi', 'et', 'amo']] |
def destroy(self):
"""
Delete the document. The *whole* document. There will be no survivors.
"""
logger.info("Destroying doc: %s" % self.path)
self.fs.rm_rf(self.path)
logger.info("Done") | Delete the document. The *whole* document. There will be no survivors. |
def tenengrad(img, ksize=3):
''''TENG' algorithm (Krotkov86)'''
Gx = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=1, dy=0, ksize=ksize)
Gy = cv2.Sobel(img, ddepth=cv2.CV_64F, dx=0, dy=1, ksize=ksize)
FM = Gx*Gx + Gy*Gy
mn = cv2.mean(FM)[0]
if np.isnan(mn):
return np.nanmean(FM)
retur... | TENG' algorithm (Krotkov86) |
def plot_importance(booster, ax=None, height=0.2,
xlim=None, ylim=None, title='Feature importance',
xlabel='Feature importance', ylabel='Features',
importance_type='split', max_num_features=None,
ignore_zero=True, figsize=None, grid=True,
... | Plot model's feature importances.
Parameters
----------
booster : Booster or LGBMModel
Booster or LGBMModel instance which feature importance should be plotted.
ax : matplotlib.axes.Axes or None, optional (default=None)
Target axes instance.
If None, new figure and axes will be ... |
def populate_requirement_set(requirement_set, # type: RequirementSet
args, # type: List[str]
options, # type: Values
finder, # type: PackageFinder
session, ... | Marshal cmd line args into a requirement set. |
async def register(self):
"""Register library device id and get initial device list. """
url = '{}/Sessions'.format(self.construct_url(API_URL))
params = {'api_key': self._api_key}
reg = await self.api_request(url, params)
if reg is None:
self._registered = False
... | Register library device id and get initial device list. |
def groupby(self, by=None, axis=0, level=None, as_index=True, sort=True,
group_keys=True, squeeze=False):
"""Returns a groupby on the schema rdd. This returns a GroupBy object.
Note that grouping by a column name will be faster than most other
options due to implementation."""
... | Returns a groupby on the schema rdd. This returns a GroupBy object.
Note that grouping by a column name will be faster than most other
options due to implementation. |
def processed(self):
'''Increase the processed task counter and show progress message'''
self.processed_tasks += 1
qsize = self.tasks.qsize()
if qsize > 0:
progress('[%d task(s) completed, %d remaining, %d thread(s)]', self.processed_tasks, qsize, len(self.workers))
else:
progress('[%d t... | Increase the processed task counter and show progress message |
def get_families_by_ids(self, family_ids=None):
"""Gets a ``FamilyList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the families
specified in the ``Id`` list, in the order of the list,
including duplicates, or an error results if an ``Id`` ... | Gets a ``FamilyList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the families
specified in the ``Id`` list, in the order of the list,
including duplicates, or an error results if an ``Id`` in the
supplied list is not found or inaccessible. ... |
async def handle(self, record):
"""
Call the handlers for the specified record.
This method is used for unpickled records received from a socket, as
well as those created locally. Logger-level filtering is applied.
"""
if (not self.disabled) and self.filter(record):
... | Call the handlers for the specified record.
This method is used for unpickled records received from a socket, as
well as those created locally. Logger-level filtering is applied. |
def copy_data_from_remote(args, nni_config, trial_content, path_list, host_list, temp_nni_path):
'''use ssh client to copy data from remote machine to local machien'''
machine_list = nni_config.get_config('experimentConfig').get('machineList')
machine_dict = {}
local_path_list = []
for machine in ma... | use ssh client to copy data from remote machine to local machien |
def _integrate(self, time_steps, capture_elements, return_timestamps):
"""
Performs euler integration
Parameters
----------
time_steps: iterable
the time steps that the integrator progresses over
capture_elements: list
which model elements to capt... | Performs euler integration
Parameters
----------
time_steps: iterable
the time steps that the integrator progresses over
capture_elements: list
which model elements to capture - uses pysafe names
return_timestamps:
which subset of 'timesteps' ... |
def focusInEvent(self, event):
"""Reimplement Qt method to send focus change notification"""
self.focus_changed.emit()
return super(ControlWidget, self).focusInEvent(event) | Reimplement Qt method to send focus change notification |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.