code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_python_shell():
"""Determine python shell
get_python_shell() returns
'shell' (started python on command line using "python")
'ipython' (started ipython on command line using "ipython")
'ipython-notebook' (e.g., running in Spyder or started with "ipython qtconsole")
'jupyter-notebook' (... | Determine python shell
get_python_shell() returns
'shell' (started python on command line using "python")
'ipython' (started ipython on command line using "ipython")
'ipython-notebook' (e.g., running in Spyder or started with "ipython qtconsole")
'jupyter-notebook' (running in a Jupyter notebook)
... |
def snakescan(xi, yi, xf, yf):
"""Scan pixels in a snake pattern along the x-coordinate then y-coordinate
:param xi: Initial x-coordinate
:type xi: int
:param yi: Initial y-coordinate
:type yi: int
:param xf: Final x-coordinate
:type xf: int
:param yf: Final y-coordinate
:type yf: i... | Scan pixels in a snake pattern along the x-coordinate then y-coordinate
:param xi: Initial x-coordinate
:type xi: int
:param yi: Initial y-coordinate
:type yi: int
:param xf: Final x-coordinate
:type xf: int
:param yf: Final y-coordinate
:type yf: int
:returns: Coordinate generator
... |
def _rectify_countdown_or_bool(count_or_bool):
"""
used by recursive functions to specify which level to turn a bool on in
counting down yields True, True, ..., False
counting up yields False, False, False, ... True
Args:
count_or_bool (bool or int): if positive and an integer, it will coun... | used by recursive functions to specify which level to turn a bool on in
counting down yields True, True, ..., False
counting up yields False, False, False, ... True
Args:
count_or_bool (bool or int): if positive and an integer, it will count
down, otherwise it will remain the same.
... |
def _verify(self, valid_subscriptions, fix):
"""Check if `self` is valid roster item.
Valid item must have proper `subscription` and valid value for 'ask'.
:Parameters:
- `valid_subscriptions`: sequence of valid subscription values
- `fix`: if `True` than replace invali... | Check if `self` is valid roster item.
Valid item must have proper `subscription` and valid value for 'ask'.
:Parameters:
- `valid_subscriptions`: sequence of valid subscription values
- `fix`: if `True` than replace invalid 'subscription' and 'ask'
values with the... |
def open(self):
"""
Open the HID device for reading and writing.
"""
if self._is_open:
raise HIDException("Failed to open device: HIDDevice already open")
path = self.path.encode('utf-8')
dev = hidapi.hid_open_path(path)
if dev:
self._is_... | Open the HID device for reading and writing. |
def _build_str_from_chinese(chinese_items):
"""
根据解析出的中文时间字符串的关键字返回对应的标准格式字符串
"""
year, month, day = chinese_items
year = reduce(lambda a, b: a*10+b, map(CHINESE_NUMS.find, year))
return '%04d-%02d-%02d 00:00:00' % (year, _parse_chinese_field(month), _parse_chinese_field(day)) | 根据解析出的中文时间字符串的关键字返回对应的标准格式字符串 |
def delete_workspace_config(namespace, workspace, cnamespace, config):
"""Delete method configuration in workspace.
Args:
namespace (str): project to which workspace belongs
workspace (str): Workspace name
mnamespace (str): Method namespace
method (str): Method name
Swagger... | Delete method configuration in workspace.
Args:
namespace (str): project to which workspace belongs
workspace (str): Workspace name
mnamespace (str): Method namespace
method (str): Method name
Swagger:
https://api.firecloud.org/#!/Method_Configurations/deleteWorkspaceMe... |
def print_row(self, **kwargs):
'''
keys of kwargs must be the names passed to __init__(...) as `column_names`
'''
meta_string = '|'
for key in self.column_names:
float_specifier = ''
if isinstance(kwargs[key], float):
float_specifier = '.3f... | keys of kwargs must be the names passed to __init__(...) as `column_names` |
def spcol(x,knots,spline_order):
"""Computes the spline colocation matrix for knots in x.
The spline collocation matrix contains all m-p-1 bases
defined by knots. Specifically it contains the ith basis
in the ith column.
Input:
x: vector to evaluate the bases on
knots: vec... | Computes the spline colocation matrix for knots in x.
The spline collocation matrix contains all m-p-1 bases
defined by knots. Specifically it contains the ith basis
in the ith column.
Input:
x: vector to evaluate the bases on
knots: vector of knots
spline_order: orde... |
def _rebuild_all_command_chains(self):
"""
Rebuilds execution chain for all registered commands.
This method is typically called when intercepters are changed.
Because of that it is more efficient to register intercepters
before registering commands (typically it will be done in ... | Rebuilds execution chain for all registered commands.
This method is typically called when intercepters are changed.
Because of that it is more efficient to register intercepters
before registering commands (typically it will be done in abstract classes).
However, that performance penalt... |
def to_html(ds: Any) -> str:
"""
Return an HTML representation of the loom file or view, showing the upper-left 10x10 corner.
"""
rm = min(10, ds.shape[0])
cm = min(10, ds.shape[1])
html = "<p>"
if ds.attrs.__contains__("title"):
html += "<strong>" + ds.attrs["title"] + "</strong> "
html += f"{ds.shape[0]} ro... | Return an HTML representation of the loom file or view, showing the upper-left 10x10 corner. |
def _clopper_pearson_confidence_interval(samples, error_rate):
"""Computes a confidence interval for the mean of the given 1-D distribution.
Assumes (and checks) that the given distribution is Bernoulli, i.e.,
takes only two values. This licenses using the CDF of the binomial
distribution for the confidence, ... | Computes a confidence interval for the mean of the given 1-D distribution.
Assumes (and checks) that the given distribution is Bernoulli, i.e.,
takes only two values. This licenses using the CDF of the binomial
distribution for the confidence, which is tighter (for extreme
probabilities) than the DKWM inequal... |
def get_version_path(self, version=None):
'''
Returns a storage path for the archive and version
If the archive is versioned, the version number is used as the file
path and the archive path is the directory. If not, the archive path is
used as the file path.
Parameters... | Returns a storage path for the archive and version
If the archive is versioned, the version number is used as the file
path and the archive path is the directory. If not, the archive path is
used as the file path.
Parameters
----------
version : str or object
... |
def results(self, use_cache=True, dialect=None, billing_tier=None):
"""Retrieves table of results for the query. May block if the query must be executed first.
Args:
use_cache: whether to use cached results or not. Ignored if append is specified.
dialect : {'legacy', 'standard'}, default 'legacy'
... | Retrieves table of results for the query. May block if the query must be executed first.
Args:
use_cache: whether to use cached results or not. Ignored if append is specified.
dialect : {'legacy', 'standard'}, default 'legacy'
'legacy' : Use BigQuery's legacy SQL dialect.
'standard'... |
def identify(self, req, resp, resource, uri_kwargs):
"""Identify user using Authenticate header with Basic auth."""
header = req.get_header("Authorization", False)
auth = header.split(" ") if header else None
if auth is None or auth[0].lower() != 'basic':
return None
... | Identify user using Authenticate header with Basic auth. |
def update(self, fields=None, **kwargs):
"""Update the current entity.
Make an HTTP PUT call to ``self.path('base')``. Return the response.
:param fields: An iterable of field names. Only the fields named in
this iterable will be updated. No fields are updated if an empty
... | Update the current entity.
Make an HTTP PUT call to ``self.path('base')``. Return the response.
:param fields: An iterable of field names. Only the fields named in
this iterable will be updated. No fields are updated if an empty
iterable is passed in. All fields are updated if ... |
def lowdata_fmt():
'''
Validate and format lowdata from incoming unserialized request data
This tool requires that the hypermedia_in tool has already been run.
'''
if cherrypy.request.method.upper() != 'POST':
return
data = cherrypy.request.unserialized_data
# if the data was sen... | Validate and format lowdata from incoming unserialized request data
This tool requires that the hypermedia_in tool has already been run. |
def read_secret_version(self, path, version=None, mount_point=DEFAULT_MOUNT_POINT):
"""Retrieve the secret at the specified location.
Supported methods:
GET: /{mount_point}/data/{path}. Produces: 200 application/json
:param path: Specifies the path of the secret to read. This is s... | Retrieve the secret at the specified location.
Supported methods:
GET: /{mount_point}/data/{path}. Produces: 200 application/json
:param path: Specifies the path of the secret to read. This is specified as part of the URL.
:type path: str | unicode
:param version: Specifie... |
def get_segment_definer_comments(xml_file, include_version=True):
"""Returns a dict with the comment column as the value for each segment"""
from glue.ligolw.ligolw import LIGOLWContentHandler as h
lsctables.use_in(h)
# read segment definer table
xmldoc, _ = ligolw_utils.load_fileobj(xml_file,
... | Returns a dict with the comment column as the value for each segment |
def create_token(self, user):
"""
Create a signed token from a user.
"""
# The password is expected to be a secure hash but we hash it again
# for additional safety. We default to MD5 to minimize the length of
# the token. (Remember, if an attacker obtains the URL, he ca... | Create a signed token from a user. |
def __within2(value, within=None, errmsg=None, dtype=None):
'''validate that a value is in ``within`` and optionally a ``dtype``'''
valid, _value = False, value
if dtype:
try:
_value = dtype(value) # TODO: this is a bit loose when dtype is a class
valid = _value in within
... | validate that a value is in ``within`` and optionally a ``dtype`` |
def all_selected_options(self):
"""Returns a list of all selected options belonging to this select tag"""
ret = []
for opt in self.options:
if opt.is_selected():
ret.append(opt)
return ret | Returns a list of all selected options belonging to this select tag |
def pull_session(session_id=None, url='default', io_loop=None, arguments=None):
''' Create a session by loading the current server-side document.
``session.document`` will be a fresh document loaded from
the server. While the connection to the server is open,
changes made on the server side will be app... | Create a session by loading the current server-side document.
``session.document`` will be a fresh document loaded from
the server. While the connection to the server is open,
changes made on the server side will be applied to this
document, and changes made on the client side will be
synced to the... |
def configure(self, options, conf):
"""Configure the plugin and system, based on selected options.
The base plugin class sets the plugin to enabled if the enable option
for the plugin (self.enable_opt) is true.
"""
self.conf = conf
if hasattr(options, self.enable_opt):
... | Configure the plugin and system, based on selected options.
The base plugin class sets the plugin to enabled if the enable option
for the plugin (self.enable_opt) is true. |
def make_tz_aware(dt, tz='UTC', is_dst=None):
"""Add timezone information to a datetime object, only if it is naive.
>>> make_tz_aware(datetime.datetime(2001, 9, 8, 7, 6))
datetime.datetime(2001, 9, 8, 7, 6, tzinfo=<UTC>)
>>> make_tz_aware(['2010-01-01'], 'PST')
[datetime.datetime(2010, 1, 1, 0, 0,... | Add timezone information to a datetime object, only if it is naive.
>>> make_tz_aware(datetime.datetime(2001, 9, 8, 7, 6))
datetime.datetime(2001, 9, 8, 7, 6, tzinfo=<UTC>)
>>> make_tz_aware(['2010-01-01'], 'PST')
[datetime.datetime(2010, 1, 1, 0, 0, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 S... |
def _domain_event_pmsuspend_cb(conn, domain, reason, opaque):
'''
Domain suspend events handler
'''
_salt_send_domain_event(opaque, conn, domain, opaque['event'], {
'reason': 'unknown' # currently unused
}) | Domain suspend events handler |
def _get_subject_public_key(cert):
"""
Returns the SubjectPublicKey asn.1 field of the SubjectPublicKeyInfo
field of the server's certificate. This is used in the server
verification steps to thwart MitM attacks.
:param cert: X509 certificate from pyOpenSSL .get_peer_certificate... | Returns the SubjectPublicKey asn.1 field of the SubjectPublicKeyInfo
field of the server's certificate. This is used in the server
verification steps to thwart MitM attacks.
:param cert: X509 certificate from pyOpenSSL .get_peer_certificate()
:return: byte string of the asn.1 DER encode... |
def nunique(expr):
"""
The distinct count.
:param expr:
:return:
"""
output_type = types.int64
if isinstance(expr, SequenceExpr):
return NUnique(_value_type=output_type, _inputs=[expr])
elif isinstance(expr, SequenceGroupBy):
return GroupedNUnique(_data_type=output_type... | The distinct count.
:param expr:
:return: |
def get_child(self, streamId, childId, options={}):
"""Get the child of a stream."""
return self.get('stream/' + streamId + '/children/' + childId, options) | Get the child of a stream. |
def get_top_n_meanings(strings, n):
"""
Returns (text, score) for top n strings
"""
scored_strings = [(s, score_meaning(s)) for s in strings]
scored_strings.sort(key=lambda tup: -tup[1])
return scored_strings[:n] | Returns (text, score) for top n strings |
def get_resource_metadata(self, resource=None):
"""
Get resource metadata
:param resource: The name of the resource to get metadata for
:return: list
"""
result = self._make_metadata_request(meta_id=0, metadata_type='METADATA-RESOURCE')
if resource:
re... | Get resource metadata
:param resource: The name of the resource to get metadata for
:return: list |
def screener(molecules, ensemble, sort_order):
"""
Uses the virtual screening scores for the receptors, or queries, specified in ensemble to sort the molecules in
molecules in the direction specified by sort_order.
:param molecules: a list of molecule objects (/classification/molecules.Molecules())
... | Uses the virtual screening scores for the receptors, or queries, specified in ensemble to sort the molecules in
molecules in the direction specified by sort_order.
:param molecules: a list of molecule objects (/classification/molecules.Molecules())
:param ensemble: a tuple with receptors, or a query, that s... |
def get_ssh_key():
"""Returns ssh key to connecting to cluster workers.
If the env var TUNE_CLUSTER_SSH_KEY is provided, then this key
will be used for syncing across different nodes.
"""
path = os.environ.get("TUNE_CLUSTER_SSH_KEY",
os.path.expanduser("~/ray_bootstrap_key... | Returns ssh key to connecting to cluster workers.
If the env var TUNE_CLUSTER_SSH_KEY is provided, then this key
will be used for syncing across different nodes. |
def dump_privatekey(type, pkey, cipher=None, passphrase=None):
"""
Dump the private key *pkey* into a buffer string encoded with the type
*type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it
using *cipher* and *passphrase*.
:param type: The file type (one of :const:`FILETYPE_PEM`,... | Dump the private key *pkey* into a buffer string encoded with the type
*type*. Optionally (if *type* is :const:`FILETYPE_PEM`) encrypting it
using *cipher* and *passphrase*.
:param type: The file type (one of :const:`FILETYPE_PEM`,
:const:`FILETYPE_ASN1`, or :const:`FILETYPE_TEXT`)
:param PKey... |
def token_middleware(ctx, get_response):
"""Reinject token and consistency into requests.
"""
async def middleware(request):
params = request.setdefault('params', {})
if params.get("token") is None:
params['token'] = ctx.token
return await get_response(request)
return... | Reinject token and consistency into requests. |
def get_items(self) -> Iterator[StoryItem]:
"""Retrieve all items from a story."""
yield from (StoryItem(self._context, item, self.owner_profile) for item in reversed(self._node['items'])) | Retrieve all items from a story. |
def crawl(self, urls, name='crawl', api='analyze', **kwargs):
"""Crawlbot API.
Returns a diffbot.Job object to check and retrieve crawl status.
"""
# If multiple seed URLs are specified, join with whitespace.
if isinstance(urls, list):
urls = ' '.join(urls)
u... | Crawlbot API.
Returns a diffbot.Job object to check and retrieve crawl status. |
def check_uniqueness(self, *args):
"""For a unique index, check if the given args are not used twice
For the parameters, seen BaseIndex.check_uniqueness
"""
self.get_unique_index().check_uniqueness(*self.prepare_args(args, transform=False)) | For a unique index, check if the given args are not used twice
For the parameters, seen BaseIndex.check_uniqueness |
def refresh(self):
"""Re-pulls the data from redis"""
pipe = self.redis.pipeline()
pipe.hget(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "metadata")
pipe.hget(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "choices")
pipe.hget(EXPERIMENT_REDIS_KEY_TEMPLATE % self.name, "default-choice... | Re-pulls the data from redis |
def perform_word_selection(self, event=None):
"""
Performs word selection
:param event: QMouseEvent
"""
self.editor.setTextCursor(
TextHelper(self.editor).word_under_cursor(True))
if event:
event.accept() | Performs word selection
:param event: QMouseEvent |
def _strip_metadata(self, my_dict):
"""
Create a copy of dict and remove not needed data
"""
new_dict = copy.deepcopy(my_dict)
if const.START in new_dict:
del new_dict[const.START]
if const.END in new_dict:
del new_dict[const.END]
if const.... | Create a copy of dict and remove not needed data |
def retrieve(self, request, project, pk=None):
"""
GET method implementation for a note detail
"""
try:
serializer = JobNoteSerializer(JobNote.objects.get(id=pk))
return Response(serializer.data)
except JobNote.DoesNotExist:
return Response("N... | GET method implementation for a note detail |
def subsc_search(self, article_code, **kwargs):
'''taobao.vas.subsc.search 订购记录导出
用于ISV查询自己名下的应用及收费项目的订购记录'''
request = TOPRequest('taobao.vas.subsc.search')
request['article_code'] = article_code
for k, v in kwargs.iteritems():
if k not in ('item_code', 'nic... | taobao.vas.subsc.search 订购记录导出
用于ISV查询自己名下的应用及收费项目的订购记录 |
def raw_pitch_accuracy(ref_voicing, ref_cent, est_voicing, est_cent,
cent_tolerance=50):
"""Compute the raw pitch accuracy given two pitch (frequency) sequences in
cents and matching voicing indicator sequences. The first pitch and voicing
arrays are treated as the reference (truth), ... | Compute the raw pitch accuracy given two pitch (frequency) sequences in
cents and matching voicing indicator sequences. The first pitch and voicing
arrays are treated as the reference (truth), and the second two as the
estimate (prediction). All 4 sequences must be of the same length.
Examples
---... |
def assign(self, **kwargs):
r"""
Assign new columns to a DataFrame.
Returns a new object with all original columns in addition to new ones.
Existing columns that are re-assigned will be overwritten.
Parameters
----------
**kwargs : dict of {str: callable or Seri... | r"""
Assign new columns to a DataFrame.
Returns a new object with all original columns in addition to new ones.
Existing columns that are re-assigned will be overwritten.
Parameters
----------
**kwargs : dict of {str: callable or Series}
The column names are... |
def endpoint(self, endpoint):
"""Like :meth:`Flask.endpoint` but for a blueprint. This does not
prefix the endpoint with the blueprint name, this has to be done
explicitly by the user of this method. If the endpoint is prefixed
with a `.` it will be registered to the current blueprint,... | Like :meth:`Flask.endpoint` but for a blueprint. This does not
prefix the endpoint with the blueprint name, this has to be done
explicitly by the user of this method. If the endpoint is prefixed
with a `.` it will be registered to the current blueprint, otherwise
it's an application in... |
def parse_ipv6_literal_host(entity, default_port):
"""Validates an IPv6 literal host:port string.
Returns a 2-tuple of IPv6 literal followed by port where
port is default_port if it wasn't specified in entity.
:Parameters:
- `entity`: A string that represents an IPv6 literal enclosed
... | Validates an IPv6 literal host:port string.
Returns a 2-tuple of IPv6 literal followed by port where
port is default_port if it wasn't specified in entity.
:Parameters:
- `entity`: A string that represents an IPv6 literal enclosed
in braces (e.g. '[::1]' or '[::1]:27017').
... |
def delete(self, obj):
"""
Delete an object in CDSTAR and remove it from the catalog.
:param obj: An object ID or an Object instance.
"""
obj = self.api.get_object(getattr(obj, 'id', obj))
obj.delete()
self.remove(obj.id) | Delete an object in CDSTAR and remove it from the catalog.
:param obj: An object ID or an Object instance. |
def _get_request_type(self):
"""Find requested request type in POST request."""
value = self.document.tag.lower()
if value in allowed_request_types[self.params['service']]:
self.params["request"] = value
else:
raise OWSInvalidParameterValue("Request type %s is not... | Find requested request type in POST request. |
def repr_args(args):
"""formats a list of function arguments prettily but as working code
(kwargs are tuples (argname, argvalue)
"""
res = []
for x in args:
if isinstance(x, tuple) and len(x) == 2:
key, value = x
# todo: exclude this key if value is its default
... | formats a list of function arguments prettily but as working code
(kwargs are tuples (argname, argvalue) |
def all(cls, klass, db_session=None):
"""
returns all objects of specific type - will work correctly with
sqlalchemy inheritance models, you should normally use models
base_query() instead of this function its for bw. compat purposes
:param klass:
:param db_session:
... | returns all objects of specific type - will work correctly with
sqlalchemy inheritance models, you should normally use models
base_query() instead of this function its for bw. compat purposes
:param klass:
:param db_session:
:return: |
def check_enable_mode(self, check_string=""):
"""Check if in enable mode. Return boolean.
:param check_string: Identification of privilege mode from device
:type check_string: str
"""
self.write_channel(self.RETURN)
output = self.read_until_prompt()
return check_... | Check if in enable mode. Return boolean.
:param check_string: Identification of privilege mode from device
:type check_string: str |
def jobs(request):
''' This is the view used by the executor.py scripts for getting / putting the test results.
Fetching some file for testing is changing the database, so using GET here is not really RESTish. Whatever.
A visible shared secret in the request is no problem, since the executors come
... | This is the view used by the executor.py scripts for getting / putting the test results.
Fetching some file for testing is changing the database, so using GET here is not really RESTish. Whatever.
A visible shared secret in the request is no problem, since the executors come
from trusted network... |
def get_correlation(self, t1, t2):
"""
Computes the correlation coefficient for the specified periods.
:param float t1:
First period of interest.
:param float t2:
Second period of interest.
:return float rho:
The predicted correlation coeffi... | Computes the correlation coefficient for the specified periods.
:param float t1:
First period of interest.
:param float t2:
Second period of interest.
:return float rho:
The predicted correlation coefficient. |
def update_devices(self, devices):
"""Update values from response of URL_DEVICES, callback if changed."""
for qspacket in devices:
try:
qsid = qspacket[QS_ID]
except KeyError:
_LOGGER.debug("Device without ID: %s", qspacket)
continu... | Update values from response of URL_DEVICES, callback if changed. |
def ud_grade_ipix(ipix, nside_in, nside_out, nest=False):
"""
Upgrade or degrade resolution of a pixel list.
Parameters:
-----------
ipix:array-like
the input pixel(s)
nside_in:int
the nside of the input pixel(s)
nside_out:int
the desired nside of the output pixel(s)
ord... | Upgrade or degrade resolution of a pixel list.
Parameters:
-----------
ipix:array-like
the input pixel(s)
nside_in:int
the nside of the input pixel(s)
nside_out:int
the desired nside of the output pixel(s)
order:str
pixel ordering of input and output ("RING" or "NESTED")
... |
def reconnect(self):
""" (Re)establish the gateway connection
@return: True if connection was established
"""
self._converters.clear()
self._gateway = None
self._xsltFactory = None
try:
# print("Starting Java gateway on port: %s" % self._gwPort)
... | (Re)establish the gateway connection
@return: True if connection was established |
def requires(self, extras=()):
"""List of Requirements needed for this distro if `extras` are used"""
dm = self._dep_map
deps = []
deps.extend(dm.get(None, ()))
for ext in extras:
try:
deps.extend(dm[safe_extra(ext)])
except KeyError:
... | List of Requirements needed for this distro if `extras` are used |
def _do_search(conf):
'''
Builds connection and search arguments, performs the LDAP search and
formats the results as a dictionary appropriate for pillar use.
'''
# Build LDAP connection args
connargs = {}
for name in ['server', 'port', 'tls', 'binddn', 'bindpw', 'anonymous']:
connar... | Builds connection and search arguments, performs the LDAP search and
formats the results as a dictionary appropriate for pillar use. |
def yellow(cls):
"Make the text foreground color yellow."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.FOREGROUND_MASK
wAttributes |= win32.FOREGROUND_YELLOW
cls._set_text_attributes(wAttributes) | Make the text foreground color yellow. |
def _started_channels(self):
"""Reimplemented to make a history request and load %guiref."""
super(IPythonWidget, self)._started_channels()
self._load_guiref_magic()
self.kernel_manager.shell_channel.history(hist_access_type='tail',
n=100... | Reimplemented to make a history request and load %guiref. |
def _add_study_provenance(
self,
phenotyping_center,
colony,
project_fullname,
pipeline_name,
pipeline_stable_id,
procedure_stable_id,
procedure_name,
parameter_stable_id,
parameter_name,
... | :param phenotyping_center: str, from self.files['all']
:param colony: str, from self.files['all']
:param project_fullname: str, from self.files['all']
:param pipeline_name: str, from self.files['all']
:param pipeline_stable_id: str, from self.files['all']
:param procedure_stable_... |
def get_agents(self):
"""Gets all ``Agents``.
In plenary mode, the returned list contains all known agents or
an error results. Otherwise, the returned list may contain only
those agents that are accessible through this session.
return: (osid.authentication.AgentList) - a list ... | Gets all ``Agents``.
In plenary mode, the returned list contains all known agents or
an error results. Otherwise, the returned list may contain only
those agents that are accessible through this session.
return: (osid.authentication.AgentList) - a list of ``Agents``
raise: Ope... |
def astype(self, dtype):
"""Return a copy of this space with new ``dtype``.
Parameters
----------
dtype :
Scalar data type of the returned space. Can be provided
in any way the `numpy.dtype` constructor understands, e.g.
as built-in type or as a strin... | Return a copy of this space with new ``dtype``.
Parameters
----------
dtype :
Scalar data type of the returned space. Can be provided
in any way the `numpy.dtype` constructor understands, e.g.
as built-in type or as a string. Data types with non-trivial
... |
def _set_src_vtep_ip(self, v, load=False):
"""
Setter method for src_vtep_ip, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/src_vtep_ip (inet:ipv4-address)
If this variable is read-only (config: false) in the
source YANG file, then _set_src_vtep_ip is considered as a private
... | Setter method for src_vtep_ip, mapped from YANG variable /overlay/access_list/type/vxlan/standard/seq/src_vtep_ip (inet:ipv4-address)
If this variable is read-only (config: false) in the
source YANG file, then _set_src_vtep_ip is considered as a private
method. Backends looking to populate this variable sho... |
def _authenticate(self):
"""Authenticate user and generate token."""
self.cleanup_headers()
url = LOGIN_ENDPOINT
data = self.query(
url,
method='POST',
extra_params={
'email': self.__username,
'password': self.__password... | Authenticate user and generate token. |
def check_subscriber_key_length(app_configs=None, **kwargs):
"""
Check that DJSTRIPE_SUBSCRIBER_CUSTOMER_KEY fits in metadata.
Docs: https://stripe.com/docs/api#metadata
"""
from . import settings as djstripe_settings
messages = []
key = djstripe_settings.SUBSCRIBER_CUSTOMER_KEY
key_size = len(str(key))
if ... | Check that DJSTRIPE_SUBSCRIBER_CUSTOMER_KEY fits in metadata.
Docs: https://stripe.com/docs/api#metadata |
def pandasdfsummarytojson(df, ndigits=3):
"""
Convert the result of a
Parameters
----------
df : The result of a Pandas describe operation.
ndigits : int, optional - The number of significant digits to round to.
Returns
-------
A json object which captures the describe. Keys are f... | Convert the result of a
Parameters
----------
df : The result of a Pandas describe operation.
ndigits : int, optional - The number of significant digits to round to.
Returns
-------
A json object which captures the describe. Keys are field names and
values are dictionaries with all of... |
def all(cls, sort=None, limit=None):
"""Returns all objects of this type. Alias for where() (without filter arguments).
See `where` for documentation on the `sort` and `limit` parameters.
"""
return cls.where(sort=sort, limit=limit) | Returns all objects of this type. Alias for where() (without filter arguments).
See `where` for documentation on the `sort` and `limit` parameters. |
def parse_config(data: dict) -> dict:
"""Parse MIP config file.
Args:
data (dict): raw YAML input from MIP analysis config file
Returns:
dict: parsed data
"""
return {
'email': data.get('email'),
'family': data['family_id'],
'samples': [{
'id': s... | Parse MIP config file.
Args:
data (dict): raw YAML input from MIP analysis config file
Returns:
dict: parsed data |
def get_tasks(self):
"""
Get the tasks attached to the instance
Returns
-------
list
List of tasks (:class:`asyncio.Task`)
"""
tasks = self._get_tasks()
tasks.extend(self._streams.get_tasks(self))
return tasks | Get the tasks attached to the instance
Returns
-------
list
List of tasks (:class:`asyncio.Task`) |
def diffuser_conical(Di1, Di2, l=None, angle=None, fd=None, Re=None,
roughness=0.0, method='Rennels'):
r'''Returns the loss coefficient for any conical pipe diffuser.
This calculation has four methods available.
The 'Rennels' [1]_ formulas are as follows (three different formulas a... | r'''Returns the loss coefficient for any conical pipe diffuser.
This calculation has four methods available.
The 'Rennels' [1]_ formulas are as follows (three different formulas are
used, depending on the angle and the ratio of diameters):
For 0 to 20 degrees, all aspect ratios:
.. math::
... |
def print_err(*args, **kwargs):
""" A wrapper for print() that uses stderr by default. """
if kwargs.get('file', None) is None:
kwargs['file'] = sys.stderr
color = dict_pop_or(kwargs, 'color', True)
# Use color if asked, but only if the file is a tty.
if color and kwargs['file'].isatty():
... | A wrapper for print() that uses stderr by default. |
def get_as(self, cls: Type[MaybeBytesT]) -> Sequence[MaybeBytesT]:
"""Return the list of parsed objects."""
_ = cls # noqa
return cast(Sequence[MaybeBytesT], self.items) | Return the list of parsed objects. |
def optionally_with_args(phase, **kwargs):
"""Apply only the args that the phase knows.
If the phase has a **kwargs-style argument, it counts as knowing all args.
Args:
phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or
iterable of those, the phase or phase group (or iterable) to ... | Apply only the args that the phase knows.
If the phase has a **kwargs-style argument, it counts as knowing all args.
Args:
phase: phase_descriptor.PhaseDescriptor or PhaseGroup or callable, or
iterable of those, the phase or phase group (or iterable) to apply
with_args to.
**kwargs: argume... |
def fix(csvfile):
'''Apply a fix (ie. remove plain names)'''
header('Apply fixes from {}', csvfile.name)
bads = []
reader = csv.reader(csvfile)
reader.next() # Skip header
for id, _, sources, dests in reader:
advice = Advice.objects.get(id=id)
sources = [s.strip() for s in sourc... | Apply a fix (ie. remove plain names) |
def outgoing_caller_ids(self):
"""
Access the outgoing_caller_ids
:returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList
:rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList
"""
if self._outgoing_caller_ids is None:
... | Access the outgoing_caller_ids
:returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList
:rtype: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdList |
def get_autoscaling_group_properties(asg_client, env, service):
"""
Gets the autoscaling group properties based on the service name that is provided. This function will attempt the find
the autoscaling group base on the following logic:
1. If the service name provided matches the autoscaling group name
2.... | Gets the autoscaling group properties based on the service name that is provided. This function will attempt the find
the autoscaling group base on the following logic:
1. If the service name provided matches the autoscaling group name
2. If the service name provided matches the Name tag of the autoscaling gr... |
def mode_number(self, rows: List[Row], column: NumberColumn) -> Number:
"""
Takes a list of rows and a column and returns the most frequent value under
that column in those rows.
"""
most_frequent_list = self._get_most_frequent_values(rows, column)
if not most_frequent_li... | Takes a list of rows and a column and returns the most frequent value under
that column in those rows. |
def _conflicted_data_points(L):
"""Returns an indicator vector where ith element = 1 if x_i is labeled by
at least two LFs that give it disagreeing labels."""
m = sparse.diags(np.ravel(L.max(axis=1).todense()))
return np.ravel(np.max(m @ (L != 0) != L, axis=1).astype(int).todense()) | Returns an indicator vector where ith element = 1 if x_i is labeled by
at least two LFs that give it disagreeing labels. |
def check_schema_coverage(doc, schema):
'''
FORWARD CHECK OF DOCUMENT
This routine looks at each element in the doc, and makes sure there
is a matching 'name' in the schema at that level.
'''
error_list = []
to_delete = []
for entry in doc.list_tuples():
(name, value, index,... | FORWARD CHECK OF DOCUMENT
This routine looks at each element in the doc, and makes sure there
is a matching 'name' in the schema at that level. |
def _write_passphrase(stream, passphrase, encoding):
"""Write the passphrase from memory to the GnuPG process' stdin.
:type stream: file, :class:`~io.BytesIO`, or :class:`~io.StringIO`
:param stream: The input file descriptor to write the password to.
:param str passphrase: The passphrase for the secre... | Write the passphrase from memory to the GnuPG process' stdin.
:type stream: file, :class:`~io.BytesIO`, or :class:`~io.StringIO`
:param stream: The input file descriptor to write the password to.
:param str passphrase: The passphrase for the secret key material.
:param str encoding: The data encoding e... |
def autoprefixer(input, **kw):
"""Run autoprefixer"""
cmd = '%s -b "%s" %s' % (current_app.config.get('AUTOPREFIXER_BIN'),
current_app.config.get('AUTOPREFIXER_BROWSERS'),
input)
subprocess.call(cmd, shell=True) | Run autoprefixer |
def _parse_nicknameinuse(client, command, actor, args):
"""Parse a NICKNAMEINUSE message and dispatch an event.
The parameter passed along with the event is the nickname
which is already in use.
"""
nick, _, _ = args.rpartition(" ")
client.dispatch_event("NICKNAMEINUSE", nick) | Parse a NICKNAMEINUSE message and dispatch an event.
The parameter passed along with the event is the nickname
which is already in use. |
def assign_objective_requisite(self, objective_id, requisite_objective_id):
"""Creates a requirement dependency between two ``Objectives``.
arg: objective_id (osid.id.Id): the ``Id`` of the dependent
``Objective``
arg: requisite_objective_id (osid.id.Id): the ``Id`` of the... | Creates a requirement dependency between two ``Objectives``.
arg: objective_id (osid.id.Id): the ``Id`` of the dependent
``Objective``
arg: requisite_objective_id (osid.id.Id): the ``Id`` of the
required ``Objective``
raise: AlreadyExists - ``objective_id`... |
def write_byte(self, address, value):
"""Writes the byte to unaddressed register in a device. """
LOGGER.debug("Writing byte %s to device %s!", bin(value), hex(address))
return self.driver.write_byte(address, value) | Writes the byte to unaddressed register in a device. |
def restore_state(self, state):
"""Restore the current state of this emulated object.
Args:
state (dict): A previously dumped state produced by dump_state.
"""
super(ReferenceController, self).restore_state(state)
state_name = state.get('state_name')
state_... | Restore the current state of this emulated object.
Args:
state (dict): A previously dumped state produced by dump_state. |
def parse(self, data):
# type: (bytes) -> None
'''
Parse the passed in data into a UDF ICB Tag.
Parameters:
data - The data to parse.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInternalError('UDF ICB Ta... | Parse the passed in data into a UDF ICB Tag.
Parameters:
data - The data to parse.
Returns:
Nothing. |
def handle_cf_error(error_pointer):
"""
Checks a CFErrorRef and throws an exception if there is an error to report
:param error_pointer:
A CFErrorRef
:raises:
OSError - when the CFErrorRef contains an error
"""
if is_null(error_pointer):
return
error = unwrap(erro... | Checks a CFErrorRef and throws an exception if there is an error to report
:param error_pointer:
A CFErrorRef
:raises:
OSError - when the CFErrorRef contains an error |
def list_models(self, limit=-1, offset=-1):
"""Get a list of models in the registry.
Parameters
----------
limit : int
Limit number of items in the result set
offset : int
Set offset in list (order as defined by object store)
Returns
-------
li... | Get a list of models in the registry.
Parameters
----------
limit : int
Limit number of items in the result set
offset : int
Set offset in list (order as defined by object store)
Returns
-------
list(ModelHandle) |
def disconnect(self, signal=None, slot=None, transform=None, condition=None):
"""Removes connection(s) between this objects signal and connected slot(s)
signal: the signal this class will emit, to cause the slot method to be called
receiver: the object containing the slot method to be cal... | Removes connection(s) between this objects signal and connected slot(s)
signal: the signal this class will emit, to cause the slot method to be called
receiver: the object containing the slot method to be called
slot: the slot method or function to call
transform: an optiona... |
def attach_bytes(key, the_bytes):
"""Adds a ModuleAttachment to the current graph.
Args:
key: A string with the unique key of the attachment.
the_bytes: A bytes object with the serialized attachment.
"""
tf_v1.add_to_collection(
_ATTACHMENT_COLLECTION_INTERNAL,
module_attachment_pb2.ModuleA... | Adds a ModuleAttachment to the current graph.
Args:
key: A string with the unique key of the attachment.
the_bytes: A bytes object with the serialized attachment. |
def setCustomColorRamp(self, colors=[], interpolatedPoints=10):
"""
Accepts a list of RGB tuples and interpolates between them to create a custom color ramp.
Returns the color ramp as a list of RGB tuples.
"""
self._colorRamp = ColorRampGenerator.generateCustomColorRamp(colors, i... | Accepts a list of RGB tuples and interpolates between them to create a custom color ramp.
Returns the color ramp as a list of RGB tuples. |
def from_utf8(buf, errors='replace'):
""" Decodes a UTF-8 compatible, ASCII string into a unicode object.
`buf`
string or unicode string to convert.
Returns unicode` string.
* Raises a ``UnicodeDecodeError`` exception if encoding failed and
`errors` isn't set to 'rep... | Decodes a UTF-8 compatible, ASCII string into a unicode object.
`buf`
string or unicode string to convert.
Returns unicode` string.
* Raises a ``UnicodeDecodeError`` exception if encoding failed and
`errors` isn't set to 'replace'. |
def pause(self, instance_id, keep_provisioned=True):
"""shuts down the instance without destroying it.
The AbstractCloudProvider class uses 'stop' to refer to destroying
a VM, so use 'pause' to mean powering it down while leaving it
allocated.
:param str instance_id: instance i... | shuts down the instance without destroying it.
The AbstractCloudProvider class uses 'stop' to refer to destroying
a VM, so use 'pause' to mean powering it down while leaving it
allocated.
:param str instance_id: instance identifier
:return: None |
def xmlrpc_provision(self, app_id, path_to_cert_or_cert, environment, timeout=15):
""" Starts an APNSService for the this app_id and keeps it running
Arguments:
app_id the app_id to provision for APNS
path_to_cert_or_cert absolute path to the APNS SSL cert or a
... | Starts an APNSService for the this app_id and keeps it running
Arguments:
app_id the app_id to provision for APNS
path_to_cert_or_cert absolute path to the APNS SSL cert or a
string containing the .pem file
environment ... |
def read_json(self, params=None):
"""Get information about the current entity.
Call :meth:`read_raw`. Check the response status code, decode JSON and
return the decoded JSON as a dict.
:return: A dict. The server's response, with all JSON decoded.
:raises: ``requests.exceptions... | Get information about the current entity.
Call :meth:`read_raw`. Check the response status code, decode JSON and
return the decoded JSON as a dict.
:return: A dict. The server's response, with all JSON decoded.
:raises: ``requests.exceptions.HTTPError`` if the response has an HTTP
... |
def asyncPipeRegex(context=None, _INPUT=None, conf=None, **kwargs):
"""An operator that asynchronously replaces text in items using regexes.
Each has the general format: "In [field] replace [match] with [replace]".
Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT ... | An operator that asynchronously replaces text in items using regexes.
Each has the general format: "In [field] replace [match] with [replace]".
Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : asyncPipe like object (twisted Deferred iterable of items)
conf : {
... |
def handle_sketch_version(msg):
"""Process an internal sketch version message."""
if not msg.gateway.is_sensor(msg.node_id):
return None
msg.gateway.sensors[msg.node_id].sketch_version = msg.payload
msg.gateway.alert(msg)
return None | Process an internal sketch version message. |
def read_config(config_fname=None):
"""Parse input configuration file and return a config dict."""
if not config_fname:
config_fname = DEFAULT_CONFIG_FNAME
try:
with open(config_fname, 'r') as config_file:
config = yaml.load(config_file)
except IOError as exc:
if ex... | Parse input configuration file and return a config dict. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.