code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def raise_for_redefined_annotation(self, line: str, position: int, annotation: str) -> None:
"""Raise an exception if the given annotation is already defined.
:raises: RedefinedAnnotationError
"""
if self.disallow_redefinition and self.has_annotation(annotation):
raise Redef... | Raise an exception if the given annotation is already defined.
:raises: RedefinedAnnotationError | Below is the the instruction that describes the task:
### Input:
Raise an exception if the given annotation is already defined.
:raises: RedefinedAnnotationError
### Response:
def raise_for_redefined_annotation(self, line: str, position: int, annotation: str) -> None:
"""Raise an exception if the ... |
def update_disparity_map(self):
"""
Update disparity map in GUI.
The disparity image is normalized to the range 0-255 and then divided by
255, because OpenCV multiplies it by 255 when displaying. This is
because the pixels are stored as floating points.
"""
dispa... | Update disparity map in GUI.
The disparity image is normalized to the range 0-255 and then divided by
255, because OpenCV multiplies it by 255 when displaying. This is
because the pixels are stored as floating points. | Below is the the instruction that describes the task:
### Input:
Update disparity map in GUI.
The disparity image is normalized to the range 0-255 and then divided by
255, because OpenCV multiplies it by 255 when displaying. This is
because the pixels are stored as floating points.
### Resp... |
def resample_ann(resampled_t, ann_sample):
"""
Compute the new annotation indices
Parameters
----------
resampled_t : numpy array
Array of signal locations as returned by scipy.signal.resample
ann_sample : numpy array
Array of annotation locations
Returns
-------
re... | Compute the new annotation indices
Parameters
----------
resampled_t : numpy array
Array of signal locations as returned by scipy.signal.resample
ann_sample : numpy array
Array of annotation locations
Returns
-------
resampled_ann_sample : numpy array
Array of resam... | Below is the the instruction that describes the task:
### Input:
Compute the new annotation indices
Parameters
----------
resampled_t : numpy array
Array of signal locations as returned by scipy.signal.resample
ann_sample : numpy array
Array of annotation locations
Returns
... |
def stop(self):
'''
Stops chrome if it's running.
'''
try:
if (self.websock and self.websock.sock
and self.websock.sock.connected):
self.logger.info('shutting down websocket connection')
try:
self.websock... | Stops chrome if it's running. | Below is the the instruction that describes the task:
### Input:
Stops chrome if it's running.
### Response:
def stop(self):
'''
Stops chrome if it's running.
'''
try:
if (self.websock and self.websock.sock
and self.websock.sock.connected):
... |
def plain(self):
"""
Get a string representation of this XML document.
@return: A I{plain} string.
@rtype: basestring
"""
s = []
s.append(self.DECL)
root = self.root()
if root is not None:
s.append(root.plain())
return ''.join(s... | Get a string representation of this XML document.
@return: A I{plain} string.
@rtype: basestring | Below is the the instruction that describes the task:
### Input:
Get a string representation of this XML document.
@return: A I{plain} string.
@rtype: basestring
### Response:
def plain(self):
"""
Get a string representation of this XML document.
@return: A I{plain} string.
... |
def grab_java_message():
"""scan through the java output text and extract the bad java messages that may or may not happened when
unit tests are run. It will not record any bad java messages that are stored in g_ok_java_messages.
:return: none
"""
global g_temp_filename
global g_current_testn... | scan through the java output text and extract the bad java messages that may or may not happened when
unit tests are run. It will not record any bad java messages that are stored in g_ok_java_messages.
:return: none | Below is the the instruction that describes the task:
### Input:
scan through the java output text and extract the bad java messages that may or may not happened when
unit tests are run. It will not record any bad java messages that are stored in g_ok_java_messages.
:return: none
### Response:
def grab_j... |
def add_unique_template_variables(self, options):
"""Update map template variables specific to image visual"""
options.update(dict(
image=self.image,
coordinates=self.coordinates)) | Update map template variables specific to image visual | Below is the the instruction that describes the task:
### Input:
Update map template variables specific to image visual
### Response:
def add_unique_template_variables(self, options):
"""Update map template variables specific to image visual"""
options.update(dict(
image=self.image,
... |
def add_function(self, function_id=None, function=None, inputs=None,
outputs=None, input_domain=None, weight=None,
inp_weight=None, out_weight=None, description=None,
filters=None, await_domain=None, await_result=None,
**kwargs):
... | Add a single function node to dispatcher.
:param function_id:
Function node id.
If None will be assigned as <fun.__name__>.
:type function_id: str, optional
:param function:
Data node estimation function.
:type function: callable, optional
:... | Below is the the instruction that describes the task:
### Input:
Add a single function node to dispatcher.
:param function_id:
Function node id.
If None will be assigned as <fun.__name__>.
:type function_id: str, optional
:param function:
Data node estim... |
def assign(self, objects, nurest_object_type, async=False, callback=None, commit=True):
""" Reference a list of objects into the current resource
Args:
objects (list): list of NURESTObject to link
nurest_object_type (type): Type of the object to link
... | Reference a list of objects into the current resource
Args:
objects (list): list of NURESTObject to link
nurest_object_type (type): Type of the object to link
callback (function): Callback method that should be fired at the end
Returns:
... | Below is the the instruction that describes the task:
### Input:
Reference a list of objects into the current resource
Args:
objects (list): list of NURESTObject to link
nurest_object_type (type): Type of the object to link
callback (function): Callback m... |
def _get_go2nt_all(self, rcntobj):
"""For each GO id, put all printable fields in one namedtuple."""
### tic = timeit.default_timer()
go2nt = {}
ntobj = cx.namedtuple("NtGo", " ".join(self.prt_flds))
### tic = _rpt_hms(tic, "GoSubDag: _Init::get_go2nt")
tcntobj = self.kws... | For each GO id, put all printable fields in one namedtuple. | Below is the the instruction that describes the task:
### Input:
For each GO id, put all printable fields in one namedtuple.
### Response:
def _get_go2nt_all(self, rcntobj):
"""For each GO id, put all printable fields in one namedtuple."""
### tic = timeit.default_timer()
go2nt = {}
... |
def loads(s, model=None, parser=None):
"""Deserialize s (a str) to a Python object."""
with StringIO(s) as f:
return load(f, model=model, parser=parser) | Deserialize s (a str) to a Python object. | Below is the the instruction that describes the task:
### Input:
Deserialize s (a str) to a Python object.
### Response:
def loads(s, model=None, parser=None):
"""Deserialize s (a str) to a Python object."""
with StringIO(s) as f:
return load(f, model=model, parser=parser) |
def output(self):
"""output()
Return the resource database in text representation.
"""
self.lock.acquire()
text = output_db('', self.db)
self.lock.release()
return text | output()
Return the resource database in text representation. | Below is the the instruction that describes the task:
### Input:
output()
Return the resource database in text representation.
### Response:
def output(self):
"""output()
Return the resource database in text representation.
"""
self.lock.acquire()
text = output_db... |
def run(self, scenario=None, only=None, **kwargs):
"""
Run MAGICC and parse the output.
As a reminder, putting ``out_parameters=1`` will cause MAGICC to write out its
parameters into ``out/PARAMETERS.OUT`` and they will then be read into
``output.metadata["parameters"]`` where `... | Run MAGICC and parse the output.
As a reminder, putting ``out_parameters=1`` will cause MAGICC to write out its
parameters into ``out/PARAMETERS.OUT`` and they will then be read into
``output.metadata["parameters"]`` where ``output`` is the returned object.
Parameters
---------... | Below is the the instruction that describes the task:
### Input:
Run MAGICC and parse the output.
As a reminder, putting ``out_parameters=1`` will cause MAGICC to write out its
parameters into ``out/PARAMETERS.OUT`` and they will then be read into
``output.metadata["parameters"]`` where ``o... |
def factor_product(*args):
"""
Returns factor product over `args`.
Parameters
----------
args: `BaseFactor` instances.
factors to be multiplied
Returns
-------
BaseFactor: `BaseFactor` representing factor product over all the `BaseFactor` instances in args.
Examples
--... | Returns factor product over `args`.
Parameters
----------
args: `BaseFactor` instances.
factors to be multiplied
Returns
-------
BaseFactor: `BaseFactor` representing factor product over all the `BaseFactor` instances in args.
Examples
--------
>>> from pgmpy.factors.discr... | Below is the the instruction that describes the task:
### Input:
Returns factor product over `args`.
Parameters
----------
args: `BaseFactor` instances.
factors to be multiplied
Returns
-------
BaseFactor: `BaseFactor` representing factor product over all the `BaseFactor` instances... |
def get_observed_strains_and_df(observation, observation_dict):
"""
observation example: 'ros_simulated'
observation_dict example: {'ros_simulated': [['NT12204_755', 'wt'], ['NT12120_270', 'wt'], ...] ...}
"""
observed_df = pd.DataFrame.from_records(observation_dict[observation], columns=['strain','... | observation example: 'ros_simulated'
observation_dict example: {'ros_simulated': [['NT12204_755', 'wt'], ['NT12120_270', 'wt'], ...] ...} | Below is the the instruction that describes the task:
### Input:
observation example: 'ros_simulated'
observation_dict example: {'ros_simulated': [['NT12204_755', 'wt'], ['NT12120_270', 'wt'], ...] ...}
### Response:
def get_observed_strains_and_df(observation, observation_dict):
"""
observation exampl... |
def shapely_formatter(_, vertices, codes=None):
"""`Shapely`_ style contour formatter.
Contours are returned as a list of :class:`shapely.geometry.LineString`,
:class:`shapely.geometry.LinearRing`, and :class:`shapely.geometry.Point`
geometry elements.
Filled contours return a list of :class:`shap... | `Shapely`_ style contour formatter.
Contours are returned as a list of :class:`shapely.geometry.LineString`,
:class:`shapely.geometry.LinearRing`, and :class:`shapely.geometry.Point`
geometry elements.
Filled contours return a list of :class:`shapely.geometry.Polygon`
elements instead.
.. not... | Below is the the instruction that describes the task:
### Input:
`Shapely`_ style contour formatter.
Contours are returned as a list of :class:`shapely.geometry.LineString`,
:class:`shapely.geometry.LinearRing`, and :class:`shapely.geometry.Point`
geometry elements.
Filled contours return a list o... |
def collate_fonts_data(fonts_data):
"""Collate individual fonts data into a single glyph data list."""
glyphs = {}
for family in fonts_data:
for glyph in family:
if glyph['unicode'] not in glyphs:
glyphs[glyph['unicode']] = glyph
else:
c = gly... | Collate individual fonts data into a single glyph data list. | Below is the the instruction that describes the task:
### Input:
Collate individual fonts data into a single glyph data list.
### Response:
def collate_fonts_data(fonts_data):
"""Collate individual fonts data into a single glyph data list."""
glyphs = {}
for family in fonts_data:
for glyph in ... |
def _format_localizable_token(self, dt, token, locale):
"""
Formats a DateTime instance
with a given localizable token and locale.
:param dt: The instance to format
:type dt: pendulum.DateTime
:param token: The token to use
:type token: str
:param local... | Formats a DateTime instance
with a given localizable token and locale.
:param dt: The instance to format
:type dt: pendulum.DateTime
:param token: The token to use
:type token: str
:param locale: The locale to use
:type locale: Locale
:rtype: str | Below is the the instruction that describes the task:
### Input:
Formats a DateTime instance
with a given localizable token and locale.
:param dt: The instance to format
:type dt: pendulum.DateTime
:param token: The token to use
:type token: str
:param locale: The ... |
def _has_flaky_attributes(cls, test):
"""
Returns True if the test callable in question is marked as flaky.
:param test:
The test that is being prepared to run
:type test:
:class:`nose.case.Test` or :class:`Function`
:return:
:rtype:
`... | Returns True if the test callable in question is marked as flaky.
:param test:
The test that is being prepared to run
:type test:
:class:`nose.case.Test` or :class:`Function`
:return:
:rtype:
`bool` | Below is the the instruction that describes the task:
### Input:
Returns True if the test callable in question is marked as flaky.
:param test:
The test that is being prepared to run
:type test:
:class:`nose.case.Test` or :class:`Function`
:return:
:rtype:
... |
def do_execute(self):
"""
The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str
"""
result = None
cont = self.input.payload
serialization.write_all(
str(self.resolve_option("output")),
... | The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str | Below is the the instruction that describes the task:
### Input:
The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str
### Response:
def do_execute(self):
"""
The actual execution of the actor.
:return: None if successful, othe... |
def get_account_history(self, account_id, **kwargs):
""" List account activity. Account activity either increases or
decreases your account balance.
Entry type indicates the reason for the account change.
* transfer: Funds moved to/from Coinbase to cbpro
* match: Funds moved as ... | List account activity. Account activity either increases or
decreases your account balance.
Entry type indicates the reason for the account change.
* transfer: Funds moved to/from Coinbase to cbpro
* match: Funds moved as a result of a trade
* fee: Fee as a result of a trade... | Below is the the instruction that describes the task:
### Input:
List account activity. Account activity either increases or
decreases your account balance.
Entry type indicates the reason for the account change.
* transfer: Funds moved to/from Coinbase to cbpro
* match: Funds moved... |
def render_crispy_form(form, helper=None, context=None):
"""
Renders a form and returns its HTML output.
This function wraps the template logic in a function easy to use in a Django view.
"""
from crispy_forms.templatetags.crispy_forms_tags import CrispyFormNode
if helper is not None:
... | Renders a form and returns its HTML output.
This function wraps the template logic in a function easy to use in a Django view. | Below is the the instruction that describes the task:
### Input:
Renders a form and returns its HTML output.
This function wraps the template logic in a function easy to use in a Django view.
### Response:
def render_crispy_form(form, helper=None, context=None):
"""
Renders a form and returns its HTML... |
def strongest_match(cls, overlay, mode, backend=None):
"""
Returns the single strongest matching compositor operation
given an overlay. If no matches are found, None is returned.
The best match is defined as the compositor operation with the
highest match value as returned by th... | Returns the single strongest matching compositor operation
given an overlay. If no matches are found, None is returned.
The best match is defined as the compositor operation with the
highest match value as returned by the match_level method. | Below is the the instruction that describes the task:
### Input:
Returns the single strongest matching compositor operation
given an overlay. If no matches are found, None is returned.
The best match is defined as the compositor operation with the
highest match value as returned by the matc... |
def validate_aead(self, nonce, key_handle, aead, cleartext):
"""
Validate the contents of an AEAD using the YubiHSM. The matching is done
inside the YubiHSM so the contents of the AEAD is never exposed (well,
except indirectionally when the cleartext does match).
The cleartext s... | Validate the contents of an AEAD using the YubiHSM. The matching is done
inside the YubiHSM so the contents of the AEAD is never exposed (well,
except indirectionally when the cleartext does match).
The cleartext should naturally be of the same length as the AEAD minus
the size of the M... | Below is the the instruction that describes the task:
### Input:
Validate the contents of an AEAD using the YubiHSM. The matching is done
inside the YubiHSM so the contents of the AEAD is never exposed (well,
except indirectionally when the cleartext does match).
The cleartext should natura... |
def ResolvePrefix(self, subject, attribute_prefix, timestamp=None,
limit=None):
"""Retrieve a set of value matching for this subject's attribute.
Args:
subject: The subject that we will search.
attribute_prefix: The attribute prefix.
timestamp: A range of times for conside... | Retrieve a set of value matching for this subject's attribute.
Args:
subject: The subject that we will search.
attribute_prefix: The attribute prefix.
timestamp: A range of times for consideration (In microseconds). Can be a
constant such as ALL_TIMESTAMPS or NEWEST_TIMESTAMP or a tuple o... | Below is the the instruction that describes the task:
### Input:
Retrieve a set of value matching for this subject's attribute.
Args:
subject: The subject that we will search.
attribute_prefix: The attribute prefix.
timestamp: A range of times for consideration (In microseconds). Can be a
... |
def execute_codegen(self, target, target_workdir):
"""
Invoke the conan pex to fetch conan packages specified by a
`ExternalNativeLibrary` target.
:param ExternalNativeLibrary target: a target containing conan package specifications.
:param str target_workdir: where to copy the installed package co... | Invoke the conan pex to fetch conan packages specified by a
`ExternalNativeLibrary` target.
:param ExternalNativeLibrary target: a target containing conan package specifications.
:param str target_workdir: where to copy the installed package contents to. | Below is the the instruction that describes the task:
### Input:
Invoke the conan pex to fetch conan packages specified by a
`ExternalNativeLibrary` target.
:param ExternalNativeLibrary target: a target containing conan package specifications.
:param str target_workdir: where to copy the installed pack... |
def parse_config():
"""Parse the configuration and create required services.
Note:
Either takes the configuration from the environment (a variable
named ``FLASH_CONFIG``) or a file at the module root (named
``config.json``). Either way, it will attempt to parse it as
JSON, expecting the... | Parse the configuration and create required services.
Note:
Either takes the configuration from the environment (a variable
named ``FLASH_CONFIG``) or a file at the module root (named
``config.json``). Either way, it will attempt to parse it as
JSON, expecting the following format::
... | Below is the the instruction that describes the task:
### Input:
Parse the configuration and create required services.
Note:
Either takes the configuration from the environment (a variable
named ``FLASH_CONFIG``) or a file at the module root (named
``config.json``). Either way, it will attemp... |
def T(self):
"Time zone of this machine; e.g. 'EST' or 'MDT'"
name = self.timezone and self.timezone.tzname(self.data) or None
if name is None:
name = self.format('O')
return unicode(name) | Time zone of this machine; e.g. 'EST' or 'MDT | Below is the the instruction that describes the task:
### Input:
Time zone of this machine; e.g. 'EST' or 'MDT
### Response:
def T(self):
"Time zone of this machine; e.g. 'EST' or 'MDT'"
name = self.timezone and self.timezone.tzname(self.data) or None
if name is None:
name = self.format('O')
... |
def _machine_eps(dtype):
"""Returns the machine epsilon for the supplied dtype."""
if isinstance(dtype, tf.DType):
dtype = dtype.as_numpy_dtype()
return np.finfo(dtype).eps | Returns the machine epsilon for the supplied dtype. | Below is the the instruction that describes the task:
### Input:
Returns the machine epsilon for the supplied dtype.
### Response:
def _machine_eps(dtype):
"""Returns the machine epsilon for the supplied dtype."""
if isinstance(dtype, tf.DType):
dtype = dtype.as_numpy_dtype()
return np.finfo(dtype).eps |
def busca_errores_data(self):
"""
Busca errores o inconsistencias en los datos adquiridos
:return: Dataframe de errores encontrados
"""
data_busqueda = self.append_delta_index(TS_DATA_DEM, data_delta=self.data[self.masterkey].copy())
idx_desconex = (((data_busqueda.index ... | Busca errores o inconsistencias en los datos adquiridos
:return: Dataframe de errores encontrados | Below is the the instruction that describes the task:
### Input:
Busca errores o inconsistencias en los datos adquiridos
:return: Dataframe de errores encontrados
### Response:
def busca_errores_data(self):
"""
Busca errores o inconsistencias en los datos adquiridos
:return: Datafra... |
def BuildTemplates(self):
"""Builds the client templates.
We dont need to run special compilers so just enter the virtualenv and
build. Python will already find its own MSVC for python compilers.
"""
if args.config:
build_args = [
"--verbose", "--config", args.config, "build", "--ou... | Builds the client templates.
We dont need to run special compilers so just enter the virtualenv and
build. Python will already find its own MSVC for python compilers. | Below is the the instruction that describes the task:
### Input:
Builds the client templates.
We dont need to run special compilers so just enter the virtualenv and
build. Python will already find its own MSVC for python compilers.
### Response:
def BuildTemplates(self):
"""Builds the client templates... |
def dlogpdf_link_dvar(self, inv_link_f, y, Y_metadata=None):
"""
Gradient of the log-likelihood function at y given f, w.r.t variance parameter (t_noise)
.. math::
\\frac{d \\ln p(y_{i}|\lambda(f_{i}))}{d\\sigma^{2}} = \\frac{v((y_{i} - \lambda(f_{i}))^{2} - \\sigma^{2})}{2\\sigma^{... | Gradient of the log-likelihood function at y given f, w.r.t variance parameter (t_noise)
.. math::
\\frac{d \\ln p(y_{i}|\lambda(f_{i}))}{d\\sigma^{2}} = \\frac{v((y_{i} - \lambda(f_{i}))^{2} - \\sigma^{2})}{2\\sigma^{2}(\\sigma^{2}v + (y_{i} - \lambda(f_{i}))^{2})}
:param inv_link_f: late... | Below is the the instruction that describes the task:
### Input:
Gradient of the log-likelihood function at y given f, w.r.t variance parameter (t_noise)
.. math::
\\frac{d \\ln p(y_{i}|\lambda(f_{i}))}{d\\sigma^{2}} = \\frac{v((y_{i} - \lambda(f_{i}))^{2} - \\sigma^{2})}{2\\sigma^{2}(\\sigma^{... |
def parse(self, obj):
"""
Parse the object's properties according to its default types.
"""
for k, default in obj.__class__.defaults.items():
typ = type(default)
if typ is str:
continue
v = getattr(obj, k)
if typ is int:
... | Parse the object's properties according to its default types. | Below is the the instruction that describes the task:
### Input:
Parse the object's properties according to its default types.
### Response:
def parse(self, obj):
"""
Parse the object's properties according to its default types.
"""
for k, default in obj.__class__.defaults.items():
... |
def invalid_type_error(method_name, arg_name, got_value, expected_type,
version='0.13.0'):
"""Raise a CompilationException when an adapter method available to macros
has changed.
"""
got_type = type(got_value)
msg = ("As of {version}, 'adapter.{method_name}' expects argument "... | Raise a CompilationException when an adapter method available to macros
has changed. | Below is the the instruction that describes the task:
### Input:
Raise a CompilationException when an adapter method available to macros
has changed.
### Response:
def invalid_type_error(method_name, arg_name, got_value, expected_type,
version='0.13.0'):
"""Raise a CompilationExcepti... |
def shippingaddress_update(self, tid, session, **kwargs):
'''taobao.trade.shippingaddress.update 更改交易的收货地址'''
request = TOPRequest('taobao.trade.shippingaddress.update')
request['tid'] = tid
for k, v in kwargs.iteritems():
if k not in ('receiver_name','receiver_phone','receiv... | taobao.trade.shippingaddress.update 更改交易的收货地址 | Below is the the instruction that describes the task:
### Input:
taobao.trade.shippingaddress.update 更改交易的收货地址
### Response:
def shippingaddress_update(self, tid, session, **kwargs):
'''taobao.trade.shippingaddress.update 更改交易的收货地址'''
request = TOPRequest('taobao.trade.shippingaddress.update')
... |
def headerlist(self):
""" WSGI conform list of (header, value) tuples. """
if 'Content-Type' not in self.headers:
self.headers.add_header('Content-Type', self.default_content_type)
if self._cookies:
for c in self._cookies.values():
self.headers.add_header(... | WSGI conform list of (header, value) tuples. | Below is the the instruction that describes the task:
### Input:
WSGI conform list of (header, value) tuples.
### Response:
def headerlist(self):
""" WSGI conform list of (header, value) tuples. """
if 'Content-Type' not in self.headers:
self.headers.add_header('Content-Type', self.defa... |
def _position_and_velocity_TEME_km(self, t):
"""Return the raw true equator mean equinox (TEME) vectors from SGP4.
Returns a tuple of NumPy arrays ``([x y z], [xdot ydot zdot])``
expressed in kilometers and kilometers per second. Note that we
assume the TLE epoch to be a UTC date, per ... | Return the raw true equator mean equinox (TEME) vectors from SGP4.
Returns a tuple of NumPy arrays ``([x y z], [xdot ydot zdot])``
expressed in kilometers and kilometers per second. Note that we
assume the TLE epoch to be a UTC date, per AIAA 2006-6753. | Below is the the instruction that describes the task:
### Input:
Return the raw true equator mean equinox (TEME) vectors from SGP4.
Returns a tuple of NumPy arrays ``([x y z], [xdot ydot zdot])``
expressed in kilometers and kilometers per second. Note that we
assume the TLE epoch to be a U... |
def make_request(method, url, params=None, data=None, headers=None, auth=None):
"""
Make an HTTP request.
:param str method: "POST", "GET", "PUT" or "DELETE"
:param str url: URL to process request.
:param dict params: Params to add to the URL.
:param dict data: Form data.
:pa... | Make an HTTP request.
:param str method: "POST", "GET", "PUT" or "DELETE"
:param str url: URL to process request.
:param dict params: Params to add to the URL.
:param dict data: Form data.
:param dict headers: Headers to request.
:param tuple auth: Username and token. | Below is the the instruction that describes the task:
### Input:
Make an HTTP request.
:param str method: "POST", "GET", "PUT" or "DELETE"
:param str url: URL to process request.
:param dict params: Params to add to the URL.
:param dict data: Form data.
:param dict headers: Head... |
def keyspace_exists(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None):
'''
Check if a keyspace exists in a Cassandra cluster.
:param keyspace The keyspace name to check for.
:type keyspace: str
:param contact_points: The Cassandra cluster addresses, can either be... | Check if a keyspace exists in a Cassandra cluster.
:param keyspace The keyspace name to check for.
:type keyspace: str
:param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs.
:type contact_points: str | list[str]
:param cql_user: The Cas... | Below is the the instruction that describes the task:
### Input:
Check if a keyspace exists in a Cassandra cluster.
:param keyspace The keyspace name to check for.
:type keyspace: str
:param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs.
:typ... |
def moveToXY(self, vehID, edgeID, lane, x, y, angle=tc.INVALID_DOUBLE_VALUE, keepRoute=1):
'''Place vehicle at the given x,y coordinates and force it's angle to
the given value (for drawing).
If the angle is set to INVALID_DOUBLE_VALUE, the vehicle assumes the
natural angle of the edge o... | Place vehicle at the given x,y coordinates and force it's angle to
the given value (for drawing).
If the angle is set to INVALID_DOUBLE_VALUE, the vehicle assumes the
natural angle of the edge on which it is driving.
If keepRoute is set to 1, the closest position
within the exist... | Below is the the instruction that describes the task:
### Input:
Place vehicle at the given x,y coordinates and force it's angle to
the given value (for drawing).
If the angle is set to INVALID_DOUBLE_VALUE, the vehicle assumes the
natural angle of the edge on which it is driving.
If... |
def extract_journal_reference(line, override_kbs_files=None):
"""Extract the journal reference from string.
Extracts the journal reference from string and parses for specific
journal information.
"""
kbs = get_kbs(custom_kbs_files=override_kbs_files)
references, dummy_m, dummy_c, dummy_co = par... | Extract the journal reference from string.
Extracts the journal reference from string and parses for specific
journal information. | Below is the the instruction that describes the task:
### Input:
Extract the journal reference from string.
Extracts the journal reference from string and parses for specific
journal information.
### Response:
def extract_journal_reference(line, override_kbs_files=None):
"""Extract the journal referen... |
def update_vcl(self, service_id, version_number, name_key, **kwargs):
"""Update the uploaded VCL for a particular service and version."""
body = self._formdata(kwargs, FastlyVCL.FIELDS)
content = self._fetch("/service/%s/version/%d/vcl/%s" % (service_id, version_number, name_key), method="PUT", body=body)
retur... | Update the uploaded VCL for a particular service and version. | Below is the the instruction that describes the task:
### Input:
Update the uploaded VCL for a particular service and version.
### Response:
def update_vcl(self, service_id, version_number, name_key, **kwargs):
"""Update the uploaded VCL for a particular service and version."""
body = self._formdata(kwargs, Fa... |
def _gen_vevent(self, event, vevent):
"""Generate vevent from given event"""
vevent.add('dtstart').value = event['dtstart'][0]
vevent.add('dtstamp').value = datetime.fromtimestamp(self._mtime)
vevent.add('summary').value = event['msg']
vevent.add('uid').value = event['uid']
... | Generate vevent from given event | Below is the the instruction that describes the task:
### Input:
Generate vevent from given event
### Response:
def _gen_vevent(self, event, vevent):
"""Generate vevent from given event"""
vevent.add('dtstart').value = event['dtstart'][0]
vevent.add('dtstamp').value = datetime.fromtimestamp... |
def verify(self) -> None:
"""Raise a |RuntimeError| and removes all handled neural networks,
if the they are defined inconsistently.
Dispite all automated safety checks explained in the general
documentation on class |anntools.SeasonalANN|, it is still possible
to destroy the in... | Raise a |RuntimeError| and removes all handled neural networks,
if the they are defined inconsistently.
Dispite all automated safety checks explained in the general
documentation on class |anntools.SeasonalANN|, it is still possible
to destroy the inner consistency of a |anntools.Season... | Below is the the instruction that describes the task:
### Input:
Raise a |RuntimeError| and removes all handled neural networks,
if the they are defined inconsistently.
Dispite all automated safety checks explained in the general
documentation on class |anntools.SeasonalANN|, it is still po... |
def split_df(df):
'''
Split a dataframe in two dataframes: one with the history of agents,
and one with the environment history
'''
envmask = (df['agent_id'] == 'env')
n_env = envmask.sum()
if n_env == len(df):
return df, None
elif n_env == 0:
return None, df
agents, ... | Split a dataframe in two dataframes: one with the history of agents,
and one with the environment history | Below is the the instruction that describes the task:
### Input:
Split a dataframe in two dataframes: one with the history of agents,
and one with the environment history
### Response:
def split_df(df):
'''
Split a dataframe in two dataframes: one with the history of agents,
and one with the enviro... |
def setContextDoc(self, doc):
"""Set the doc of an xpathContext """
if doc is None: doc__o = None
else: doc__o = doc._o
libxml2mod.xmlXPathSetContextDoc(self._o, doc__o) | Set the doc of an xpathContext | Below is the the instruction that describes the task:
### Input:
Set the doc of an xpathContext
### Response:
def setContextDoc(self, doc):
"""Set the doc of an xpathContext """
if doc is None: doc__o = None
else: doc__o = doc._o
libxml2mod.xmlXPathSetContextDoc(self._o, doc__o) |
def safe_get(d, key, def_val=None):
"""
Helper function to fetch value from a dictionary
* `d` - Dictionary to fetch value from
* `key` - Key to lookup in dictionary
* `def_val` - Default value to return if dict does not have a member with key
"""
if d.has_key(key):
return d[key... | Helper function to fetch value from a dictionary
* `d` - Dictionary to fetch value from
* `key` - Key to lookup in dictionary
* `def_val` - Default value to return if dict does not have a member with key | Below is the the instruction that describes the task:
### Input:
Helper function to fetch value from a dictionary
* `d` - Dictionary to fetch value from
* `key` - Key to lookup in dictionary
* `def_val` - Default value to return if dict does not have a member with key
### Response:
def safe_get(d,... |
def run(self, value, errors, request):
"""Return thing, but abort validation if request.user cannot view."""
thing = super(ViewableDBThing, self).run(value, errors, request)
if errors:
return None
if not thing.can_view(request.user):
message = 'Insufficient permis... | Return thing, but abort validation if request.user cannot view. | Below is the the instruction that describes the task:
### Input:
Return thing, but abort validation if request.user cannot view.
### Response:
def run(self, value, errors, request):
"""Return thing, but abort validation if request.user cannot view."""
thing = super(ViewableDBThing, self).run(value,... |
def replace_species(self, species_mapping):
"""
Swap species.
Args:
species_mapping (dict): dict of species to swap. Species can be
elements too. E.g., {Element("Li"): Element("Na")} performs
a Li for Na substitution. The second species can be a
... | Swap species.
Args:
species_mapping (dict): dict of species to swap. Species can be
elements too. E.g., {Element("Li"): Element("Na")} performs
a Li for Na substitution. The second species can be a
sp_and_occu dict. For example, a site with 0.5 Si tha... | Below is the the instruction that describes the task:
### Input:
Swap species.
Args:
species_mapping (dict): dict of species to swap. Species can be
elements too. E.g., {Element("Li"): Element("Na")} performs
a Li for Na substitution. The second species can be a
... |
def fix_chain_id(self):
"""fill in missing chain identifier"""
for i in xrange(len(self.lines)):
line = self.lines[i]
if line.startswith("ATOM") and line[21] == ' ':
self.lines[i] = line[:21] + 'A' + line[22:] | fill in missing chain identifier | Below is the the instruction that describes the task:
### Input:
fill in missing chain identifier
### Response:
def fix_chain_id(self):
"""fill in missing chain identifier"""
for i in xrange(len(self.lines)):
line = self.lines[i]
if line.startswith("ATOM") and line[21] == '... |
def setup_combine(final_file, data):
"""Setup the data and outputs to allow merging data back together.
"""
if "align_split" not in data:
return final_file, data
align_dir = os.path.dirname(final_file)
base, ext = os.path.splitext(os.path.basename(final_file))
start, end = [int(x) for x ... | Setup the data and outputs to allow merging data back together. | Below is the the instruction that describes the task:
### Input:
Setup the data and outputs to allow merging data back together.
### Response:
def setup_combine(final_file, data):
"""Setup the data and outputs to allow merging data back together.
"""
if "align_split" not in data:
return final_f... |
def upload_from_url(cls, url, store=None, filename=None):
"""Uploads file from given url and returns ``FileFromUrl`` instance.
Args:
- url (str): URL of file to upload to
- store (Optional[bool]): Should the file be automatically stored
upon upload. Defaults to N... | Uploads file from given url and returns ``FileFromUrl`` instance.
Args:
- url (str): URL of file to upload to
- store (Optional[bool]): Should the file be automatically stored
upon upload. Defaults to None.
- False - do not store file
- Tr... | Below is the the instruction that describes the task:
### Input:
Uploads file from given url and returns ``FileFromUrl`` instance.
Args:
- url (str): URL of file to upload to
- store (Optional[bool]): Should the file be automatically stored
upon upload. Defaults to N... |
def get_translocation(self):
"""Extract INDRA Translocation Statements."""
qstr = "$.events.frames[@.type is 'translocation']"
res = self.tree.execute(qstr)
if res is None:
return
for r in res:
epistemics = self._get_epistemics(r)
if epistemics... | Extract INDRA Translocation Statements. | Below is the the instruction that describes the task:
### Input:
Extract INDRA Translocation Statements.
### Response:
def get_translocation(self):
"""Extract INDRA Translocation Statements."""
qstr = "$.events.frames[@.type is 'translocation']"
res = self.tree.execute(qstr)
if res ... |
def get_file_named(self, fldr, xtn):
"""
scans a directory for files like *.GZ or *.ZIP and returns
the filename of the first one found (should only be one of
each file here
"""
res = [] # list of Sample objects
for root, _, files in os.walk(fldr):
... | scans a directory for files like *.GZ or *.ZIP and returns
the filename of the first one found (should only be one of
each file here | Below is the the instruction that describes the task:
### Input:
scans a directory for files like *.GZ or *.ZIP and returns
the filename of the first one found (should only be one of
each file here
### Response:
def get_file_named(self, fldr, xtn):
"""
scans a directory for files li... |
def run_from_argv(self, argv):
"""
Set the default Gherkin test runner for its options to be parsed.
"""
self.test_runner = test_runner_class
super(Command, self).run_from_argv(argv) | Set the default Gherkin test runner for its options to be parsed. | Below is the the instruction that describes the task:
### Input:
Set the default Gherkin test runner for its options to be parsed.
### Response:
def run_from_argv(self, argv):
"""
Set the default Gherkin test runner for its options to be parsed.
"""
self.test_runner = test_runner_c... |
def get_resource(request, resource, allow_multiple=False, full_clean=True, default_to_not_supplied=False):
"""
Get a resource instance from ``request.body``.
Note error code 98 is returned in multiple places, this is to prevent leakage of details of defined resources.
"""
# Decode the request body... | Get a resource instance from ``request.body``.
Note error code 98 is returned in multiple places, this is to prevent leakage of details of defined resources. | Below is the the instruction that describes the task:
### Input:
Get a resource instance from ``request.body``.
Note error code 98 is returned in multiple places, this is to prevent leakage of details of defined resources.
### Response:
def get_resource(request, resource, allow_multiple=False, full_clean=True... |
def _store_object(self, obj_name, content, etag=None, chunked=False,
chunk_size=None, headers=None):
"""
Handles the low-level creation of a storage object and the uploading of
the contents of that object.
"""
head_etag = headers.pop("ETag", "")
if chunked:
... | Handles the low-level creation of a storage object and the uploading of
the contents of that object. | Below is the the instruction that describes the task:
### Input:
Handles the low-level creation of a storage object and the uploading of
the contents of that object.
### Response:
def _store_object(self, obj_name, content, etag=None, chunked=False,
chunk_size=None, headers=None):
"""
... |
def todict(self):
"""Convert namedtuple to dict."""
return OrderedDict((name, self[i]) for i, name in enumerate(self._fields)) | Convert namedtuple to dict. | Below is the the instruction that describes the task:
### Input:
Convert namedtuple to dict.
### Response:
def todict(self):
"""Convert namedtuple to dict."""
return OrderedDict((name, self[i]) for i, name in enumerate(self._fields)) |
def build_raw_request_message(self, request, args, is_completed=False):
"""build protocol level message based on request and args.
request object contains meta information about outgoing request.
args are the currently chunk data from argstreams
is_completed tells the flags of the messa... | build protocol level message based on request and args.
request object contains meta information about outgoing request.
args are the currently chunk data from argstreams
is_completed tells the flags of the message
:param request: Request
:param args: array of arg streams
... | Below is the the instruction that describes the task:
### Input:
build protocol level message based on request and args.
request object contains meta information about outgoing request.
args are the currently chunk data from argstreams
is_completed tells the flags of the message
:p... |
def shared_otuids(groups):
"""
Get shared OTUIDs between all unique combinations of groups.
:type groups: Dict
:param groups: {Category name: OTUIDs in category}
:return type: dict
:return: Dict keyed on group combination and their shared OTUIDs as values.
"""
for g in sorted(groups):
... | Get shared OTUIDs between all unique combinations of groups.
:type groups: Dict
:param groups: {Category name: OTUIDs in category}
:return type: dict
:return: Dict keyed on group combination and their shared OTUIDs as values. | Below is the the instruction that describes the task:
### Input:
Get shared OTUIDs between all unique combinations of groups.
:type groups: Dict
:param groups: {Category name: OTUIDs in category}
:return type: dict
:return: Dict keyed on group combination and their shared OTUIDs as values.
### Res... |
def chained_set(self, value, command='set', *keys):
"""
chained_set takes the value to
enter into the dictionary, a command of what
to do with the value, and a sequence of keys.
Examples:
d = {}
d.chained_set(1,'append','level 1','level 2')
-> d['level... | chained_set takes the value to
enter into the dictionary, a command of what
to do with the value, and a sequence of keys.
Examples:
d = {}
d.chained_set(1,'append','level 1','level 2')
-> d['level 1']['level 2'] = [1]
d.chained_set(2,'append','level 1','level... | Below is the the instruction that describes the task:
### Input:
chained_set takes the value to
enter into the dictionary, a command of what
to do with the value, and a sequence of keys.
Examples:
d = {}
d.chained_set(1,'append','level 1','level 2')
-> d['level 1'... |
def verify(self, data, signature=None, keyrings=None, homedir=None):
'''
`data` <string> the data to verify.
`signature` <string> The signature, if detached from the data.
`keyrings` <list of string> Additional keyrings to search in.
`homedir` <string> Override the configured hom... | `data` <string> the data to verify.
`signature` <string> The signature, if detached from the data.
`keyrings` <list of string> Additional keyrings to search in.
`homedir` <string> Override the configured homedir. | Below is the the instruction that describes the task:
### Input:
`data` <string> the data to verify.
`signature` <string> The signature, if detached from the data.
`keyrings` <list of string> Additional keyrings to search in.
`homedir` <string> Override the configured homedir.
### Response: ... |
def _disconnected(self, uri):
"""Disconnected callback from Crazyflie API"""
self.param_updater.close()
self.is_updated = False
# Clear all values from the previous Crazyflie
self.toc = Toc()
self.values = {} | Disconnected callback from Crazyflie API | Below is the the instruction that describes the task:
### Input:
Disconnected callback from Crazyflie API
### Response:
def _disconnected(self, uri):
"""Disconnected callback from Crazyflie API"""
self.param_updater.close()
self.is_updated = False
# Clear all values from the previou... |
def fetch_by_uuid(uuid):
"""
Serve publications by UUID.
"""
# fetch all - private and public - publications
all_pubs = [
pub
for pub in search_publications(DBPublication(uuid=uuid))
]
if not all_pubs:
abort(404, "Dokument s UUID '%s' není dostupný." % (uuid))
p... | Serve publications by UUID. | Below is the the instruction that describes the task:
### Input:
Serve publications by UUID.
### Response:
def fetch_by_uuid(uuid):
"""
Serve publications by UUID.
"""
# fetch all - private and public - publications
all_pubs = [
pub
for pub in search_publications(DBPublication(u... |
def _handle_break(self, node, scope, ctxt, stream):
"""Handle break node
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
"""
self._dlog("handling break")
raise errors.InterpBreak() | Handle break node
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO | Below is the the instruction that describes the task:
### Input:
Handle break node
:node: TODO
:scope: TODO
:ctxt: TODO
:stream: TODO
:returns: TODO
### Response:
def _handle_break(self, node, scope, ctxt, stream):
"""Handle break node
:node: TODO
:... |
def log_run_info(self, model_name):
"""Collect most of the TF runtime information for the local env.
The schema of the run info follows official/benchmark/datastore/schema.
Args:
model_name: string, the name of the model.
"""
run_info = {
"model_name": model_name,
"machine_co... | Collect most of the TF runtime information for the local env.
The schema of the run info follows official/benchmark/datastore/schema.
Args:
model_name: string, the name of the model. | Below is the the instruction that describes the task:
### Input:
Collect most of the TF runtime information for the local env.
The schema of the run info follows official/benchmark/datastore/schema.
Args:
model_name: string, the name of the model.
### Response:
def log_run_info(self, model_name):
... |
def load_images(image_files, resize=True):
"""Load images from files and optionally resize it."""
images = []
for image_file in image_files:
with file_io.FileIO(image_file, 'r') as ff:
images.append(ff.read())
if resize is False:
return images
# To resize, run a tf session so we can reuse 'dec... | Load images from files and optionally resize it. | Below is the the instruction that describes the task:
### Input:
Load images from files and optionally resize it.
### Response:
def load_images(image_files, resize=True):
"""Load images from files and optionally resize it."""
images = []
for image_file in image_files:
with file_io.FileIO(image_file, 'r'... |
def build_riskinputs(self, kind):
"""
:param kind:
kind of hazard getter, can be 'poe' or 'gmf'
:returns:
a list of RiskInputs objects, sorted by IMT.
"""
logging.info('Building risk inputs from %d realization(s)', self.R)
imtls = self.oqparam.imtl... | :param kind:
kind of hazard getter, can be 'poe' or 'gmf'
:returns:
a list of RiskInputs objects, sorted by IMT. | Below is the the instruction that describes the task:
### Input:
:param kind:
kind of hazard getter, can be 'poe' or 'gmf'
:returns:
a list of RiskInputs objects, sorted by IMT.
### Response:
def build_riskinputs(self, kind):
"""
:param kind:
kind of haza... |
def get_books(self):
"""
Retrieves all the books published by the artist
:return: List. Books published by the artist
"""
return itunespy.lookup(id=self.artist_id, entity=itunespy.entities['ebook'])[1:] | Retrieves all the books published by the artist
:return: List. Books published by the artist | Below is the the instruction that describes the task:
### Input:
Retrieves all the books published by the artist
:return: List. Books published by the artist
### Response:
def get_books(self):
"""
Retrieves all the books published by the artist
:return: List. Books published by the ... |
def parser_help_text(help_text):
"""Takes the help text supplied as a doc string and extraxts the
description and any param arguments."""
if help_text is None:
return None, {}
main_text = ''
params_help = {}
for line in help_text.splitlines():
line = line.strip()
match ... | Takes the help text supplied as a doc string and extraxts the
description and any param arguments. | Below is the the instruction that describes the task:
### Input:
Takes the help text supplied as a doc string and extraxts the
description and any param arguments.
### Response:
def parser_help_text(help_text):
"""Takes the help text supplied as a doc string and extraxts the
description and any param a... |
def serialize(self, data: Dict, fields=None, toBytes=True):
"""
Serializes a dict to bytes preserving the order (in sorted order)
:param data: the data to be serialized
:return: serialized data as bytes
"""
if isinstance(data, Dict):
data = self._sort_dict(dat... | Serializes a dict to bytes preserving the order (in sorted order)
:param data: the data to be serialized
:return: serialized data as bytes | Below is the the instruction that describes the task:
### Input:
Serializes a dict to bytes preserving the order (in sorted order)
:param data: the data to be serialized
:return: serialized data as bytes
### Response:
def serialize(self, data: Dict, fields=None, toBytes=True):
"""
S... |
def _classify_directory_contents(filesystem, root):
"""Classify contents of a directory as files/directories.
Args:
filesystem: The fake filesystem used for implementation
root: (str) Directory to examine.
Returns:
(tuple) A tuple consisting of three values: the directory examined,... | Classify contents of a directory as files/directories.
Args:
filesystem: The fake filesystem used for implementation
root: (str) Directory to examine.
Returns:
(tuple) A tuple consisting of three values: the directory examined,
a list containing all of the directory entries, an... | Below is the the instruction that describes the task:
### Input:
Classify contents of a directory as files/directories.
Args:
filesystem: The fake filesystem used for implementation
root: (str) Directory to examine.
Returns:
(tuple) A tuple consisting of three values: the directory... |
def list_mbeds(self):
""" List details of connected devices
@return Returns list of structures with detailed info about each mbed
@details Function returns list of dictionaries with mbed attributes
'mount_point', TargetID name etc.
Function returns mbed list with platform names... | List details of connected devices
@return Returns list of structures with detailed info about each mbed
@details Function returns list of dictionaries with mbed attributes
'mount_point', TargetID name etc.
Function returns mbed list with platform names if possible | Below is the the instruction that describes the task:
### Input:
List details of connected devices
@return Returns list of structures with detailed info about each mbed
@details Function returns list of dictionaries with mbed attributes
'mount_point', TargetID name etc.
Function re... |
def ctype(self):
"""Returns the name of the c_type from iso_c_binding to use when declaring
the output parameter for interaction with python ctypes.
"""
if self.dtype == "logical":
return "C_BOOL"
elif self.dtype == "complex":
#We don't actually know what ... | Returns the name of the c_type from iso_c_binding to use when declaring
the output parameter for interaction with python ctypes. | Below is the the instruction that describes the task:
### Input:
Returns the name of the c_type from iso_c_binding to use when declaring
the output parameter for interaction with python ctypes.
### Response:
def ctype(self):
"""Returns the name of the c_type from iso_c_binding to use when declaring... |
def __fetch_user_data(self, tag_type, user_link):
"""Get data associated to an user"""
user_name = self.client.user_name(user_link)
user = {}
if not user_name:
return user
user_raw = self.client.user(user_name)
user = json.loads(user_raw)
return u... | Get data associated to an user | Below is the the instruction that describes the task:
### Input:
Get data associated to an user
### Response:
def __fetch_user_data(self, tag_type, user_link):
"""Get data associated to an user"""
user_name = self.client.user_name(user_link)
user = {}
if not user_name:
... |
def add_job(self, func, *args):
"""Add a job that should return a reply to be sent.
A job is a tuple of function and optional args. Keyword arguments
can be passed via use of functools.partial. The job should return a
string that should be sent by the gateway protocol.
The asyn... | Add a job that should return a reply to be sent.
A job is a tuple of function and optional args. Keyword arguments
can be passed via use of functools.partial. The job should return a
string that should be sent by the gateway protocol.
The async version of this method will send the repl... | Below is the the instruction that describes the task:
### Input:
Add a job that should return a reply to be sent.
A job is a tuple of function and optional args. Keyword arguments
can be passed via use of functools.partial. The job should return a
string that should be sent by the gateway p... |
def run_step(context):
"""Get, set, unset $ENVs.
Context is a dictionary or dictionary-like. context is mandatory.
Input context is:
env:
get: {dict}
set: {dict}
unset: [list]
At least one of env's sub-keys (get, set or unset) must exist.
This step wil... | Get, set, unset $ENVs.
Context is a dictionary or dictionary-like. context is mandatory.
Input context is:
env:
get: {dict}
set: {dict}
unset: [list]
At least one of env's sub-keys (get, set or unset) must exist.
This step will run whatever combination of ... | Below is the the instruction that describes the task:
### Input:
Get, set, unset $ENVs.
Context is a dictionary or dictionary-like. context is mandatory.
Input context is:
env:
get: {dict}
set: {dict}
unset: [list]
At least one of env's sub-keys (get, set o... |
def get_dihedral_degrees(self, indices, start_row=0):
"""Return the dihedrals between given atoms.
Calculates the dihedral angle in degrees between the atoms with
indices ``i, b, a, d``.
The indices can be given in three ways:
* As simple list ``[i, b, a, d]``
* As list... | Return the dihedrals between given atoms.
Calculates the dihedral angle in degrees between the atoms with
indices ``i, b, a, d``.
The indices can be given in three ways:
* As simple list ``[i, b, a, d]``
* As list of lists: ``[[i1, b1, a1, d1], [i2, b2, a2, d2]...]``
* ... | Below is the the instruction that describes the task:
### Input:
Return the dihedrals between given atoms.
Calculates the dihedral angle in degrees between the atoms with
indices ``i, b, a, d``.
The indices can be given in three ways:
* As simple list ``[i, b, a, d]``
* As ... |
def _encrypt(self, data, recipients,
default_key=None,
passphrase=None,
armor=True,
encrypt=True,
symmetric=False,
always_trust=True,
output=None,
throw_keyids=False,
... | Encrypt the message read from the file-like object **data**.
:param str data: The file or bytestream to encrypt.
:param str recipients: The recipients to encrypt to. Recipients must
be specified keyID/fingerprint.
.. warning:: Care should be taken in Python2 to ... | Below is the the instruction that describes the task:
### Input:
Encrypt the message read from the file-like object **data**.
:param str data: The file or bytestream to encrypt.
:param str recipients: The recipients to encrypt to. Recipients must
be specified keyID/f... |
def run(self):
"""
Delete user modules to force Python to deeply reload them
Do not del modules which are considered as system modules, i.e.
modules installed in subdirectories of Python interpreter's binary
Do not del C modules
"""
self.modnames_to_reload = []
... | Delete user modules to force Python to deeply reload them
Do not del modules which are considered as system modules, i.e.
modules installed in subdirectories of Python interpreter's binary
Do not del C modules | Below is the the instruction that describes the task:
### Input:
Delete user modules to force Python to deeply reload them
Do not del modules which are considered as system modules, i.e.
modules installed in subdirectories of Python interpreter's binary
Do not del C modules
### Response:
d... |
def _parse_remind_line(self, line, text):
"""Parse a line of remind output into a dict
line -- the remind output
text -- the original remind input
"""
event = {}
line = line.split(None, 6)
dat = [int(f) for f in line[0].split('/')]
if line[4] != '*':
... | Parse a line of remind output into a dict
line -- the remind output
text -- the original remind input | Below is the the instruction that describes the task:
### Input:
Parse a line of remind output into a dict
line -- the remind output
text -- the original remind input
### Response:
def _parse_remind_line(self, line, text):
"""Parse a line of remind output into a dict
line -- the r... |
def discard(self, value):
'''Remove an element *value* from a set if it is a member.'''
return self.cache.remove((self.value_pickler.dumps(value),)) | Remove an element *value* from a set if it is a member. | Below is the the instruction that describes the task:
### Input:
Remove an element *value* from a set if it is a member.
### Response:
def discard(self, value):
'''Remove an element *value* from a set if it is a member.'''
return self.cache.remove((self.value_pickler.dumps(value),)) |
def delete_resource(self, uri, purge=False):
"""Delete file or folder
uri -- mediafire URI
Keyword arguments:
purge -- delete the resource without sending it to Trash.
"""
try:
resource = self.get_resource_by_uri(uri)
except ResourceNotFoundError:
... | Delete file or folder
uri -- mediafire URI
Keyword arguments:
purge -- delete the resource without sending it to Trash. | Below is the the instruction that describes the task:
### Input:
Delete file or folder
uri -- mediafire URI
Keyword arguments:
purge -- delete the resource without sending it to Trash.
### Response:
def delete_resource(self, uri, purge=False):
"""Delete file or folder
uri... |
def records(self):
"""Returns all records in a dbf file."""
if not self.numRecords:
self.__dbfHeader()
records = []
f = self.__getFileObj(self.dbf)
f.seek(self.__dbfHeaderLength())
for i in range(self.numRecords):
r = self.__record()
... | Returns all records in a dbf file. | Below is the the instruction that describes the task:
### Input:
Returns all records in a dbf file.
### Response:
def records(self):
"""Returns all records in a dbf file."""
if not self.numRecords:
self.__dbfHeader()
records = []
f = self.__getFileObj(self.dbf)
... |
def get_definition(self, name: YangIdentifier,
kw: YangIdentifier) -> Optional["Statement"]:
"""Search ancestor statements for a definition.
Args:
name: Name of a grouping or datatype (with no prefix).
kw: ``grouping`` or ``typedef``.
Raises:
... | Search ancestor statements for a definition.
Args:
name: Name of a grouping or datatype (with no prefix).
kw: ``grouping`` or ``typedef``.
Raises:
DefinitionNotFound: If the definition is not found. | Below is the the instruction that describes the task:
### Input:
Search ancestor statements for a definition.
Args:
name: Name of a grouping or datatype (with no prefix).
kw: ``grouping`` or ``typedef``.
Raises:
DefinitionNotFound: If the definition is not found... |
def confusion_matrix(targets, predictions):
r"""
Compute the confusion matrix for classifier predictions.
Parameters
----------
targets : SArray
Ground truth class labels (cannot be of type float).
predictions : SArray
The prediction that corresponds to each target value.
... | r"""
Compute the confusion matrix for classifier predictions.
Parameters
----------
targets : SArray
Ground truth class labels (cannot be of type float).
predictions : SArray
The prediction that corresponds to each target value.
This vector must have the same length as ``ta... | Below is the the instruction that describes the task:
### Input:
r"""
Compute the confusion matrix for classifier predictions.
Parameters
----------
targets : SArray
Ground truth class labels (cannot be of type float).
predictions : SArray
The prediction that corresponds to eac... |
def range_hist(items, bins):
"""
Bins items into a discrete histogram by values and/or ranges.
items = [1, 2, 3, 4, 5, 6, 7]
bins = [0, 1, 2, (3, float('inf'))]
ut.range_hist(items, bins)
"""
big_hist = ut.dict_hist(items)
hist = ut.odict([(b, 0) for b in bins])
for k, ... | Bins items into a discrete histogram by values and/or ranges.
items = [1, 2, 3, 4, 5, 6, 7]
bins = [0, 1, 2, (3, float('inf'))]
ut.range_hist(items, bins) | Below is the the instruction that describes the task:
### Input:
Bins items into a discrete histogram by values and/or ranges.
items = [1, 2, 3, 4, 5, 6, 7]
bins = [0, 1, 2, (3, float('inf'))]
ut.range_hist(items, bins)
### Response:
def range_hist(items, bins):
"""
Bins items into... |
def redirect(to, headers=None, status=302,
content_type='text/html; charset=utf-8'):
'''Abort execution and cause a 302 redirect (by default).
:param to: path or fully qualified URL to redirect to
:param headers: optional dict of headers to include in the new request
:param status: status ... | Abort execution and cause a 302 redirect (by default).
:param to: path or fully qualified URL to redirect to
:param headers: optional dict of headers to include in the new request
:param status: status code (int) of the new request, defaults to 302
:param content_type: the content type (string) of the ... | Below is the the instruction that describes the task:
### Input:
Abort execution and cause a 302 redirect (by default).
:param to: path or fully qualified URL to redirect to
:param headers: optional dict of headers to include in the new request
:param status: status code (int) of the new request, defau... |
def new(self, func_or_exp, *args, **kwargs):
"""Add a new background job and start it in a separate thread.
There are two types of jobs which can be created:
1. Jobs based on expressions which can be passed to an eval() call.
The expression must be given as a string. For example:
... | Add a new background job and start it in a separate thread.
There are two types of jobs which can be created:
1. Jobs based on expressions which can be passed to an eval() call.
The expression must be given as a string. For example:
job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]])
... | Below is the the instruction that describes the task:
### Input:
Add a new background job and start it in a separate thread.
There are two types of jobs which can be created:
1. Jobs based on expressions which can be passed to an eval() call.
The expression must be given as a string. For ... |
def route(rule=None, blueprint=None, defaults=None, endpoint=None,
is_member=False, methods=None, only_if=None, **rule_options):
"""
Decorator to set default route rules for a view function. The arguments this
function accepts are very similar to Flask's :meth:`~flask.Flask.route`,
however, th... | Decorator to set default route rules for a view function. The arguments this
function accepts are very similar to Flask's :meth:`~flask.Flask.route`,
however, the ``is_member`` perhaps deserves an example::
class UserResource(ModelResource):
class Meta:
model = User
... | Below is the the instruction that describes the task:
### Input:
Decorator to set default route rules for a view function. The arguments this
function accepts are very similar to Flask's :meth:`~flask.Flask.route`,
however, the ``is_member`` perhaps deserves an example::
class UserResource(ModelRes... |
def parse_properties(parent_index_name, parent_name, nested_path, esProperties):
"""
RETURN THE COLUMN DEFINITIONS IN THE GIVEN esProperties OBJECT
"""
columns = FlatList()
for name, property in esProperties.items():
index_name = parent_index_name
column_name = concat_field(parent_na... | RETURN THE COLUMN DEFINITIONS IN THE GIVEN esProperties OBJECT | Below is the the instruction that describes the task:
### Input:
RETURN THE COLUMN DEFINITIONS IN THE GIVEN esProperties OBJECT
### Response:
def parse_properties(parent_index_name, parent_name, nested_path, esProperties):
"""
RETURN THE COLUMN DEFINITIONS IN THE GIVEN esProperties OBJECT
"""
colum... |
def skip_whitespace(self, newlines=0):
"""Moves the position forwards to the next non newline space character.
If newlines >= 1 include newlines as spaces.
"""
if newlines:
while not self.eos:
if self.get_char().isspace():
self.eat_length(1... | Moves the position forwards to the next non newline space character.
If newlines >= 1 include newlines as spaces. | Below is the the instruction that describes the task:
### Input:
Moves the position forwards to the next non newline space character.
If newlines >= 1 include newlines as spaces.
### Response:
def skip_whitespace(self, newlines=0):
"""Moves the position forwards to the next non newline space charac... |
def to_array(self):
"""
Serializes this Document to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
"""
array = super(Document, self).to_array()
array['file_id'] = u(self.file_id) # py2: type unicode, py3: type str
if self.... | Serializes this Document to a dictionary.
:return: dictionary representation of this object.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Serializes this Document to a dictionary.
:return: dictionary representation of this object.
:rtype: dict
### Response:
def to_array(self):
"""
Serializes this Document to a dictionary.
:return: dictionary re... |
def rule(rules, strict_slashes=False, api_func=None, *args, **kwargs):
"""
Add a API route to the 'api' blueprint.
:param rules: rule string or string list
:param strict_slashes: same to Blueprint.route, but default value is False
:param api_func: a function that returns a JSON serializable object
... | Add a API route to the 'api' blueprint.
:param rules: rule string or string list
:param strict_slashes: same to Blueprint.route, but default value is False
:param api_func: a function that returns a JSON serializable object
or a Flask Response, or raises ApiException
:param args: o... | Below is the the instruction that describes the task:
### Input:
Add a API route to the 'api' blueprint.
:param rules: rule string or string list
:param strict_slashes: same to Blueprint.route, but default value is False
:param api_func: a function that returns a JSON serializable object
... |
def get_html_lang_tags(index_page):
"""
Return `languages` stored in ``<meta>`` tags.
``<meta http-equiv="Content-language" content="cs">`` -> ``cs``
Args:
index_page (str): HTML content of the page you wish to analyze.
Returns:
list: List of :class:`.SourceString` objects.
""... | Return `languages` stored in ``<meta>`` tags.
``<meta http-equiv="Content-language" content="cs">`` -> ``cs``
Args:
index_page (str): HTML content of the page you wish to analyze.
Returns:
list: List of :class:`.SourceString` objects. | Below is the the instruction that describes the task:
### Input:
Return `languages` stored in ``<meta>`` tags.
``<meta http-equiv="Content-language" content="cs">`` -> ``cs``
Args:
index_page (str): HTML content of the page you wish to analyze.
Returns:
list: List of :class:`.SourceSt... |
def get_course_list_name(curriculum_abbr, course_number, section_id,
quarter, year):
"""
Return the list address of UW course email list
"""
return "%s%s%s_%s%s" % (
_get_list_name_curr_abbr(curriculum_abbr),
course_number,
section_id.lower(),
qua... | Return the list address of UW course email list | Below is the the instruction that describes the task:
### Input:
Return the list address of UW course email list
### Response:
def get_course_list_name(curriculum_abbr, course_number, section_id,
quarter, year):
"""
Return the list address of UW course email list
"""
return... |
def deferred_call(self, callback, *args, **kwargs):
""" We have to wake up the reactor after every call because it may
calculate a long delay where it can sleep which causes events that
happen during this period to seem really slow as they do not get
processed until after the reactor ... | We have to wake up the reactor after every call because it may
calculate a long delay where it can sleep which causes events that
happen during this period to seem really slow as they do not get
processed until after the reactor "wakes up" | Below is the the instruction that describes the task:
### Input:
We have to wake up the reactor after every call because it may
calculate a long delay where it can sleep which causes events that
happen during this period to seem really slow as they do not get
processed until after the rea... |
def pretrain_procedure(self, layer_objs, layer_graphs, set_params_func,
train_set, validation_set=None):
"""Perform unsupervised pretraining of the model.
:param layer_objs: list of model objects (autoencoders or rbms)
:param layer_graphs: list of model tf.Graph objec... | Perform unsupervised pretraining of the model.
:param layer_objs: list of model objects (autoencoders or rbms)
:param layer_graphs: list of model tf.Graph objects
:param set_params_func: function used to set the parameters after
pretraining
:param train_set: training set
... | Below is the the instruction that describes the task:
### Input:
Perform unsupervised pretraining of the model.
:param layer_objs: list of model objects (autoencoders or rbms)
:param layer_graphs: list of model tf.Graph objects
:param set_params_func: function used to set the parameters aft... |
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
init_py = readfile(os.path.join(package, '__init__.py'))
return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1) | Return package version as listed in `__version__` in `init.py`. | Below is the the instruction that describes the task:
### Input:
Return package version as listed in `__version__` in `init.py`.
### Response:
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
init_py = readfile(os.path.join(package, '__init__.py'))
... |
def _reportFutures(self):
"""Sends futures status updates to broker at intervals of
scoop.TIME_BETWEEN_STATUS_REPORTS seconds. Is intended to be run by a
separate thread."""
try:
while True:
time.sleep(scoop.TIME_BETWEEN_STATUS_REPORTS)
fids = ... | Sends futures status updates to broker at intervals of
scoop.TIME_BETWEEN_STATUS_REPORTS seconds. Is intended to be run by a
separate thread. | Below is the the instruction that describes the task:
### Input:
Sends futures status updates to broker at intervals of
scoop.TIME_BETWEEN_STATUS_REPORTS seconds. Is intended to be run by a
separate thread.
### Response:
def _reportFutures(self):
"""Sends futures status updates to broker at... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.