code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def range_(range, no_border, html):
"""Prints the given range in a formatted table either in a plain ASCII or HTML.
The only required argument is the range definition, e.g. "A2s+ A5o+ 55+"
"""
from .hand import Range
border = not no_border
result = Range(range).to_html() if html else Range(rang... | Prints the given range in a formatted table either in a plain ASCII or HTML.
The only required argument is the range definition, e.g. "A2s+ A5o+ 55+" |
def _compute(self):
"""Compute y min and max and y scale and set labels"""
self.min_ = self._min or 0
self.max_ = self._max or 0
if self.max_ - self.min_ == 0:
self.min_ -= 1
self.max_ += 1
self._box.set_polar_box(0, 1, self.min_, self.max_) | Compute y min and max and y scale and set labels |
def deprecated(replacement=None, message=None):
"""
Decorator to mark classes or functions as deprecated,
with a possible replacement.
Args:
replacement (callable): A replacement class or method.
message (str): A warning message to be displayed.
Returns:
Original function, ... | Decorator to mark classes or functions as deprecated,
with a possible replacement.
Args:
replacement (callable): A replacement class or method.
message (str): A warning message to be displayed.
Returns:
Original function, but with a warning to use the updated class. |
def hget(self, hashkey, attribute):
"""Emulate hget."""
redis_hash = self._get_hash(hashkey, 'HGET')
return redis_hash.get(self._encode(attribute)) | Emulate hget. |
def get_parser():
"Specifies the arguments and defaults, and returns the parser."
parser = argparse.ArgumentParser(prog="hiwenet")
parser.add_argument("-f", "--in_features_path", action="store", dest="in_features_path",
required=True,
help="Abs. path to file... | Specifies the arguments and defaults, and returns the parser. |
def enabled(name, runas=None):
'''
Ensure the RabbitMQ plugin is enabled.
name
The name of the plugin
runas
The user to run the rabbitmq-plugin command as
'''
ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}
try:
plugin_enabled = __salt__['rabbitm... | Ensure the RabbitMQ plugin is enabled.
name
The name of the plugin
runas
The user to run the rabbitmq-plugin command as |
def find_from(path):
"""Find path of an .ensime config, searching recursively upward from path.
Args:
path (str): Path of a file or directory from where to start searching.
Returns:
str: Canonical path of nearest ``.ensime``, or ``None`` if not found.
"""
... | Find path of an .ensime config, searching recursively upward from path.
Args:
path (str): Path of a file or directory from where to start searching.
Returns:
str: Canonical path of nearest ``.ensime``, or ``None`` if not found. |
def segment_intersection1(start0, end0, start1, end1, s):
"""Image for :func:`.segment_intersection` docstring."""
if NO_IMAGES:
return
line0 = bezier.Curve.from_nodes(stack1d(start0, end0))
line1 = bezier.Curve.from_nodes(stack1d(start1, end1))
ax = line0.plot(2)
line1.plot(256, ax=ax)... | Image for :func:`.segment_intersection` docstring. |
def make_tuple(stream, tuple_key, values, roots=None):
"""Creates a HeronTuple
:param stream: protobuf message ``StreamId``
:param tuple_key: tuple id
:param values: a list of values
:param roots: a list of protobuf message ``RootId``
"""
component_name = stream.component_name
stream_id... | Creates a HeronTuple
:param stream: protobuf message ``StreamId``
:param tuple_key: tuple id
:param values: a list of values
:param roots: a list of protobuf message ``RootId`` |
def elasticsearch_matcher(text_log_error):
"""
Query Elasticsearch and score the results.
Uses a filtered search checking test, status, expected, and the message
as a phrase query with non-alphabet tokens removed.
"""
# Note: Elasticsearch is currently disabled in all environments (see bug 1527... | Query Elasticsearch and score the results.
Uses a filtered search checking test, status, expected, and the message
as a phrase query with non-alphabet tokens removed. |
def _get_dataruns(self):
'''Returns a list of dataruns, in order.
'''
if self._data_runs is None:
raise DataStreamError("Resident datastream don't have dataruns")
if not self._data_runs_sorted:
self._data_runs.sort(key=_itemgetter(0))
self._data_runs_... | Returns a list of dataruns, in order. |
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if argv is None:
argv = sys.argv
# setup command line parser
parser = U.OptionParser(version="%prog version: $Id$",
usage=usage,
... | script main.
parses command line options in sys.argv, unless *argv* is given. |
def IterateAllClientSnapshots(self, min_last_ping=None, batch_size=50000):
"""Iterates over all available clients and yields client snapshot objects.
Args:
min_last_ping: If provided, only snapshots for clients with last-ping
timestamps newer than (or equal to) the given value will be returned.
... | Iterates over all available clients and yields client snapshot objects.
Args:
min_last_ping: If provided, only snapshots for clients with last-ping
timestamps newer than (or equal to) the given value will be returned.
batch_size: Always reads <batch_size> snapshots at a time.
Yields:
... |
def _sendline(self, line):
"""Send exactly one line to the device
Args:
line str: data send to device
"""
logging.info('%s: sending line', self.port)
# clear buffer
self._lines = []
try:
self._read()
except socket.error:
... | Send exactly one line to the device
Args:
line str: data send to device |
def interp_value(mass, age, feh, icol,
grid, mass_col, ages, fehs, grid_Ns):
# return_box):
"""mass, age, feh are *single values* at which values are desired
icol is the column index of desired value
grid is nfeh x nage x max(nmass) x ncols array
mass_col is the colum... | mass, age, feh are *single values* at which values are desired
icol is the column index of desired value
grid is nfeh x nage x max(nmass) x ncols array
mass_col is the column index of mass
ages is grid of ages
fehs is grid of fehs
grid_Ns keeps track of nmass in each slice (beyond this are nans... |
def validate_gcs_path(path, require_object):
""" Check whether a given path is a valid GCS path.
Args:
path: the config to check.
require_object: if True, the path has to be an object path but not bucket path.
Raises:
Exception if the path is invalid
"""
bucket, key = datalab.storage._bucket.par... | Check whether a given path is a valid GCS path.
Args:
path: the config to check.
require_object: if True, the path has to be an object path but not bucket path.
Raises:
Exception if the path is invalid |
def view_dupl_sources(token, dstore):
"""
Show the sources with the same ID and the truly duplicated sources
"""
fields = ['source_id', 'code', 'gidx1', 'gidx2', 'num_ruptures']
dic = group_array(dstore['source_info'].value[fields], 'source_id')
sameid = []
dupl = []
for source_id, group... | Show the sources with the same ID and the truly duplicated sources |
def open(
self,
fs_url, # type: Text
writeable=True, # type: bool
create=False, # type: bool
cwd=".", # type: Text
default_protocol="osfs", # type: Text
):
# type: (...) -> Tuple[FS, Text]
"""Open a filesystem from a FS URL.
Returns a tup... | Open a filesystem from a FS URL.
Returns a tuple of a filesystem object and a path. If there is
no path in the FS URL, the path value will be `None`.
Arguments:
fs_url (str): A filesystem URL.
writeable (bool, optional): `True` if the filesystem must be
... |
def sepBy1(p, sep):
'''`sepBy1(p, sep)` parses one or more occurrences of `p`, separated by
`sep`. Returns a list of values returned by `p`.'''
return separated(p, sep, 1, maxt=float('inf'), end=False) | `sepBy1(p, sep)` parses one or more occurrences of `p`, separated by
`sep`. Returns a list of values returned by `p`. |
def _save_json_file(
self, file, val,
pretty=False, compact=True, sort=True, encoder=None
):
"""
Save data to json file
:param file: Writable file or path to file
:type file: FileIO | str | unicode
:param val: Value or struct to save
:type val: None |... | Save data to json file
:param file: Writable file or path to file
:type file: FileIO | str | unicode
:param val: Value or struct to save
:type val: None | int | float | str | list | dict
:param pretty: Format data to be readable (default: False)
:type pretty: bool
... |
def _format_text(self, text):
"""
Format a paragraph of free-form text for inclusion in the
help output at the current indentation level.
"""
text_width = max(self.width - self.current_indent, 11)
indent = " "*self.current_indent
return textwrap.fill(text,
... | Format a paragraph of free-form text for inclusion in the
help output at the current indentation level. |
def constant_tuples(self):
"""
Returns
-------
constants: [(String, Constant)]
"""
return [constant_tuple for tuple_prior in self.tuple_prior_tuples for constant_tuple in
tuple_prior[1].constant_tuples] + self.direct_constant_tuples | Returns
-------
constants: [(String, Constant)] |
def energy(self, strand, dotparens, temp=37.0, pseudo=False, material=None,
dangles='some', sodium=1.0, magnesium=0.0):
'''Calculate the free energy of a given sequence structure. Runs the
\'energy\' command.
:param strand: Strand on which to run energy. Strands must be either
... | Calculate the free energy of a given sequence structure. Runs the
\'energy\' command.
:param strand: Strand on which to run energy. Strands must be either
coral.DNA or coral.RNA).
:type strand: coral.DNA or coral.RNA
:param dotparens: The structure in dotparens no... |
def _finalize_ticks(self, axis, element, xticks, yticks, zticks):
"""
Apply ticks with appropriate offsets.
"""
yalignments = None
if xticks is not None:
ticks, labels, yalignments = zip(*sorted(xticks, key=lambda x: x[0]))
xticks = (list(ticks), list(labe... | Apply ticks with appropriate offsets. |
def check_errors(self, response):
" Check some common errors."
# Read content.
content = response.content
if 'status' not in content:
raise self.GeneralError('We expect a status field.')
# Return the decoded content if status is success.
if content['status'... | Check some common errors. |
def applyMassCalMs1(msrunContainer, specfile, dataFit, **kwargs):
"""Applies a correction function to the MS1 ion m/z arrays in order to
correct for a m/z dependent m/z error.
:param msrunContainer: intance of :class:`maspy.core.MsrunContainer`,
containing the :class:`maspy.core.Sai` items of the "... | Applies a correction function to the MS1 ion m/z arrays in order to
correct for a m/z dependent m/z error.
:param msrunContainer: intance of :class:`maspy.core.MsrunContainer`,
containing the :class:`maspy.core.Sai` items of the "specfile".
:param specfile: filename of an ms-run file to which the m... |
def _determine_scheduled_actions(scheduled_actions, scheduled_actions_from_pillar):
'''
helper method for present, ensure scheduled actions are setup
'''
tmp = copy.deepcopy(
__salt__['config.option'](scheduled_actions_from_pillar, {})
)
# merge with data from state
if scheduled_act... | helper method for present, ensure scheduled actions are setup |
def toggle_spot_cfg(self):
"""Show the dialog where you select graphics and a name for a place,
or hide it if already showing.
"""
if self.app.manager.current == 'spotcfg':
dummyplace = self.screendummyplace
self.ids.placetab.remove_widget(dummyplace)
... | Show the dialog where you select graphics and a name for a place,
or hide it if already showing. |
def as_xml(self):
"""Return the XML error representation.
:returntype: :etree:`ElementTree.Element`"""
result = ElementTree.Element(self.error_qname)
result.append(deepcopy(self.condition))
if self.text:
text = ElementTree.SubElement(result, self.text_qname)
... | Return the XML error representation.
:returntype: :etree:`ElementTree.Element` |
def register(self, lookup: Lookup, encoder: Encoder, decoder: Decoder, label: str=None) -> None:
"""
Registers the given ``encoder`` and ``decoder`` under the given
``lookup``. A unique string label may be optionally provided that can
be used to refer to the registration by name.
... | Registers the given ``encoder`` and ``decoder`` under the given
``lookup``. A unique string label may be optionally provided that can
be used to refer to the registration by name.
:param lookup: A type string or type string matcher function
(predicate). When the registry is querie... |
def _wait_for_exec_ready(self):
"""
Wait for response.
:return: CliResponse object coming in
:raises: TestStepTimeout, TestStepError
"""
while not self.response_received.wait(1) and self.query_timeout != 0:
if self.query_timeout != 0 and self.query_timeout < ... | Wait for response.
:return: CliResponse object coming in
:raises: TestStepTimeout, TestStepError |
def gen(self):
"""
Generate stable LogicalIds based on the prefix and given data. This method ensures that the logicalId is
deterministic and stable based on input prefix & data object. In other words:
logicalId changes *if and only if* either the `prefix` or `data_obj` changes
... | Generate stable LogicalIds based on the prefix and given data. This method ensures that the logicalId is
deterministic and stable based on input prefix & data object. In other words:
logicalId changes *if and only if* either the `prefix` or `data_obj` changes
Internally we simply use a SHA... |
def post_signup(self, user, login_user=None, send_email=None):
"""Executes post signup actions: sending the signal, logging in the user and
sending the welcome email
"""
self.signup_signal.send(self, user=user)
if (login_user is None and self.options["login_user_on_signup"]) or ... | Executes post signup actions: sending the signal, logging in the user and
sending the welcome email |
def get_objectives(self):
"""Gets the objective list resulting from the search.
return: (osid.learning.ObjectiveList) - the objective list
raise: IllegalState - list already retrieved
*compliance: mandatory -- This method must be implemented.*
"""
if self.retrieved:
... | Gets the objective list resulting from the search.
return: (osid.learning.ObjectiveList) - the objective list
raise: IllegalState - list already retrieved
*compliance: mandatory -- This method must be implemented.* |
def get_unix_ioctl_terminal_size():
"""Get the terminal size of a UNIX terminal using the ioctl UNIX command."""
def ioctl_gwinsz(fd):
try:
import fcntl
import termios
import struct
return struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
... | Get the terminal size of a UNIX terminal using the ioctl UNIX command. |
def upload(self):
"""
upload via the method configured
:return:
"""
if self.upload_method == "setup":
self.upload_by_setup()
if self.upload_method == "twine":
self.upload_by_twine()
if self.upload_method == "gemfury":
self.uploa... | upload via the method configured
:return: |
def getChangeSets(self):
"""Get all the ChangeSets of this workitem
:return: a :class:`list` contains all the
:class:`rtcclient.models.ChangeSet` objects
:rtype: list
"""
changeset_tag = ("rtc_cm:com.ibm.team.filesystem.workitems."
"change_s... | Get all the ChangeSets of this workitem
:return: a :class:`list` contains all the
:class:`rtcclient.models.ChangeSet` objects
:rtype: list |
async def get_object(self, Bucket: str, Key: str, **kwargs) -> dict:
"""
S3 GetObject. Takes same args as Boto3 documentation
Decrypts any CSE
:param Bucket: S3 Bucket
:param Key: S3 Key (filepath)
:return: returns same response as a normal S3 get_object
"""
... | S3 GetObject. Takes same args as Boto3 documentation
Decrypts any CSE
:param Bucket: S3 Bucket
:param Key: S3 Key (filepath)
:return: returns same response as a normal S3 get_object |
def wrsamp(self, expanded=False, write_dir=''):
"""
Write a wfdb header file and any associated dat files from this
object.
Parameters
----------
expanded : bool, optional
Whether to write the expanded signal (e_d_signal) instead
of the uniform si... | Write a wfdb header file and any associated dat files from this
object.
Parameters
----------
expanded : bool, optional
Whether to write the expanded signal (e_d_signal) instead
of the uniform signal (d_signal).
write_dir : str, optional
The d... |
def as_ul(self, show_leaf=True, current_linkable=False, class_current="active_link"):
"""
It returns breadcrumb as ul
"""
return self.__do_menu("as_ul", show_leaf, current_linkable, class_current) | It returns breadcrumb as ul |
def _fuzzy_custom_query(issn, titles):
"""
Este metodo constroi a lista de filtros por título de periódico que
será aplicada na pesquisa boleana como match por similaridade "should".
A lista de filtros é coletada do template de pesquisa customizada
do periódico, q... | Este metodo constroi a lista de filtros por título de periódico que
será aplicada na pesquisa boleana como match por similaridade "should".
A lista de filtros é coletada do template de pesquisa customizada
do periódico, quanto este template existir. |
def public_copy(self):
"""Yield the corresponding public node for this node."""
d = dict(chain_code=self._chain_code, depth=self._depth,
parent_fingerprint=self._parent_fingerprint,
child_index=self._child_index, public_pair=self.public_pair())
return self.__cla... | Yield the corresponding public node for this node. |
def get(self, request, bot_id, id, format=None):
"""
Get hook by id
---
serializer: HookSerializer
responseMessages:
- code: 401
message: Not authenticated
"""
return super(HookDetail, self).get(request, bot_id, id, format) | Get hook by id
---
serializer: HookSerializer
responseMessages:
- code: 401
message: Not authenticated |
def cmd_show(docid):
"""
Arguments: <doc_id>
Show document information (but not its content, see 'dump').
See 'search' for the document id.
Possible JSON replies:
--
{
"status": "error", "exception": "yyy",
"reason": "xxxx", "args": "(xxxx, )"
}
... | Arguments: <doc_id>
Show document information (but not its content, see 'dump').
See 'search' for the document id.
Possible JSON replies:
--
{
"status": "error", "exception": "yyy",
"reason": "xxxx", "args": "(xxxx, )"
}
--
{
"sta... |
def make_witness_input_and_witness(outpoint, sequence,
stack=None, **kwargs):
'''
Outpoint, int, list(bytearray) -> (Input, InputWitness)
'''
if 'decred' in riemann.get_current_network_name():
return(make_witness_input(outpoint, sequence),
make_d... | Outpoint, int, list(bytearray) -> (Input, InputWitness) |
def result(self):
""" Concatenate accumulated tensors """
return {k: torch.stack(v) for k, v in self.accumulants.items()} | Concatenate accumulated tensors |
def describe_keypairs(self, *keypair_names):
"""Returns information about key pairs available."""
keypairs = {}
for index, keypair_name in enumerate(keypair_names):
keypairs["KeyName.%d" % (index + 1)] = keypair_name
query = self.query_factory(
action="DescribeKey... | Returns information about key pairs available. |
def subprogram_prototype(vo):
'''Generate a canonical prototype string
Args:
vo (VhdlFunction, VhdlProcedure): Subprogram object
Returns:
Prototype string.
'''
plist = '; '.join(str(p) for p in vo.parameters)
if isinstance(vo, VhdlFunction):
if len(vo.parameters) > 0:
proto = 'functio... | Generate a canonical prototype string
Args:
vo (VhdlFunction, VhdlProcedure): Subprogram object
Returns:
Prototype string. |
def create_table(cls):
"""
create_table
Manually create a temporary table for model in test data base.
:return:
"""
schema_editor = getattr(connection, 'schema_editor', None)
if schema_editor:
with schema_editor() as schema_editor:
sch... | create_table
Manually create a temporary table for model in test data base.
:return: |
def find(self, title):
"""Fetch and return the first spreadsheet with the given title.
Args:
title(str): title/name of the spreadsheet to return
Returns:
SpreadSheet: new SpreadSheet instance
Raises:
KeyError: if no spreadsheet with the given ``title`... | Fetch and return the first spreadsheet with the given title.
Args:
title(str): title/name of the spreadsheet to return
Returns:
SpreadSheet: new SpreadSheet instance
Raises:
KeyError: if no spreadsheet with the given ``title`` is found |
def tgread_bool(self):
"""Reads a Telegram boolean value."""
value = self.read_int(signed=False)
if value == 0x997275b5: # boolTrue
return True
elif value == 0xbc799737: # boolFalse
return False
else:
raise RuntimeError('Invalid boolean code ... | Reads a Telegram boolean value. |
def delete_queue(queues):
"""Delete the given queues."""
current_queues.delete(queues=queues)
click.secho(
'Queues {} have been deleted.'.format(
queues or current_queues.queues.keys()),
fg='green'
) | Delete the given queues. |
def random_filter(objects, reduction_factor, seed=42):
"""
Given a list of objects, returns a sublist by extracting randomly
some elements. The reduction factor (< 1) tells how small is the extracted
list compared to the original list.
"""
assert 0 < reduction_factor <= 1, reduction_factor
r... | Given a list of objects, returns a sublist by extracting randomly
some elements. The reduction factor (< 1) tells how small is the extracted
list compared to the original list. |
def pos(self):
""" The position of this event in the local coordinate system of the
visual.
"""
if self._pos is None:
tr = self.visual.get_transform('canvas', 'visual')
self._pos = tr.map(self.mouse_event.pos)
return self._pos | The position of this event in the local coordinate system of the
visual. |
def _get_owner_cover_photo_upload_server(session, group_id, crop_x=0, crop_y=0, crop_x2=795, crop_y2=200):
"""
https://vk.com/dev/photos.getOwnerCoverPhotoUploadServer
"""
group_id = abs(group_id)
response = session.fetch("photos.getOwnerCoverPhotoUploadServer", group_id=group_id... | https://vk.com/dev/photos.getOwnerCoverPhotoUploadServer |
def parse(self, rrstr):
# type: (bytes) -> None
'''
Parse a Rock Ridge Sharing Protocol record out of a string.
Parameters:
rrstr - The string to parse the record out of.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexcep... | Parse a Rock Ridge Sharing Protocol record out of a string.
Parameters:
rrstr - The string to parse the record out of.
Returns:
Nothing. |
def _get_aggregated_node_list(self, data):
"""
Returns list of main and secondary mac addresses.
"""
node_list = []
for node in data:
local_addresses = [node['primary']]
if 'secondary' in node:
local_addresses += node['secondary']
... | Returns list of main and secondary mac addresses. |
def color_from_hls(hue, light, sat):
""" Takes a hls color and converts to proper hue
Bulbs use a BGR order instead of RGB """
if light > 0.95: #too bright, let's just switch to white
return 256
elif light < 0.05: #too dark, let's shut it off
return -1
else:
hue = (-hue ... | Takes a hls color and converts to proper hue
Bulbs use a BGR order instead of RGB |
def delay(self, seconds=0, minutes=0):
"""
Parameters
----------
seconds: float
The number of seconds to freeze in place.
"""
minutes += int(seconds / 60)
seconds = seconds % 60
seconds += float(minutes * 60)
self.robot.pause()
... | Parameters
----------
seconds: float
The number of seconds to freeze in place. |
def __request_mark_sent(self, requestId):
"""Set send time & clear exception from request if set, ignoring non-existent requests"""
with self.__requests:
try:
req = self.__requests[requestId]
except KeyError:
# request might have had a response alr... | Set send time & clear exception from request if set, ignoring non-existent requests |
async def build_proof_req_json(self, cd_id2spec: dict, cache_only: bool = False) -> str:
"""
Build and return indy-sdk proof request for input attributes and timestamps by cred def id.
Raise AbsentInterval if caller specifies cache_only and default non-revocation intervals, but
revocati... | Build and return indy-sdk proof request for input attributes and timestamps by cred def id.
Raise AbsentInterval if caller specifies cache_only and default non-revocation intervals, but
revocation cache does not have delta frames for any revocation registries on a specified cred def.
:param cd... |
def result(self, state, action):
'''Return the resulting state after moving a piece to the empty space.
(the "action" parameter contains the piece to move)
'''
rows = string_to_list(state)
row_e, col_e = find_location(rows, 'e')
row_n, col_n = find_location(rows, actio... | Return the resulting state after moving a piece to the empty space.
(the "action" parameter contains the piece to move) |
def _iso_handler(obj):
"""
Transforms an object into it's ISO format, if possible.
If the object can't be transformed, then an error is raised for the JSON
parser.
This is meant to be used on datetime instances, but will work with any
object having a method called isoformat.
:param obj: o... | Transforms an object into it's ISO format, if possible.
If the object can't be transformed, then an error is raised for the JSON
parser.
This is meant to be used on datetime instances, but will work with any
object having a method called isoformat.
:param obj: object to transform into it's ISO fo... |
def get_advances_declines(self, as_json=False):
"""
:return: a list of dictionaries with advance decline data
:raises: URLError, HTTPError
"""
url = self.advances_declines_url
req = Request(url, None, self.headers)
# raises URLError or HTTPError
resp = sel... | :return: a list of dictionaries with advance decline data
:raises: URLError, HTTPError |
def is_avro(path_or_buffer):
"""Return True if path (or buffer) points to an Avro file.
Parameters
----------
path_or_buffer: path to file or file-like object
Path to file
"""
if is_str(path_or_buffer):
fp = open(path_or_buffer, 'rb')
close = True
else:
fp = ... | Return True if path (or buffer) points to an Avro file.
Parameters
----------
path_or_buffer: path to file or file-like object
Path to file |
def sendhello(self):
try:
# send hello
cli_hello_msg = "<hello>\n" +\
" <capabilities>\n" +\
" <capability>urn:ietf:params:netconf:base:1.0</capability>\n" +\
" </capabilities>\n" +\
... | end of function exchgcaps |
def field(self, name):
"""
Returns the field on this struct with the given name. Will try to find this
name on all ancestors if this struct extends another.
If found, returns a dict with keys: 'name', 'comment', 'type', 'is_array'
If not found, returns None
:Parameters... | Returns the field on this struct with the given name. Will try to find this
name on all ancestors if this struct extends another.
If found, returns a dict with keys: 'name', 'comment', 'type', 'is_array'
If not found, returns None
:Parameters:
name
string name of... |
def create_marking_iobject(self,
uid=None,
timestamp=timezone.now(),
metadata_dict=None,
id_namespace_uri=DINGOS_DEFAULT_ID_NAMESPACE_URI,
iobject_family_name=DINGOS... | A specialized version of create_iobject with defaults set such that a default marking object is created. |
def _check_samples_line(klass, arr):
"""Peform additional check on samples line"""
if len(arr) <= len(REQUIRE_NO_SAMPLE_HEADER):
if tuple(arr) != REQUIRE_NO_SAMPLE_HEADER:
raise exceptions.IncorrectVCFFormat(
"Sample header line indicates no sample but doe... | Peform additional check on samples line |
def user_lookup(self, ids, id_type="user_id"):
"""
A generator that returns users for supplied user ids, screen_names,
or an iterator of user_ids of either. Use the id_type to indicate
which you are supplying (user_id or screen_name)
"""
if id_type not in ['user_id', 'sc... | A generator that returns users for supplied user ids, screen_names,
or an iterator of user_ids of either. Use the id_type to indicate
which you are supplying (user_id or screen_name) |
def _generate_type_code_query(self, value):
"""Generate type-code queries.
Notes:
If the value of the type-code query exists in `TYPECODE_VALUE_TO_FIELD_AND_VALUE_PAIRS_MAPPING, then we
query the specified field, along with the given value according to the mapping.
S... | Generate type-code queries.
Notes:
If the value of the type-code query exists in `TYPECODE_VALUE_TO_FIELD_AND_VALUE_PAIRS_MAPPING, then we
query the specified field, along with the given value according to the mapping.
See: https://github.com/inspirehep/inspire-query-parser/... |
def convert_rect(self, rect):
'''
Converts the relative position of @rect into an absolute position.To be
used for event considerations, blitting is handled directly by the
Container().
'''
return self.container.convert_rect(rect.move(self.pos)) | Converts the relative position of @rect into an absolute position.To be
used for event considerations, blitting is handled directly by the
Container(). |
def inspiral_range(psd, snr=8, mass1=1.4, mass2=1.4, fmin=None, fmax=None,
horizon=False):
"""Calculate the inspiral sensitive distance from a GW strain PSD
The method returns the distance (in megaparsecs) to which an compact
binary inspiral with the given component masses would be detec... | Calculate the inspiral sensitive distance from a GW strain PSD
The method returns the distance (in megaparsecs) to which an compact
binary inspiral with the given component masses would be detectable
given the instrumental PSD. The calculation is as defined in:
https://dcc.ligo.org/LIGO-T030276/public... |
def do_stack(self,args):
"""Go to the specified stack. stack -h for detailed help."""
parser = CommandArgumentParser("stack")
parser.add_argument(dest='stack',help='stack index or name');
args = vars(parser.parse_args(args))
print "loading stack {}".format(args['stack'])
... | Go to the specified stack. stack -h for detailed help. |
def all_instr(self, start, end, instr, target=None, include_beyond_target=False):
"""
Find all `instr` in the block from start to end.
`instr` is any Python opcode or a list of opcodes
If `instr` is an opcode with a target (like a jump), a target
destination can be specified whic... | Find all `instr` in the block from start to end.
`instr` is any Python opcode or a list of opcodes
If `instr` is an opcode with a target (like a jump), a target
destination can be specified which must match precisely.
Return a list with indexes to them or [] if none found. |
def update_config(self, d):
"""
Updates the config object.
:param d: dict
"""
for key, value in d.items():
if hasattr(self, key):
if key == "requirements":
items, value = value, []
for item in items:
... | Updates the config object.
:param d: dict |
def list_all_zip_codes_geo_zones(cls, **kwargs):
"""List ZipCodesGeoZones
Return a list of ZipCodesGeoZones
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_zip_codes_geo_zones(async=T... | List ZipCodesGeoZones
Return a list of ZipCodesGeoZones
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_zip_codes_geo_zones(async=True)
>>> result = thread.get()
:param async... |
def _register_elements(self, elements):
""" Takes elements from the metadata class and creates a base model for all backend models .
"""
self.elements = elements
for key, obj in elements.items():
obj.contribute_to_class(self.metadata, key)
# Create the common Django... | Takes elements from the metadata class and creates a base model for all backend models . |
def tlog_inv(y, th=1, r=_display_max, d=_l_mmax):
"""
Inverse truncated log10 transform.
Values
Parameters
----------
y : num | num iterable
values to be transformed.
th : num
Inverse values below th are transormed to th.
Must be > positive.
r : num (default = 10... | Inverse truncated log10 transform.
Values
Parameters
----------
y : num | num iterable
values to be transformed.
th : num
Inverse values below th are transormed to th.
Must be > positive.
r : num (default = 10**4)
maximal transformed value.
d : num (default =... |
def adjustWPPointer(self):
'''Adjust the position and orientation of
the waypoint pointer.'''
self.headingWPText.set_size(self.fontSize)
headingRotate = mpl.transforms.Affine2D().rotate_deg_around(0.0,0.0,-self.wpBearing+self.heading)+self.axes.transData
self.headingWPText.set_t... | Adjust the position and orientation of
the waypoint pointer. |
def get_summarizer(self, name):
'''
import summarizers on-demand
'''
if name in self.summarizers:
pass
elif name == 'lexrank':
from . import lexrank
self.summarizers[name] = lexrank.summarize
elif name == 'mcp':
from . impor... | import summarizers on-demand |
def _get_object_from_python_path(python_path):
"""Method that will fetch a Marshmallow schema from a path to it.
Args:
python_path (str): The string path to the Marshmallow schema.
Returns:
marshmallow.Schema: The schema matching the provided path.
Raises:
... | Method that will fetch a Marshmallow schema from a path to it.
Args:
python_path (str): The string path to the Marshmallow schema.
Returns:
marshmallow.Schema: The schema matching the provided path.
Raises:
TypeError: This is raised if the specified object ... |
def _Reg2Py(data, size, data_type):
"""Converts a Windows Registry value to the corresponding Python data type."""
if data_type == winreg.REG_DWORD:
if size == 0:
return 0
# DWORD is an unsigned 32-bit integer, see:
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/262627d8-34... | Converts a Windows Registry value to the corresponding Python data type. |
def get_instance(self, payload):
"""
Build an instance of ReservationInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance
:rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.Reser... | Build an instance of ReservationInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance
:rtype: twilio.rest.taskrouter.v1.workspace.task.reservation.ReservationInstance |
def fit(self, X):
"""Compute the Robust Shared Response Model
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, timepoints]
Each element in the list contains the fMRI data of one subject.
"""
logger.info('Starting RSRM')
# ... | Compute the Robust Shared Response Model
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, timepoints]
Each element in the list contains the fMRI data of one subject. |
def read_saved_screenshot_to_array(self, screen_id, bitmap_format):
"""Screenshot in requested format is retrieved to an array of bytes.
in screen_id of type int
Saved guest screen to read from.
in bitmap_format of type :class:`BitmapFormat`
The requested format.
... | Screenshot in requested format is retrieved to an array of bytes.
in screen_id of type int
Saved guest screen to read from.
in bitmap_format of type :class:`BitmapFormat`
The requested format.
out width of type int
Image width.
out height of type i... |
def modulate(data):
'''
Generate Bell 202 AFSK samples for the given symbol generator
Consumes raw wire symbols and produces the corresponding AFSK samples.
'''
seconds_per_sample = 1.0 / audiogen.sampler.FRAME_RATE
phase, seconds, bits = 0, 0, 0
# construct generators
clock = (x / BAUD_RATE for x in itertoo... | Generate Bell 202 AFSK samples for the given symbol generator
Consumes raw wire symbols and produces the corresponding AFSK samples. |
def assemble(
iterable, patterns=None, minimum_items=2, case_sensitive=True,
assume_padded_when_ambiguous=False
):
'''Assemble items in *iterable* into discreet collections.
*patterns* may be specified as a list of regular expressions to limit
the returned collection possibilities. Use this when in... | Assemble items in *iterable* into discreet collections.
*patterns* may be specified as a list of regular expressions to limit
the returned collection possibilities. Use this when interested in
collections that only match specific patterns. Each pattern must contain
the expression from :py:data:`DIGITS_... |
def initialize_segment_register_x64(self, state, concrete_target):
"""
Set the gs register in the angr to the value of the fs register in the concrete process
:param state: state which will be modified
:param concrete_target: concrete target that will be used to read t... | Set the gs register in the angr to the value of the fs register in the concrete process
:param state: state which will be modified
:param concrete_target: concrete target that will be used to read the fs register
:return: None |
def get_rlzs_by_gsim(oqparam):
"""
Return an ordered dictionary gsim -> [realization index]. Work for
gsim logic trees with a single tectonic region type.
"""
cinfo = source.CompositionInfo.fake(get_gsim_lt(oqparam))
ra = cinfo.get_rlzs_assoc()
dic = {}
for rlzi, gsim_by_trt in enumerate... | Return an ordered dictionary gsim -> [realization index]. Work for
gsim logic trees with a single tectonic region type. |
def create(self, date_at=None, minutes=0, note='', user_id=None,
project_id=None, service_id=None):
""" date_at - date of time entry. Format YYYY-MM-DD. default: today
minutes - default: 0
note - default: '' (empty string)
user_id - default: actual user id (onl... | date_at - date of time entry. Format YYYY-MM-DD. default: today
minutes - default: 0
note - default: '' (empty string)
user_id - default: actual user id (only admin users can edit this)
project_id - default: None
service_id - default: None |
def resource_get(self, resource_name):
"""
Return resource info
:param resource_name: Resource name as returned by resource_get_list()
:type resource_name: str
:return: Resource information (empty if not found)
name: Resource name
hash: Resource hash
... | Return resource info
:param resource_name: Resource name as returned by resource_get_list()
:type resource_name: str
:return: Resource information (empty if not found)
name: Resource name
hash: Resource hash
path: Path to resource
checked: Last ti... |
def lambda_handler(event, context):
"""Main handler."""
auth = check_auth(event, role=["admin"])
if not auth['success']:
return auth
table = boto3.resource("dynamodb").Table(os.environ['database'])
results = table.scan()
output = {'success': True, 'events': list(), 'eventsCount': 0}
... | Main handler. |
def user_segment(self):
"""
| Comment: The id of the user segment to which this section belongs
"""
if self.api and self.user_segment_id:
return self.api._get_user_segment(self.user_segment_id) | | Comment: The id of the user segment to which this section belongs |
def parse_sv_frequencies(variant):
"""Parsing of some custom sv frequencies
These are very specific at the moment, this will hopefully get better over time when the
field of structural variants is more developed.
Args:
variant(cyvcf2.Variant)
Returns:
sv_frequencies(dict)
... | Parsing of some custom sv frequencies
These are very specific at the moment, this will hopefully get better over time when the
field of structural variants is more developed.
Args:
variant(cyvcf2.Variant)
Returns:
sv_frequencies(dict) |
def iter_issue_events(self, number=-1, etag=None):
"""Iterates over issue events on this repository.
:param int number: (optional), number of events to return. Default: -1
returns all available events
:param str etag: (optional), ETag from a previous request to the same
... | Iterates over issue events on this repository.
:param int number: (optional), number of events to return. Default: -1
returns all available events
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns: generator of
:class:`Is... |
def usage(ecode, msg=''):
"""
Print usage and msg and exit with given code.
"""
print >> sys.stderr, __doc__
if msg:
print >> sys.stderr, msg
sys.exit(ecode) | Print usage and msg and exit with given code. |
def set_coords(self, names, inplace=None):
"""Given names of one or more variables, set them as coordinates
Parameters
----------
names : str or list of str
Name(s) of variables in this dataset to convert into coordinates.
inplace : bool, optional
If True... | Given names of one or more variables, set them as coordinates
Parameters
----------
names : str or list of str
Name(s) of variables in this dataset to convert into coordinates.
inplace : bool, optional
If True, modify this dataset inplace. Otherwise, create a new... |
def add_consumer_tag(self, tag):
"""Add a Consumer tag.
:param str tag: Consumer tag.
:return:
"""
if not is_string(tag):
raise AMQPChannelError('consumer tag needs to be a string')
if tag not in self._consumer_tags:
self._consumer_tags.append(tag... | Add a Consumer tag.
:param str tag: Consumer tag.
:return: |
def file_or_filename(input):
"""
Return a file-like object ready to be read from the beginning. `input` is either
a filename (gz/bz2 also supported) or a file-like object supporting seek.
"""
if isinstance(input, string_types):
# input was a filename: open as file
yield smart_open(i... | Return a file-like object ready to be read from the beginning. `input` is either
a filename (gz/bz2 also supported) or a file-like object supporting seek. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.