code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def inline(self, article):
"""
Returns all inline attachments associated with article_id where (Such attachments has ``inline=True`` flag).
Inline attachments and its url can be referenced in the HTML body of the article.
:param article: Numeric article id or :class:`Article` object.
... | Returns all inline attachments associated with article_id where (Such attachments has ``inline=True`` flag).
Inline attachments and its url can be referenced in the HTML body of the article.
:param article: Numeric article id or :class:`Article` object.
:return: Generator with all associated i... |
def get_assessment_taken_admin_session(self, proxy):
"""Gets the ``OsidSession`` associated with the assessment taken administration service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.AssessmentTakenAdminSession) - an
``AssessmentTakenAdminSession``
... | Gets the ``OsidSession`` associated with the assessment taken administration service.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.AssessmentTakenAdminSession) - an
``AssessmentTakenAdminSession``
raise: NullArgument - ``proxy`` is ``null``
raise: ... |
def clip_boxes(boxes, im_shape):
"""
Clip boxes to image boundaries.
:param boxes: [N, 4* num_classes]
:param im_shape: tuple of 2
:return: [N, 4* num_classes]
"""
# x1 >= 0
boxes[:, 0::4] = np.maximum(np.minimum(boxes[:, 0::4], im_shape[1] - 1), 0)
# y1 >= 0
boxes[:, 1::4] = np.... | Clip boxes to image boundaries.
:param boxes: [N, 4* num_classes]
:param im_shape: tuple of 2
:return: [N, 4* num_classes] |
def transform_tensor(self, tensor):
"""
Applies rotation portion to a tensor. Note that tensor has to be in
full form, not the Voigt form.
Args:
tensor (numpy array): a rank n tensor
Returns:
Transformed tensor.
"""
dim = tensor.shape
... | Applies rotation portion to a tensor. Note that tensor has to be in
full form, not the Voigt form.
Args:
tensor (numpy array): a rank n tensor
Returns:
Transformed tensor. |
def subscribe(self, objectID, varIDs=None, begin=0, end=2**31 - 1):
"""subscribe(string, list(integer), double, double) -> None
Subscribe to one or more object values for the given interval.
"""
if varIDs is None:
if tc.LAST_STEP_VEHICLE_NUMBER in self._retValFunc:
... | subscribe(string, list(integer), double, double) -> None
Subscribe to one or more object values for the given interval. |
def sign(xml, stream, password=None):
"""
Sign an XML document with the given private key file. This will add a
<Signature> element to the document.
:param lxml.etree._Element xml: The document to sign
:param file stream: The private key to sign the document with
:param str password: The passwo... | Sign an XML document with the given private key file. This will add a
<Signature> element to the document.
:param lxml.etree._Element xml: The document to sign
:param file stream: The private key to sign the document with
:param str password: The password used to access the private key
:rtype: Non... |
def _mantissa(dval):
"""Extract the _mantissa bits from a double-precision floating
point value."""
bb = _double_as_bytes(dval)
mantissa = bb[1] & 0x0f << 48
mantissa += bb[2] << 40
mantissa += bb[3] << 32
mantissa += bb[4]
return mantissa | Extract the _mantissa bits from a double-precision floating
point value. |
def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the servi... | Return the status for a service.
If the name contains globbing, a dict mapping service name to True/False
values is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Signature... |
def connect(dbapi_connection, connection_record):
"""
Called once by SQLAlchemy for each new SQLite DB-API connection.
Here is where we issue some PRAGMA statements to configure how we're
going to access the SQLite database.
@param dbapi_connection:
A newly connecte... | Called once by SQLAlchemy for each new SQLite DB-API connection.
Here is where we issue some PRAGMA statements to configure how we're
going to access the SQLite database.
@param dbapi_connection:
A newly connected raw SQLite DB-API connection.
@param connection_record:
... |
def _parse_ip_stats_link_show(raw_result):
"""
Parse the 'ip -s link show dev <dev>' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show interface command in a \
dictionary of the form:
::
{
'rx_b... | Parse the 'ip -s link show dev <dev>' command raw output.
:param str raw_result: vtysh raw result string.
:rtype: dict
:return: The parsed result of the show interface command in a \
dictionary of the form:
::
{
'rx_bytes': 0,
'rx_packets': 0,
'rx_... |
def swapWH(self):
"""!
\~english Swap width and height of rectangles
\~chinese 交换矩形高宽边数据
"""
width = self.width
self.width = self.height
self.height = width | !
\~english Swap width and height of rectangles
\~chinese 交换矩形高宽边数据 |
def copy(self, copy_backends=True, copy_default_backend=True,
copy_cache=None, copy_history=None):
"""Copy the circuit.
:params
copy_backends :bool copy backends if True.
copy_default_backend :bool copy default_backend if True.
"""
copied = Circuit(self.n_qu... | Copy the circuit.
:params
copy_backends :bool copy backends if True.
copy_default_backend :bool copy default_backend if True. |
def set(self, key, val):
"""Sets a value in a key.
Args:
key (str): Key for the value.
val: Value to set.
Returns:
Retrieved value.
"""
self._create_file_if_none_exists()
with open(self.filename, 'r+b') as file_object:
cache_pickle = pickle.load(file_object)
cache... | Sets a value in a key.
Args:
key (str): Key for the value.
val: Value to set.
Returns:
Retrieved value. |
def _valmatch(vs, ss, op, varsort, semi, section):
"""
Return `True` if for every paired *v* and *s* from *vs* and *ss*:
v <> s (subsumption or equality if *semi* is `None`)
v == s (equality)
s == '*'
s == '!' and v == `None`
s == '[xyz]' and varsort == 'xyz'
"""
... | Return `True` if for every paired *v* and *s* from *vs* and *ss*:
v <> s (subsumption or equality if *semi* is `None`)
v == s (equality)
s == '*'
s == '!' and v == `None`
s == '[xyz]' and varsort == 'xyz' |
def unique_ordered(list_):
"""
Returns unique items in ``list_`` in the order they were seen.
Args:
list_ (list):
Returns:
list: unique_list - unique list which maintains order
CommandLine:
python -m utool.util_list --exec-unique_ordered
Example:
>>> # ENABLE_... | Returns unique items in ``list_`` in the order they were seen.
Args:
list_ (list):
Returns:
list: unique_list - unique list which maintains order
CommandLine:
python -m utool.util_list --exec-unique_ordered
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_lis... |
def charge_credit_card(self, credit_card_psp_object: Model, amount: Money, client_ref: str) -> Tuple[bool, Model]:
"""
:param credit_card_psp_object: an instance representing the credit card in the psp
:param amount: the amount to charge
:param client_ref: a reference that will appear on... | :param credit_card_psp_object: an instance representing the credit card in the psp
:param amount: the amount to charge
:param client_ref: a reference that will appear on the customer's credit card report
:return: a tuple (success, payment_psp_object) |
def read_wv_master_file(wv_master_file, lines='brightest', debugplot=0):
"""read arc line wavelengths from external file.
Parameters
----------
wv_master_file : string
File name of txt file containing the wavelength database.
lines : string
Indicates which lines to read. For files w... | read arc line wavelengths from external file.
Parameters
----------
wv_master_file : string
File name of txt file containing the wavelength database.
lines : string
Indicates which lines to read. For files with a single column
or two columns this parameter is irrelevant. For fil... |
def show_clock_output_clock_time_timezone(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_clock = ET.Element("show_clock")
config = show_clock
output = ET.SubElement(show_clock, "output")
clock_time = ET.SubElement(output, "clock-tim... | Auto Generated Code |
def add_basic_block(self, basic_block):
"""Adds the given basic block in the function"""
assert(isinstance(basic_block, BasicBlock))
self.basic_block_list.append(basic_block) | Adds the given basic block in the function |
def _loop_thread_main(self):
"""Main background thread running the event loop."""
asyncio.set_event_loop(self.loop)
self._loop_check.inside_loop = True
try:
self._logger.debug("Starting loop in background thread")
self.loop.run_forever()
self._logger... | Main background thread running the event loop. |
def parse_skypos(ra, dec):
"""
Function to parse RA and Dec input values and turn them into decimal
degrees
Input formats could be:
["nn","nn","nn.nn"]
"nn nn nn.nnn"
"nn:nn:nn.nn"
"nnH nnM nn.nnS" or "nnD nnM nn.nnS"
nn.nnnnnnnn
"nn.nnnnnnn"
"""
... | Function to parse RA and Dec input values and turn them into decimal
degrees
Input formats could be:
["nn","nn","nn.nn"]
"nn nn nn.nnn"
"nn:nn:nn.nn"
"nnH nnM nn.nnS" or "nnD nnM nn.nnS"
nn.nnnnnnnn
"nn.nnnnnnn" |
def plot_as_routes(route_shapes, ax=None, spatial_bounds=None, map_alpha=0.8, plot_scalebar=True, legend=True,
return_smopy_map=False, line_width_attribute=None, line_width_scale=1.0, map_style=None):
"""
Parameters
----------
route_shapes: list of dicts that should have the following... | Parameters
----------
route_shapes: list of dicts that should have the following keys
name, type, agency, lats, lons
with types
list, list, str, list, list
ax: axis object
spatial_bounds: dict
map_alpha:
plot_scalebar: bool
legend:
return_smopy_map:
... |
def accept_proposed_value(self):
"""Changes the current value to the proposed value."""
if self.proposed_value is not None:
self.current_value = self.proposed_value
self.proposed_value = None
return | Changes the current value to the proposed value. |
def getObjectForProxy(self, proxy):
"""
Returns the unproxied version of C{proxy} as stored in the context, or
unproxies the proxy and returns that 'raw' object.
@see: L{pyamf.flex.unproxy_object}
@since: 0.6
"""
obj = self.proxied_objects.get(id(proxy))
... | Returns the unproxied version of C{proxy} as stored in the context, or
unproxies the proxy and returns that 'raw' object.
@see: L{pyamf.flex.unproxy_object}
@since: 0.6 |
def polar_map(hist: Histogram2D, ax: Axes, *, show_zero: bool = True, show_colorbar: bool = True, **kwargs):
"""Polar map of polar histograms.
Similar to map, but supports less parameters."""
data = get_data(hist, cumulative=False, flatten=True,
density=kwargs.pop("density", False))
... | Polar map of polar histograms.
Similar to map, but supports less parameters. |
def _cells(nb):
"""Yield all cells in an nbformat-insensitive manner"""
if nb.nbformat < 4:
for ws in nb.worksheets:
for cell in ws.cells:
yield cell
else:
for cell in nb.cells:
yield cell | Yield all cells in an nbformat-insensitive manner |
def write_svg(self):
"""
Returns PUML from the system as a SVG image. Requires plantuml library.
"""
import plantuml
puml = self.write_puml()
server = plantuml.PlantUML(url=self.url)
svg = server.processes(puml)
return svg | Returns PUML from the system as a SVG image. Requires plantuml library. |
def __assert_param_consistency(args, argx_list_):
"""
debugging function for accepts_scalar_input2
checks to make sure all the iterable inputs are of the same length
"""
if util_arg.NO_ASSERTS:
return
if len(argx_list_) == 0:
return True
argx_flags = [util_iter.isiterable(arg... | debugging function for accepts_scalar_input2
checks to make sure all the iterable inputs are of the same length |
def calculate_shanten(self, tiles_34, open_sets_34=None, chiitoitsu=True, kokushi=True):
"""
Return the count of tiles before tempai
:param tiles_34: 34 tiles format array
:param open_sets_34: array of array of 34 tiles format
:param chiitoitsu: bool
:param kokushi: bool
... | Return the count of tiles before tempai
:param tiles_34: 34 tiles format array
:param open_sets_34: array of array of 34 tiles format
:param chiitoitsu: bool
:param kokushi: bool
:return: int |
def modify(self, contact_id, contact_name, province, city, addr, session, **kwargs):
'''taobao.logistics.address.modify 卖家地址库修改
卖家地址库修改'''
request = TOPRequest('taobao.logistics.address.modify')
request['contact_id'] = contact_id
request['contact_name'] = contact_name
... | taobao.logistics.address.modify 卖家地址库修改
卖家地址库修改 |
def language_name(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> str:
"""
Give the name of the language (not the entire tag, just the language part)
in a natural language. The target language can be given as a string or
another Language object.
By default, things are nam... | Give the name of the language (not the entire tag, just the language part)
in a natural language. The target language can be given as a string or
another Language object.
By default, things are named in English:
>>> Language.get('fr').language_name()
'French'
>>> Langua... |
def tuple_signature_for_components(components: Sequence[Mapping[str, Any]]) -> str:
"""Equivalent to ``function_signature_for_name_and_inputs('', components)``."""
ts = []
for c in components:
t: str = c['type']
if t.startswith('tuple'):
assert len(t) == 5... | Equivalent to ``function_signature_for_name_and_inputs('', components)``. |
def setimdi(self, node): #OBSOLETE
"""OBSOLETE"""
ns = {'imdi': 'http://www.mpi.nl/IMDI/Schema/IMDI'}
self.metadatatype = MetaDataType.IMDI
if LXE:
self.metadata = ElementTree.tostring(node, xml_declaration=False, pretty_print=True, encoding='utf-8')
else:
... | OBSOLETE |
def preferences(self, section=None):
"""
Return a list of all registered preferences
or a list of preferences registered for a given section
:param section: The section name under which the preference is registered
:type section: str.
:return: a list of :py:class:`prefs.... | Return a list of all registered preferences
or a list of preferences registered for a given section
:param section: The section name under which the preference is registered
:type section: str.
:return: a list of :py:class:`prefs.BasePreference` instances |
def value(self, view, template=None):
"""Get the value for a `ConfigView`.
May raise a `NotFoundError` if the value is missing (and the
template requires it) or a `ConfigValueError` for invalid values.
"""
if view.exists():
value, _ = view.first()
return ... | Get the value for a `ConfigView`.
May raise a `NotFoundError` if the value is missing (and the
template requires it) or a `ConfigValueError` for invalid values. |
def remove_acl(path):
"""
Remove the ACL of the file or folder located on the given path.
Also remove the ACL of any file and folder below the given one,
recursively.
Args:
path (str): Path to the file or folder to remove the ACL for,
recursively.
"""
# Some fil... | Remove the ACL of the file or folder located on the given path.
Also remove the ACL of any file and folder below the given one,
recursively.
Args:
path (str): Path to the file or folder to remove the ACL for,
recursively. |
def get_all_keys(reactor, key_type, value_type, etcd_address):
"""Returns all keys from etcd.
:param reactor: reference to Twisted' reactor.
:param etcd_address: Address with port number where etcd is
running.
:return: An instance of txaioetcd.Range containing all keys and
their values.... | Returns all keys from etcd.
:param reactor: reference to Twisted' reactor.
:param etcd_address: Address with port number where etcd is
running.
:return: An instance of txaioetcd.Range containing all keys and
their values. |
def _convertTmp(self, tmpCacheEntry):
"""
Moves a tmp file to the upload dir, resampling it if necessary, and then deleting the tmp entries.
:param tmpCacheEntry: the cache entry.
:return:
"""
from analyser.common.signal import loadSignalFromWav
tmpCacheEntry['sta... | Moves a tmp file to the upload dir, resampling it if necessary, and then deleting the tmp entries.
:param tmpCacheEntry: the cache entry.
:return: |
def set_video_mode_hint(self, display, enabled, change_origin, origin_x, origin_y, width, height, bits_per_pixel):
"""Asks VirtualBox to request the given video mode from
the guest. This is just a hint and it cannot be guaranteed
that the requested resolution will be used. Guest Additions
... | Asks VirtualBox to request the given video mode from
the guest. This is just a hint and it cannot be guaranteed
that the requested resolution will be used. Guest Additions
are required for the request to be seen by guests. The caller
should issue the request and wait for a resolution cha... |
def _collectAsArrow(self):
"""
Returns all records as a list of ArrowRecordBatches, pyarrow must be installed
and available on driver and worker Python environments.
.. note:: Experimental.
"""
with SCCallSiteSync(self._sc) as css:
sock_info = self._jdf.colle... | Returns all records as a list of ArrowRecordBatches, pyarrow must be installed
and available on driver and worker Python environments.
.. note:: Experimental. |
def select_postponed_date(self):
"""
The time intervals at which the workflow is to be extended are determined.
.. code-block:: python
# request:
{
'task_inv_key': string,
}
"""
_form = forms.Jso... | The time intervals at which the workflow is to be extended are determined.
.. code-block:: python
# request:
{
'task_inv_key': string,
} |
async def _send(self, http_verb, api_url, req_args):
"""Sends the request out for transmission.
Args:
http_verb (str): The HTTP verb. e.g. 'GET' or 'POST'.
api_url (str): The Slack API url. e.g. 'https://slack.com/api/chat.postMessage'
req_args (dict): The request ar... | Sends the request out for transmission.
Args:
http_verb (str): The HTTP verb. e.g. 'GET' or 'POST'.
api_url (str): The Slack API url. e.g. 'https://slack.com/api/chat.postMessage'
req_args (dict): The request arguments to be attached to the request.
e.g.
... |
def _remove_remote_node_data_bag():
"""Removes generated 'node' data_bag from the remote node"""
node_data_bag_path = os.path.join(env.node_work_path, 'data_bags', 'node')
if exists(node_data_bag_path):
sudo("rm -rf {0}".format(node_data_bag_path)) | Removes generated 'node' data_bag from the remote node |
def ready(self):
'''Whether or not enough time has passed since the last failure'''
if self._last_failed:
delta = time.time() - self._last_failed
return delta >= self.backoff()
return True | Whether or not enough time has passed since the last failure |
def contains_one_of(*fields):
"""Enables ensuring that one of multiple optional fields is set"""
message = 'Must contain any one of the following fields: {0}'.format(', '.join(fields))
def check_contains(endpoint_fields):
for field in fields:
if field in endpoint_fields:
... | Enables ensuring that one of multiple optional fields is set |
def _get_query_sets_for_object(o):
"""
Determines the correct query set based on the object.
If the object is a literal, it will return a query set over LiteralStatements.
If the object is a URIRef or BNode, it will return a query set over Statements.
If the object is unknown, it will return both t... | Determines the correct query set based on the object.
If the object is a literal, it will return a query set over LiteralStatements.
If the object is a URIRef or BNode, it will return a query set over Statements.
If the object is unknown, it will return both the LiteralStatement and Statement query sets.
... |
def _pick_keywords(db):
"""
Go thru downloaded data stored in `db` and filter keywords, which are
parsed and then yielded.
Shows nice progress bar.
Args:
db (obj): Opened database connection.
Yields:
obj: :class:`KeywordInfo` instances for yeach keyword.
"""
for key, v... | Go thru downloaded data stored in `db` and filter keywords, which are
parsed and then yielded.
Shows nice progress bar.
Args:
db (obj): Opened database connection.
Yields:
obj: :class:`KeywordInfo` instances for yeach keyword. |
def _convert_agg_to_wx_bitmap(agg, bbox):
"""
Convert the region of the agg buffer bounded by bbox to a wx.Bitmap. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance.
"""
if bbox is None:
# agg => rgba buffer -> bitmap
return w... | Convert the region of the agg buffer bounded by bbox to a wx.Bitmap. If
bbox is None, the entire buffer is converted.
Note: agg must be a backend_agg.RendererAgg instance. |
def _default_config(self, return_type):
""" Generates a default instance of whatever the type requested was (in case of miss)
:param return_type: type, type of object requested
:return: object, instance of return_type
"""
if return_type == list:
return [k for k in se... | Generates a default instance of whatever the type requested was (in case of miss)
:param return_type: type, type of object requested
:return: object, instance of return_type |
def standardize_language(language, plugin):
"""Maps a string to the equivalent Pygments language.
Returns the standardized language string.
"""
if not language:
return None
# standardize language for this plugin
if plugin:
plugin = plugin.split(' ')[-1].split('/')[0].split('-'... | Maps a string to the equivalent Pygments language.
Returns the standardized language string. |
def set_record(self, name, record_id, record):
"""Save a record into the cache.
Args:
name (string): The name to save the model under.
record_id (int): The record id.
record (:class:`cinder_data.model.CinderModel`): The model
"""
if name not in self._... | Save a record into the cache.
Args:
name (string): The name to save the model under.
record_id (int): The record id.
record (:class:`cinder_data.model.CinderModel`): The model |
def to_html(self, table_width=5):
"""Write the program information to HTML code, which can be saved,
printed and brought to the gym.
Parameters
----------
table_width
The table with of the HTML code.
Returns
-------
string
HTML co... | Write the program information to HTML code, which can be saved,
printed and brought to the gym.
Parameters
----------
table_width
The table with of the HTML code.
Returns
-------
string
HTML code. |
def Read(self, file_object):
"""Reads the next uncompressed data from the gzip stream.
Args:
file_object (FileIO): file object that contains the compressed stream.
Returns:
bytes: next uncompressed data from the compressed stream.
"""
file_object.seek(self.last_read, os.SEEK_SET)
r... | Reads the next uncompressed data from the gzip stream.
Args:
file_object (FileIO): file object that contains the compressed stream.
Returns:
bytes: next uncompressed data from the compressed stream. |
def source_path(self):
"""The name in a form suitable for use in a filesystem.
Excludes the revision
"""
# Need to do this to ensure the function produces the
# bundle path when called from subclasses
names = [k for k, _, _ in self._name_parts]
parts = [self.so... | The name in a form suitable for use in a filesystem.
Excludes the revision |
def make_csv(data):
""" Returns the content of a CSV file with the data of the dict/list data """
# Convert sub-dicts to news cols
for entry in data:
rval = entry
if isinstance(data, dict):
rval = data[entry]
todel = []
toadd = {}
for key, val in rval.item... | Returns the content of a CSV file with the data of the dict/list data |
def all_intersects_all(self, other):
"""
Returns True if self and other have the same keys, and each
segmentlist intersects the corresponding segmentlist in the
other; returns False if this is not the case or if either
dictionary is empty.
See also:
.intersects(), .all_intersects(), .intersects_all()
... | Returns True if self and other have the same keys, and each
segmentlist intersects the corresponding segmentlist in the
other; returns False if this is not the case or if either
dictionary is empty.
See also:
.intersects(), .all_intersects(), .intersects_all() |
def route(
self,
path: str,
methods: Optional[List[str]]=None,
endpoint: Optional[str]=None,
defaults: Optional[dict]=None,
host: Optional[str]=None,
subdomain: Optional[str]=None,
*,
provide_automatic_options: O... | Add a route to the blueprint.
This is designed to be used as a decorator, and has the same arguments
as :meth:`~quart.Quart.route`. An example usage,
.. code-block:: python
blueprint = Blueprint(__name__)
@blueprint.route('/')
def route():
.... |
def render_pdf_file_to_image_files(pdf_file_name, output_filename_root, program_to_use):
"""Render all the pages of the PDF file at pdf_file_name to image files with
path and filename prefix given by output_filename_root. Any directories must
have already been created, and the calling program is responsibl... | Render all the pages of the PDF file at pdf_file_name to image files with
path and filename prefix given by output_filename_root. Any directories must
have already been created, and the calling program is responsible for
deleting any directories or image files. The program program_to_use,
currently ei... |
def ellipse(data, channels,
center, a, b, theta=0,
log=False, full_output=False):
"""
Gate that preserves events inside an ellipse-shaped region.
Events are kept if they satisfy the following relationship::
(x/a)**2 + (y/b)**2 <= 1
where `x` and `y` are the coordinates... | Gate that preserves events inside an ellipse-shaped region.
Events are kept if they satisfy the following relationship::
(x/a)**2 + (y/b)**2 <= 1
where `x` and `y` are the coordinates of the event list, after
substracting `center` and rotating by -`theta`. This is mathematically
equivalent to... |
def get_subsequence_from_property(self, property_key, property_value, condition,
return_resnums=False, copy_letter_annotations=True):
"""Get a subsequence as a new SeqProp object given a certain property you want to find in the
original SeqProp's letter_annotation
... | Get a subsequence as a new SeqProp object given a certain property you want to find in the
original SeqProp's letter_annotation
This can be used to do something like extract the subsequence of exposed residues, so you can can run
calculations on that subsequence. Useful if you have questions li... |
def get_field_min_max(self, name, **query_dict):
"""Returns the minimum and maximum values of the specified field. This requires
two search calls to the service, each requesting a single value of a single
field.
@param name(string) Name of the field
@param q(string) Query identi... | Returns the minimum and maximum values of the specified field. This requires
two search calls to the service, each requesting a single value of a single
field.
@param name(string) Name of the field
@param q(string) Query identifying range of records for min and max values
@param... |
def to_vec4(self, isPoint):
"""Converts this vector3 into a vector4 instance."""
vec4 = Vector4()
vec4.x = self.x
vec4.y = self.y
vec4.z = self.z
if isPoint:
vec4.w = 1
else:
vec4.w = 0
return vec4 | Converts this vector3 into a vector4 instance. |
def exit_config_mode(self, exit_config="return", pattern=r">"):
"""Exit config mode."""
return super(HPComwareBase, self).exit_config_mode(
exit_config=exit_config, pattern=pattern
) | Exit config mode. |
def iter_cookie_browse_sorting(cookies):
'''
Get sorting-cookie from cookies dictionary.
:yields: tuple of path and sorting property
:ytype: 2-tuple of strings
'''
try:
data = cookies.get('browse-sorting', 'e30=').encode('ascii')
for path, prop in json.loads(base64.b64decode(dat... | Get sorting-cookie from cookies dictionary.
:yields: tuple of path and sorting property
:ytype: 2-tuple of strings |
def load(self, filething):
"""Load tags from a filename.
Raises apev2.error
"""
data = _APEv2Data(filething.fileobj)
if data.tag:
self.clear()
self.__parse_tag(data.tag, data.items)
else:
raise APENoHeaderError("No APE tag found") | Load tags from a filename.
Raises apev2.error |
def getParser():
"Creates and returns the argparse parser object."
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter, description=__description__)
parser.add_argument('input', help='the input image')
parser.add_argument('output', help='the output image')
parser.ad... | Creates and returns the argparse parser object. |
def clear(self):
"""Clear Redis and ThreatConnect data defined in profile.
Redis Data:
.. code-block:: javascript
{
"data_type": "redis",
"variable": "#App:4768:tc.adversary!TCEntity"
}
ThreatConnect Data:
.. code-block:: j... | Clear Redis and ThreatConnect data defined in profile.
Redis Data:
.. code-block:: javascript
{
"data_type": "redis",
"variable": "#App:4768:tc.adversary!TCEntity"
}
ThreatConnect Data:
.. code-block:: javascript
{
... |
def read_graph(filename, directed=False, weighted=False, default_weight=None):
"""Read a graph from a text file
:param filename: plain text file. All numbers are separated by space.
Starts with a line containing n (#vertices) and m (#edges).
Then m lines follow, for each edge.
... | Read a graph from a text file
:param filename: plain text file. All numbers are separated by space.
Starts with a line containing n (#vertices) and m (#edges).
Then m lines follow, for each edge.
Vertices are numbered from 0 to n-1.
Line for unweighted edge u... |
def to_superuser(email_class, **data):
"""
Email superusers
"""
for user in get_user_model().objects.filter(is_superuser=True):
try:
email_class().send([user.email], user.language, **data)
except AttributeError:
email_class().send([user.email], translation.get_lan... | Email superusers |
def package(self):
"""Packages lambda data for deployment into a zip"""
logger.info('Packaging lambda {}'.format(self.lambda_name))
zfh = io.BytesIO()
if os.path.exists(os.path.join(self.lambda_dir, '.env')):
logger.warn(
'A .env file exists in your Lambda di... | Packages lambda data for deployment into a zip |
def main():
"""
NAME
pmag_results_extract.py
DESCRIPTION
make a tab delimited output file from pmag_results table
SYNTAX
pmag_results_extract.py [command line options]
OPTIONS
-h prints help message and quits
-f RFILE, specify pmag_results table; default ... | NAME
pmag_results_extract.py
DESCRIPTION
make a tab delimited output file from pmag_results table
SYNTAX
pmag_results_extract.py [command line options]
OPTIONS
-h prints help message and quits
-f RFILE, specify pmag_results table; default is pmag_results.txt
... |
def get_view_and_name(self, attname):
"""
Gets a view or bundle and returns it
and it's url_name.
"""
view = getattr(self, attname, None)
if attname in self._children:
view = self._get_bundle_from_promise(attname)
if view:
if attname in se... | Gets a view or bundle and returns it
and it's url_name. |
def parse_response(self, response):
"""Parses the API response and raises appropriate
errors if raise_errors was set to True
:param response: response from requests http call
:returns: dictionary of response
:rtype: dict
"""
payload = None
try:
... | Parses the API response and raises appropriate
errors if raise_errors was set to True
:param response: response from requests http call
:returns: dictionary of response
:rtype: dict |
def mark_best_classification(text_log_error, classified_failure):
"""
Wrapper for setting best_classification on both TextLogError and FailureLine.
Set the given ClassifiedFailure as best_classification for the given
TextLogError. Handles the duplication of best_classification on FailureLine
so you... | Wrapper for setting best_classification on both TextLogError and FailureLine.
Set the given ClassifiedFailure as best_classification for the given
TextLogError. Handles the duplication of best_classification on FailureLine
so you don't have to! |
def is_edge_consistent(graph, u, v):
"""Check if all edges between two nodes have the same relation.
:param pybel.BELGraph graph: A BEL Graph
:param tuple u: The source BEL node
:param tuple v: The target BEL node
:return: If all edges from the source to target node have the same relation
:rtyp... | Check if all edges between two nodes have the same relation.
:param pybel.BELGraph graph: A BEL Graph
:param tuple u: The source BEL node
:param tuple v: The target BEL node
:return: If all edges from the source to target node have the same relation
:rtype: bool |
def strategy(self, *names, **kwargs):
"""
StrategyDict wrapping method for adding a new strategy.
Parameters
----------
*names :
Positional arguments with all names (strings) that could be used to
call the strategy to be added, to be used both as key items and as
attribute names.
... | StrategyDict wrapping method for adding a new strategy.
Parameters
----------
*names :
Positional arguments with all names (strings) that could be used to
call the strategy to be added, to be used both as key items and as
attribute names.
keep_name :
Boolean keyword-only paramet... |
def multinterp(x, y, xquery, slow=False):
"""Multiple linear interpolations
Parameters
----------
x : array_like, shape=(N,)
sorted array of x values
y : array_like, shape=(N, M)
array of y values corresponding to each x value
xquery : array_like, shape=(M,)
array of que... | Multiple linear interpolations
Parameters
----------
x : array_like, shape=(N,)
sorted array of x values
y : array_like, shape=(N, M)
array of y values corresponding to each x value
xquery : array_like, shape=(M,)
array of query values
slow : boolean, default=False
... |
def daterange_(self, datecol, date_start, op, **args):
"""
Returns a DataSwim instance with rows in a date range
"""
df = self._daterange(datecol, date_start, op, **args)
if df is None:
self.err("Can not select date range data")
return self._duplicate_(df) | Returns a DataSwim instance with rows in a date range |
def add_data_flow_to_state(from_port, to_port):
"""Interface method between Gaphas and RAFCON core for adding data flows
The method checks the types of the given ports and their relation. From this the necessary parameters for the
add_dat_flow method of the RAFCON core are determined. Also the parent state... | Interface method between Gaphas and RAFCON core for adding data flows
The method checks the types of the given ports and their relation. From this the necessary parameters for the
add_dat_flow method of the RAFCON core are determined. Also the parent state is derived from the ports.
:param from_port: Port... |
def _interfaces_added(self, object_path, interfaces_and_properties):
"""Internal method."""
added = object_path not in self._objects
self._objects.setdefault(object_path, {})
old_state = copy(self._objects[object_path])
self._objects[object_path].update(interfaces_and_properties)... | Internal method. |
def http_error_handler(f):
"""Handle 404 errors returned by the API server
"""
def hrefs_to_resources(hrefs):
for href in hrefs.replace(',', '').split():
type, uuid = href.split('/')[-2:]
yield Resource(type, uuid=uuid)
def hrefs_list_to_resources(hrefs_list):
f... | Handle 404 errors returned by the API server |
def to_internal_value(self, data):
"""Return the underlying object(s), given the serialized form."""
if self.kwargs['many']:
serializer = self.serializer.child
if not isinstance(data, list):
raise ParseError("'%s' value must be a list" % self.field_name)
... | Return the underlying object(s), given the serialized form. |
def logical_size(self, name):
"""Returns the logical size (before compression) of file `name`."""
digest = self._digest_for_link(name)
logical_size = self.db.get('{}:logical_size'.format(digest).encode())
if logical_size:
return int(logical_size.decode())
else:
... | Returns the logical size (before compression) of file `name`. |
def customData( self, key, default = None ):
"""
Returns data that has been stored on this menu.
:param key | <str>
default | <variant>
:return <variant>
"""
key = nativestring(key)
menu = self
whil... | Returns data that has been stored on this menu.
:param key | <str>
default | <variant>
:return <variant> |
def _all_get_node_by_name(self, name):
"""Returns an HDF5 node by the path specified in `name`"""
path_name = name.replace('.', '/')
where = '/%s/%s' % (self._trajectory_name, path_name)
return self._hdf5file.get_node(where=where) | Returns an HDF5 node by the path specified in `name` |
async def _make_connection(self):
"""Construct a connection to Redis."""
return await aioredis.create_redis(
'redis://{}:{}'.format(
self._redis_params.get('host', 'localhost'),
self._redis_params.get('port', 6379)
),
db=int(self._redis... | Construct a connection to Redis. |
def aggregations(self):
"""
Override parent method. Obtain list of the terms and their corresponding
values using "terms" aggregations for the previous time period.
:returns: a data frame containing terms and their corresponding values
"""
prev_month_start = get_prev_mo... | Override parent method. Obtain list of the terms and their corresponding
values using "terms" aggregations for the previous time period.
:returns: a data frame containing terms and their corresponding values |
def _find_matching_expectation(self, args, kwargs):
"""Return a matching expectation.
Returns the first expectation that matches the ones declared. Tries one with specific
arguments first, then falls back to an expectation that allows arbitrary arguments.
:return: The matching ``Expect... | Return a matching expectation.
Returns the first expectation that matches the ones declared. Tries one with specific
arguments first, then falls back to an expectation that allows arbitrary arguments.
:return: The matching ``Expectation``, if one was found.
:rtype: Expectation, None |
def group_keys_by_replica(session, keyspace, table, keys):
"""
Returns a :class:`dict` with the keys grouped per host. This can be
used to more accurately group by IN clause or to batch the keys per host.
If a valid replica is not found for a particular key it will be grouped under
:class:`~.NO_VAL... | Returns a :class:`dict` with the keys grouped per host. This can be
used to more accurately group by IN clause or to batch the keys per host.
If a valid replica is not found for a particular key it will be grouped under
:class:`~.NO_VALID_REPLICA`
Example usage::
result = group_keys_by_replica... |
def deref(self, data):
"""AWS doesn't quite have Swagger 2.0 validation right and will fail
on some refs. So, we need to convert to deref before
upload."""
# We have to make a deepcopy here to create a proper JSON
# compatible object, otherwise `json.dumps` fails when it
... | AWS doesn't quite have Swagger 2.0 validation right and will fail
on some refs. So, we need to convert to deref before
upload. |
def parse_contact(self):
"""Parse a top level contact expression, these consist of a name
expression a special char and an email expression.
The characters found in a name and email expression are returned.
"""
self.parse_whitespace()
name = self.parse_name() # parse a ... | Parse a top level contact expression, these consist of a name
expression a special char and an email expression.
The characters found in a name and email expression are returned. |
def get_filetypes2wildcards(filetypes):
"""Returns OrderedDict of filetypes to wildcards
The filetypes that are provided in the filetypes parameter are checked for
availability. Only available filetypes are inluded in the return ODict.
Parameters
----------
filetypes: Iterable of strings
\... | Returns OrderedDict of filetypes to wildcards
The filetypes that are provided in the filetypes parameter are checked for
availability. Only available filetypes are inluded in the return ODict.
Parameters
----------
filetypes: Iterable of strings
\tFiletype list |
def get_geometry_from_name(self, name):
"""
Returns the coordination geometry of the given name.
:param name: The name of the coordination geometry.
"""
for gg in self.cg_list:
if gg.name == name or name in gg.alternative_names:
return gg
raise... | Returns the coordination geometry of the given name.
:param name: The name of the coordination geometry. |
def oqi(ql, qs, ns=None, rc=None, ot=None, coe=None, moc=None):
"""
This function is a wrapper for
:meth:`~pywbem.WBEMConnection.OpenQueryInstances`.
Open an enumeration session to execute a query in a namespace and to
retrieve the instances representing the query result.
Use the :func:`~wbemc... | This function is a wrapper for
:meth:`~pywbem.WBEMConnection.OpenQueryInstances`.
Open an enumeration session to execute a query in a namespace and to
retrieve the instances representing the query result.
Use the :func:`~wbemcli.pi` function to retrieve the next set of
instances or the :func:`~wbc... |
def my_import(name, path=None):
"""Return imported module for the given name."""
# Documentation for importlib says this may be needed to pick up
# modules created after the program has started
if hasattr(importlib, 'invalidate_caches'):
# python 3.3+
importlib.invalidate_caches()
... | Return imported module for the given name. |
def recursiveRepr(self, stuff, thunk=repr):
"""
Recursive repr().
"""
ID = id(stuff)
if ID in self.active:
return '%s(...)' % (stuff.__class__.__name__,)
else:
try:
self.active[ID] = stuff
return thunk(stuff)
... | Recursive repr(). |
def calculate_category_probability(self):
"""
Caches the individual probabilities for each category
"""
total_tally = 0.0
probs = {}
for category, bayes_category in \
self.categories.get_categories().items():
count = bayes_category.get_tally()
... | Caches the individual probabilities for each category |
def locateChild(self, context, segments):
"""
Delegate child lookup to the wrapped resource but wrap whatever results
in another instance of this wrapper.
"""
childDeferred = maybeDeferred(
self.wrappedResource.locateChild, context, segments)
def childLocated(... | Delegate child lookup to the wrapped resource but wrap whatever results
in another instance of this wrapper. |
def set_reprompt_text(self, text):
"""Set response reprompt output speech as plain text type.
Args:
text: str. Response speech used when type is 'PlainText'. Cannot
exceed 8,000 characters.
"""
self.response.reprompt.outputSpeech.type = 'PlainText'
se... | Set response reprompt output speech as plain text type.
Args:
text: str. Response speech used when type is 'PlainText'. Cannot
exceed 8,000 characters. |
def doc_id(self):
"""Returns the couchbase document's id, object property.
:returns: The document id (that is created from :attr:'doc_type' and
:attr:'__key_field__' value, or auto-hashed document id at first
saving).
:rtype: unicode
"""
if self.id:
... | Returns the couchbase document's id, object property.
:returns: The document id (that is created from :attr:'doc_type' and
:attr:'__key_field__' value, or auto-hashed document id at first
saving).
:rtype: unicode |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.