positive stringlengths 100 30.3k | anchor stringlengths 1 15k |
|---|---|
def metadataURL(self, value):
"""gets/sets the public metadata url"""
if value != self._metadataURL:
self._metadataURL = value
self._metaFS = None | gets/sets the public metadata url |
def update_data(self, update_data_finished_cb):
"""Request an update of the anchor data"""
if not self._update_data_finished_cb and self.nr_of_anchors > 0:
self._update_data_finished_cb = update_data_finished_cb
self.anchor_data = {}
self.data_valid = False
... | Request an update of the anchor data |
def SetParserProp(self, prop, value):
"""Change the parser processing behaviour by changing some of
its internal properties. Note that some properties can only
be changed before any read has been done. """
ret = libxml2mod.xmlTextReaderSetParserProp(self._o, prop, value)
ret... | Change the parser processing behaviour by changing some of
its internal properties. Note that some properties can only
be changed before any read has been done. |
def render(self, xml, context, raise_on_errors=True):
"""Render xml string and apply XSLT transfomation with context"""
if xml:
self.xml = xml
# render XSL
self.render_xsl(self.root, context)
# create root XSL sheet
xsl_ns = self.namespaces[... | Render xml string and apply XSLT transfomation with context |
def services(namespace='default', **kwargs):
'''
Return a list of kubernetes services defined in the namespace
CLI Examples::
salt '*' kubernetes.services
salt '*' kubernetes.services namespace=default
'''
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.clien... | Return a list of kubernetes services defined in the namespace
CLI Examples::
salt '*' kubernetes.services
salt '*' kubernetes.services namespace=default |
def find_executable(name, names=None, required=True):
"""Utility function to find an executable in PATH
name: program to find. Use given value if absolute path
names: list of additional names. For instance
>>> find_executable('sed', names=['gsed'])
required: If True, then the function raises a... | Utility function to find an executable in PATH
name: program to find. Use given value if absolute path
names: list of additional names. For instance
>>> find_executable('sed', names=['gsed'])
required: If True, then the function raises an Exception
if the program is not found else the function... |
async def delTrigger(self, iden):
'''
Deletes a trigger from the cortex
'''
trig = self.cell.triggers.get(iden)
self._trig_auth_check(trig.get('useriden'))
self.cell.triggers.delete(iden) | Deletes a trigger from the cortex |
def segment_radial_distances(neurites, neurite_type=NeuriteType.all, origin=None):
'''Lengths of the segments in a collection of neurites'''
def _seg_rd(sec, pos):
'''list of radial distances of all segments of a section'''
# TODO: remove this disable when pylint is fixed
# pylint: disab... | Lengths of the segments in a collection of neurites |
def write_percolator_xml(staticxml, feats, fn):
"""Given the static percolator xml root and process info nodes, and all
psms and peptides as iterators in a dict {'peptide': pep_iterator, 'psm':
psm_iterator}, this generates percolator out data into a file."""
# First get xml until psms opening element ... | Given the static percolator xml root and process info nodes, and all
psms and peptides as iterators in a dict {'peptide': pep_iterator, 'psm':
psm_iterator}, this generates percolator out data into a file. |
def set_event_definition_list(self, value):
"""
Setter for 'event_definition_list' field.
:param value - a new value of 'event_definition_list' field. Must be a list of EventDefinition objects
"""
if value is None or not isinstance(value, list):
raise TypeError("Event... | Setter for 'event_definition_list' field.
:param value - a new value of 'event_definition_list' field. Must be a list of EventDefinition objects |
def get_dependency_structure(self, artifact=None, include_dependencies=False):
"""
Reads dependency structure. If an artifact is passed in you get only its dependencies otherwise the complete
structure is returned.
:param artifact: an artifact task or artifact name if only an artifact's... | Reads dependency structure. If an artifact is passed in you get only its dependencies otherwise the complete
structure is returned.
:param artifact: an artifact task or artifact name if only an artifact's deps are needed
:param include_dependencies: flag to include also dependencies in returned... |
def timedelta_days(days: int) -> timedelta64:
"""
Convert a duration in days to a NumPy ``timedelta64`` object.
"""
int_days = int(days)
if int_days != days:
raise ValueError("Fractional days passed to timedelta_days: "
"{!r}".format(days))
try:
# Do not ... | Convert a duration in days to a NumPy ``timedelta64`` object. |
def getFrameDimensions(data, page_width, page_height):
"""Calculate dimensions of a frame
Returns left, top, width and height of the frame in points.
"""
box = data.get("-pdf-frame-box", [])
if len(box) == 4:
return [getSize(x) for x in box]
top = getSize(data.get("top", 0))
left = ... | Calculate dimensions of a frame
Returns left, top, width and height of the frame in points. |
def index_pix_in_pixels(pix,pixels,sort=False,outside=-1):
"""
Find the indices of a set of pixels into another set of pixels.
!!! ASSUMES SORTED PIXELS !!!
Parameters:
-----------
pix : set of search pixels
pixels : set of reference pixels
Returns:
--------
index : index ... | Find the indices of a set of pixels into another set of pixels.
!!! ASSUMES SORTED PIXELS !!!
Parameters:
-----------
pix : set of search pixels
pixels : set of reference pixels
Returns:
--------
index : index into the reference pixels |
def is_visa(n):
"""Checks if credit card number fits the visa format."""
n, length = str(n), len(str(n))
if length >= 13 and length <= 16:
if n[0] == '4':
return True
return False | Checks if credit card number fits the visa format. |
def visit_UnaryOp(self, node):
"""Interfere with ``not`` operation to :func:`numpy.logical_not`."""
if isinstance(node.op, Not):
self._debug('UnaryOp', node.op, incr=1)
operand = self[node.operand]
self._debug('|-', operand, incr=2)
tn = self._tn()
... | Interfere with ``not`` operation to :func:`numpy.logical_not`. |
def kippenhahn(self, num_frame, xax, t0_model=0,
title='Kippenhahn diagram', tp_agb=0., t_eps=5.e2,
plot_star_mass=True, symbol_size=8, c12_bm=False,
print_legend=True):
"""Kippenhahn plot as a function of time or model.
Parameters
------... | Kippenhahn plot as a function of time or model.
Parameters
----------
num_frame : integer
Number of frame to plot this plot into, if <0 open no new
figure.
xax : string
Either 'model', 'time' or 'logtimerev' to indicate what is
to be used ... |
def handle_aliases_in_init_files(name, import_alias_mapping):
"""Returns either None or the handled alias.
Used in add_module.
"""
for key, val in import_alias_mapping.items():
# e.g. Foo == Foo
# e.g. Foo.Bar startswith Foo.
if name == val or \
name.startswith(va... | Returns either None or the handled alias.
Used in add_module. |
def _g_3(self):
"""omega3 < omega < omega4"""
# return 3 * (1.0 - self._n_3()) / (self._vertices_omegas[3] - self._omega)
return (3 * self._f(1, 3) * self._f(2, 3) /
(self._vertices_omegas[3] - self._vertices_omegas[0])) | omega3 < omega < omega4 |
def get_name_init(self, name):
"""Get initial name of symbol.
"""
self._register_name(name)
return self._var_name_mappers[name].get_init() | Get initial name of symbol. |
def load_config(self, config):
"""Load AMP parameters from the configuration file."""
# Read AMP confifuration.
# For ex, the AMP foo should have the following section:
#
# [foo]
# enable=true
# regex=\/usr\/bin\/nginx
# refresh=60
#
# and... | Load AMP parameters from the configuration file. |
def ifinstalled(parser, token):
"""
Old-style ``if`` tag that renders contents if the given app is
installed. The main use case is:
{% ifinstalled app_name %}
{% include "app_name/template.html" %}
{% endifinstalled %}
so we need to manually pull out all tokens if the app isn't
install... | Old-style ``if`` tag that renders contents if the given app is
installed. The main use case is:
{% ifinstalled app_name %}
{% include "app_name/template.html" %}
{% endifinstalled %}
so we need to manually pull out all tokens if the app isn't
installed, since if we used a normal ``if`` tag wit... |
def get_as_integer(self, key):
"""
Converts map element into an integer or returns 0 if conversion is not possible.
:param key: an index of element to get.
:return: integer value ot the element or 0 if conversion is not supported.
"""
value = self.get(key)
retur... | Converts map element into an integer or returns 0 if conversion is not possible.
:param key: an index of element to get.
:return: integer value ot the element or 0 if conversion is not supported. |
def is_purine(nucleotide, allow_extended_nucleotides=False):
"""Is the nucleotide a purine"""
if not allow_extended_nucleotides and nucleotide not in STANDARD_NUCLEOTIDES:
raise ValueError(
"{} is a non-standard nucleotide, neither purine or pyrimidine".format(nucleotide))
return nucleot... | Is the nucleotide a purine |
def make_view_field(field, obj=None, types_convert_map=None, fields_convert_map=None,
value=__default_value__, auto_convert=True):
"""
If auto_convert, then all values will be converted to string format, otherwise
remain the orignal value
"""
from uliweb.utils.textconvert import text2html... | If auto_convert, then all values will be converted to string format, otherwise
remain the orignal value |
def s(self):
"""
step to the next node in the execution order
"""
next_node=self._exe_order[self.step]
self._eval(next_node)
self.step+=1
if self.step==len(self._exe_order):
return self._finish()
else:
# if stepping, return the value of the node we just
# evaled
return self._break(value=self... | step to the next node in the execution order |
def build_exception_info_response(dbg, thread_id, request_seq, set_additional_thread_info, iter_visible_frames_info, max_frames):
'''
:return ExceptionInfoResponse
'''
thread = pydevd_find_thread_by_id(thread_id)
additional_info = set_additional_thread_info(thread)
topmost_frame = additional_inf... | :return ExceptionInfoResponse |
def get_mongo_query_from_arguments(self, reserved_attributes=[]):
"""Generate a mongo query from the given URL query parameters, handles OR query via multiples
:param list reserved_attributes: A list of attributes you want to exclude from this particular query
:return: dict
"""
... | Generate a mongo query from the given URL query parameters, handles OR query via multiples
:param list reserved_attributes: A list of attributes you want to exclude from this particular query
:return: dict |
def __get_method_abbrev(self):
"""Abbreviated form of clustering method parameter.
Used to guess output filenames for MOTHUR.
"""
abbrevs = {
'furthest': 'fn',
'nearest': 'nn',
'average': 'an',
}
if self.Parameters['method'].isOn():
... | Abbreviated form of clustering method parameter.
Used to guess output filenames for MOTHUR. |
def run_aconvasp_command(command, structure):
"""
Helper function for calling aconvasp with different arguments
"""
poscar = Poscar(structure)
p = subprocess.Popen(command, stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
ou... | Helper function for calling aconvasp with different arguments |
def layout(self, slide):
""" Return layout information for slide """
image = Image.new('RGB', (WIDTH, HEIGHT), 'black')
draw = ImageDraw.Draw(image)
draw.font = self.font
self.vertical_layout(draw, slide)
self.horizontal_layout(draw, slide)
ret... | Return layout information for slide |
def map(self, f, preservesPartitioning=False):
"""
Return a new RDD by applying a function to each element of this RDD.
>>> rdd = sc.parallelize(["b", "a", "c"])
>>> sorted(rdd.map(lambda x: (x, 1)).collect())
[('a', 1), ('b', 1), ('c', 1)]
"""
def func(_, iterat... | Return a new RDD by applying a function to each element of this RDD.
>>> rdd = sc.parallelize(["b", "a", "c"])
>>> sorted(rdd.map(lambda x: (x, 1)).collect())
[('a', 1), ('b', 1), ('c', 1)] |
def fields_dict(cls):
"""
Return an ordered dictionary of ``attrs`` attributes for a class, whose
keys are the attribute names.
:param type cls: Class to introspect.
:raise TypeError: If *cls* is not a class.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
cla... | Return an ordered dictionary of ``attrs`` attributes for a class, whose
keys are the attribute names.
:param type cls: Class to introspect.
:raise TypeError: If *cls* is not a class.
:raise attr.exceptions.NotAnAttrsClassError: If *cls* is not an ``attrs``
class.
:rtype: an ordered dict w... |
def get_foldrate_at_temp(ref_rate, new_temp, ref_temp=37.0):
"""Scale the predicted kinetic folding rate of a protein to temperature T, based on the relationship ln(k_f)∝1/T
Args:
ref_rate (float): Kinetic folding rate calculated from the function :func:`~ssbio.protein.sequence.properties.kinetic_foldi... | Scale the predicted kinetic folding rate of a protein to temperature T, based on the relationship ln(k_f)∝1/T
Args:
ref_rate (float): Kinetic folding rate calculated from the function :func:`~ssbio.protein.sequence.properties.kinetic_folding_rate.get_foldrate`
new_temp (float): Temperature in degre... |
def reset(self):
"Reset the hidden states."
[r.reset() for r in self.rnns if hasattr(r, 'reset')]
if self.qrnn: self.hidden = [self._one_hidden(l) for l in range(self.n_layers)]
else: self.hidden = [(self._one_hidden(l), self._one_hidden(l)) for l in range(self.n_layers)] | Reset the hidden states. |
def from_file(self, fname, comment_lead=['c'], compressed_with='use_ext'):
"""
Read a CNF formula from a file in the DIMACS format. A file name is
expected as an argument. A default argument is ``comment_lead`` for
parsing comment lines. A given file can be compressed by eith... | Read a CNF formula from a file in the DIMACS format. A file name is
expected as an argument. A default argument is ``comment_lead`` for
parsing comment lines. A given file can be compressed by either
gzip, bzip2, or lzma.
:param fname: name of a file to parse.
... |
def _getAlias(self, auth_level_uri):
"""Return the alias for the specified auth level URI.
@raises KeyError: if no alias is defined
"""
for (alias, existing_uri) in self.auth_level_aliases.iteritems():
if auth_level_uri == existing_uri:
return alias
... | Return the alias for the specified auth level URI.
@raises KeyError: if no alias is defined |
def find_instance_and_eni_by_ip(vpc_info, ip):
"""
Given a specific IP address, find the EC2 instance and ENI.
We need this information for setting the route.
Returns instance and emi in a tuple.
"""
for instance in vpc_info['instances']:
for eni in instance.interfaces:
fo... | Given a specific IP address, find the EC2 instance and ENI.
We need this information for setting the route.
Returns instance and emi in a tuple. |
def autobuild_arm_program(elfname, test_dir=os.path.join('firmware', 'test'), patch=True):
"""
Build the an ARM module for all targets and build all unit tests. If pcb files are given, also build those.
"""
try:
#Build for all targets
family = utilities.get_family('module_settings.json'... | Build the an ARM module for all targets and build all unit tests. If pcb files are given, also build those. |
def get_widgets(self, duplicates):
"Create and format widget set."
widgets = []
for (img,fp,human_readable_label) in self._all_images[:self._batch_size]:
img_widget = self.make_img_widget(img, layout=Layout(height='250px', width='300px'))
dropdown = self.make_dropdown_wid... | Create and format widget set. |
def add_package(
self, target=None, package_manager=None,
package=None, type_option=None, version_option=None,
node_paths=None, workunit_name=None, workunit_labels=None):
"""Add an additional package using requested package_manager."""
package_manager = package_manager or self.get_package_manager(t... | Add an additional package using requested package_manager. |
def get_strain_label(entry, viral=False):
"""Try to extract a strain from an assemly summary entry.
First this checks 'infraspecific_name', then 'isolate', then
it tries to get it from 'organism_name'. If all fails, it
falls back to just returning the assembly accesion number.
"""
def get_strai... | Try to extract a strain from an assemly summary entry.
First this checks 'infraspecific_name', then 'isolate', then
it tries to get it from 'organism_name'. If all fails, it
falls back to just returning the assembly accesion number. |
def move(self, from_stash, to_stash, filter_func=None):
"""
Move states from one stash to another.
:param from_stash: Take matching states from this stash.
:param to_stash: Put matching states into this stash.
:param filter_func: Stash states that match this filter. Should b... | Move states from one stash to another.
:param from_stash: Take matching states from this stash.
:param to_stash: Put matching states into this stash.
:param filter_func: Stash states that match this filter. Should be a function that takes
a state and returns True... |
def collect_results(self) -> Optional[Tuple[int, Dict[str, float]]]:
"""
Returns the decoded checkpoint and the decoder metrics or None if the queue is empty.
"""
self.wait_to_finish()
if self.decoder_metric_queue.empty():
if self._results_pending:
sel... | Returns the decoded checkpoint and the decoder metrics or None if the queue is empty. |
def _check_security_groups(self, names):
"""
Raise an exception if any of the named security groups does not exist.
:param List[str] groups: List of security group names
:raises: `SecurityGroupError` if group does not exist
"""
self._init_os_api()
log.debug("Chec... | Raise an exception if any of the named security groups does not exist.
:param List[str] groups: List of security group names
:raises: `SecurityGroupError` if group does not exist |
def is_instrinsic(input):
"""
Checks if the given input is an intrinsic function dictionary. Intrinsic function is a dictionary with single
key that is the name of the intrinsics.
:param input: Input value to check if it is an intrinsic
:return: True, if yes
"""
if input is not None \
... | Checks if the given input is an intrinsic function dictionary. Intrinsic function is a dictionary with single
key that is the name of the intrinsics.
:param input: Input value to check if it is an intrinsic
:return: True, if yes |
def _handledFailedSuccessor(self, jobNode, jobGraph, successorJobStoreID):
"""Deal with the successor having failed. Return True if there are
still active successors. Return False if all successors have failed
and the job is queued to run to handle the failed successors."""
logger.debug(... | Deal with the successor having failed. Return True if there are
still active successors. Return False if all successors have failed
and the job is queued to run to handle the failed successors. |
def _cancel_job(self, job, force):
"""Cancel job using streamtool."""
import streamsx.st as st
if st._has_local_install:
return st._cancel_job(job.id, force,
domain_id=job.get_instance().get_domain().id, instance_id=job.get_instance().id)
return False | Cancel job using streamtool. |
def parse_post(self, response):
'''
根据 :meth:`.ZhihuDailySpider.parse` 中生成的具体文章地址,获取到文章内容,
并对其进行格式化处理,结果填充到对象属性 ``item_list`` 中
:param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象
'''
content = json.loads(response.body.decode(), encoding='UTF-8')
post = response.... | 根据 :meth:`.ZhihuDailySpider.parse` 中生成的具体文章地址,获取到文章内容,
并对其进行格式化处理,结果填充到对象属性 ``item_list`` 中
:param Response response: 由 ``Scrapy`` 调用并传入的请求响应对象 |
def newNodeEatName(self, name):
"""Creation of a new node element. @ns is optional (None). """
ret = libxml2mod.xmlNewNodeEatName(self._o, name)
if ret is None:raise treeError('xmlNewNodeEatName() failed')
__tmp = xmlNode(_obj=ret)
return __tmp | Creation of a new node element. @ns is optional (None). |
def fileName(self):
"""
Returns the filename.
:return <str>
"""
if self._filename:
return self._filename
filename = nativestring(super(XSettings, self).fileName())
if self._customFormat:
filename, ext = os.p... | Returns the filename.
:return <str> |
def sender(self, func, routing=None, routing_re=None):
"""
Registers a sender function
"""
if routing and not isinstance(routing, list):
routing = [routing]
if routing_re:
if not isinstance(routing_re, list):
routing_re = [routing_re]
... | Registers a sender function |
def notify(title,
message,
secret,
endpoint=None,
level=3,
link=None,
retcode=None):
"""
Required parameter:
* ``secret`` - The Pushjet service secret token, created with
http://docs.pushjet.io/docs/creating-a-new-service
... | Required parameter:
* ``secret`` - The Pushjet service secret token, created with
http://docs.pushjet.io/docs/creating-a-new-service
Optional parameters:
* ``endpoint`` - custom Pushjet API endpoint
(defaults to https://api.pushjet.io)
* ``level`` - The importance le... |
def _extract_list_from_generator(generator):
"""
Iterates over a generator to extract all the objects and add them to a list.
Useful when the objects have to be used multiple times.
"""
extracted = []
for i in generator:
extracted.append(list(i))
return extracted | Iterates over a generator to extract all the objects and add them to a list.
Useful when the objects have to be used multiple times. |
def run_migrations():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
with engine.connect() as connection:
context.configure(
connection=connection,
target_metadata=Model.metadata)
... | Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context. |
def listeners_iter(self):
"""Return an iterator over the mapping of event => listeners bound.
The listener list(s) returned should **not** be mutated.
NOTE(harlowja): Each listener in the yielded (event, listeners)
tuple is an instance of the :py:class:`~.Listener` type, which
... | Return an iterator over the mapping of event => listeners bound.
The listener list(s) returned should **not** be mutated.
NOTE(harlowja): Each listener in the yielded (event, listeners)
tuple is an instance of the :py:class:`~.Listener` type, which
itself wraps a provided callback (an... |
def add_pool(arg, opts, shell_opts):
""" Add a pool.
"""
p = Pool()
p.name = opts.get('name')
p.description = opts.get('description')
p.default_type = opts.get('default-type')
p.ipv4_default_prefix_length = opts.get('ipv4_default_prefix_length')
p.ipv6_default_prefix_length = opts.get('... | Add a pool. |
def add(self, document_data, document_id=None):
"""Create a document in the Firestore database with the provided data.
Args:
document_data (dict): Property names and values to use for
creating the document.
document_id (Optional[str]): The document identifier wit... | Create a document in the Firestore database with the provided data.
Args:
document_data (dict): Property names and values to use for
creating the document.
document_id (Optional[str]): The document identifier within the
current collection. If not provided... |
def upload_string(to_upload, media_type=None, keep_open=False, wait_on_close=False, **kwargs):
"""
:param to_upload: String to upload into a file
:type to_upload: string
:param media_type: Internet Media Type
:type media_type: string
:param keep_open: If False, closes the file after uploading
... | :param to_upload: String to upload into a file
:type to_upload: string
:param media_type: Internet Media Type
:type media_type: string
:param keep_open: If False, closes the file after uploading
:type keep_open: boolean
:param wait_on_close: If True, waits for the file to close
:type wait_on... |
def pretty_str(self, indent=0):
"""Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation.
"""
spaces = ' ' * indent
params = ', '.join(map(lambda p: p.result + ' ' + p.name,
... | Return a human-readable string representation of this object.
Kwargs:
indent (int): The amount of spaces to use as indentation. |
def read(self, line, f, data):
"""See :meth:`PunchParser.read`"""
assert("hessian" not in data)
f.readline()
N = len(data["symbols"])
hessian = np.zeros((3*N, 3*N), float)
tmp = hessian.ravel()
counter = 0
while True:
line = f.readline()
... | See :meth:`PunchParser.read` |
def _npy2fits(d, table_type='binary', write_bitcols=False):
"""
d is the full element from the descr
"""
npy_dtype = d[1][1:]
if npy_dtype[0] == 'S' or npy_dtype[0] == 'U':
name, form, dim = _npy_string2fits(d, table_type=table_type)
else:
name, form, dim = _npy_num2fits(
... | d is the full element from the descr |
def get_bin_ids_by_resource(self, resource_id):
"""Gets the list of ``Bin`` ``Ids`` mapped to a ``Resource``.
arg: resource_id (osid.id.Id): ``Id`` of a ``Resource``
return: (osid.id.IdList) - list of bin ``Ids``
raise: NotFound - ``resource_id`` is not found
raise: NullAr... | Gets the list of ``Bin`` ``Ids`` mapped to a ``Resource``.
arg: resource_id (osid.id.Id): ``Id`` of a ``Resource``
return: (osid.id.IdList) - list of bin ``Ids``
raise: NotFound - ``resource_id`` is not found
raise: NullArgument - ``resource_id`` is ``null``
raise: Operat... |
def pairs_to_dict(response, encoding):
"Create a dict given a list of key/value pairs"
it = iter(response)
return dict(((k.decode(encoding), v) for k, v in zip(it, it))) | Create a dict given a list of key/value pairs |
def get_all():
'''
Return all available boot services
CLI Example:
.. code-block:: bash
salt '*' service.get_all
'''
ret = set()
lines = glob.glob('/etc/init.d/*')
for line in lines:
service = line.split('/etc/init.d/')[1]
# Remove README. If it's an enabled s... | Return all available boot services
CLI Example:
.. code-block:: bash
salt '*' service.get_all |
def validate(self, value):
"""
Accepts: str, unicode, bool
Returns: bool
"""
if isinstance(value, bool):
return value
if isinstance(value, (str, unicode)):
if value.lower() == "true":
value = True
elif value.lower() == "... | Accepts: str, unicode, bool
Returns: bool |
def _forward(X, s=1.1, gamma=1., k=5):
"""
Forward dynamic algorithm for burstness automaton HMM, from `Kleinberg
(2002) <http://www.cs.cornell.edu/home/kleinber/bhs.pdf>`_.
Parameters
----------
X : list
A series of time-gaps between events.
s : float
(default: 1.1) Scaling... | Forward dynamic algorithm for burstness automaton HMM, from `Kleinberg
(2002) <http://www.cs.cornell.edu/home/kleinber/bhs.pdf>`_.
Parameters
----------
X : list
A series of time-gaps between events.
s : float
(default: 1.1) Scaling parameter ( > 1.)that controls graininess of
... |
def parse_with(self, node):
"""
Parses <With>
@param node: Node containing the <With> element
@type node: xml.etree.Element
"""
if 'instance' in node.lattrib:
instance = node.lattrib['instance']
list = None
index = None
elif '... | Parses <With>
@param node: Node containing the <With> element
@type node: xml.etree.Element |
def from_api_repr(cls, resource, zone):
"""Factory: construct a change set given its API representation
:type resource: dict
:param resource: change set representation returned from the API.
:type zone: :class:`google.cloud.dns.zone.ManagedZone`
:param zone: A zone which holds... | Factory: construct a change set given its API representation
:type resource: dict
:param resource: change set representation returned from the API.
:type zone: :class:`google.cloud.dns.zone.ManagedZone`
:param zone: A zone which holds zero or more change sets.
:rtype: :class:... |
def unsubscribe(user_id, from_all=False, campaign_ids=None, on_error=None, on_success=None):
""" Unsubscribe a user from some or all campaigns.
:param str | number user_id: the id you use to identify a user. this should
be static for the lifetime of a user.
:param bool from_all True to unsubscribe fro... | Unsubscribe a user from some or all campaigns.
:param str | number user_id: the id you use to identify a user. this should
be static for the lifetime of a user.
:param bool from_all True to unsubscribe from all campaigns. Take precedence over
campaigns IDs if both are given.
:param list of str ca... |
def listFiletypes(targetfilename, directory):
"""Looks for all occurences of a specified filename in a directory and
returns a list of all present file extensions of this filename.
In this cas everything after the first dot is considered to be the file
extension: ``"filename.txt" -> "txt"``, ``"filenam... | Looks for all occurences of a specified filename in a directory and
returns a list of all present file extensions of this filename.
In this cas everything after the first dot is considered to be the file
extension: ``"filename.txt" -> "txt"``, ``"filename.txt.zip" -> "txt.zip"``
:param targetfilename:... |
def addFollowOn(self, followOnJob):
"""
Adds a follow-on job, follow-on jobs will be run after the child jobs and \
their successors have been run.
:param toil.job.Job followOnJob:
:return: followOnJob
:rtype: toil.job.Job
"""
self._followOns.append(follo... | Adds a follow-on job, follow-on jobs will be run after the child jobs and \
their successors have been run.
:param toil.job.Job followOnJob:
:return: followOnJob
:rtype: toil.job.Job |
def update_slice(self, blob):
"""Update the slice proposal scale based on the relative
size of the slices compared to our initial guess."""
nexpand, ncontract = blob['nexpand'], blob['ncontract']
self.scale *= nexpand / (2. * ncontract) | Update the slice proposal scale based on the relative
size of the slices compared to our initial guess. |
def get_symbol(self, symbol):
"""
Get a specific symbol by index or name.
Args:
symbol(int or str): The index or name of the symbol to return.
Returns:
ELF.Symbol: The symbol.
Raises:
KeyError: The requested symbol does not exist.
""... | Get a specific symbol by index or name.
Args:
symbol(int or str): The index or name of the symbol to return.
Returns:
ELF.Symbol: The symbol.
Raises:
KeyError: The requested symbol does not exist. |
def answer(self):
"""Message answer
"""
if self.meta.default_answer in ["y", "Y"]:
answer = self.meta.default_answer
else:
try:
answer = raw_input("Would you like to continue [y/N]? ")
except EOFError:
print("")
... | Message answer |
def raw_response(self, cursor_id=None):
"""Check the response header from the database, without decoding BSON.
Check the response for errors and unpack.
Can raise CursorNotFound, NotMasterError, ExecutionTimeout, or
OperationFailure.
:Parameters:
- `cursor_id` (optio... | Check the response header from the database, without decoding BSON.
Check the response for errors and unpack.
Can raise CursorNotFound, NotMasterError, ExecutionTimeout, or
OperationFailure.
:Parameters:
- `cursor_id` (optional): cursor_id we sent to get this response -
... |
def setup(name, path='log', enable_debug=False):
"""
Prepare a NestedSetup.
:param name: the channel name
:param path: the path where the logs will be written
:param enable_debug: do we want to save the message at the DEBUG level
:return a nested Setup
"""
path_tmpl = os.path.join(path... | Prepare a NestedSetup.
:param name: the channel name
:param path: the path where the logs will be written
:param enable_debug: do we want to save the message at the DEBUG level
:return a nested Setup |
def handle_interceptors(args):
"""usage: {program} interceptors
List the available interceptor plugins.
"""
assert args
print('\n'.join(cosmic_ray.plugins.interceptor_names()))
return ExitCode.OK | usage: {program} interceptors
List the available interceptor plugins. |
def _coerce_consumer_group(consumer_group):
"""
Ensure that the consumer group is a text string.
:param consumer_group: :class:`bytes` or :class:`str` instance
:raises TypeError: when `consumer_group` is not :class:`bytes`
or :class:`str`
"""
if not isinstance(consumer_group, string_typ... | Ensure that the consumer group is a text string.
:param consumer_group: :class:`bytes` or :class:`str` instance
:raises TypeError: when `consumer_group` is not :class:`bytes`
or :class:`str` |
def _register_external_service(self, plugin_name, plugin_instance):
"""
Register an external service.
:param plugin_name: Service name
:param plugin_instance: PluginBase
:return:
"""
for attr in plugin_instance.get_external_services().keys():
if attr ... | Register an external service.
:param plugin_name: Service name
:param plugin_instance: PluginBase
:return: |
def describe_stream(self, stream_arn, first_shard=None):
"""Wraps :func:`boto3.DynamoDBStreams.Client.describe_stream`, handling continuation tokens.
:param str stream_arn: Stream arn, usually from the model's ``Meta.stream["arn"]``.
:param str first_shard: *(Optional)* If provided, only shards... | Wraps :func:`boto3.DynamoDBStreams.Client.describe_stream`, handling continuation tokens.
:param str stream_arn: Stream arn, usually from the model's ``Meta.stream["arn"]``.
:param str first_shard: *(Optional)* If provided, only shards after this shard id will be returned.
:return: All shards i... |
def update_aliases(aliases,aonly,x):
"helper for ctor. takes AliasX or string as second arg"
if isinstance(x,basestring): aliases[x]=x
elif isinstance(x,sqparse2.AliasX):
if not isinstance(x.alias,basestring): raise TypeError('alias not string',type(x.alias))
if isinstance(x.name,sqparse2.NameX)... | helper for ctor. takes AliasX or string as second arg |
def send_notification(self, method, *args):
"""Send a JSON-RPC notification.
The notification *method* is sent with positional arguments *args*.
"""
message = self._version.create_request(method, args, notification=True)
self.send_message(message) | Send a JSON-RPC notification.
The notification *method* is sent with positional arguments *args*. |
def get_nameid_data(self):
"""
Gets the NameID Data provided by the SAML Response from the IdP
:returns: Name ID Data (Value, Format, NameQualifier, SPNameQualifier)
:rtype: dict
"""
nameid = None
nameid_data = {}
encrypted_id_data_nodes = self.__query_a... | Gets the NameID Data provided by the SAML Response from the IdP
:returns: Name ID Data (Value, Format, NameQualifier, SPNameQualifier)
:rtype: dict |
def showtip(self, text):
"Display text in tooltip window"
self.text = text
if self.tipwindow or not self.text:
return
x, y, cx, cy = self.widget.bbox("insert")
x = x + self.widget.winfo_rootx() + 27
y = y + cy + self.widget.winfo_rooty() +27
self.tipwi... | Display text in tooltip window |
def _add_new_methods(cls):
"""Add all generated methods to result class."""
for name, method in cls.context.new_methods.items():
if hasattr(cls.context.new_class, name):
raise ValueError(
"Name collision in state machine class - '{name}'."
... | Add all generated methods to result class. |
def benchmark_forward(self):
"""Benchmark forward execution.
"""
self._setup()
def f():
self._forward()
self.mod_ext.synchronize(**self.ext_kwargs)
f() # Ignore first
self.forward_stat = self._calc_benchmark_stat(f) | Benchmark forward execution. |
def generate_datasets_report(
self, catalogs, harvest='valid', report=None,
export_path=None, catalog_ids=None, catalog_homepages=None,
catalog_orgs=None
):
"""Genera un reporte sobre las condiciones de la metadata de los
datasets contenidos en uno o varios catálo... | Genera un reporte sobre las condiciones de la metadata de los
datasets contenidos en uno o varios catálogos.
Args:
catalogs (str, dict o list): Uno (str o dict) o varios (list de
strs y/o dicts) catálogos.
harvest (str): Criterio a utilizar para determinar el val... |
def display_message(
self, subject='Find My iPhone Alert', message="This is a note",
sounds=False
):
""" Send a request to the device to play a sound.
It's possible to pass a custom message by changing the `subject`.
"""
data = json.dumps(
{
... | Send a request to the device to play a sound.
It's possible to pass a custom message by changing the `subject`. |
def pad_conv3d_lrelu(self, activations, n_filters, kernel_size, strides,
scope):
"""Pad, apply 3-D convolution and leaky relu."""
padding = [[0, 0], [1, 1], [1, 1], [1, 1], [0, 0]]
# tf.nn.conv3d accepts a list of 5 values for strides
# with first and last value equal to 1
if... | Pad, apply 3-D convolution and leaky relu. |
def checksum_file(scheme, path):
"""Return the checksum (hex digest) of a file"""
h = getattr(hashlib, scheme)()
with open(path, 'rb') as f:
chunk = f.read(65535)
while chunk:
h.update(chunk)
chunk = f.read(65535)
return h.hexdigest() | Return the checksum (hex digest) of a file |
def alias_symbol(self,
alias_symbol=None,
is_previous_symbol=None,
hgnc_symbol=None,
hgnc_identifier=None,
limit=None,
as_df=False):
"""Method to query :class:`.models.AliasSymbol` objec... | Method to query :class:`.models.AliasSymbol` objects in database
:param alias_symbol: alias symbol(s)
:type alias_symbol: str or tuple(str) or None
:param is_previous_symbol: flag for 'is previous'
:type is_previous_symbol: bool or tuple(bool) or None
:param hgnc_symbol: HGNC ... |
def _resolved_objects(pdf, xobject):
"""Retrieve rotatation info."""
return [pdf.getPage(i).get(xobject) for i in range(pdf.getNumPages())][0] | Retrieve rotatation info. |
def main(arguments=None):
"""
The main function used when ``yaml_to_database.py`` when installed as a cl tool
"""
# setup the command-line util settings
su = tools(
arguments=arguments,
docString=__doc__,
logLevel="WARNING",
options_first=False,
projectName=F... | The main function used when ``yaml_to_database.py`` when installed as a cl tool |
def emitRecordClicked(self, item):
"""
Emits the record clicked signal for the given item, provided the
signals are not currently blocked.
:param item | <QTreeWidgetItem>
"""
# load the next page
if isinstance(item, XBatchItem):
... | Emits the record clicked signal for the given item, provided the
signals are not currently blocked.
:param item | <QTreeWidgetItem> |
def get_unique_fields(fld_lists):
"""Get unique namedtuple fields, despite potential duplicates in lists of fields."""
flds = []
fld_set = set([f for flst in fld_lists for f in flst])
fld_seen = set()
# Add unique fields to list of fields in order that they appear
for fld_list in fld_lists:
... | Get unique namedtuple fields, despite potential duplicates in lists of fields. |
def saveit(func):
"""A decorator that caches the return value of a function"""
name = '_' + func.__name__
def _wrapper(self, *args, **kwds):
if not hasattr(self, name):
setattr(self, name, func(self, *args, **kwds))
return getattr(self, name)
return _wrapper | A decorator that caches the return value of a function |
def IntegerAddition(left: vertex_constructor_param_types, right: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex:
"""
Adds one vertex to another
:param left: a vertex to add
:param right: a vertex to add
"""
return Integer(context.jvm_view().IntegerAdditionVertex, label... | Adds one vertex to another
:param left: a vertex to add
:param right: a vertex to add |
def _validate_choices(options):
"""
Callback wrapper for validating click.prompt input.
Parameters
----------
options : list
List of allowed choices
Returns
-------
:func:`callable`
callback function for value_proc in :func:`click.prompt`.
Raises
------
:cl... | Callback wrapper for validating click.prompt input.
Parameters
----------
options : list
List of allowed choices
Returns
-------
:func:`callable`
callback function for value_proc in :func:`click.prompt`.
Raises
------
:class:`click.BadParameter` |
def handle_heartbeat_response_22(msg):
"""Process an internal heartbeat response message."""
if not msg.gateway.is_sensor(msg.node_id):
return None
msg.gateway.sensors[msg.node_id].heartbeat = msg.payload
msg.gateway.alert(msg)
return None | Process an internal heartbeat response message. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.