code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def create_output(data, options):
"""
Create Nagios and human readable supervisord statuses.
:param data: supervisord XML-RPC call result.
:type data: dict.
:param options: parsed commandline arguments.
:type options: optparse.Values.
:return: Nagios and human readable supervisord statuses ... | Create Nagios and human readable supervisord statuses.
:param data: supervisord XML-RPC call result.
:type data: dict.
:param options: parsed commandline arguments.
:type options: optparse.Values.
:return: Nagios and human readable supervisord statuses and exit code.
:rtype: (str, int). | Below is the the instruction that describes the task:
### Input:
Create Nagios and human readable supervisord statuses.
:param data: supervisord XML-RPC call result.
:type data: dict.
:param options: parsed commandline arguments.
:type options: optparse.Values.
:return: Nagios and human readabl... |
def _handle_result_by_index(self, idx):
"""
Handle processing when the result argument provided is an integer.
"""
if idx < 0:
return None
opts = dict(self.options)
skip = opts.pop('skip', 0)
limit = opts.pop('limit', None)
py_to_couch_validate... | Handle processing when the result argument provided is an integer. | Below is the the instruction that describes the task:
### Input:
Handle processing when the result argument provided is an integer.
### Response:
def _handle_result_by_index(self, idx):
"""
Handle processing when the result argument provided is an integer.
"""
if idx < 0:
... |
def on_connection_unblocked(self, method_frame):
"""When RabbitMQ indicates the connection is unblocked, set the state
appropriately.
:param pika.amqp_object.Method method_frame: Unblocked method frame
"""
LOGGER.debug('Connection unblocked: %r', method_frame)
self.stat... | When RabbitMQ indicates the connection is unblocked, set the state
appropriately.
:param pika.amqp_object.Method method_frame: Unblocked method frame | Below is the the instruction that describes the task:
### Input:
When RabbitMQ indicates the connection is unblocked, set the state
appropriately.
:param pika.amqp_object.Method method_frame: Unblocked method frame
### Response:
def on_connection_unblocked(self, method_frame):
"""When Rabb... |
def synchronizeLayout(primary, secondary, surface_size):
"""Synchronizes given layouts by normalizing height by using
max height of given layouts to avoid transistion dirty effects.
:param primary: Primary layout used.
:param secondary: Secondary layout used.
:param surface_size: Target surface siz... | Synchronizes given layouts by normalizing height by using
max height of given layouts to avoid transistion dirty effects.
:param primary: Primary layout used.
:param secondary: Secondary layout used.
:param surface_size: Target surface size on which layout will be displayed. | Below is the the instruction that describes the task:
### Input:
Synchronizes given layouts by normalizing height by using
max height of given layouts to avoid transistion dirty effects.
:param primary: Primary layout used.
:param secondary: Secondary layout used.
:param surface_size: Target surfac... |
def add_record(self, msg_id, rec):
"""Add a new Task Record, by msg_id."""
if self._records.has_key(msg_id):
raise KeyError("Already have msg_id %r"%(msg_id))
self._records[msg_id] = rec | Add a new Task Record, by msg_id. | Below is the the instruction that describes the task:
### Input:
Add a new Task Record, by msg_id.
### Response:
def add_record(self, msg_id, rec):
"""Add a new Task Record, by msg_id."""
if self._records.has_key(msg_id):
raise KeyError("Already have msg_id %r"%(msg_id))
self._r... |
def p_duration_information_speed(self, p):
'duration : information AT speed'
logger.debug('duration = information %s at speed %s', p[1], p[3])
p[0] = p[1].at_speed(p[3]) | duration : information AT speed | Below is the the instruction that describes the task:
### Input:
duration : information AT speed
### Response:
def p_duration_information_speed(self, p):
'duration : information AT speed'
logger.debug('duration = information %s at speed %s', p[1], p[3])
p[0] = p[1].at_speed(p[3]) |
def find_specs(self, directory):
"""Finds all specs in a given directory. Returns a list of
Example and ExampleGroup instances.
"""
specs = []
spec_files = self.file_finder.find(directory)
for spec_file in spec_files:
specs.extend(self.spec_finder.find(spec_fi... | Finds all specs in a given directory. Returns a list of
Example and ExampleGroup instances. | Below is the the instruction that describes the task:
### Input:
Finds all specs in a given directory. Returns a list of
Example and ExampleGroup instances.
### Response:
def find_specs(self, directory):
"""Finds all specs in a given directory. Returns a list of
Example and ExampleGroup ins... |
def terms(self):
"""Iterator over the terms of the sum
Yield from the (possibly) infinite list of terms of the indexed sum, if
the sum was written out explicitly. Each yielded term in an instance of
:class:`.Expression`
"""
from qnet.algebra.core.scalar_algebra import Sc... | Iterator over the terms of the sum
Yield from the (possibly) infinite list of terms of the indexed sum, if
the sum was written out explicitly. Each yielded term in an instance of
:class:`.Expression` | Below is the the instruction that describes the task:
### Input:
Iterator over the terms of the sum
Yield from the (possibly) infinite list of terms of the indexed sum, if
the sum was written out explicitly. Each yielded term in an instance of
:class:`.Expression`
### Response:
def terms(s... |
def from_p12_keyfile_buffer(cls, service_account_email, file_buffer,
private_key_password=None, scopes='',
token_uri=oauth2client.GOOGLE_TOKEN_URI,
revoke_uri=oauth2client.GOOGLE_REVOKE_URI):
"""Factory constructor f... | Factory constructor from JSON keyfile.
Args:
service_account_email: string, The email associated with the
service account.
file_buffer: stream, A buffer that implements ``read()``
and contains the PKCS#12 key contents.
... | Below is the the instruction that describes the task:
### Input:
Factory constructor from JSON keyfile.
Args:
service_account_email: string, The email associated with the
service account.
file_buffer: stream, A buffer that implements ``read()``
... |
def SetWeekdayService(self, has_service=True):
"""Set service as running (or not) on all of Monday through Friday."""
for i in range(0, 5):
self.SetDayOfWeekHasService(i, has_service) | Set service as running (or not) on all of Monday through Friday. | Below is the the instruction that describes the task:
### Input:
Set service as running (or not) on all of Monday through Friday.
### Response:
def SetWeekdayService(self, has_service=True):
"""Set service as running (or not) on all of Monday through Friday."""
for i in range(0, 5):
self.SetDayOfWeek... |
def spkw12(handle, body, center, inframe, first, last, segid, degree, n, states,
epoch0, step):
"""
Write a type 12 segment to an SPK file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw12_c.html
:param handle: Handle of an SPK file open for writing.
:type handle: int
... | Write a type 12 segment to an SPK file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw12_c.html
:param handle: Handle of an SPK file open for writing.
:type handle: int
:param body: NAIF code for an ephemeris object.
:type body: int
:param center: NAIF code for center of motion o... | Below is the the instruction that describes the task:
### Input:
Write a type 12 segment to an SPK file.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw12_c.html
:param handle: Handle of an SPK file open for writing.
:type handle: int
:param body: NAIF code for an ephemeris object.
... |
def run(self):
"""
Run the plugin.
"""
# Only run if the build was successful
if self.workflow.build_process_failed:
self.log.info("Not promoting failed build to koji")
return
self.koji_session = get_koji_session(self.workflow, self.koji_fallback)... | Run the plugin. | Below is the the instruction that describes the task:
### Input:
Run the plugin.
### Response:
def run(self):
"""
Run the plugin.
"""
# Only run if the build was successful
if self.workflow.build_process_failed:
self.log.info("Not promoting failed build to koji")... |
def leaves(value, prefix=None):
"""
LIKE items() BUT RECURSIVE, AND ONLY FOR THE LEAVES (non dict) VALUES
SEE wrap_leaves FOR THE INVERSE
:param value: THE Mapping TO TRAVERSE
:param prefix: OPTIONAL PREFIX GIVEN TO EACH KEY
:return: Data, WHICH EACH KEY BEING A PATH INTO value TREE
"""
... | LIKE items() BUT RECURSIVE, AND ONLY FOR THE LEAVES (non dict) VALUES
SEE wrap_leaves FOR THE INVERSE
:param value: THE Mapping TO TRAVERSE
:param prefix: OPTIONAL PREFIX GIVEN TO EACH KEY
:return: Data, WHICH EACH KEY BEING A PATH INTO value TREE | Below is the the instruction that describes the task:
### Input:
LIKE items() BUT RECURSIVE, AND ONLY FOR THE LEAVES (non dict) VALUES
SEE wrap_leaves FOR THE INVERSE
:param value: THE Mapping TO TRAVERSE
:param prefix: OPTIONAL PREFIX GIVEN TO EACH KEY
:return: Data, WHICH EACH KEY BEING A PATH I... |
def get_digests(self):
"""
Returns a map of images to their digests
"""
try:
pulp = get_manifests_in_pulp_repository(self.workflow)
except KeyError:
pulp = None
digests = {} # repository -> digests
for registry in self.workflow.push_conf... | Returns a map of images to their digests | Below is the the instruction that describes the task:
### Input:
Returns a map of images to their digests
### Response:
def get_digests(self):
"""
Returns a map of images to their digests
"""
try:
pulp = get_manifests_in_pulp_repository(self.workflow)
except Key... |
def parse_request(self, data):
"""Deserializes and validates a request.
Called by the server to reconstruct the serialized :py:class:`JSONRPCRequest`.
:param bytes data: The data stream received by the transport layer containing the
serialized request.
:return: A reconstruc... | Deserializes and validates a request.
Called by the server to reconstruct the serialized :py:class:`JSONRPCRequest`.
:param bytes data: The data stream received by the transport layer containing the
serialized request.
:return: A reconstructed request.
:rtype: :py:class:`JS... | Below is the the instruction that describes the task:
### Input:
Deserializes and validates a request.
Called by the server to reconstruct the serialized :py:class:`JSONRPCRequest`.
:param bytes data: The data stream received by the transport layer containing the
serialized request.
... |
def connect(slug, config_loader):
"""
Ensure .cs50.yaml and tool key exists, raises Error otherwise
Check that all required files as per .cs50.yaml are present
Returns tool specific portion of .cs50.yaml
"""
with ProgressBar(_("Connecting")):
# Parse slug
slug = Slug(slug)
... | Ensure .cs50.yaml and tool key exists, raises Error otherwise
Check that all required files as per .cs50.yaml are present
Returns tool specific portion of .cs50.yaml | Below is the the instruction that describes the task:
### Input:
Ensure .cs50.yaml and tool key exists, raises Error otherwise
Check that all required files as per .cs50.yaml are present
Returns tool specific portion of .cs50.yaml
### Response:
def connect(slug, config_loader):
"""
Ensure .cs50.yam... |
def set_path(self, path, val):
"""
Set the given value at the supplied path where path is either
a tuple of strings or a string in A.B.C format.
"""
path = tuple(path.split('.')) if isinstance(path , str) else tuple(path)
disallowed = [p for p in path if not type(self)._... | Set the given value at the supplied path where path is either
a tuple of strings or a string in A.B.C format. | Below is the the instruction that describes the task:
### Input:
Set the given value at the supplied path where path is either
a tuple of strings or a string in A.B.C format.
### Response:
def set_path(self, path, val):
"""
Set the given value at the supplied path where path is either
... |
def async_get_measurements(self, uid, fields='*'):
"""Get measurements of a device."""
return (yield from self._get('/pods/{}/measurements'.format(uid),
fields=fields))[0] | Get measurements of a device. | Below is the the instruction that describes the task:
### Input:
Get measurements of a device.
### Response:
def async_get_measurements(self, uid, fields='*'):
"""Get measurements of a device."""
return (yield from self._get('/pods/{}/measurements'.format(uid),
... |
def get_changeform_initial_data(self, request):
"""
Provide initial datas when creating an entry.
"""
get_data = super(EntryAdmin, self).get_changeform_initial_data(request)
return get_data or {
'sites': [Site.objects.get_current().pk],
'authors': [request... | Provide initial datas when creating an entry. | Below is the the instruction that describes the task:
### Input:
Provide initial datas when creating an entry.
### Response:
def get_changeform_initial_data(self, request):
"""
Provide initial datas when creating an entry.
"""
get_data = super(EntryAdmin, self).get_changeform_initia... |
def default_redirect(request, fallback_url, **kwargs):
"""
Evaluates a redirect url by consulting GET, POST and the session.
"""
redirect_field_name = kwargs.get("redirect_field_name", "next")
next = request.POST.get(redirect_field_name,
request.GET.get(redirect_field_nam... | Evaluates a redirect url by consulting GET, POST and the session. | Below is the the instruction that describes the task:
### Input:
Evaluates a redirect url by consulting GET, POST and the session.
### Response:
def default_redirect(request, fallback_url, **kwargs):
"""
Evaluates a redirect url by consulting GET, POST and the session.
"""
redirect_field_name = kwa... |
def _get_token(request):
"""
Gets authentication token from request header
Will raise 401 error if token not found
:return token: an authorization token.
"""
token = request.headers.get('Authorization')
if not token:
message = 'Token not in Authorization header'
logging.warni... | Gets authentication token from request header
Will raise 401 error if token not found
:return token: an authorization token. | Below is the the instruction that describes the task:
### Input:
Gets authentication token from request header
Will raise 401 error if token not found
:return token: an authorization token.
### Response:
def _get_token(request):
"""
Gets authentication token from request header
Will raise 401 e... |
def resizeEvent(self, event):
"""Reimplement Qt method"""
if not self.isMaximized() and not self.fullscreen_flag:
self.window_size = self.size()
QMainWindow.resizeEvent(self, event)
# To be used by the tour to be able to resize
self.sig_resized.emit(event) | Reimplement Qt method | Below is the the instruction that describes the task:
### Input:
Reimplement Qt method
### Response:
def resizeEvent(self, event):
"""Reimplement Qt method"""
if not self.isMaximized() and not self.fullscreen_flag:
self.window_size = self.size()
QMainWindow.resizeEvent(self,... |
def create(self, ex):
"helper for apply_sql in CreateX case"
if ex.name in self:
if ex.nexists: return
raise ValueError('table_exists',ex.name)
if any(c.pkey for c in ex.cols):
if ex.pkey:
raise sqparse2.SQLSyntaxError("don't mix table-level and column-level pkeys",ex)
... | helper for apply_sql in CreateX case | Below is the the instruction that describes the task:
### Input:
helper for apply_sql in CreateX case
### Response:
def create(self, ex):
"helper for apply_sql in CreateX case"
if ex.name in self:
if ex.nexists: return
raise ValueError('table_exists',ex.name)
if any(c.pkey for c in ex.... |
def getModelSummaryAsKml(self, session, path=None, documentName=None, withStreamNetwork=True, withNodes=False, styles={}):
"""
Retrieve a KML representation of the model. Includes polygonized mask map and vector stream network.
Args:
session (:mod:`sqlalchemy.orm.session.Session`): ... | Retrieve a KML representation of the model. Includes polygonized mask map and vector stream network.
Args:
session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database
path (str, optional): Path to file where KML file will be written. Defa... | Below is the the instruction that describes the task:
### Input:
Retrieve a KML representation of the model. Includes polygonized mask map and vector stream network.
Args:
session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session object bound to PostGIS enabled database
pa... |
def find_immediate_parent_tables(expr):
"""Find every first occurrence of a :class:`ibis.expr.types.TableExpr`
object in `expr`.
Parameters
----------
expr : ir.Expr
Yields
------
e : ir.Expr
Notes
-----
This function does not traverse into TableExpr objects. This means th... | Find every first occurrence of a :class:`ibis.expr.types.TableExpr`
object in `expr`.
Parameters
----------
expr : ir.Expr
Yields
------
e : ir.Expr
Notes
-----
This function does not traverse into TableExpr objects. This means that the
underlying PhysicalTable of a Select... | Below is the the instruction that describes the task:
### Input:
Find every first occurrence of a :class:`ibis.expr.types.TableExpr`
object in `expr`.
Parameters
----------
expr : ir.Expr
Yields
------
e : ir.Expr
Notes
-----
This function does not traverse into TableExpr ... |
def request(self, method, url, **kwargs):
"""
Overrides ``requests.Session.request`` to set the timeout.
"""
resp = super(ClientSession, self).request(
method, url, timeout=self._timeout, **kwargs)
return resp | Overrides ``requests.Session.request`` to set the timeout. | Below is the the instruction that describes the task:
### Input:
Overrides ``requests.Session.request`` to set the timeout.
### Response:
def request(self, method, url, **kwargs):
"""
Overrides ``requests.Session.request`` to set the timeout.
"""
resp = super(ClientSession, self).re... |
def set_shaders(self, vert, frag):
""" Set the vertex and fragment shaders.
Parameters
----------
vert : str
Source code for vertex shader.
frag : str
Source code for fragment shaders.
"""
if not vert or not frag:
raise... | Set the vertex and fragment shaders.
Parameters
----------
vert : str
Source code for vertex shader.
frag : str
Source code for fragment shaders. | Below is the the instruction that describes the task:
### Input:
Set the vertex and fragment shaders.
Parameters
----------
vert : str
Source code for vertex shader.
frag : str
Source code for fragment shaders.
### Response:
def set_shaders(self, ver... |
def readerForDoc(cur, URL, encoding, options):
"""Create an xmltextReader for an XML in-memory document. The
parsing flags @options are a combination of xmlParserOption. """
ret = libxml2mod.xmlReaderForDoc(cur, URL, encoding, options)
if ret is None:raise treeError('xmlReaderForDoc() failed')
ret... | Create an xmltextReader for an XML in-memory document. The
parsing flags @options are a combination of xmlParserOption. | Below is the the instruction that describes the task:
### Input:
Create an xmltextReader for an XML in-memory document. The
parsing flags @options are a combination of xmlParserOption.
### Response:
def readerForDoc(cur, URL, encoding, options):
"""Create an xmltextReader for an XML in-memory document. T... |
def validate_SUMTO(in_value, restriction):
"""
Test to ensure the values of a list sum to a specified value:
Parameters: a list of numeric values and a target to which the values
in the list must sum
"""
#Sometimes restriction values can accidentally be put in the template <item>100<... | Test to ensure the values of a list sum to a specified value:
Parameters: a list of numeric values and a target to which the values
in the list must sum | Below is the the instruction that describes the task:
### Input:
Test to ensure the values of a list sum to a specified value:
Parameters: a list of numeric values and a target to which the values
in the list must sum
### Response:
def validate_SUMTO(in_value, restriction):
"""
Test to ... |
def mul(self, o):
"""
Binary operation: multiplication
:param o: The other operand
:return: self * o
"""
if self.is_integer and o.is_integer:
# Two integers!
a, b = self.lower_bound, o.lower_bound
ret = StridedInterval(bits=self.bits,
... | Binary operation: multiplication
:param o: The other operand
:return: self * o | Below is the the instruction that describes the task:
### Input:
Binary operation: multiplication
:param o: The other operand
:return: self * o
### Response:
def mul(self, o):
"""
Binary operation: multiplication
:param o: The other operand
:return: self * o
... |
def prop_budget(self, budget):
"""
Set limit on the number of propagations.
"""
if self.minisat:
pysolvers.minisatgh_pbudget(self.minisat, budget) | Set limit on the number of propagations. | Below is the the instruction that describes the task:
### Input:
Set limit on the number of propagations.
### Response:
def prop_budget(self, budget):
"""
Set limit on the number of propagations.
"""
if self.minisat:
pysolvers.minisatgh_pbudget(self.minisat, budget) |
def auth_property(name, doc=None): # noqa: B902
"""A static helper function for subclasses to add extra authentication
system properties onto a class::
class FooAuthenticate(WWWAuthenticate):
special_realm = auth_property('special_realm')
For more information have ... | A static helper function for subclasses to add extra authentication
system properties onto a class::
class FooAuthenticate(WWWAuthenticate):
special_realm = auth_property('special_realm')
For more information have a look at the sourcecode to see how the
regular prop... | Below is the the instruction that describes the task:
### Input:
A static helper function for subclasses to add extra authentication
system properties onto a class::
class FooAuthenticate(WWWAuthenticate):
special_realm = auth_property('special_realm')
For more informat... |
def AppendPathEntries(
cls, path, path_separator, number_of_wildcards, skip_first):
"""Appends glob wildcards to a path.
This function will append glob wildcards "*" to a path, returning paths
with an additional glob wildcard up to the specified number. E.g. given
the path "/tmp" and a number of ... | Appends glob wildcards to a path.
This function will append glob wildcards "*" to a path, returning paths
with an additional glob wildcard up to the specified number. E.g. given
the path "/tmp" and a number of 2 wildcards, this function will return
"tmp/*", "tmp/*/*". When skip_first is true the path w... | Below is the the instruction that describes the task:
### Input:
Appends glob wildcards to a path.
This function will append glob wildcards "*" to a path, returning paths
with an additional glob wildcard up to the specified number. E.g. given
the path "/tmp" and a number of 2 wildcards, this function w... |
def get_unread(self, unset_has_mail=False, update_user=False, *args,
**kwargs):
"""Return a get_content generator for unread messages.
:param unset_has_mail: When True, clear the has_mail flag (orangered)
for the user.
:param update_user: If both `unset_has_mail` ... | Return a get_content generator for unread messages.
:param unset_has_mail: When True, clear the has_mail flag (orangered)
for the user.
:param update_user: If both `unset_has_mail` and `update user` is True,
set the `has_mail` attribute of the logged-in user to False.
T... | Below is the the instruction that describes the task:
### Input:
Return a get_content generator for unread messages.
:param unset_has_mail: When True, clear the has_mail flag (orangered)
for the user.
:param update_user: If both `unset_has_mail` and `update user` is True,
se... |
def paxos_instance(self):
"""
Returns instance of PaxosInstance (protocol implementation).
"""
# Construct instance with the constant attributes.
instance = PaxosInstance(self.network_uid, self.quorum_size)
# Set the variable attributes from the aggregate.
for na... | Returns instance of PaxosInstance (protocol implementation). | Below is the the instruction that describes the task:
### Input:
Returns instance of PaxosInstance (protocol implementation).
### Response:
def paxos_instance(self):
"""
Returns instance of PaxosInstance (protocol implementation).
"""
# Construct instance with the constant attribute... |
def _update_data(self, data={}):
'''Update the data in this object.'''
# Store the changes to prevent this update from affecting it
pending_changes = self._changes or {}
try:
del self._changes
except:
pass
# Map custom fields into our custom fiel... | Update the data in this object. | Below is the the instruction that describes the task:
### Input:
Update the data in this object.
### Response:
def _update_data(self, data={}):
'''Update the data in this object.'''
# Store the changes to prevent this update from affecting it
pending_changes = self._changes or {}
t... |
def destroy(self):
'''
Tear down the minion
'''
if self._running is False:
return
self._running = False
if hasattr(self, 'schedule'):
del self.schedule
if hasattr(self, 'pub_channel') and self.pub_channel is not None:
self.pub_... | Tear down the minion | Below is the the instruction that describes the task:
### Input:
Tear down the minion
### Response:
def destroy(self):
'''
Tear down the minion
'''
if self._running is False:
return
self._running = False
if hasattr(self, 'schedule'):
del self... |
def _wrap_result(self, response):
"""Wraps child's response in a HandlerResult to be sent back to client.
Args:
response (enum or dict): Either an integer status enum, or a dict
of attributes to be added to the protobuf response.
"""
if isinstance(response, i... | Wraps child's response in a HandlerResult to be sent back to client.
Args:
response (enum or dict): Either an integer status enum, or a dict
of attributes to be added to the protobuf response. | Below is the the instruction that describes the task:
### Input:
Wraps child's response in a HandlerResult to be sent back to client.
Args:
response (enum or dict): Either an integer status enum, or a dict
of attributes to be added to the protobuf response.
### Response:
def _w... |
def make_response(self, *args, **kwargs):
"""Create a Flask Response.
Dispatch the given arguments to the serializer best matching the
current request's Accept header.
:return: The response created by the serializing function.
:rtype: :class:`flask.Response`
:raises wer... | Create a Flask Response.
Dispatch the given arguments to the serializer best matching the
current request's Accept header.
:return: The response created by the serializing function.
:rtype: :class:`flask.Response`
:raises werkzeug.exceptions.NotAcceptable: If no media type
... | Below is the the instruction that describes the task:
### Input:
Create a Flask Response.
Dispatch the given arguments to the serializer best matching the
current request's Accept header.
:return: The response created by the serializing function.
:rtype: :class:`flask.Response`
... |
def _sim_prediction(self, sigma2, Y, scores, h, t_params, simulations):
""" Simulates a h-step ahead mean prediction
Parameters
----------
sigma2 : np.array
The past predicted values
Y : np.array
The past data
scores : np.array
The p... | Simulates a h-step ahead mean prediction
Parameters
----------
sigma2 : np.array
The past predicted values
Y : np.array
The past data
scores : np.array
The past scores
h : int
How many steps ahead for the prediction
... | Below is the the instruction that describes the task:
### Input:
Simulates a h-step ahead mean prediction
Parameters
----------
sigma2 : np.array
The past predicted values
Y : np.array
The past data
scores : np.array
The past scores
... |
def summarize_taxa(biom):
"""
Given an abundance table, group the counts by every
taxonomic level.
"""
tamtcounts = defaultdict(int)
tot_seqs = 0.0
for row, col, amt in biom['data']:
tot_seqs += amt
rtax = biom['rows'][row]['metadata']['taxonomy']
for i, t in enumera... | Given an abundance table, group the counts by every
taxonomic level. | Below is the the instruction that describes the task:
### Input:
Given an abundance table, group the counts by every
taxonomic level.
### Response:
def summarize_taxa(biom):
"""
Given an abundance table, group the counts by every
taxonomic level.
"""
tamtcounts = defaultdict(int)
tot_se... |
def summit_cover(self, minAcc, maxAcc, groupBy=None, new_reg_fields=None):
"""
*Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns only those portions of the COVER
result where the maximum number of regions overlap (this is done by returning only
regions ... | *Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns only those portions of the COVER
result where the maximum number of regions overlap (this is done by returning only
regions that start from a position after which the number of overlaps does not
increase, and s... | Below is the the instruction that describes the task:
### Input:
*Wrapper of* ``COVER``
Variant of the function :meth:`~.cover` that returns only those portions of the COVER
result where the maximum number of regions overlap (this is done by returning only
regions that start from a position... |
def register_cron(weekday=None, month=None, day=None, hour=None, minute=None, target=None):
"""Adds cron. The interface to the uWSGI signal cron facility.
.. code-block:: python
@register_cron(hour=-3) # Every 3 hours.
def repeat():
do()
.. note:: Arguments wo... | Adds cron. The interface to the uWSGI signal cron facility.
.. code-block:: python
@register_cron(hour=-3) # Every 3 hours.
def repeat():
do()
.. note:: Arguments work similarly to a standard crontab,
but instead of "*", use -1,
and instead of "/2"... | Below is the the instruction that describes the task:
### Input:
Adds cron. The interface to the uWSGI signal cron facility.
.. code-block:: python
@register_cron(hour=-3) # Every 3 hours.
def repeat():
do()
.. note:: Arguments work similarly to a standard cro... |
def _basis_data_iter(fmt, reffmt, data_dir):
'''Iterate over all basis set names, and return a tuple of
(name, data) where data is the basis set in the given format
'''
md = api.get_metadata(data_dir)
for bs, bs_md in md.items():
versions = bs_md['versions'].keys()
data = {}
... | Iterate over all basis set names, and return a tuple of
(name, data) where data is the basis set in the given format | Below is the the instruction that describes the task:
### Input:
Iterate over all basis set names, and return a tuple of
(name, data) where data is the basis set in the given format
### Response:
def _basis_data_iter(fmt, reffmt, data_dir):
'''Iterate over all basis set names, and return a tuple of
... |
def ks_unif_pelz_good(samples, statistic):
"""
Approximates the statistic distribution by a transformed Li-Chien formula.
This ought to be a bit more accurate than using the Kolmogorov limit, but
should only be used with large squared sample count times statistic.
See: doi:10.18637/jss.v039.i11 and... | Approximates the statistic distribution by a transformed Li-Chien formula.
This ought to be a bit more accurate than using the Kolmogorov limit, but
should only be used with large squared sample count times statistic.
See: doi:10.18637/jss.v039.i11 and http://www.jstor.org/stable/2985019. | Below is the the instruction that describes the task:
### Input:
Approximates the statistic distribution by a transformed Li-Chien formula.
This ought to be a bit more accurate than using the Kolmogorov limit, but
should only be used with large squared sample count times statistic.
See: doi:10.18637/js... |
def format_directive(module, package=None):
# type: (unicode, unicode) -> unicode
"""Create the automodule directive and add the options."""
directive = '.. automodule:: %s\n' % makename(package, module)
for option in OPTIONS:
directive += ' :%s:\n' % option
return directive | Create the automodule directive and add the options. | Below is the the instruction that describes the task:
### Input:
Create the automodule directive and add the options.
### Response:
def format_directive(module, package=None):
# type: (unicode, unicode) -> unicode
"""Create the automodule directive and add the options."""
directive = '.. automodule:: %... |
def transform(self, X):
"""
Transform the given data. Assumes that fit has already been called.
:param X (DataSet): the data to transform
"""
extracted = []
for columns, transformer in self.mapping:
if transformer is not None:
feature = transf... | Transform the given data. Assumes that fit has already been called.
:param X (DataSet): the data to transform | Below is the the instruction that describes the task:
### Input:
Transform the given data. Assumes that fit has already been called.
:param X (DataSet): the data to transform
### Response:
def transform(self, X):
"""
Transform the given data. Assumes that fit has already been called.
... |
def register_palette(self):
"""Converts pygmets style to urwid palatte"""
default = 'default'
palette = list(self.palette)
mapping = CONFIG['rgb_to_short']
for tok in self.style.styles.keys():
for t in tok.split()[::-1]:
st = self.style.styles[t]
... | Converts pygmets style to urwid palatte | Below is the the instruction that describes the task:
### Input:
Converts pygmets style to urwid palatte
### Response:
def register_palette(self):
"""Converts pygmets style to urwid palatte"""
default = 'default'
palette = list(self.palette)
mapping = CONFIG['rgb_to_short']
... |
def _compute_dk_dy(self, y, n):
r"""Evaluate the derivative of the outer form of the Matern kernel.
Uses the general Leibniz rule to compute the n-th derivative of:
.. math::
f(y) = \frac{2^{1-\nu}}{\Gamma(\nu)} y^{\nu/2} K_\nu(y^{1/2})
Par... | r"""Evaluate the derivative of the outer form of the Matern kernel.
Uses the general Leibniz rule to compute the n-th derivative of:
.. math::
f(y) = \frac{2^{1-\nu}}{\Gamma(\nu)} y^{\nu/2} K_\nu(y^{1/2})
Parameters
----------
y : :... | Below is the the instruction that describes the task:
### Input:
r"""Evaluate the derivative of the outer form of the Matern kernel.
Uses the general Leibniz rule to compute the n-th derivative of:
.. math::
f(y) = \frac{2^{1-\nu}}{\Gamma(\nu)} y^{\nu/2} K_\nu(... |
def _verify_run(out, cmd=None):
'''
Crash to the log if command execution was not successful.
'''
if out.get('retcode', 0) and out['stderr']:
if cmd:
log.debug('Command: \'%s\'', cmd)
log.debug('Return code: %s', out.get('retcode'))
log.debug('Error output:\n%s', out... | Crash to the log if command execution was not successful. | Below is the the instruction that describes the task:
### Input:
Crash to the log if command execution was not successful.
### Response:
def _verify_run(out, cmd=None):
'''
Crash to the log if command execution was not successful.
'''
if out.get('retcode', 0) and out['stderr']:
if cmd:
... |
def _inject_lua_code(self, lua_code):
""" Sends raw lua code and evaluate it wihtout any checking! """
msg = (ctypes.c_ubyte * len(lua_code)).from_buffer_copy(lua_code.encode())
self.call_remote_api('simxWriteStringStream', 'my_lua_code', msg) | Sends raw lua code and evaluate it wihtout any checking! | Below is the the instruction that describes the task:
### Input:
Sends raw lua code and evaluate it wihtout any checking!
### Response:
def _inject_lua_code(self, lua_code):
""" Sends raw lua code and evaluate it wihtout any checking! """
msg = (ctypes.c_ubyte * len(lua_code)).from_buffer_copy(lua_... |
def acquireConnection(self):
""" Get a connection from the pool.
Parameters:
----------------------------------------------------------------
retval: A ConnectionWrapper instance. NOTE: Caller
is responsible for calling the ConnectionWrapper
instance's rel... | Get a connection from the pool.
Parameters:
----------------------------------------------------------------
retval: A ConnectionWrapper instance. NOTE: Caller
is responsible for calling the ConnectionWrapper
instance's release() method or use it in a context ... | Below is the the instruction that describes the task:
### Input:
Get a connection from the pool.
Parameters:
----------------------------------------------------------------
retval: A ConnectionWrapper instance. NOTE: Caller
is responsible for calling the ConnectionWrapper
... |
def _find_convertable_object(self, data):
"""
Get the first instance of a `self.pod_types`
"""
data = list(data)
convertable_object_idxs = [
idx
for idx, obj
in enumerate(data)
if obj.get('kind') in self.pod_types.keys()
]
... | Get the first instance of a `self.pod_types` | Below is the the instruction that describes the task:
### Input:
Get the first instance of a `self.pod_types`
### Response:
def _find_convertable_object(self, data):
"""
Get the first instance of a `self.pod_types`
"""
data = list(data)
convertable_object_idxs = [
... |
def gen_sponsor_schedule(user, sponsor=None, num_blocks=6, surrounding_blocks=None, given_date=None):
r"""Return a list of :class:`EighthScheduledActivity`\s in which the
given user is sponsoring.
Returns:
Dictionary with:
activities
no_attendance_today
num_acts
... | r"""Return a list of :class:`EighthScheduledActivity`\s in which the
given user is sponsoring.
Returns:
Dictionary with:
activities
no_attendance_today
num_acts | Below is the the instruction that describes the task:
### Input:
r"""Return a list of :class:`EighthScheduledActivity`\s in which the
given user is sponsoring.
Returns:
Dictionary with:
activities
no_attendance_today
num_acts
### Response:
def gen_sponsor_schedu... |
def _execute_helper(self):
"""
The actual scheduler loop. The main steps in the loop are:
#. Harvest DAG parsing results through DagFileProcessorAgent
#. Find and queue executable tasks
#. Change task instance state in DB
#. Queue tasks in executor... | The actual scheduler loop. The main steps in the loop are:
#. Harvest DAG parsing results through DagFileProcessorAgent
#. Find and queue executable tasks
#. Change task instance state in DB
#. Queue tasks in executor
#. Heartbeat executor
... | Below is the the instruction that describes the task:
### Input:
The actual scheduler loop. The main steps in the loop are:
#. Harvest DAG parsing results through DagFileProcessorAgent
#. Find and queue executable tasks
#. Change task instance state in DB
#. Q... |
def compile_mof_string(self, mof_str, namespace=None, search_paths=None,
verbose=None):
"""
Compile the MOF definitions in the specified string and add the
resulting CIM objects to the specified CIM namespace of the mock
repository.
If the namespace do... | Compile the MOF definitions in the specified string and add the
resulting CIM objects to the specified CIM namespace of the mock
repository.
If the namespace does not exist, :exc:`~pywbem.CIMError` with status
CIM_ERR_INVALID_NAMESPACE is raised.
This method supports all MOF pr... | Below is the the instruction that describes the task:
### Input:
Compile the MOF definitions in the specified string and add the
resulting CIM objects to the specified CIM namespace of the mock
repository.
If the namespace does not exist, :exc:`~pywbem.CIMError` with status
CIM_ERR_... |
def forum_topic_list(self, title_matches=None, title=None,
category_id=None):
"""Function to get forum topics.
Parameters:
title_matches (str): Search body for the given terms.
title (str): Exact title match.
category_id (int): Can be: 0, 1, ... | Function to get forum topics.
Parameters:
title_matches (str): Search body for the given terms.
title (str): Exact title match.
category_id (int): Can be: 0, 1, 2 (General, Tags, Bugs & Features
respectively). | Below is the the instruction that describes the task:
### Input:
Function to get forum topics.
Parameters:
title_matches (str): Search body for the given terms.
title (str): Exact title match.
category_id (int): Can be: 0, 1, 2 (General, Tags, Bugs & Features
... |
def initial(self, request, *args, **kwargs):
"""
Runs anything that needs to occur prior to calling the method handler.
"""
self.format_kwarg = self.get_format_suffix(**kwargs)
# Ensure that the incoming request is permitted
self.perform_authentication(request)
s... | Runs anything that needs to occur prior to calling the method handler. | Below is the the instruction that describes the task:
### Input:
Runs anything that needs to occur prior to calling the method handler.
### Response:
def initial(self, request, *args, **kwargs):
"""
Runs anything that needs to occur prior to calling the method handler.
"""
self.form... |
def check_settings():
"""
Validate the users settings conf prior to deploy
"""
valid=True
if not get_version() >= '1.0':
print "FABRIC ERROR: Woven is only compatible with Fabric < 1.0"
valid = False
if not env.MEDIA_ROOT or not env.MEDIA_URL:
print "MEDIA ERROR: You must... | Validate the users settings conf prior to deploy | Below is the the instruction that describes the task:
### Input:
Validate the users settings conf prior to deploy
### Response:
def check_settings():
"""
Validate the users settings conf prior to deploy
"""
valid=True
if not get_version() >= '1.0':
print "FABRIC ERROR: Woven is only com... |
def __should_write_changes(self, old_value: StoreItem, new_value: StoreItem) -> bool:
"""
Helper method that compares two StoreItems and their e_tags and returns True if the new_value should overwrite
the old_value. Otherwise returns False.
:param old_value:
:param new_value:
... | Helper method that compares two StoreItems and their e_tags and returns True if the new_value should overwrite
the old_value. Otherwise returns False.
:param old_value:
:param new_value:
:return: | Below is the the instruction that describes the task:
### Input:
Helper method that compares two StoreItems and their e_tags and returns True if the new_value should overwrite
the old_value. Otherwise returns False.
:param old_value:
:param new_value:
:return:
### Response:
def __sh... |
def state_set(self, state, use_active_range=False):
"""Sets the internal state of the df
Example:
>>> import vaex
>>> df = vaex.from_scalars(x=1, y=2)
>>> df
# x y r
0 1 2 2.23607
>>> df['r'] = (df.x**2 + df.y**2)**0.5
>>>... | Sets the internal state of the df
Example:
>>> import vaex
>>> df = vaex.from_scalars(x=1, y=2)
>>> df
# x y r
0 1 2 2.23607
>>> df['r'] = (df.x**2 + df.y**2)**0.5
>>> state = df.state_get()
>>> state
{'active_rang... | Below is the the instruction that describes the task:
### Input:
Sets the internal state of the df
Example:
>>> import vaex
>>> df = vaex.from_scalars(x=1, y=2)
>>> df
# x y r
0 1 2 2.23607
>>> df['r'] = (df.x**2 + df.y**2)**0.5
... |
def lint(filename):
"""Lints an INI file, returning 0 in case of success."""
config = ConfigParser.ConfigParser()
try:
config.read(filename)
return 0
except ConfigParser.Error as error:
print('Error: %s' % error)
return 1
except:
print('Unexpected Error')
... | Lints an INI file, returning 0 in case of success. | Below is the the instruction that describes the task:
### Input:
Lints an INI file, returning 0 in case of success.
### Response:
def lint(filename):
"""Lints an INI file, returning 0 in case of success."""
config = ConfigParser.ConfigParser()
try:
config.read(filename)
return 0
exc... |
def _get(self, url, query=None):
"""
Wrapper for the HTTP Request,
Rate Limit Backoff is handled here,
Responses are Processed with ResourceBuilder.
"""
if query is None:
query = {}
response = retry_request(self)(self._http_get)(url, query=query)
... | Wrapper for the HTTP Request,
Rate Limit Backoff is handled here,
Responses are Processed with ResourceBuilder. | Below is the the instruction that describes the task:
### Input:
Wrapper for the HTTP Request,
Rate Limit Backoff is handled here,
Responses are Processed with ResourceBuilder.
### Response:
def _get(self, url, query=None):
"""
Wrapper for the HTTP Request,
Rate Limit Backof... |
def map_variable(
self, variable, points, input_units="same", *, name=None, parent=None, verbose=True
) -> "Data":
"""Map points of an axis to new points using linear interpolation.
Out-of-bounds points are written nan.
Parameters
----------
variable : string
... | Map points of an axis to new points using linear interpolation.
Out-of-bounds points are written nan.
Parameters
----------
variable : string
The variable to map onto.
points : array-like or int
If array, the new points. If int, new points will have the ... | Below is the the instruction that describes the task:
### Input:
Map points of an axis to new points using linear interpolation.
Out-of-bounds points are written nan.
Parameters
----------
variable : string
The variable to map onto.
points : array-like or int
... |
def remove(self, cls, originalMemberNameList, classNamingConvention):
"""
:type cls: type
:type originalMemberNameList: list(str)
:type classNamingConvention: INamingConvention
"""
self._memberDelegate.remove(cls = cls,
originalMemberNameList = originalMem... | :type cls: type
:type originalMemberNameList: list(str)
:type classNamingConvention: INamingConvention | Below is the the instruction that describes the task:
### Input:
:type cls: type
:type originalMemberNameList: list(str)
:type classNamingConvention: INamingConvention
### Response:
def remove(self, cls, originalMemberNameList, classNamingConvention):
"""
:type cls: type
:type originalMembe... |
def initialize_security_context(self):
"""
Idiomatic Python implementation of initialize_security_context, implemented as a generator function using
yield to both accept incoming and return outgoing authentication tokens
:return: The response to be returned to the server
"""
... | Idiomatic Python implementation of initialize_security_context, implemented as a generator function using
yield to both accept incoming and return outgoing authentication tokens
:return: The response to be returned to the server | Below is the the instruction that describes the task:
### Input:
Idiomatic Python implementation of initialize_security_context, implemented as a generator function using
yield to both accept incoming and return outgoing authentication tokens
:return: The response to be returned to the server
### Re... |
def get_product_string(self):
""" Get the Product String from the HID device.
:return: The Product String
:rtype: unicode
"""
self._check_device_status()
str_p = ffi.new("wchar_t[]", 255)
rv = hidapi.hid_get_product_string(self._device, str_p, 255)
... | Get the Product String from the HID device.
:return: The Product String
:rtype: unicode | Below is the the instruction that describes the task:
### Input:
Get the Product String from the HID device.
:return: The Product String
:rtype: unicode
### Response:
def get_product_string(self):
""" Get the Product String from the HID device.
:return: The Product Strin... |
def read_file(file, filename='<input>'):
"""This is a generator that yields all top-level S-expression nodes from
a given file object."""
reader = Reader(filename)
for line in file:
yield from reader.feed_line(line)
reader.finish() | This is a generator that yields all top-level S-expression nodes from
a given file object. | Below is the the instruction that describes the task:
### Input:
This is a generator that yields all top-level S-expression nodes from
a given file object.
### Response:
def read_file(file, filename='<input>'):
"""This is a generator that yields all top-level S-expression nodes from
a given file object... |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
C = self.COEFFS[imt]
mag = rup.mag - 6
d = np.sqrt(di... | See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values. | Below is the the instruction that describes the task:
### Input:
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
### Response:
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :m... |
def apps(self):
"""
Dictionary with loaded applications.
"""
logger.debug("initialize applications ...")
enabled = None
apps = self.args.apps or self._config_apps.keys()
unknown = set(apps) - set(self._config_apps.keys())
if unknown:
raise LogR... | Dictionary with loaded applications. | Below is the the instruction that describes the task:
### Input:
Dictionary with loaded applications.
### Response:
def apps(self):
"""
Dictionary with loaded applications.
"""
logger.debug("initialize applications ...")
enabled = None
apps = self.args.apps or self._... |
def get_unresolved_variables(f):
"""
Gets unresolved vars from file
"""
reporter = RReporter()
checkPath(f, reporter=reporter)
return dict(reporter.messages) | Gets unresolved vars from file | Below is the the instruction that describes the task:
### Input:
Gets unresolved vars from file
### Response:
def get_unresolved_variables(f):
"""
Gets unresolved vars from file
"""
reporter = RReporter()
checkPath(f, reporter=reporter)
return dict(reporter.messages) |
def change_encryption(self, current_password, cipher, new_password, new_password_id):
"""Starts encryption of this medium. This means that the stored data in the
medium is encrypted.
This medium will be placed to :py:attr:`MediumState.locked_write`
state.
Pleas... | Starts encryption of this medium. This means that the stored data in the
medium is encrypted.
This medium will be placed to :py:attr:`MediumState.locked_write`
state.
Please note that the results can be either returned straight away,
or later as the result of t... | Below is the the instruction that describes the task:
### Input:
Starts encryption of this medium. This means that the stored data in the
medium is encrypted.
This medium will be placed to :py:attr:`MediumState.locked_write`
state.
Please note that the results can ... |
def declare_artefact(self, value):
# type: (Any) -> ProvEntity
"""Create data artefact entities for all file objects."""
if value is None:
# FIXME: If this can happen in CWL, we'll
# need a better way to represent this in PROV
return self.document.entity(
... | Create data artefact entities for all file objects. | Below is the the instruction that describes the task:
### Input:
Create data artefact entities for all file objects.
### Response:
def declare_artefact(self, value):
# type: (Any) -> ProvEntity
"""Create data artefact entities for all file objects."""
if value is None:
# FIXME: ... |
def _filter_insane_successors(self, successors):
"""
Throw away all successors whose target doesn't make sense
This method is called after we resolve an indirect jump using an unreliable method (like, not through one of
the indirect jump resolvers, but through either pure concrete execu... | Throw away all successors whose target doesn't make sense
This method is called after we resolve an indirect jump using an unreliable method (like, not through one of
the indirect jump resolvers, but through either pure concrete execution or backward slicing) to filter out the
obviously incorre... | Below is the the instruction that describes the task:
### Input:
Throw away all successors whose target doesn't make sense
This method is called after we resolve an indirect jump using an unreliable method (like, not through one of
the indirect jump resolvers, but through either pure concrete execu... |
def bounce_local(name, drain=False):
'''
Bounce Traffic Server on the local node. Bouncing Traffic Server shuts down
and immediately restarts the Traffic Server node.
This option modifies the behavior of traffic_line -b and traffic_line -L
such that traffic_server is not shut down until the number ... | Bounce Traffic Server on the local node. Bouncing Traffic Server shuts down
and immediately restarts the Traffic Server node.
This option modifies the behavior of traffic_line -b and traffic_line -L
such that traffic_server is not shut down until the number of active client
connections drops to the num... | Below is the the instruction that describes the task:
### Input:
Bounce Traffic Server on the local node. Bouncing Traffic Server shuts down
and immediately restarts the Traffic Server node.
This option modifies the behavior of traffic_line -b and traffic_line -L
such that traffic_server is not shut do... |
def help_center_section_articles(self, id, locale=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/articles#list-articles"
api_path = "/api/v2/help_center/sections/{id}/articles.json"
api_path = api_path.format(id=id)
if locale:
api_opt_path = "/api/v... | https://developer.zendesk.com/rest_api/docs/help_center/articles#list-articles | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/help_center/articles#list-articles
### Response:
def help_center_section_articles(self, id, locale=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/articles#list-articles"
... |
def expected_dense_regression_log_prob(A, Sigma, stats):
"""
Expected log likelihood of p(y | x) where
y ~ N(Ax, Sigma)
and expectation is wrt q(y,x). We only need expected
sufficient statistics E[yy.T], E[yx.T], E[xx.T], and n,
where n is the number of observations.
:param A: r... | Expected log likelihood of p(y | x) where
y ~ N(Ax, Sigma)
and expectation is wrt q(y,x). We only need expected
sufficient statistics E[yy.T], E[yx.T], E[xx.T], and n,
where n is the number of observations.
:param A: regression matrix
:param Sigma: observation covariance
:param... | Below is the the instruction that describes the task:
### Input:
Expected log likelihood of p(y | x) where
y ~ N(Ax, Sigma)
and expectation is wrt q(y,x). We only need expected
sufficient statistics E[yy.T], E[yx.T], E[xx.T], and n,
where n is the number of observations.
:param A: r... |
def get_atom_serial_numbers_from_pdb_residue_ids(self, pdb_residue_ids, ignore_these_atoms = [], ignore_these_conformations = []):
'''Checks to make sure that each atom type is unique per residue.'''
atom_list = []
for pdb_residue_id in pdb_residue_ids:
chain = pdb_residue_id[0]
... | Checks to make sure that each atom type is unique per residue. | Below is the the instruction that describes the task:
### Input:
Checks to make sure that each atom type is unique per residue.
### Response:
def get_atom_serial_numbers_from_pdb_residue_ids(self, pdb_residue_ids, ignore_these_atoms = [], ignore_these_conformations = []):
'''Checks to make sure that each a... |
def ffl_path(self, site, frametype):
"""Returns the path of the FFL file for the given site and frametype
Examples
--------
>>> from gwpy.io.datafind import FflConnection
>>> conn = FflConnection()
>>> print(conn.ffl_path('V', 'V1Online'))
/virgoData/ffl/V1Online... | Returns the path of the FFL file for the given site and frametype
Examples
--------
>>> from gwpy.io.datafind import FflConnection
>>> conn = FflConnection()
>>> print(conn.ffl_path('V', 'V1Online'))
/virgoData/ffl/V1Online.ffl | Below is the the instruction that describes the task:
### Input:
Returns the path of the FFL file for the given site and frametype
Examples
--------
>>> from gwpy.io.datafind import FflConnection
>>> conn = FflConnection()
>>> print(conn.ffl_path('V', 'V1Online'))
/v... |
def module_path(self, filepath):
"""given a filepath like /base/path/to/module.py this will convert it to
path.to.module so it can be imported"""
possible_modbits = re.split('[\\/]', filepath.strip('\\/'))
basename = possible_modbits[-1]
prefixes = possible_modbits[0:-1]
... | given a filepath like /base/path/to/module.py this will convert it to
path.to.module so it can be imported | Below is the the instruction that describes the task:
### Input:
given a filepath like /base/path/to/module.py this will convert it to
path.to.module so it can be imported
### Response:
def module_path(self, filepath):
"""given a filepath like /base/path/to/module.py this will convert it to
... |
def _copy(self):
""" needs to update page numbers """
ins = copy.copy(self)
ins._fire_page_number(self.page_number + 1)
return ins | needs to update page numbers | Below is the the instruction that describes the task:
### Input:
needs to update page numbers
### Response:
def _copy(self):
""" needs to update page numbers """
ins = copy.copy(self)
ins._fire_page_number(self.page_number + 1)
return ins |
def delete_index(es, index_name: str):
"""Delete the terms index"""
if not index_name:
log.warn("No index name given to delete")
return None
result = es.indices.delete(index=index_name)
return result | Delete the terms index | Below is the the instruction that describes the task:
### Input:
Delete the terms index
### Response:
def delete_index(es, index_name: str):
"""Delete the terms index"""
if not index_name:
log.warn("No index name given to delete")
return None
result = es.indices.delete(index=index_nam... |
def DbMySqlSelect(self, argin):
""" This is a very low level command.
It executes the specified SELECT command on TANGO database and returns its result without filter.
:param argin: MySql Select command
:type: tango.DevString
:return: MySql Select command result
- sval... | This is a very low level command.
It executes the specified SELECT command on TANGO database and returns its result without filter.
:param argin: MySql Select command
:type: tango.DevString
:return: MySql Select command result
- svalues : select results
- lvalue[n] : ... | Below is the the instruction that describes the task:
### Input:
This is a very low level command.
It executes the specified SELECT command on TANGO database and returns its result without filter.
:param argin: MySql Select command
:type: tango.DevString
:return: MySql Select comma... |
def path_end_to_end_distance(neurite):
'''Calculate and return end-to-end-distance of a given neurite.'''
trunk = neurite.root_node.points[0]
return max(morphmath.point_dist(l.points[-1], trunk)
for l in neurite.root_node.ileaf()) | Calculate and return end-to-end-distance of a given neurite. | Below is the the instruction that describes the task:
### Input:
Calculate and return end-to-end-distance of a given neurite.
### Response:
def path_end_to_end_distance(neurite):
'''Calculate and return end-to-end-distance of a given neurite.'''
trunk = neurite.root_node.points[0]
return max(morphmath.... |
def parse_init_dat(infile):
"""Parse the main init.dat file which contains the modeling results
The first line of the file init.dat contains stuff like::
"120 easy 40 8"
The other lines look like this::
" 161 11.051 1 1guqA MUSTER"
and getting the first 1... | Parse the main init.dat file which contains the modeling results
The first line of the file init.dat contains stuff like::
"120 easy 40 8"
The other lines look like this::
" 161 11.051 1 1guqA MUSTER"
and getting the first 10 gives you the top 10 templates us... | Below is the the instruction that describes the task:
### Input:
Parse the main init.dat file which contains the modeling results
The first line of the file init.dat contains stuff like::
"120 easy 40 8"
The other lines look like this::
" 161 11.051 1 1guqA MUSTER... |
def merge_labeled_intervals(x_intervals, x_labels, y_intervals, y_labels):
r"""Merge the time intervals of two sequences.
Parameters
----------
x_intervals : np.ndarray
Array of interval times (seconds)
x_labels : list or None
List of labels
y_intervals : np.ndarray
Arra... | r"""Merge the time intervals of two sequences.
Parameters
----------
x_intervals : np.ndarray
Array of interval times (seconds)
x_labels : list or None
List of labels
y_intervals : np.ndarray
Array of interval times (seconds)
y_labels : list or None
List of label... | Below is the the instruction that describes the task:
### Input:
r"""Merge the time intervals of two sequences.
Parameters
----------
x_intervals : np.ndarray
Array of interval times (seconds)
x_labels : list or None
List of labels
y_intervals : np.ndarray
Array of inter... |
def append_lookup_key(model, lookup_key):
"Transform spanned__lookup__key into all possible translation versions, on all levels"
pieces = lookup_key.split('__', 1)
fields = append_translated(model, (pieces[0],))
if len(pieces) > 1:
# Check if we are doing a lookup to a related trans model
... | Transform spanned__lookup__key into all possible translation versions, on all levels | Below is the the instruction that describes the task:
### Input:
Transform spanned__lookup__key into all possible translation versions, on all levels
### Response:
def append_lookup_key(model, lookup_key):
"Transform spanned__lookup__key into all possible translation versions, on all levels"
pieces = looku... |
def verify(self):
"""
Verifies an IPN and a PDT.
Checks for obvious signs of weirdness in the payment and flags appropriately.
"""
self.response = self._postback().decode('ascii')
self.clear_flag()
self._verify_postback()
if not self.flag:
if s... | Verifies an IPN and a PDT.
Checks for obvious signs of weirdness in the payment and flags appropriately. | Below is the the instruction that describes the task:
### Input:
Verifies an IPN and a PDT.
Checks for obvious signs of weirdness in the payment and flags appropriately.
### Response:
def verify(self):
"""
Verifies an IPN and a PDT.
Checks for obvious signs of weirdness in the payme... |
def forwards(self, orm):
"Write your forwards methods here."
# Note: Don't use "from appname.models import ModelName".
# Use orm.ModelName to refer to models in this application,
# and orm['appname.ModelName'] for models in other applications.
from account_keeping.models import ... | Write your forwards methods here. | Below is the the instruction that describes the task:
### Input:
Write your forwards methods here.
### Response:
def forwards(self, orm):
"Write your forwards methods here."
# Note: Don't use "from appname.models import ModelName".
# Use orm.ModelName to refer to models in this application... |
def read_file(pth, use_str=False):
"""
读取文件, 并返回内容,
如果读取失败,返回None
:param pth:
:type pth:
:return:
:rtype:
"""
cont = None
try:
with open(u'' + pth, 'rb') as fp:
cont = fp.read()
if use_str:
cont = to_str(cont)
except Exception... | 读取文件, 并返回内容,
如果读取失败,返回None
:param pth:
:type pth:
:return:
:rtype: | Below is the the instruction that describes the task:
### Input:
读取文件, 并返回内容,
如果读取失败,返回None
:param pth:
:type pth:
:return:
:rtype:
### Response:
def read_file(pth, use_str=False):
"""
读取文件, 并返回内容,
如果读取失败,返回None
:param pth:
:type pth:
:return:
:rtype:
... |
def to_json(self):
"""
:return: str
"""
json_dict = self.to_json_basic()
json_dict['pulses'] = self.pulses
json_dict['counter'] = self.counter
json_dict['kwh'] = self.kwh
json_dict['delay'] = self.delay
json_dict['watt'] = self.watt
json_di... | :return: str | Below is the the instruction that describes the task:
### Input:
:return: str
### Response:
def to_json(self):
"""
:return: str
"""
json_dict = self.to_json_basic()
json_dict['pulses'] = self.pulses
json_dict['counter'] = self.counter
json_dict['kwh'] = self.... |
def static(path, no_input):
'''Compile and collect static files into path'''
log = logging.getLogger('webassets')
log.addHandler(logging.StreamHandler())
log.setLevel(logging.DEBUG)
cmdenv = CommandLineEnvironment(assets, log)
cmdenv.build()
if exists(path):
warning('{0} directory ... | Compile and collect static files into path | Below is the the instruction that describes the task:
### Input:
Compile and collect static files into path
### Response:
def static(path, no_input):
'''Compile and collect static files into path'''
log = logging.getLogger('webassets')
log.addHandler(logging.StreamHandler())
log.setLevel(logging.DE... |
def jcrop_js(js_url=None, with_jquery=True):
"""Load jcrop Javascript file.
:param js_url: The custom JavaScript URL.
:param with_jquery: Include jQuery or not, default to ``True``.
"""
serve_local = current_app.config['AVATARS_SERVE_LOCAL']
if js_url is None:
... | Load jcrop Javascript file.
:param js_url: The custom JavaScript URL.
:param with_jquery: Include jQuery or not, default to ``True``. | Below is the the instruction that describes the task:
### Input:
Load jcrop Javascript file.
:param js_url: The custom JavaScript URL.
:param with_jquery: Include jQuery or not, default to ``True``.
### Response:
def jcrop_js(js_url=None, with_jquery=True):
"""Load jcrop Javascript file.
... |
def example_method(self, i3s_output_list, i3s_config):
"""
This method will return an empty text message
so it will NOT be displayed on your i3bar.
If you want something displayed you should write something
in the 'full_text' key of your response.
See the i3bar protocol... | This method will return an empty text message
so it will NOT be displayed on your i3bar.
If you want something displayed you should write something
in the 'full_text' key of your response.
See the i3bar protocol spec for more information:
http://i3wm.org/docs/i3bar-protocol.htm... | Below is the the instruction that describes the task:
### Input:
This method will return an empty text message
so it will NOT be displayed on your i3bar.
If you want something displayed you should write something
in the 'full_text' key of your response.
See the i3bar protocol spec ... |
def update_metadata(self, bucket, label, params):
'''Update the metadata with the provided dictionary of params.
:param parmams: dictionary of key values (json serializable).
'''
if self.mode !="r":
try:
payload = self._get_bucket_md(bucket)
excep... | Update the metadata with the provided dictionary of params.
:param parmams: dictionary of key values (json serializable). | Below is the the instruction that describes the task:
### Input:
Update the metadata with the provided dictionary of params.
:param parmams: dictionary of key values (json serializable).
### Response:
def update_metadata(self, bucket, label, params):
'''Update the metadata with the provided dictio... |
def jhk_to_vmag(jmag,hmag,kmag):
'''Converts given J, H, Ks mags to a V magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted V band magnitude.
'''
return convert_constants(jmag,hmag,... | Converts given J, H, Ks mags to a V magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted V band magnitude. | Below is the the instruction that describes the task:
### Input:
Converts given J, H, Ks mags to a V magnitude value.
Parameters
----------
jmag,hmag,kmag : float
2MASS J, H, Ks mags of the object.
Returns
-------
float
The converted V band magnitude.
### Response:
def j... |
def estimateTdisrupt(self,deltaAngle):
"""
NAME:
estimateTdisrupt
PURPOSE:
estimate the time of disruption
INPUT:
deltaAngle- spread in angle since disruption
OUTPUT:
time in natural units
HISTORY:
2013-11-27... | NAME:
estimateTdisrupt
PURPOSE:
estimate the time of disruption
INPUT:
deltaAngle- spread in angle since disruption
OUTPUT:
time in natural units
HISTORY:
2013-11-27 - Written - Bovy (IAS) | Below is the the instruction that describes the task:
### Input:
NAME:
estimateTdisrupt
PURPOSE:
estimate the time of disruption
INPUT:
deltaAngle- spread in angle since disruption
OUTPUT:
time in natural units
HISTORY:
... |
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenames:
_debug_linter_status("mdl", filename, show_lint_files)
try:
proc = subprocess.Popen(["mdl"] + matc... | Run markdownlint on matched_filenames. | Below is the the instruction that describes the task:
### Input:
Run markdownlint on matched_filenames.
### Response:
def _run_markdownlint(matched_filenames, show_lint_files):
"""Run markdownlint on matched_filenames."""
from prospector.message import Message, Location
for filename in matched_filenam... |
def convert_kv_to_dict(data):
"""
convert text values in format:
key1=value1
key2=value2
to dict {'key1':'value1', 'key2':'value2'}
:param data: string containing lines with these values
:return: dict
"""
output = {}
for line in data.split("\n"):
stripped = line.strip()
... | convert text values in format:
key1=value1
key2=value2
to dict {'key1':'value1', 'key2':'value2'}
:param data: string containing lines with these values
:return: dict | Below is the the instruction that describes the task:
### Input:
convert text values in format:
key1=value1
key2=value2
to dict {'key1':'value1', 'key2':'value2'}
:param data: string containing lines with these values
:return: dict
### Response:
def convert_kv_to_dict(data):
"""
conver... |
def _unset_child(self, name, child):
"""
Untie child from parent.
:param name: Child name.
:param child: Parentable object.
"""
if name not in self._children or self._children[name] is not child:
msg = 'Child {child} with name "{name}" is not found'
... | Untie child from parent.
:param name: Child name.
:param child: Parentable object. | Below is the the instruction that describes the task:
### Input:
Untie child from parent.
:param name: Child name.
:param child: Parentable object.
### Response:
def _unset_child(self, name, child):
"""
Untie child from parent.
:param name: Child name.
:param child... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.