code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def rate_unstable(self):
"""Returns an unstable rate based on the last two entries in the timing data. Less intensive to compute."""
if not self.started or self.stalled:
return 0.0
x1, y1 = self._timing_data[-2]
x2, y2 = self._timing_data[-1]
return (y2 - y1) / (x2 - ... | Returns an unstable rate based on the last two entries in the timing data. Less intensive to compute. |
def post_event(api_key=None,
app_key=None,
title=None,
text=None,
date_happened=None,
priority=None,
host=None,
tags=None,
alert_type=None,
aggregation_key=None,
source_t... | Post an event to the Datadog stream.
CLI Example
.. code-block:: bash
salt-call datadog.post_event api_key='0123456789' \\
app_key='9876543210' \\
title='Salt Highstate' \\
text="Salt highst... |
def disable_nn_ha(self, active_name, snn_host_id, snn_check_point_dir_list,
snn_name=None):
"""
Disable high availability with automatic failover for an HDFS NameNode.
@param active_name: Name of the NamdeNode role that is going to be active after
High Availability is disabled... | Disable high availability with automatic failover for an HDFS NameNode.
@param active_name: Name of the NamdeNode role that is going to be active after
High Availability is disabled.
@param snn_host_id: Id of the host where the new SecondaryNameNode will be created.
@param snn_check... |
def get_agent_sock_path(env=None, sp=subprocess):
"""Parse gpgconf output to find out GPG agent UNIX socket path."""
args = [util.which('gpgconf'), '--list-dirs']
output = check_output(args=args, env=env, sp=sp)
lines = output.strip().split(b'\n')
dirs = dict(line.split(b':', 1) for line in lines)
... | Parse gpgconf output to find out GPG agent UNIX socket path. |
def run_global_hook(hook_name, *args):
'''Attempt to run a global hook by name with args'''
hook_finder = HookFinder(get_global_hook_path())
hook = hook_finder(hook_name)
if hook:
hook.run(*args) | Attempt to run a global hook by name with args |
def top_prior(name, z_shape, learn_prior="normal", temperature=1.0):
"""Unconditional prior distribution.
Args:
name: variable scope
z_shape: Shape of the mean / scale of the prior distribution.
learn_prior: Possible options are "normal" and "single_conv".
If set to "single_conv", the ... | Unconditional prior distribution.
Args:
name: variable scope
z_shape: Shape of the mean / scale of the prior distribution.
learn_prior: Possible options are "normal" and "single_conv".
If set to "single_conv", the gaussian is parametrized by a
single convolutional layer ... |
def code(item):
"""
Turn a NameID class instance into a quoted string of comma separated
attribute,value pairs. The attribute names are replaced with digits.
Depends on knowledge on the specific order of the attributes for the
class that is used.
:param item: The class instance
:return: A q... | Turn a NameID class instance into a quoted string of comma separated
attribute,value pairs. The attribute names are replaced with digits.
Depends on knowledge on the specific order of the attributes for the
class that is used.
:param item: The class instance
:return: A quoted string |
def running_state(self, running_state):
"""Sets the running_state of this MaintenanceWindow.
:param running_state: The running_state of this MaintenanceWindow. # noqa: E501
:type: str
"""
allowed_values = ["ONGOING", "PENDING", "ENDED"] # noqa: E501
if running_state n... | Sets the running_state of this MaintenanceWindow.
:param running_state: The running_state of this MaintenanceWindow. # noqa: E501
:type: str |
def send_signal(self, signum):
"""Send the signal *signum* to the child.
On Windows, SIGTERM, SIGKILL and SIGINT are emulated using
TerminateProcess(). This will cause the child to exit unconditionally
with status 1. No other signals can be sent on Windows.
"""
if self._... | Send the signal *signum* to the child.
On Windows, SIGTERM, SIGKILL and SIGINT are emulated using
TerminateProcess(). This will cause the child to exit unconditionally
with status 1. No other signals can be sent on Windows. |
def get_username(uid,**kwargs):
"""
Return the username of a given user_id
"""
rs = db.DBSession.query(User.username).filter(User.id==uid).one()
if rs is None:
raise ResourceNotFoundError("User with ID %s not found"%uid)
return rs.username | Return the username of a given user_id |
def index(self, row, column, parent):
""" The index should point to the corresponding QtControl in the
enaml object hierarchy.
"""
item = parent.internalPointer()
#: If the parent is None
d = self.declaration if item is None else item.declaration
if row < len(d._... | The index should point to the corresponding QtControl in the
enaml object hierarchy. |
def remove(self, indices):
"""
Remove the fragments corresponding to the given list of indices.
:param indices: the list of indices to be removed
:type indices: list of int
:raises ValueError: if one of the indices is not valid
"""
if not self._is_valid_index(in... | Remove the fragments corresponding to the given list of indices.
:param indices: the list of indices to be removed
:type indices: list of int
:raises ValueError: if one of the indices is not valid |
def _package_exists(path):
# type: (str) -> bool
"""
Checks if the given Python path matches a valid file or a valid container
file
:param path: A Python path
:return: True if the module or its container exists
"""
while path:
if os.path.exists(path):
return True
... | Checks if the given Python path matches a valid file or a valid container
file
:param path: A Python path
:return: True if the module or its container exists |
def repartition(self, numPartitions):
"""Repartition every RDD.
:rtype: DStream
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([['h... | Repartition every RDD.
:rtype: DStream
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([['hello', 'world']])
... .repartition(2)... |
def to_int(b:Any)->Union[int,List[int]]:
"Convert `b` to an int or list of ints (if `is_listy`); raises exception if not convertible"
if is_listy(b): return [to_int(x) for x in b]
else: return int(b) | Convert `b` to an int or list of ints (if `is_listy`); raises exception if not convertible |
def add_primary_key(self, column="id"):
"""Add primary key constraint to specified column
"""
if not self.primary_key:
sql = """ALTER TABLE {s}.{t}
ADD PRIMARY KEY ({c})
""".format(
s=self.schema, t=self.name, c=column
... | Add primary key constraint to specified column |
def _resize_panels(self):
"""
Resize panels
"""
self.theme.setup_figure(self.figure)
self.facet.spaceout_and_resize_panels() | Resize panels |
def handle(cls, value, **kwargs):
"""Use a value from the environment or fall back to a default if the
environment doesn't contain the variable.
Format of value:
<env_var>::<default value>
For example:
Groups: ${default app_security_groups::sg-12345,sg-6789... | Use a value from the environment or fall back to a default if the
environment doesn't contain the variable.
Format of value:
<env_var>::<default value>
For example:
Groups: ${default app_security_groups::sg-12345,sg-67890}
If `app_security_groups` is defin... |
def _signal_handler(self, signal_interupt, frame): # pylint: disable=W0613
"""Handle singal interrupt.
Args:
signal_interupt ([type]): [Description]
frame ([type]): [Description]
"""
if self.container is not None:
print('{}{}Stopping docker container... | Handle singal interrupt.
Args:
signal_interupt ([type]): [Description]
frame ([type]): [Description] |
def _init_browser(self):
"""Update this everytime the CERN SSO login form is refactored."""
self.browser = splinter.Browser('phantomjs')
self.browser.visit(self.server_url)
self.browser.find_link_by_partial_text("Sign in").click()
self.browser.fill(
'ctl00$ctl00$NICEM... | Update this everytime the CERN SSO login form is refactored. |
def load_phonopy(filename, structure, dim, symprec=0.01, primitive_matrix=None,
factor=VaspToTHz, symmetrise=True, born=None, write_fc=False):
"""Load phonopy output and return an ``phonopy.Phonopy`` object.
Args:
filename (str): Path to phonopy output. Can be any of ``FORCE_SETS``,
... | Load phonopy output and return an ``phonopy.Phonopy`` object.
Args:
filename (str): Path to phonopy output. Can be any of ``FORCE_SETS``,
``FORCE_CONSTANTS``, or ``force_constants.hdf5``.
structure (:obj:`~pymatgen.core.structure.Structure`): The unitcell
structure.
... |
def parse_command_line(self, argv=None):
"""override to allow old '-pylab' flag with deprecation warning"""
argv = sys.argv[1:] if argv is None else argv
if '-pylab' in argv:
# deprecated `-pylab` given,
# warn and transform into current syntax
argv = argv[:... | override to allow old '-pylab' flag with deprecation warning |
def start(self):
"""Starts the external measurement program."""
assert not self.is_running(), 'Attempted to start an energy measurement while one was already running.'
self._measurement_process = subprocess.Popen(
[self._executable, '-r'],
stdout=subprocess.PIPE,
... | Starts the external measurement program. |
def dist(self, src, tar):
"""Return the NCD between two strings using zlib compression.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
float
Compress... | Return the NCD between two strings using zlib compression.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
Returns
-------
float
Compression distance
Examples
... |
def _nested_relations(self, relation):
"""
Get the deeply nested relations for a given top-level relation.
:rtype: dict
"""
nested = {}
for name, constraints in self._eager_load.items():
if self._is_nested(name, relation):
nested[name[len(rel... | Get the deeply nested relations for a given top-level relation.
:rtype: dict |
def _add_default_tz_bindings(self, context, switch, network_id):
"""Configure any additional default transport zone bindings."""
default_tz = CONF.NVP.default_tz
# If there is no default tz specified it's pointless to try
# and add any additional default tz bindings.
if not defa... | Configure any additional default transport zone bindings. |
def yticksize(self, size, index=1):
"""Set the tick font size.
Parameters
----------
size : int
Returns
-------
Chart
"""
self.layout['yaxis' + str(index)]['tickfont']['size'] = size
return self | Set the tick font size.
Parameters
----------
size : int
Returns
-------
Chart |
def cursor(self, offset=0, limit=None, order_by=None, as_dict=False):
"""
See expression.fetch() for input description.
:return: query cursor
"""
if offset and limit is None:
raise DataJointError('limit is required when offset is set')
sql = self.make_sql()
... | See expression.fetch() for input description.
:return: query cursor |
def line_line_collide(line1, line2):
"""Determine if two line segments meet.
This is a helper for :func:`convex_hull_collide` in the
special case that the two convex hulls are actually
just line segments. (Even in this case, this is only
problematic if both segments are on a single line.)
Args... | Determine if two line segments meet.
This is a helper for :func:`convex_hull_collide` in the
special case that the two convex hulls are actually
just line segments. (Even in this case, this is only
problematic if both segments are on a single line.)
Args:
line1 (numpy.ndarray): ``2 x 2`` a... |
def get_loss_maps(dstore, kind):
"""
:param dstore: a DataStore instance
:param kind: 'rlzs' or 'stats'
"""
oq = dstore['oqparam']
name = 'loss_maps-%s' % kind
if name in dstore: # event_based risk
return _to_loss_maps(dstore[name].value, oq.loss_maps_dt())
name = 'loss_curves-%... | :param dstore: a DataStore instance
:param kind: 'rlzs' or 'stats' |
def get_wbfmt(self, data_nt=None):
"""Return format for text cell."""
if data_nt is None or self.b_plain:
return self.fmtname2wbfmtobj.get('plain')
# User namedtuple field/value for color
if self.ntfld_wbfmt is not None:
return self.__get_wbfmt_usrfld(data_nt)
... | Return format for text cell. |
def get_distance_to(self, origin=None, other_atoms=None, sort=False):
"""Return a Cartesian with a column for the distance from origin.
"""
if origin is None:
origin = np.zeros(3)
elif pd.api.types.is_list_like(origin):
origin = np.array(origin, dtype='f8')
... | Return a Cartesian with a column for the distance from origin. |
def load(path=None, first_data_line='auto', filters='*.*', text='Select a file, FACEHEAD.', default_directory='default_directory', quiet=True, header_only=False, transpose=False, **kwargs):
"""
Loads a data file into the databox data class. Returns the data object.
Most keyword arguments are sent to databo... | Loads a data file into the databox data class. Returns the data object.
Most keyword arguments are sent to databox.load() so check there
for documentation.(if their function isn't obvious).
Parameters
----------
path=None
Supply a path to a data file; None means use a dialog.
first_dat... |
def verify_message(self, message):
"""Verify the checksum of the message."""
if verify_checksum(
message,
self.in_checksum.get(message.id, 0),
):
self.in_checksum[message.id] = message.checksum[1]
if message.flags == FlagsType.none:
... | Verify the checksum of the message. |
def aggregate(self, rankings, epsilon, max_iters):
"""
Description:
Minorization-Maximization algorithm which returns an
estimate of the ground-truth parameters, gamma for
the given data.
Parameters:
rankings: set of rankings to aggregate
... | Description:
Minorization-Maximization algorithm which returns an
estimate of the ground-truth parameters, gamma for
the given data.
Parameters:
rankings: set of rankings to aggregate
epsilon: convergence condition value, set to None for itera... |
def user_parse(data):
"""Parse information from the provider."""
_user = data.get('user_info', {})
_id = _user.get('id') or _user.get('uid')
yield 'id', _id
yield 'locale', _user.get('default_lang')
yield 'username', _user.get('display_name')
first_name, _, last_n... | Parse information from the provider. |
def update_alias_mapping(settings, alias, new_mapping):
"""
Override `alias` mapping in the user configuration file with the given `new_mapping`, which should be a tuple with
2 or 3 elements (in the form `(project_id, activity_id, role_id)`).
"""
mapping = aliases_database[alias]
new_mapping = M... | Override `alias` mapping in the user configuration file with the given `new_mapping`, which should be a tuple with
2 or 3 elements (in the form `(project_id, activity_id, role_id)`). |
def want_host_notification(self, notifways, timeperiods, timestamp, state, n_type,
business_impact, cmd=None):
"""Check if notification options match the state of the host
:param timestamp: time we want to notify the contact (usually now)
:type timestamp: int
... | Check if notification options match the state of the host
:param timestamp: time we want to notify the contact (usually now)
:type timestamp: int
:param state: host or service state ("UP", "DOWN" ..)
:type state: str
:param n_type: type of notification ("PROBLEM", "RECOVERY" ..)... |
def post_mortem(traceback):
"""Work with an exception in a post-mortem debugger.
Try to use `ipdb` first, falling back to `pdb`.
"""
try:
from ipdb import post_mortem
except ImportError:
from pdb import post_mortem
message = "Entering post-mortem debugger. Type `help` for help.... | Work with an exception in a post-mortem debugger.
Try to use `ipdb` first, falling back to `pdb`. |
def update_interfaces(self, added_sg, updated_sg, removed_sg):
"""Handles changes to interfaces' security groups
Calls refresh_interfaces on argument VIFs. Set security groups on
added_sg's VIFs. Unsets security groups on removed_sg's VIFs.
"""
if not (added_sg or updated_sg or ... | Handles changes to interfaces' security groups
Calls refresh_interfaces on argument VIFs. Set security groups on
added_sg's VIFs. Unsets security groups on removed_sg's VIFs. |
def is_holiday(self, date):
""" Whether holiday judges
:param datetime date: datetime.date object
:rtype: bool
"""
time = [
date.year,
date.month,
date.day,
date.isoweekday(),
_extract_week_number(date)
]
... | Whether holiday judges
:param datetime date: datetime.date object
:rtype: bool |
def send_handle_delete_request(self, **args):
'''
Send a HTTP DELETE request to the handle server to delete either an
entire handle or to some specified values from a handle record,
using the requests module.
:param handle: The handle.
:param indices: Optional. A... | Send a HTTP DELETE request to the handle server to delete either an
entire handle or to some specified values from a handle record,
using the requests module.
:param handle: The handle.
:param indices: Optional. A list of indices to delete. Defaults to
None (i.e. the... |
def get_comments(self, commentable_type, id_):
"""
commentable_type: 'Press', 'Review', 'Startup', 'StartupRole', 'StatusUpdate'
"""
return _get_request(_COM.format(c_api=_C_API_BEGINNING,
ct=commentable_type,
id_=id... | commentable_type: 'Press', 'Review', 'Startup', 'StartupRole', 'StatusUpdate' |
def salt_minion():
'''
Start the salt minion in a subprocess.
Auto restart minion on error.
'''
import signal
import salt.utils.platform
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
import multiprocessing
if '' in sys.path:
s... | Start the salt minion in a subprocess.
Auto restart minion on error. |
def post_process_data(self, voltage=None, incremental_capacity=None,
voltage_step=None):
"""perform post-processing (smoothing, normalisation, interpolation) of
the data"""
logging.debug("post-processing data")
if voltage is None:
voltage = self.vo... | perform post-processing (smoothing, normalisation, interpolation) of
the data |
def parseJSON(js):
"""
{
kv_type : "",
type : "",
actors : <Actors list>
[
{
actorName : <String>,
formula: <String>,
events: ["->b", "b->"],
tr... | {
kv_type : "",
type : "",
actors : <Actors list>
[
{
actorName : <String>,
formula: <String>,
events: ["->b", "b->"],
trace: [],
speed: 1,... |
def get_dataset(self, ds_name, mode='r'):
"""
Returns a h5py dataset given its registered name.
:param ds_name: string
Name of the dataset to be returned.
:return:
"""
if ds_name in self._datasets:
return self._datasets[ds_name]
else:
... | Returns a h5py dataset given its registered name.
:param ds_name: string
Name of the dataset to be returned.
:return: |
def meter_data_from_json(data, orient="list"):
""" Load meter data from json.
Default format::
[
['2017-01-01T00:00:00+00:00', 3.5],
['2017-02-01T00:00:00+00:00', 0.4],
['2017-03-01T00:00:00+00:00', 0.46],
]
Parameters
----------
data : :any:`li... | Load meter data from json.
Default format::
[
['2017-01-01T00:00:00+00:00', 3.5],
['2017-02-01T00:00:00+00:00', 0.4],
['2017-03-01T00:00:00+00:00', 0.46],
]
Parameters
----------
data : :any:`list`
List elements are each a rows of data.
... |
def inject(self, raw_data, row_change_callback=None):
""" Use this function to add rows or update existing rows in the
spreadsheet.
Args:
raw_data (dict): A dictionary of dictionaries. Where the keys of the
outer dictionary uniquely identify each row of data, a... | Use this function to add rows or update existing rows in the
spreadsheet.
Args:
raw_data (dict): A dictionary of dictionaries. Where the keys of the
outer dictionary uniquely identify each row of data, and the inner
dictionaries represent the field,value p... |
def on_done(self):
"""
Reimplemented from :meth:`~AsyncViewBase.on_done`
"""
if self._d:
self._d.callback(self)
self._d = None | Reimplemented from :meth:`~AsyncViewBase.on_done` |
def enforce_timezone(cls, value):
"""
When `self.default_timezone` is `None`, always return naive datetimes.
When `self.default_timezone` is not `None`, always return aware datetimes.
"""
field_timezone = cls.default_timezone()
if (field_timezone is not None) and not is_... | When `self.default_timezone` is `None`, always return naive datetimes.
When `self.default_timezone` is not `None`, always return aware datetimes. |
def create(name, dry_run, verbose, query=None, parent=None):
"""Create new collection."""
if parent is not None:
parent = Collection.query.filter_by(name=parent).one().id
collection = Collection(name=name, dbquery=query, parent_id=parent)
db.session.add(collection)
if verbose:
click.... | Create new collection. |
def box(self, x0, y0, width, height):
"""Create a box on ASCII canvas.
Args:
x0 (int): x coordinate of the box corner.
y0 (int): y coordinate of the box corner.
width (int): box width.
height (int): box height.
"""
assert width > 1
... | Create a box on ASCII canvas.
Args:
x0 (int): x coordinate of the box corner.
y0 (int): y coordinate of the box corner.
width (int): box width.
height (int): box height. |
def masses_of_galaxies_within_circles_in_units(self, radius : dim.Length, unit_mass='angular',
critical_surface_density=None):
"""Compute the total mass of all galaxies in this plane within a circle of specified radius.
See *galaxy.angular_mass_within_... | Compute the total mass of all galaxies in this plane within a circle of specified radius.
See *galaxy.angular_mass_within_circle* and *mass_profiles.angular_mass_within_circle* for details
of how this is performed.
Parameters
----------
radius : float
The radius of ... |
def convert_pmod(pmod):
"""Update BEL1 pmod() protein modification term"""
if pmod.args[0].value in spec["bel1_migration"]["protein_modifications"]:
pmod.args[0].value = spec["bel1_migration"]["protein_modifications"][
pmod.args[0].value
]
return pmod | Update BEL1 pmod() protein modification term |
def _tensor_proto_to_health_pill(self, tensor_event, node_name, device,
output_slot):
"""Converts an event_accumulator.TensorEvent to a HealthPillEvent.
Args:
tensor_event: The event_accumulator.TensorEvent to convert.
node_name: The name of the node (without the ... | Converts an event_accumulator.TensorEvent to a HealthPillEvent.
Args:
tensor_event: The event_accumulator.TensorEvent to convert.
node_name: The name of the node (without the output slot).
device: The device.
output_slot: The integer output slot this health pill is relevant to.
Returns... |
def set_step(self, value, block_events=False):
"""
Sets the step of the number box.
Setting block_events=True will temporarily block the widget from
sending any signals when setting the value.
"""
if block_events: self.block_events()
self._widget.setSingleStep(va... | Sets the step of the number box.
Setting block_events=True will temporarily block the widget from
sending any signals when setting the value. |
def download_and_compile_igraph(self):
"""Downloads and compiles the C core of igraph."""
print("We will now try to download and compile the C core from scratch.")
print("Version number of the C core: %s" % self.c_core_versions[0])
if len(self.c_core_versions) > 1:
print("We ... | Downloads and compiles the C core of igraph. |
def setCurveModel(self, model):
"""Sets the stimulus model for the calibration curve test
:param model: Stimulus model that has a tone curve configured
:type model: :class:`StimulusModel <sparkle.stim.stimulus_model.StimulusModel>`
"""
self.stimModel = model
self.ui.curv... | Sets the stimulus model for the calibration curve test
:param model: Stimulus model that has a tone curve configured
:type model: :class:`StimulusModel <sparkle.stim.stimulus_model.StimulusModel>` |
def value_eq(self, other):
"""Sorted comparison of values."""
self_sorted = ordered.ordered(self.getvalues())
other_sorted = ordered.ordered(repeated.getvalues(other))
return self_sorted == other_sorted | Sorted comparison of values. |
async def reset_config(self, to_default):
"""
Restore application config to default values.
:param list to_default: A list of config options to be reset to their
default value.
"""
app_facade = client.ApplicationFacade.from_connection(self.connection)
log.debug(... | Restore application config to default values.
:param list to_default: A list of config options to be reset to their
default value. |
def preferred(self):
"""
Get the preferred subtag.
:return: preferred :class:`language_tags.Subtag.Subtag` if exists, otherwise None.
"""
if 'Preferred-Value' in self.data['record']:
preferred = self.data['record']['Preferred-Value']
type = self.data['typ... | Get the preferred subtag.
:return: preferred :class:`language_tags.Subtag.Subtag` if exists, otherwise None. |
def _expand_syntax_quote(
ctx: ReaderContext, form: IterableLispForm
) -> Iterable[LispForm]:
"""Expand syntax quoted forms to handle unquoting and unquote-splicing.
The unquoted form (unquote x) becomes:
(list x)
The unquote-spliced form (unquote-splicing x) becomes
x
All other f... | Expand syntax quoted forms to handle unquoting and unquote-splicing.
The unquoted form (unquote x) becomes:
(list x)
The unquote-spliced form (unquote-splicing x) becomes
x
All other forms are recursively processed as by _process_syntax_quoted_form
and are returned as:
(list f... |
def show_firmware_version_output_show_firmware_version_build_time(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_firmware_version = ET.Element("show_firmware_version")
config = show_firmware_version
output = ET.SubElement(show_firmware_vers... | Auto Generated Code |
def get_maintenance_window(self, id, **kwargs): # noqa: E501
"""Get a specific maintenance window # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_maintena... | Get a specific maintenance window # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_maintenance_window(id, async_req=True)
>>> result = thread.get()
... |
def _hmm_command(self, input_pipe, pairs_to_run):
r"""INTERNAL method for getting cmdline for running a batch of HMMs.
Parameters
----------
input_pipe: as hmmsearch
pairs_to_run: list
list with 2 members: (1) list of hmm and output file, (2) number of
CP... | r"""INTERNAL method for getting cmdline for running a batch of HMMs.
Parameters
----------
input_pipe: as hmmsearch
pairs_to_run: list
list with 2 members: (1) list of hmm and output file, (2) number of
CPUs to use when searching
Returns
-------
... |
def scene_on(self):
"""Trigger group/scene to ON level."""
user_data = Userdata({'d1': self._group,
'd2': 0x00,
'd3': 0x00,
'd4': 0x11,
'd5': 0xff,
'd6': ... | Trigger group/scene to ON level. |
def set_hosts_file_entry_for_role(self, role_name, network_name='user-net', fqdn=None, domain_name=None):
"""Adds an entry to the hosts file for a scenario host given
the role name and network name
:param role_name: (str) role name of the host to add
:param network_name: (str) Name of t... | Adds an entry to the hosts file for a scenario host given
the role name and network name
:param role_name: (str) role name of the host to add
:param network_name: (str) Name of the network to add to the hosts file
:param fqdn: (str) Fully qualified domain name to use in the hosts file e... |
def mkdir(path):
"""Make a directory and its parents.
Args:
path (str): path to create
Returns:
None
Raises:
OSError if the directory cannot be created.
"""
try:
os.makedirs(path)
# sanity check
if not os.path.isdir(path): # pragma: no cover
... | Make a directory and its parents.
Args:
path (str): path to create
Returns:
None
Raises:
OSError if the directory cannot be created. |
def events(self, year, simple=False, keys=False):
"""
Get a list of events in a given year.
:param year: Year to get events from.
:param keys: Get only keys of the events rather than full data.
:param simple: Get only vital data.
:return: List of string event keys or Eve... | Get a list of events in a given year.
:param year: Year to get events from.
:param keys: Get only keys of the events rather than full data.
:param simple: Get only vital data.
:return: List of string event keys or Event objects. |
def move(self, path, raise_if_exists=False):
"""
Call MockFileSystem's move command
"""
self.fs.move(self.path, path, raise_if_exists) | Call MockFileSystem's move command |
def validate_is_primary(self, is_primary):
"""
Validate the provided 'is_primary' parameter.
Returns:
The validated 'is_primary' value.
Raises:
serializers.ValidationError:
If the user attempted to mark an unverified email as
thei... | Validate the provided 'is_primary' parameter.
Returns:
The validated 'is_primary' value.
Raises:
serializers.ValidationError:
If the user attempted to mark an unverified email as
their primary email address. |
def referenceable(method):
"""Used in BaseSerializer and its sub-classes to flatten referenceable
values. Hide the reference handling from sub-classes.
For example, to make strings referenceable in a sub-class only use
this decorator with decorate flatten_str()."""
def wrapper(self, value, *args):
... | Used in BaseSerializer and its sub-classes to flatten referenceable
values. Hide the reference handling from sub-classes.
For example, to make strings referenceable in a sub-class only use
this decorator with decorate flatten_str(). |
def get_annotated_chain_sequence_string(self, chain_id, use_seqres_sequences_if_possible, raise_Exception_if_not_found = True):
'''A helper function to return the Sequence for a chain. If use_seqres_sequences_if_possible then we return the SEQRES
Sequence if it exists. We return a tuple of values, th... | A helper function to return the Sequence for a chain. If use_seqres_sequences_if_possible then we return the SEQRES
Sequence if it exists. We return a tuple of values, the first identifying which sequence was returned. |
def create_binding(site, hostheader='', ipaddress='*', port=80, protocol='http',
sslflags=None):
'''
Create an IIS Web Binding.
.. note::
This function only validates against the binding
ipaddress:port:hostheader combination, and will return True even if the
bind... | Create an IIS Web Binding.
.. note::
This function only validates against the binding
ipaddress:port:hostheader combination, and will return True even if the
binding already exists with a different configuration. It will not
modify the configuration of an existing binding.
Arg... |
def _show_loading_page(self):
"""Show animation while the kernel is loading."""
self.shellwidget.hide()
self.infowidget.show()
self.info_page = self.loading_page
self.set_info_page() | Show animation while the kernel is loading. |
def pop_marker(self, reset):
""" Pop a marker off of the marker stack. If reset is True then the
iterator will be returned to the state it was in before the
corresponding call to push_marker().
"""
saved = self.saved_markers.pop()
if reset:
self.marker = sa... | Pop a marker off of the marker stack. If reset is True then the
iterator will be returned to the state it was in before the
corresponding call to push_marker(). |
def plot_all(*args, **kwargs):
'''
Read all the trial data and plot the result of applying a function on them.
'''
dfs = do_all(*args, **kwargs)
ps = []
for line in dfs:
f, df, config = line
df.plot(title=config['name'])
ps.append(df)
return ps | Read all the trial data and plot the result of applying a function on them. |
def gather_facts_list(self, file):
"""
Return a list of facts.
"""
facts = []
contents = utils.file_to_string(os.path.join(self.paths["role"],
file))
contents = re.sub(r"\s+", "", contents)
matches = self.regex_facts.findal... | Return a list of facts. |
def select_objects(self, json_string, expr):
"""
Return list of elements from _json_string_, matching [ http://objectpath.org// | ObjectPath] expression.
*Args:*\n
_json_string_ - JSON string;\n
_expr_ - ObjectPath expression;
*Returns:*\n
List of found elements... | Return list of elements from _json_string_, matching [ http://objectpath.org// | ObjectPath] expression.
*Args:*\n
_json_string_ - JSON string;\n
_expr_ - ObjectPath expression;
*Returns:*\n
List of found elements. If no elements were found, empty list will be returned
... |
def checksum(command):
"""Function to calculate checksum as per Satel manual."""
crc = 0x147A
for b in command:
# rotate (crc 1 bit left)
crc = ((crc << 1) & 0xFFFF) | (crc & 0x8000) >> 15
crc = crc ^ 0xFFFF
crc = (crc + (crc >> 8) + b) & 0xFFFF
return crc | Function to calculate checksum as per Satel manual. |
def reinitialize_command(self, command, reinit_subcommands=0):
"""
Supplement reinitialize_command to work around
http://bugs.python.org/issue20819
"""
cmd = self.distribution.reinitialize_command(
command, reinit_subcommands)
if command in ('install', 'instal... | Supplement reinitialize_command to work around
http://bugs.python.org/issue20819 |
def get_output_volume():
'''
Get the output volume (range 0 to 100)
CLI Example:
.. code-block:: bash
salt '*' desktop.get_output_volume
'''
cmd = 'osascript -e "get output volume of (get volume settings)"'
call = __salt__['cmd.run_all'](
cmd,
output_loglevel='debu... | Get the output volume (range 0 to 100)
CLI Example:
.. code-block:: bash
salt '*' desktop.get_output_volume |
def _add_junction(item):
'''
Adds a junction to the _current_statement.
'''
type_, channels = _expand_one_key_dictionary(item)
junction = UnnamedStatement(type='junction')
for item in channels:
type_, value = _expand_one_key_dictionary(item)
channel = UnnamedStatement(type='chann... | Adds a junction to the _current_statement. |
def query(self, query_text, n=10):
"""Return a list of n (score, docid) pairs for the best matches.
Also handle the special syntax for 'learn: command'."""
if query_text.startswith("learn:"):
doctext = os.popen(query_text[len("learn:"):], 'r').read()
self.index_document(d... | Return a list of n (score, docid) pairs for the best matches.
Also handle the special syntax for 'learn: command'. |
def getClassPath():
""" Get the full java class path.
Includes user added paths and the environment CLASSPATH.
"""
global _CLASSPATHS
global _SEP
out=[]
for path in _CLASSPATHS:
if path=='':
continue
if path.endswith('*'):
paths=_glob.glob(path+".jar"... | Get the full java class path.
Includes user added paths and the environment CLASSPATH. |
def bookSSE(symbols=None, on_data=None, token='', version=''):
'''Book shows IEX’s bids and asks for given symbols.
https://iexcloud.io/docs/api/#deep-book
Args:
symbols (string); Tickers to request
on_data (function): Callback on data
token (string); Access token
version (... | Book shows IEX’s bids and asks for given symbols.
https://iexcloud.io/docs/api/#deep-book
Args:
symbols (string); Tickers to request
on_data (function): Callback on data
token (string); Access token
version (string); API version |
def chart_type(cls, plot):
"""
Return the member of :ref:`XlChartType` that corresponds to the chart
type of *plot*.
"""
try:
chart_type_method = {
'AreaPlot': cls._differentiate_area_chart_type,
'Area3DPlot': cls._differentiate_a... | Return the member of :ref:`XlChartType` that corresponds to the chart
type of *plot*. |
def get_inline_views_from_fieldsets(fieldsets):
"""Returns a list of field names from an admin fieldsets structure."""
inline_views = []
for _, opts in fieldsets or ():
if 'fieldsets' in opts:
inline_views += get_inline_views_from_fieldsets(opts.get('fieldsets'))
elif 'inline_vie... | Returns a list of field names from an admin fieldsets structure. |
def plot_border(mask, should_plot_border, units, kpc_per_arcsec, pointsize, zoom_offset_pixels):
"""Plot the borders of the mask or the array on the figure.
Parameters
-----------t.
mask : ndarray of data.array.mask.Mask
The mask applied to the array, the edge of which is plotted as a set of po... | Plot the borders of the mask or the array on the figure.
Parameters
-----------t.
mask : ndarray of data.array.mask.Mask
The mask applied to the array, the edge of which is plotted as a set of points over the plotted array.
should_plot_border : bool
If a mask is supplied, its borders pi... |
def to_file(self, output_file, smooth_fwhm=0, outdtype=None):
"""Save the Numpy array created from to_matrix function to the output_file.
Will save into the file: outmat, mask_indices, vol_shape and self.others (put here whatever you want)
data: Numpy array with shape N x prod(vol.shape)
... | Save the Numpy array created from to_matrix function to the output_file.
Will save into the file: outmat, mask_indices, vol_shape and self.others (put here whatever you want)
data: Numpy array with shape N x prod(vol.shape)
containing the N files as flat vectors.
mas... |
def null_space(M, k, k_skip=1, eigen_solver='arpack',
random_state=None, solver_kwds=None):
"""
Find the null space of a matrix M: eigenvectors associated with 0 eigenvalues
Parameters
----------
M : {array, matrix, sparse matrix, LinearOperator}
Input covariance matrix: shou... | Find the null space of a matrix M: eigenvectors associated with 0 eigenvalues
Parameters
----------
M : {array, matrix, sparse matrix, LinearOperator}
Input covariance matrix: should be symmetric positive semi-definite
k : integer
Number of eigenvalues/vectors to return
k_skip : int... |
def coupleTo_vswitch(userid, vswitch_name):
""" Couple to vswitch.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:network_info: dict of network info
"""
print("\nCoupleing to vswitch for %s ..." % userid)
vswitch_info = client.send_request('guest_nic_c... | Couple to vswitch.
Input parameters:
:userid: USERID of the guest, last 8 if length > 8
:network_info: dict of network info |
def start(grains=False, grain_keys=None, pillar=False, pillar_keys=None):
'''
Execute the Thorium runtime
'''
state = salt.thorium.ThorState(
__opts__,
grains,
grain_keys,
pillar,
pillar_keys)
state.start_runtime() | Execute the Thorium runtime |
def uchroot(*args, **kwargs):
"""
Return a customizable uchroot command.
Args:
args: List of additional arguments for uchroot (typical: mounts)
Return:
chroot_cmd
"""
uchroot_cmd = with_mounts(*args, uchroot_cmd_fn=no_llvm, **kwargs)
return uchroot_cmd["--"] | Return a customizable uchroot command.
Args:
args: List of additional arguments for uchroot (typical: mounts)
Return:
chroot_cmd |
def remove_handlers_bound_to_instance(self, obj):
"""
Remove all handlers bound to given object instance.
This is useful to remove all handler methods that are part of an instance.
:param object obj: Remove handlers that are methods of this instance
"""
for handler in se... | Remove all handlers bound to given object instance.
This is useful to remove all handler methods that are part of an instance.
:param object obj: Remove handlers that are methods of this instance |
def _get_available_encodings():
"""Get a list of the available encodings to make it easy to
tab-complete the command line interface.
Inspiration from http://stackoverflow.com/a/3824405/564709
"""
available_encodings = set(encodings.aliases.aliases.values())
paths = [os.path.dirname(encodings.__... | Get a list of the available encodings to make it easy to
tab-complete the command line interface.
Inspiration from http://stackoverflow.com/a/3824405/564709 |
def save(self) -> None:
"""
Saves all changed values to the database.
"""
for name, field in self.fields.items():
value = self.cleaned_data[name]
if isinstance(value, UploadedFile):
# Delete old file
fname = self._s.get(name, as_typ... | Saves all changed values to the database. |
def delete_job(job_id,
deployment_name,
token_manager=None,
app_url=defaults.APP_URL):
"""
delete a job with a specific job id
"""
headers = token_manager.get_access_token_headers()
data_url = get_data_url_for_job(job_id,
... | delete a job with a specific job id |
def open(self, filename, mode='r', bufsize=-1):
"""
Open a file on the remote system and return a file-like object.
"""
sftp_client = self.open_sftp()
return sftp_client.open(filename, mode, bufsize) | Open a file on the remote system and return a file-like object. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.