code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _cleanup(lst):
'''
Return a list of non-empty dictionaries.
'''
clean = []
for ele in lst:
if ele and isinstance(ele, dict):
clean.append(ele)
return clean | Return a list of non-empty dictionaries. | Below is the the instruction that describes the task:
### Input:
Return a list of non-empty dictionaries.
### Response:
def _cleanup(lst):
'''
Return a list of non-empty dictionaries.
'''
clean = []
for ele in lst:
if ele and isinstance(ele, dict):
clean.append(ele)
retu... |
def render(self, name, color=True, just=None, **kwargs):
"""
Render the selected prompt.
Parameters
----------
name : str
Which prompt to render. One of 'in', 'in2', 'out', 'rewrite'
color : bool
If True (default), include ANSI escape sequence... | Render the selected prompt.
Parameters
----------
name : str
Which prompt to render. One of 'in', 'in2', 'out', 'rewrite'
color : bool
If True (default), include ANSI escape sequences for a coloured prompt.
just : bool
If True, justify the p... | Below is the the instruction that describes the task:
### Input:
Render the selected prompt.
Parameters
----------
name : str
Which prompt to render. One of 'in', 'in2', 'out', 'rewrite'
color : bool
If True (default), include ANSI escape sequences for a ... |
def _set_data(self):
"""
This method will be called to set Series data
"""
if getattr(self, 'data', False) and not getattr(self, '_x', False) and not getattr(self, '_y', False):
_x = XVariable()
_y = YVariable()
_x.contribute_to_class(self, 'X', self.d... | This method will be called to set Series data | Below is the the instruction that describes the task:
### Input:
This method will be called to set Series data
### Response:
def _set_data(self):
"""
This method will be called to set Series data
"""
if getattr(self, 'data', False) and not getattr(self, '_x', False) and not getattr(... |
def seed_aws_organization(ctx, owner):
"""Seeds SWAG from an AWS organziation."""
swag = create_swag_from_ctx(ctx)
accounts = swag.get_all()
_ids = [result.get('id') for result in accounts]
client = boto3.client('organizations')
paginator = client.get_paginator('list_accounts')
response_ite... | Seeds SWAG from an AWS organziation. | Below is the the instruction that describes the task:
### Input:
Seeds SWAG from an AWS organziation.
### Response:
def seed_aws_organization(ctx, owner):
"""Seeds SWAG from an AWS organziation."""
swag = create_swag_from_ctx(ctx)
accounts = swag.get_all()
_ids = [result.get('id') for result in acc... |
def timezone(client, location, timestamp=None, language=None):
"""Get time zone for a location on the earth, as well as that location's
time offset from UTC.
:param location: The latitude/longitude value representing the location to
look up.
:type location: string, dict, list, or tuple
:pa... | Get time zone for a location on the earth, as well as that location's
time offset from UTC.
:param location: The latitude/longitude value representing the location to
look up.
:type location: string, dict, list, or tuple
:param timestamp: Timestamp specifies the desired time as seconds since
... | Below is the the instruction that describes the task:
### Input:
Get time zone for a location on the earth, as well as that location's
time offset from UTC.
:param location: The latitude/longitude value representing the location to
look up.
:type location: string, dict, list, or tuple
:par... |
def analyse(self, traj, network, current_subrun, subrun_list, network_dict):
"""Extracts monitor data and plots.
Data extraction is done if all subruns have been completed,
i.e. `len(subrun_list)==0`
First, extracts results from the monitors and stores them into `traj`.
Next, ... | Extracts monitor data and plots.
Data extraction is done if all subruns have been completed,
i.e. `len(subrun_list)==0`
First, extracts results from the monitors and stores them into `traj`.
Next, uses the extracted data for plots.
:param traj:
Trajectory contain... | Below is the the instruction that describes the task:
### Input:
Extracts monitor data and plots.
Data extraction is done if all subruns have been completed,
i.e. `len(subrun_list)==0`
First, extracts results from the monitors and stores them into `traj`.
Next, uses the extracted ... |
def _checkSetpointValue( setpointvalue, maxvalue ):
"""Check that the given setpointvalue is valid.
Args:
* setpointvalue (numerical): The setpoint value to be checked. Must be positive.
* maxvalue (numerical): Upper limit for setpoint value. Must be positive.
Raises:
... | Check that the given setpointvalue is valid.
Args:
* setpointvalue (numerical): The setpoint value to be checked. Must be positive.
* maxvalue (numerical): Upper limit for setpoint value. Must be positive.
Raises:
TypeError, ValueError | Below is the the instruction that describes the task:
### Input:
Check that the given setpointvalue is valid.
Args:
* setpointvalue (numerical): The setpoint value to be checked. Must be positive.
* maxvalue (numerical): Upper limit for setpoint value. Must be positive.
Raises:... |
def init_config(self, app):
"""Initialize configuration.
:param app: An instance of :class:`~flask.Flask`.
"""
_vars = ['BASE_TEMPLATE', 'COVER_TEMPLATE', 'SETTINGS_TEMPLATE']
# Sets RequireJS config and SASS binary as well if not already set.
for k in dir(config):
... | Initialize configuration.
:param app: An instance of :class:`~flask.Flask`. | Below is the the instruction that describes the task:
### Input:
Initialize configuration.
:param app: An instance of :class:`~flask.Flask`.
### Response:
def init_config(self, app):
"""Initialize configuration.
:param app: An instance of :class:`~flask.Flask`.
"""
_vars =... |
def print_stats(self, stream=None):
"""
Log annotated garbage objects to console or file.
:param stream: open file, uses sys.stdout if not given
"""
if not stream: # pragma: no cover
stream = sys.stdout
self.metadata.sort(key=lambda x: -x.size)
stream... | Log annotated garbage objects to console or file.
:param stream: open file, uses sys.stdout if not given | Below is the the instruction that describes the task:
### Input:
Log annotated garbage objects to console or file.
:param stream: open file, uses sys.stdout if not given
### Response:
def print_stats(self, stream=None):
"""
Log annotated garbage objects to console or file.
:param ... |
def delete_archives(self, *archives):
'''
Delete archives
:return:
'''
# Remove paths
_archives = []
for archive in archives:
_archives.append(os.path.basename(archive))
archives = _archives[:]
ret = {'files': {}, 'errors': {}}
... | Delete archives
:return: | Below is the the instruction that describes the task:
### Input:
Delete archives
:return:
### Response:
def delete_archives(self, *archives):
'''
Delete archives
:return:
'''
# Remove paths
_archives = []
for archive in archives:
_archives... |
def multenterbox(msg="Fill in values for the fields.", title=" ",
fields=(), values=()):
r"""
Show screen with multiple data entry fields.
If there are fewer values than names, the list of values is padded with
empty strings until the number of values is the same as the number
of n... | r"""
Show screen with multiple data entry fields.
If there are fewer values than names, the list of values is padded with
empty strings until the number of values is the same as the number
of names.
If there are more values than names, the list of values
is truncated so that there are as many ... | Below is the the instruction that describes the task:
### Input:
r"""
Show screen with multiple data entry fields.
If there are fewer values than names, the list of values is padded with
empty strings until the number of values is the same as the number
of names.
If there are more values than ... |
def _forwardImplementation(self, inbuf, outbuf):
""" Proportional probability method.
"""
assert self.module
propensities = self.module.getActionValues(0)
summedProps = sum(propensities)
probabilities = propensities / summedProps
action = eventGenerator(probabi... | Proportional probability method. | Below is the the instruction that describes the task:
### Input:
Proportional probability method.
### Response:
def _forwardImplementation(self, inbuf, outbuf):
""" Proportional probability method.
"""
assert self.module
propensities = self.module.getActionValues(0)
summed... |
def query(url, **kwargs):
'''
Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function <salt.utils.http.query>`:
.. autofunction:: salt.utils.http.query
CLI Example:
.. code-block:: bash
salt '*' http.que... | Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function <salt.utils.http.query>`:
.. autofunction:: salt.utils.http.query
CLI Example:
.. code-block:: bash
salt '*' http.query http://somelink.com/
salt '... | Below is the the instruction that describes the task:
### Input:
Query a resource, and decode the return data
Passes through all the parameters described in the
:py:func:`utils.http.query function <salt.utils.http.query>`:
.. autofunction:: salt.utils.http.query
CLI Example:
.. code-block:: ... |
def pipe_subelement(context=None, _INPUT=None, conf=None, **kwargs):
"""An operator extracts select sub-elements from a feed. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : pipe2py.modules pipe like object (iterable of items)
conf : {'path': {'value': <element pat... | An operator extracts select sub-elements from a feed. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : pipe2py.modules pipe like object (iterable of items)
conf : {'path': {'value': <element path>}}
Yields
------
_OUTPUT : items | Below is the the instruction that describes the task:
### Input:
An operator extracts select sub-elements from a feed. Not loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : pipe2py.modules pipe like object (iterable of items)
conf : {'path': {'value': <element path>}}
... |
def get_target_forums_for_moved_topics(self, user):
""" Returns a list of forums in which the considered user can add topics that have been
moved from another forum.
"""
return [f for f in self._get_forums_for_user(user, ['can_move_topics', ]) if f.is_forum] | Returns a list of forums in which the considered user can add topics that have been
moved from another forum. | Below is the the instruction that describes the task:
### Input:
Returns a list of forums in which the considered user can add topics that have been
moved from another forum.
### Response:
def get_target_forums_for_moved_topics(self, user):
""" Returns a list of forums in which the considered u... |
def import_split(import_name):
""" takes a dotted string path and returns the components:
import_split('path') == 'path', None, None
import_split('path.part.object') == 'path.part', 'object', None
import_split('path.part:object') == 'path.part', 'object', None
import_split('path.part... | takes a dotted string path and returns the components:
import_split('path') == 'path', None, None
import_split('path.part.object') == 'path.part', 'object', None
import_split('path.part:object') == 'path.part', 'object', None
import_split('path.part:object.attribute')
== 'pat... | Below is the the instruction that describes the task:
### Input:
takes a dotted string path and returns the components:
import_split('path') == 'path', None, None
import_split('path.part.object') == 'path.part', 'object', None
import_split('path.part:object') == 'path.part', 'object', None
... |
def makescacoldesc(columnname, value,
datamanagertype='',
datamanagergroup='',
options=0, maxlen=0, comment='',
valuetype='', keywords={}):
"""Create description of a scalar column.
A description for a scalar column can be created from... | Create description of a scalar column.
A description for a scalar column can be created from a name for
the column and a data value, which is used only to determine the
type of the column. Note that a dict value is also possible.
It is possible to create the column description in more detail
by gi... | Below is the the instruction that describes the task:
### Input:
Create description of a scalar column.
A description for a scalar column can be created from a name for
the column and a data value, which is used only to determine the
type of the column. Note that a dict value is also possible.
It ... |
def from_elements(cls, items=None):
"""Create a :class:`Dict` of constants from a live dictionary.
:param items: The items to store in the node.
:type items: dict
:returns: The created dictionary node.
:rtype: Dict
"""
node = cls()
if items is None:
... | Create a :class:`Dict` of constants from a live dictionary.
:param items: The items to store in the node.
:type items: dict
:returns: The created dictionary node.
:rtype: Dict | Below is the the instruction that describes the task:
### Input:
Create a :class:`Dict` of constants from a live dictionary.
:param items: The items to store in the node.
:type items: dict
:returns: The created dictionary node.
:rtype: Dict
### Response:
def from_elements(cls, ite... |
def components(self):
"""
Return a dataframe of the components (days, hours, minutes,
seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.
Returns
-------
a DataFrame
"""
from pandas import DataFrame
columns = ['days', 'hours', 'm... | Return a dataframe of the components (days, hours, minutes,
seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.
Returns
-------
a DataFrame | Below is the the instruction that describes the task:
### Input:
Return a dataframe of the components (days, hours, minutes,
seconds, milliseconds, microseconds, nanoseconds) of the Timedeltas.
Returns
-------
a DataFrame
### Response:
def components(self):
"""
Retu... |
def idxmin(self, axis=0, skipna=True, *args, **kwargs):
"""
Return the row label of the minimum value.
If multiple values equal the minimum, the first row label with that
value is returned.
Parameters
----------
skipna : bool, default True
Exclude NA... | Return the row label of the minimum value.
If multiple values equal the minimum, the first row label with that
value is returned.
Parameters
----------
skipna : bool, default True
Exclude NA/null values. If the entire Series is NA, the result
will be NA.... | Below is the the instruction that describes the task:
### Input:
Return the row label of the minimum value.
If multiple values equal the minimum, the first row label with that
value is returned.
Parameters
----------
skipna : bool, default True
Exclude NA/null v... |
def __field_to_subfields(self, field):
"""Fully describes data represented by field, including the nested case.
In the case that the field is not a message field, we have no fields nested
within a message definition, so we can simply return that field. However, in
the nested case, we can't simply descr... | Fully describes data represented by field, including the nested case.
In the case that the field is not a message field, we have no fields nested
within a message definition, so we can simply return that field. However, in
the nested case, we can't simply describe the data with one field or even
with o... | Below is the the instruction that describes the task:
### Input:
Fully describes data represented by field, including the nested case.
In the case that the field is not a message field, we have no fields nested
within a message definition, so we can simply return that field. However, in
the nested case... |
def list(self, **params):
"""
Retrieve text messages
Returns Text Messages, according to the parameters provided
:calls: ``get /text_messages``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which repres... | Retrieve text messages
Returns Text Messages, according to the parameters provided
:calls: ``get /text_messages``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent collection of TextMessages.
:rtype... | Below is the the instruction that describes the task:
### Input:
Retrieve text messages
Returns Text Messages, according to the parameters provided
:calls: ``get /text_messages``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-sty... |
def add_point_region(self, y: float, x: float) -> Graphic:
"""Add a point graphic to the data item.
:param x: The x coordinate, in relative units [0.0, 1.0]
:param y: The y coordinate, in relative units [0.0, 1.0]
:return: The :py:class:`nion.swift.Facade.Graphic` object that was added.... | Add a point graphic to the data item.
:param x: The x coordinate, in relative units [0.0, 1.0]
:param y: The y coordinate, in relative units [0.0, 1.0]
:return: The :py:class:`nion.swift.Facade.Graphic` object that was added.
.. versionadded:: 1.0
Scriptable: Yes | Below is the the instruction that describes the task:
### Input:
Add a point graphic to the data item.
:param x: The x coordinate, in relative units [0.0, 1.0]
:param y: The y coordinate, in relative units [0.0, 1.0]
:return: The :py:class:`nion.swift.Facade.Graphic` object that was added.
... |
def getTJstr(text, glyphs, simple, ordering):
""" Return a PDF string enclosed in [] brackets, suitable for the PDF TJ
operator.
Notes:
The input string is converted to either 2 or 4 hex digits per character.
Args:
simple: no glyphs: 2-chars, use char codes as the glyph
... | Return a PDF string enclosed in [] brackets, suitable for the PDF TJ
operator.
Notes:
The input string is converted to either 2 or 4 hex digits per character.
Args:
simple: no glyphs: 2-chars, use char codes as the glyph
glyphs: 2-chars, use glyphs instead of char codes (Sym... | Below is the the instruction that describes the task:
### Input:
Return a PDF string enclosed in [] brackets, suitable for the PDF TJ
operator.
Notes:
The input string is converted to either 2 or 4 hex digits per character.
Args:
simple: no glyphs: 2-chars, use char codes as the glyph
... |
def clone(self, screen, scene):
"""
Create a clone of this Dialog into a new Screen.
:param screen: The new Screen object to clone into.
:param scene: The new Scene object to clone into.
"""
# Only clone the object if the function is safe to do so.
if self._on_cl... | Create a clone of this Dialog into a new Screen.
:param screen: The new Screen object to clone into.
:param scene: The new Scene object to clone into. | Below is the the instruction that describes the task:
### Input:
Create a clone of this Dialog into a new Screen.
:param screen: The new Screen object to clone into.
:param scene: The new Scene object to clone into.
### Response:
def clone(self, screen, scene):
"""
Create a clone o... |
def set_base_headers(self, hdr):
"""Set metadata in FITS headers."""
hdr['NUMXVER'] = (__version__, 'Numina package version')
hdr['NUMRNAM'] = (self.__class__.__name__, 'Numina recipe name')
hdr['NUMRVER'] = (self.__version__, 'Numina recipe version')
return hdr | Set metadata in FITS headers. | Below is the the instruction that describes the task:
### Input:
Set metadata in FITS headers.
### Response:
def set_base_headers(self, hdr):
"""Set metadata in FITS headers."""
hdr['NUMXVER'] = (__version__, 'Numina package version')
hdr['NUMRNAM'] = (self.__class__.__name__, 'Numina recip... |
def clear(self):
"""Clear all work items from the session.
This removes any associated results as well.
"""
with self._conn:
self._conn.execute('DELETE FROM results')
self._conn.execute('DELETE FROM work_items') | Clear all work items from the session.
This removes any associated results as well. | Below is the the instruction that describes the task:
### Input:
Clear all work items from the session.
This removes any associated results as well.
### Response:
def clear(self):
"""Clear all work items from the session.
This removes any associated results as well.
"""
wi... |
def p_intermfluent_def(self, p):
'''intermfluent_def : IDENT LPAREN param_list RPAREN COLON LCURLY INTERMEDIATE COMMA type_spec COMMA LEVEL ASSIGN_EQUAL range_const RCURLY SEMI
| IDENT COLON LCURLY INTERMEDIATE COMMA type_spec COMMA LEVEL ASSIGN_EQUAL range_const RCURLY SEMI'''
... | intermfluent_def : IDENT LPAREN param_list RPAREN COLON LCURLY INTERMEDIATE COMMA type_spec COMMA LEVEL ASSIGN_EQUAL range_const RCURLY SEMI
| IDENT COLON LCURLY INTERMEDIATE COMMA type_spec COMMA LEVEL ASSIGN_EQUAL range_const RCURLY SEMI | Below is the the instruction that describes the task:
### Input:
intermfluent_def : IDENT LPAREN param_list RPAREN COLON LCURLY INTERMEDIATE COMMA type_spec COMMA LEVEL ASSIGN_EQUAL range_const RCURLY SEMI
| IDENT COLON LCURLY INTERMEDIATE COMMA type_spec COMMA LEVEL ASSIGN_EQUAL range_c... |
def authenticate_device(self, api_token, device_token, email=None,
user_url=None, override=False, fetch=True):
"""Set credentials for Device authentication.
Args:
api_token (str): Token issued to your Application through the Gem
Developer Console.
... | Set credentials for Device authentication.
Args:
api_token (str): Token issued to your Application through the Gem
Developer Console.
device_token (str): Physical device identifier. You will receive this
from a user.devices.create call or from users.create.
... | Below is the the instruction that describes the task:
### Input:
Set credentials for Device authentication.
Args:
api_token (str): Token issued to your Application through the Gem
Developer Console.
device_token (str): Physical device identifier. You will receive this
... |
def circular_shift(X):
"""Shifts circularly the X squre matrix in order to get a
time-lag matrix."""
N = X.shape[0]
L = np.zeros(X.shape)
for i in range(N):
L[i, :] = np.asarray([X[(i + j) % N, j] for j in range(N)])
return L | Shifts circularly the X squre matrix in order to get a
time-lag matrix. | Below is the the instruction that describes the task:
### Input:
Shifts circularly the X squre matrix in order to get a
time-lag matrix.
### Response:
def circular_shift(X):
"""Shifts circularly the X squre matrix in order to get a
time-lag matrix."""
N = X.shape[0]
L = np.zeros(X.shape... |
def after_serving(self, func: Callable) -> Callable:
"""Add a after serving function.
This will allow the function provided to be called once after
anything is served (after last byte is sent).
This is designed to be used as a decorator. An example usage,
.. code-block:: pytho... | Add a after serving function.
This will allow the function provided to be called once after
anything is served (after last byte is sent).
This is designed to be used as a decorator. An example usage,
.. code-block:: python
@app.after_serving
def func():
... | Below is the the instruction that describes the task:
### Input:
Add a after serving function.
This will allow the function provided to be called once after
anything is served (after last byte is sent).
This is designed to be used as a decorator. An example usage,
.. code-block:: ... |
def file_size(self):
""":return: size of file we manager"""
if self._file_size is None:
if isinstance(self._path_or_fd, string_types()):
self._file_size = os.stat(self._path_or_fd).st_size
else:
self._file_size = os.fstat(self._path_or_fd).st_size
... | :return: size of file we manager | Below is the the instruction that describes the task:
### Input:
:return: size of file we manager
### Response:
def file_size(self):
""":return: size of file we manager"""
if self._file_size is None:
if isinstance(self._path_or_fd, string_types()):
self._file_size = os.s... |
def iterkeys(obj):
"Get key iterator from dictionary for Python 2 and 3"
return iter(obj.keys()) if sys.version_info.major == 3 else obj.iterkeys() | Get key iterator from dictionary for Python 2 and 3 | Below is the the instruction that describes the task:
### Input:
Get key iterator from dictionary for Python 2 and 3
### Response:
def iterkeys(obj):
"Get key iterator from dictionary for Python 2 and 3"
return iter(obj.keys()) if sys.version_info.major == 3 else obj.iterkeys() |
def dump(self):
"""Save analytics report to a temporary file.
Returns:
str: path to the temporary file that contains the analytics report.
"""
import tempfile
with tempfile.NamedTemporaryFile(delete=False, mode="w") as fobj:
json.dump(self.info, fobj)
... | Save analytics report to a temporary file.
Returns:
str: path to the temporary file that contains the analytics report. | Below is the the instruction that describes the task:
### Input:
Save analytics report to a temporary file.
Returns:
str: path to the temporary file that contains the analytics report.
### Response:
def dump(self):
"""Save analytics report to a temporary file.
Returns:
... |
def flush(self):
"""
Wait until history is read but no more than 10 cycles
in case a browser session is closed.
"""
i = 0
while self._frame_data.is_dirty and i < 10:
i += 1
time.sleep(0.1) | Wait until history is read but no more than 10 cycles
in case a browser session is closed. | Below is the the instruction that describes the task:
### Input:
Wait until history is read but no more than 10 cycles
in case a browser session is closed.
### Response:
def flush(self):
"""
Wait until history is read but no more than 10 cycles
in case a browser session is closed.
... |
def _clean_suffix(string, suffix):
"""
If string endswith the suffix, remove it. Else leave it alone.
"""
suffix_len = len(suffix)
if len(string) < suffix_len:
# the string param was shorter than the suffix
raise ValueError("A suffix can not be bigger than string argument.")
if ... | If string endswith the suffix, remove it. Else leave it alone. | Below is the the instruction that describes the task:
### Input:
If string endswith the suffix, remove it. Else leave it alone.
### Response:
def _clean_suffix(string, suffix):
"""
If string endswith the suffix, remove it. Else leave it alone.
"""
suffix_len = len(suffix)
if len(string) < suff... |
async def list_batches(self, request):
"""Fetches list of batches from validator, optionally filtered by id.
Request:
query:
- head: The id of the block to use as the head of the chain
- id: Comma separated list of batch ids to include in results
Res... | Fetches list of batches from validator, optionally filtered by id.
Request:
query:
- head: The id of the block to use as the head of the chain
- id: Comma separated list of batch ids to include in results
Response:
data: JSON array of fully expan... | Below is the the instruction that describes the task:
### Input:
Fetches list of batches from validator, optionally filtered by id.
Request:
query:
- head: The id of the block to use as the head of the chain
- id: Comma separated list of batch ids to include in r... |
def supported(aln):
"""Get only the supported consensus residues in each column.
Meaning:
- Omit majority-gap columns
- Omit columns where no residue type appears more than once
- In case of a tie, return all the top-scoring residue types
(no prioritization)
Returns a *list* -- not a str... | Get only the supported consensus residues in each column.
Meaning:
- Omit majority-gap columns
- Omit columns where no residue type appears more than once
- In case of a tie, return all the top-scoring residue types
(no prioritization)
Returns a *list* -- not a string! -- where elements are ... | Below is the the instruction that describes the task:
### Input:
Get only the supported consensus residues in each column.
Meaning:
- Omit majority-gap columns
- Omit columns where no residue type appears more than once
- In case of a tie, return all the top-scoring residue types
(no prioriti... |
def get_not_num(self, seq, num=0):
'''Find the index of first non num element'''
ind = next((i for i, x in enumerate(seq) if x != num), None)
if ind == None:
return self.board_size
else:
return ind | Find the index of first non num element | Below is the the instruction that describes the task:
### Input:
Find the index of first non num element
### Response:
def get_not_num(self, seq, num=0):
'''Find the index of first non num element'''
ind = next((i for i, x in enumerate(seq) if x != num), None)
if ind == None:
re... |
def OSLibpath(self):
"""
Microsoft Windows SDK Libraries Paths
"""
ref = os.path.join(self.si.WindowsSdkDir, 'References')
libpath = []
if self.vc_ver <= 9.0:
libpath += self.OSLibraries
if self.vc_ver >= 11.0:
libpath += [os.path.join(re... | Microsoft Windows SDK Libraries Paths | Below is the the instruction that describes the task:
### Input:
Microsoft Windows SDK Libraries Paths
### Response:
def OSLibpath(self):
"""
Microsoft Windows SDK Libraries Paths
"""
ref = os.path.join(self.si.WindowsSdkDir, 'References')
libpath = []
if self.vc_ve... |
def start(self):
""" Initialize websockets, say hello, and start listening for events
"""
self.connect()
if not self.isAlive():
super(WAMPClient,self).start()
self.hello()
return self | Initialize websockets, say hello, and start listening for events | Below is the the instruction that describes the task:
### Input:
Initialize websockets, say hello, and start listening for events
### Response:
def start(self):
""" Initialize websockets, say hello, and start listening for events
"""
self.connect()
if not self.isAlive():
... |
def set_global_provenance(wf: Workflow, registry: Registry):
"""Compute a global provenance key for the entire workflow
before evaluation. This key can be used to store and retrieve
results in a database. The key computed in this stage is different
from the (local) provenance key that can be computed fo... | Compute a global provenance key for the entire workflow
before evaluation. This key can be used to store and retrieve
results in a database. The key computed in this stage is different
from the (local) provenance key that can be computed for a node
if all its arguments are known.
In cases where a r... | Below is the the instruction that describes the task:
### Input:
Compute a global provenance key for the entire workflow
before evaluation. This key can be used to store and retrieve
results in a database. The key computed in this stage is different
from the (local) provenance key that can be computed f... |
def before(self, callback: Union[Callable, str]) -> "Control":
"""Register a control method that reacts before the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If ... | Register a control method that reacts before the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If given as a string, then the control will look
up a method ... | Below is the the instruction that describes the task:
### Input:
Register a control method that reacts before the trigger method is called.
Parameters:
callback:
The control method. If given as a callable, then that function will be
used as the callback. If given... |
def persistent_popen_align3(data, samples, chunk):
""" notes """
## data are already chunked, read in the whole thing
with open(chunk, 'rb') as infile:
clusts = infile.read().split("//\n//\n")[:-1]
## snames to ensure sorted order
samples.sort(key=lambda x: x.name)
snames = [sampl... | notes | Below is the the instruction that describes the task:
### Input:
notes
### Response:
def persistent_popen_align3(data, samples, chunk):
""" notes """
## data are already chunked, read in the whole thing
with open(chunk, 'rb') as infile:
clusts = infile.read().split("//\n//\n")[:-1]
#... |
def _did_receive_response(self, connection):
""" Receive a response from the connection """
if connection.has_timeouted:
bambou_logger.info("NURESTConnection has timeout.")
return
has_callbacks = connection.has_callbacks()
should_post = not has_callbacks
... | Receive a response from the connection | Below is the the instruction that describes the task:
### Input:
Receive a response from the connection
### Response:
def _did_receive_response(self, connection):
""" Receive a response from the connection """
if connection.has_timeouted:
bambou_logger.info("NURESTConnection has timeou... |
def report_response(response,
request_headers=True, request_body=True,
response_headers=False, response_body=False,
redirection=False):
"""
生成响应报告
:param response: ``requests.models.Response`` 对象
:param request_headers: 是否加入请求头
:param requ... | 生成响应报告
:param response: ``requests.models.Response`` 对象
:param request_headers: 是否加入请求头
:param request_body: 是否加入请求体
:param response_headers: 是否加入响应头
:param response_body: 是否加入响应体
:param redirection: 是否加入重定向响应
:return: str | Below is the the instruction that describes the task:
### Input:
生成响应报告
:param response: ``requests.models.Response`` 对象
:param request_headers: 是否加入请求头
:param request_body: 是否加入请求体
:param response_headers: 是否加入响应头
:param response_body: 是否加入响应体
:param redirection: 是否加入重定向响应
:return: str... |
def RepackTemplates(self,
repack_configs,
templates,
output_dir,
config=None,
sign=False,
signed_template=False):
"""Call repacker in a subprocess."""
pool = multiprocessing.Pool(p... | Call repacker in a subprocess. | Below is the the instruction that describes the task:
### Input:
Call repacker in a subprocess.
### Response:
def RepackTemplates(self,
repack_configs,
templates,
output_dir,
config=None,
sign=False,
... |
def on_batch_end(self, last_target, train, **kwargs):
"Update the metrics if not `train`"
if train: return
bs = last_target.size(0)
for name in self.names:
self.metrics[name] += bs * self.learn.loss_func.metrics[name].detach().cpu()
self.nums += bs | Update the metrics if not `train` | Below is the the instruction that describes the task:
### Input:
Update the metrics if not `train`
### Response:
def on_batch_end(self, last_target, train, **kwargs):
"Update the metrics if not `train`"
if train: return
bs = last_target.size(0)
for name in self.names:
se... |
def delete_menu(self, menu):
""" Delete the specified menu
:param menu:
:type menu:
:returns:
:rtype:
:raises:
"""
if menu.parent is None:
del self.menus[menu.name()]
menu._delete() | Delete the specified menu
:param menu:
:type menu:
:returns:
:rtype:
:raises: | Below is the the instruction that describes the task:
### Input:
Delete the specified menu
:param menu:
:type menu:
:returns:
:rtype:
:raises:
### Response:
def delete_menu(self, menu):
""" Delete the specified menu
:param menu:
:type menu:
... |
def add_config(parser):
""" add config """
# the default config path
default_config_path = config.get_heron_conf_dir()
parser.add_argument(
'--config-path',
metavar='(a string; path to cluster config; default: "' + default_config_path + '")',
default=os.path.join(config.get_heron_dir(), defau... | add config | Below is the the instruction that describes the task:
### Input:
add config
### Response:
def add_config(parser):
""" add config """
# the default config path
default_config_path = config.get_heron_conf_dir()
parser.add_argument(
'--config-path',
metavar='(a string; path to cluster config; def... |
def makeResetPacket(ID, param):
"""
Resets a servo to one of 3 reset states:
XL320_RESET_ALL = 0xFF
XL320_RESET_ALL_BUT_ID = 0x01
XL320_RESET_ALL_BUT_ID_BAUD_RATE = 0x02
"""
if param not in [0x01, 0x02, 0xff]:
raise Exception('Packet.makeResetPacket invalide parameter {}'.format(par... | Resets a servo to one of 3 reset states:
XL320_RESET_ALL = 0xFF
XL320_RESET_ALL_BUT_ID = 0x01
XL320_RESET_ALL_BUT_ID_BAUD_RATE = 0x02 | Below is the the instruction that describes the task:
### Input:
Resets a servo to one of 3 reset states:
XL320_RESET_ALL = 0xFF
XL320_RESET_ALL_BUT_ID = 0x01
XL320_RESET_ALL_BUT_ID_BAUD_RATE = 0x02
### Response:
def makeResetPacket(ID, param):
"""
Resets a servo to one of 3 reset ... |
def _update_kube_events(self, instance, pods_list, event_items):
"""
Process kube events and send ddog events
The namespace filtering is done here instead of KubeEventRetriever
to avoid interfering with service discovery
"""
node_ip, node_name = self.kubeutil.get_node_inf... | Process kube events and send ddog events
The namespace filtering is done here instead of KubeEventRetriever
to avoid interfering with service discovery | Below is the the instruction that describes the task:
### Input:
Process kube events and send ddog events
The namespace filtering is done here instead of KubeEventRetriever
to avoid interfering with service discovery
### Response:
def _update_kube_events(self, instance, pods_list, event_items):
... |
def send(device_id, description, **kwargs):
"""
Site: http://parse.com
API: https://www.parse.com/docs/push_guide#scheduled/REST
Desc: Best app for system administrators
"""
headers = {
"X-Parse-Application-Id": settings.PARSE_APP_ID,
"X-Parse-REST-API-Key": settings.PARSE_API_KE... | Site: http://parse.com
API: https://www.parse.com/docs/push_guide#scheduled/REST
Desc: Best app for system administrators | Below is the the instruction that describes the task:
### Input:
Site: http://parse.com
API: https://www.parse.com/docs/push_guide#scheduled/REST
Desc: Best app for system administrators
### Response:
def send(device_id, description, **kwargs):
"""
Site: http://parse.com
API: https://www.parse.... |
def add_group(self, groupname, statements):
"""
Adds a group
@type groupname: bytes
@type statements: str
"""
msg = OmapiMessage.open(b"group")
msg.message.append(("create", struct.pack("!I", 1)))
msg.obj.append(("name", groupname))
msg.obj.append(("statements", statements))
response = self.query_se... | Adds a group
@type groupname: bytes
@type statements: str | Below is the the instruction that describes the task:
### Input:
Adds a group
@type groupname: bytes
@type statements: str
### Response:
def add_group(self, groupname, statements):
"""
Adds a group
@type groupname: bytes
@type statements: str
"""
msg = OmapiMessage.open(b"group")
msg.message.appe... |
def _register_plotter(cls, identifier, module, plotter_name,
plotter_cls=None):
"""
Register a plotter in the :class:`Project` class to easy access it
Parameters
----------
identifier: str
Name of the attribute that is used to filter for the... | Register a plotter in the :class:`Project` class to easy access it
Parameters
----------
identifier: str
Name of the attribute that is used to filter for the instances
belonging to this plotter
module: str
The module from where to import the `plotter_... | Below is the the instruction that describes the task:
### Input:
Register a plotter in the :class:`Project` class to easy access it
Parameters
----------
identifier: str
Name of the attribute that is used to filter for the instances
belonging to this plotter
... |
def replace(self, text=None):
"""
Replaces the selected occurrence.
:param text: The replacement text. If it is None, the lineEditReplace's
text is used instead.
:return True if the text could be replace properly, False if there is
no more occurrenc... | Replaces the selected occurrence.
:param text: The replacement text. If it is None, the lineEditReplace's
text is used instead.
:return True if the text could be replace properly, False if there is
no more occurrences to replace. | Below is the the instruction that describes the task:
### Input:
Replaces the selected occurrence.
:param text: The replacement text. If it is None, the lineEditReplace's
text is used instead.
:return True if the text could be replace properly, False if there is
... |
def get_value(self, series, key):
""" we always want to get an index value, never a value """
if not is_scalar(key):
raise InvalidIndexError
k = com.values_from_object(key)
loc = self.get_loc(k)
new_values = com.values_from_object(series)[loc]
return new_val... | we always want to get an index value, never a value | Below is the the instruction that describes the task:
### Input:
we always want to get an index value, never a value
### Response:
def get_value(self, series, key):
""" we always want to get an index value, never a value """
if not is_scalar(key):
raise InvalidIndexError
k = co... |
def get_nodes():
""" Returns all nodes in a list of dicts format
"""
cfg_file = "/etc/nago/nago.ini"
config = ConfigParser.ConfigParser()
config.read(cfg_file)
result = {}
for section in config.sections():
if section in ['main']:
continue
token = section
n... | Returns all nodes in a list of dicts format | Below is the the instruction that describes the task:
### Input:
Returns all nodes in a list of dicts format
### Response:
def get_nodes():
""" Returns all nodes in a list of dicts format
"""
cfg_file = "/etc/nago/nago.ini"
config = ConfigParser.ConfigParser()
config.read(cfg_file)
result =... |
def get_imports(self, module, return_fqn=False):
"""return set of imported modules that are in self
:param module: PyModule
:return: (set - str) of path names
"""
# print('####', module.fqn)
# print(self.by_name.keys(), '\n\n')
imports = set()
raw_imports ... | return set of imported modules that are in self
:param module: PyModule
:return: (set - str) of path names | Below is the the instruction that describes the task:
### Input:
return set of imported modules that are in self
:param module: PyModule
:return: (set - str) of path names
### Response:
def get_imports(self, module, return_fqn=False):
"""return set of imported modules that are in self
... |
def lru_cache(maxsize=128, typed=False):
"""
Least-recently-used cache decorator, which is a backport of the same
function in Python >= 3.2.
If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.
If *typed* is True, arguments of different types will be... | Least-recently-used cache decorator, which is a backport of the same
function in Python >= 3.2.
If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.
If *typed* is True, arguments of different types will be cached separately.
For example, f(3.0) and f(3) ... | Below is the the instruction that describes the task:
### Input:
Least-recently-used cache decorator, which is a backport of the same
function in Python >= 3.2.
If *maxsize* is set to None, the LRU features are disabled and the cache
can grow without bound.
If *typed* is True, arguments of differe... |
def fix_flags(self, flags):
"""Fixes standard TensorBoard CLI flags to parser."""
FlagsError = base_plugin.FlagsError
if flags.version_tb:
pass
elif flags.inspect:
if flags.logdir and flags.event_file:
raise FlagsError(
'Must specify either --logdir or --event_file, but n... | Fixes standard TensorBoard CLI flags to parser. | Below is the the instruction that describes the task:
### Input:
Fixes standard TensorBoard CLI flags to parser.
### Response:
def fix_flags(self, flags):
"""Fixes standard TensorBoard CLI flags to parser."""
FlagsError = base_plugin.FlagsError
if flags.version_tb:
pass
elif flags.inspect:
... |
def generate(inputfilename, outputfilename='', dump=0, **flags):
"""Generate a grammar, given an input filename (X.g)
and an output filename (defaulting to X.py)."""
if not outputfilename:
if inputfilename[-2:] == '.g':
outputfilename = inputfilename[:-2] + '.py'
else:
... | Generate a grammar, given an input filename (X.g)
and an output filename (defaulting to X.py). | Below is the the instruction that describes the task:
### Input:
Generate a grammar, given an input filename (X.g)
and an output filename (defaulting to X.py).
### Response:
def generate(inputfilename, outputfilename='', dump=0, **flags):
"""Generate a grammar, given an input filename (X.g)
and an outp... |
def bond_initialize_canonical_averages(
canonical_statistics, **kwargs
):
"""
Initialize the canonical averages from a single-run cluster statistics
Parameters
----------
canonical_statistics : 1-D structured ndarray
Typically contains the canonical statistics for a range of values
... | Initialize the canonical averages from a single-run cluster statistics
Parameters
----------
canonical_statistics : 1-D structured ndarray
Typically contains the canonical statistics for a range of values
of the occupation probability ``p``.
The dtype is the result of `canonical_sta... | Below is the the instruction that describes the task:
### Input:
Initialize the canonical averages from a single-run cluster statistics
Parameters
----------
canonical_statistics : 1-D structured ndarray
Typically contains the canonical statistics for a range of values
of the occupation... |
def get_grid(self):
"""
Standardize the layout of the table into grids
"""
mentions, lines = _split_text_n_lines(self.elems)
# Sort mentions in reading order where y values are snapped to half
# height-sized grid
mentions.sort(key=lambda m: (m.yc_grid, m.xc))
... | Standardize the layout of the table into grids | Below is the the instruction that describes the task:
### Input:
Standardize the layout of the table into grids
### Response:
def get_grid(self):
"""
Standardize the layout of the table into grids
"""
mentions, lines = _split_text_n_lines(self.elems)
# Sort mentions in readi... |
def _identify_dict(core):
"""Specification for a dictionary."""
if not core:
return {}, 1, (), int
core = core.copy()
key = sorted(core.keys(), key=chaospy.poly.base.sort_key)[0]
shape = numpy.array(core[key]).shape
dtype = numpy.array(core[key]).dtype
dim = len(key)
return core... | Specification for a dictionary. | Below is the the instruction that describes the task:
### Input:
Specification for a dictionary.
### Response:
def _identify_dict(core):
"""Specification for a dictionary."""
if not core:
return {}, 1, (), int
core = core.copy()
key = sorted(core.keys(), key=chaospy.poly.base.sort_key)[0]
... |
def load(self, record_key, secret_key=''):
'''
a method to retrieve byte data of appdata record
:param record_key: string with name of record
:param secret_key: [optional] string used to decrypt data
:return: byte data for record body
'''
title =... | a method to retrieve byte data of appdata record
:param record_key: string with name of record
:param secret_key: [optional] string used to decrypt data
:return: byte data for record body | Below is the the instruction that describes the task:
### Input:
a method to retrieve byte data of appdata record
:param record_key: string with name of record
:param secret_key: [optional] string used to decrypt data
:return: byte data for record body
### Response:
def load(self, reco... |
def broken_seqs(ol,break_points):
'''
ol = initRange(0,20,1)
ol
break_points = [1,6,14,9]
secs = broken_seqs(ol,break_points)
forEach(secs,print)
'''
bps = list(break_points)
length = ol.__len__()
rgs = rangize(bps,length)
rslt = []
for i in range(0,rg... | ol = initRange(0,20,1)
ol
break_points = [1,6,14,9]
secs = broken_seqs(ol,break_points)
forEach(secs,print) | Below is the the instruction that describes the task:
### Input:
ol = initRange(0,20,1)
ol
break_points = [1,6,14,9]
secs = broken_seqs(ol,break_points)
forEach(secs,print)
### Response:
def broken_seqs(ol,break_points):
'''
ol = initRange(0,20,1)
ol
brea... |
def MakeType(name, base_classes,
namespace):
"""A compatibility wrapper for the `type` built-in function.
In Python 2 `type` (used as a type constructor) requires the name argument to
be a `bytes` object whereas in Python 3 it is required to be an `unicode`
object. Since class name is human readab... | A compatibility wrapper for the `type` built-in function.
In Python 2 `type` (used as a type constructor) requires the name argument to
be a `bytes` object whereas in Python 3 it is required to be an `unicode`
object. Since class name is human readable text rather than arbitrary stream
of bytes, the Python 3 b... | Below is the the instruction that describes the task:
### Input:
A compatibility wrapper for the `type` built-in function.
In Python 2 `type` (used as a type constructor) requires the name argument to
be a `bytes` object whereas in Python 3 it is required to be an `unicode`
object. Since class name is human ... |
def OS_filter(x,h,N,mode=0):
"""
Overlap and save transform domain FIR filtering.
This function implements the classical overlap and save method of
transform domain filtering using a length P FIR filter.
Parameters
----------
x : input signal to be filtered as an ndarray
h : FI... | Overlap and save transform domain FIR filtering.
This function implements the classical overlap and save method of
transform domain filtering using a length P FIR filter.
Parameters
----------
x : input signal to be filtered as an ndarray
h : FIR filter coefficients as an ndarray of le... | Below is the the instruction that describes the task:
### Input:
Overlap and save transform domain FIR filtering.
This function implements the classical overlap and save method of
transform domain filtering using a length P FIR filter.
Parameters
----------
x : input signal to be filte... |
def feeling_lucky(cls, obj):
"""Tries to convert given object to an UTC timestamp is ms, based
on its type.
"""
if isinstance(obj, six.string_types):
return cls.from_str(obj)
elif isinstance(obj, six.integer_types) and obj <= MAX_POSIX_TIMESTAMP:
return cl... | Tries to convert given object to an UTC timestamp is ms, based
on its type. | Below is the the instruction that describes the task:
### Input:
Tries to convert given object to an UTC timestamp is ms, based
on its type.
### Response:
def feeling_lucky(cls, obj):
"""Tries to convert given object to an UTC timestamp is ms, based
on its type.
"""
if isins... |
def make_argument_subquery(arg):
"""
Decide when a Join argument needs to be wrapped in a subquery
"""
return Subquery.create(arg) if isinstance(arg, (GroupBy, Projection)) or arg.restriction else arg | Decide when a Join argument needs to be wrapped in a subquery | Below is the the instruction that describes the task:
### Input:
Decide when a Join argument needs to be wrapped in a subquery
### Response:
def make_argument_subquery(arg):
"""
Decide when a Join argument needs to be wrapped in a subquery
"""
return Subquery.create(arg) if isinstan... |
def highlight_cell_surroundings(self, target_y, target_x):
"""
highlights the cells around a target to make it simpler
to see on a grid. Currently assumes the target is within
the boundary by 1 on all sides
"""
#print('SELF_WORLD', self.world)
#print('target_y, ta... | highlights the cells around a target to make it simpler
to see on a grid. Currently assumes the target is within
the boundary by 1 on all sides | Below is the the instruction that describes the task:
### Input:
highlights the cells around a target to make it simpler
to see on a grid. Currently assumes the target is within
the boundary by 1 on all sides
### Response:
def highlight_cell_surroundings(self, target_y, target_x):
"""
... |
def get_objective_hierarchy_design_session(self, proxy):
"""Gets the session for designing objective hierarchies.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveHierarchyDesignSession) - an
``ObjectiveHierarchyDesignSession``
raise: NullArgume... | Gets the session for designing objective hierarchies.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveHierarchyDesignSession) - an
``ObjectiveHierarchyDesignSession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable ... | Below is the the instruction that describes the task:
### Input:
Gets the session for designing objective hierarchies.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.learning.ObjectiveHierarchyDesignSession) - an
``ObjectiveHierarchyDesignSession``
raise: NullArgum... |
def get_error(exc):
"""
Return the appropriate HTTP status code according to the Exception/Error.
"""
if isinstance(exc, HTTPError):
# Returning the HTTP Error code coming from requests module
return exc.response.status_code, text(exc.response.content)
if isinstance(exc, Timeout):
... | Return the appropriate HTTP status code according to the Exception/Error. | Below is the the instruction that describes the task:
### Input:
Return the appropriate HTTP status code according to the Exception/Error.
### Response:
def get_error(exc):
"""
Return the appropriate HTTP status code according to the Exception/Error.
"""
if isinstance(exc, HTTPError):
# Re... |
def get_top_segmentations(table, n):
"""
Parameters
----------
table : matrix of probabilities
Each cell (i, j) of `table` gives the probability that i and j are in
the same symbol.
n : int
Number of best segmentations which get returned
"""
stroke_count = list(range(... | Parameters
----------
table : matrix of probabilities
Each cell (i, j) of `table` gives the probability that i and j are in
the same symbol.
n : int
Number of best segmentations which get returned | Below is the the instruction that describes the task:
### Input:
Parameters
----------
table : matrix of probabilities
Each cell (i, j) of `table` gives the probability that i and j are in
the same symbol.
n : int
Number of best segmentations which get returned
### Response:
def... |
def get_sequence_rule_enablers_by_search(self, sequence_rule_enabler_query, sequence_rule_enabler_search):
"""Pass through to provider SequenceRuleEnablerSearchSession.get_sequence_rule_enablers_by_search"""
# Implemented from azosid template for -
# osid.resource.ResourceSearchSession.get_resou... | Pass through to provider SequenceRuleEnablerSearchSession.get_sequence_rule_enablers_by_search | Below is the the instruction that describes the task:
### Input:
Pass through to provider SequenceRuleEnablerSearchSession.get_sequence_rule_enablers_by_search
### Response:
def get_sequence_rule_enablers_by_search(self, sequence_rule_enabler_query, sequence_rule_enabler_search):
"""Pass through to provide... |
def cookies(self):
"""
Retrieve the cookies header from all the users who visited.
"""
return (self.get_query()
.select(PageView.ip, PageView.headers['Cookie'])
.where(PageView.headers['Cookie'].is_null(False))
.tuples()) | Retrieve the cookies header from all the users who visited. | Below is the the instruction that describes the task:
### Input:
Retrieve the cookies header from all the users who visited.
### Response:
def cookies(self):
"""
Retrieve the cookies header from all the users who visited.
"""
return (self.get_query()
.select(PageView... |
def m2i(self, pkt, m):
"""
Try to parse one of the TLS subprotocols (ccs, alert, handshake or
application_data). This is used inside a loop managed by .getfield().
"""
cls = Raw
if pkt.type == 22:
if len(m) >= 1:
msgtype = orb(m[0])
... | Try to parse one of the TLS subprotocols (ccs, alert, handshake or
application_data). This is used inside a loop managed by .getfield(). | Below is the the instruction that describes the task:
### Input:
Try to parse one of the TLS subprotocols (ccs, alert, handshake or
application_data). This is used inside a loop managed by .getfield().
### Response:
def m2i(self, pkt, m):
"""
Try to parse one of the TLS subprotocols (ccs, a... |
def as_dictlist(self):
""" Returns a dictlist with values
[
{
"row": "row_a",
"col": "col_a",
"value": 1,
}
]
"""
data = []
for row_i, row in enumerate(self.row_index):
... | Returns a dictlist with values
[
{
"row": "row_a",
"col": "col_a",
"value": 1,
}
] | Below is the the instruction that describes the task:
### Input:
Returns a dictlist with values
[
{
"row": "row_a",
"col": "col_a",
"value": 1,
}
]
### Response:
def as_dictlist(self):
""" Re... |
def sapm_effective_irradiance(self, poa_direct, poa_diffuse,
airmass_absolute, aoi,
reference_irradiance=1000):
"""
Use the :py:func:`sapm_effective_irradiance` function, the input
parameters, and ``self.module_parameters`` to c... | Use the :py:func:`sapm_effective_irradiance` function, the input
parameters, and ``self.module_parameters`` to calculate
effective irradiance.
Parameters
----------
poa_direct : numeric
The direct irradiance incident upon the module.
poa_diffuse : numeric
... | Below is the the instruction that describes the task:
### Input:
Use the :py:func:`sapm_effective_irradiance` function, the input
parameters, and ``self.module_parameters`` to calculate
effective irradiance.
Parameters
----------
poa_direct : numeric
The direct i... |
def print_portfolio_info(returns, avg_rets, weights):
"""
Print information on expected portfolio performance.
"""
ret = (weights * avg_rets).sum()
std = (weights * returns).sum(1).std()
sharpe = ret / std
print("Optimal weights:\n{}\n".format(weights))
print("Expected return: {}".form... | Print information on expected portfolio performance. | Below is the the instruction that describes the task:
### Input:
Print information on expected portfolio performance.
### Response:
def print_portfolio_info(returns, avg_rets, weights):
"""
Print information on expected portfolio performance.
"""
ret = (weights * avg_rets).sum()
std = (weights ... |
def fcm_send_message(
registration_id,
title=None,
body=None,
icon=None,
data=None,
sound=None,
badge=None,
low_priority=False,
condition=None,
time_to_live=None,
click_action=None,
collapse_key=None,
delay_while_idl... | Copied from https://github.com/olucurious/PyFCM/blob/master/pyfcm/fcm.py:
Send push notification to a single device
Args:
registration_id (str): FCM device registration IDs.
body (str): Message string to display in the notification tray
data (dict): Data message payload to send alone or... | Below is the the instruction that describes the task:
### Input:
Copied from https://github.com/olucurious/PyFCM/blob/master/pyfcm/fcm.py:
Send push notification to a single device
Args:
registration_id (str): FCM device registration IDs.
body (str): Message string to display in the notific... |
def parameter(self, parameter_id):
"""Return the specified global parameter (the entire object, not just the value)"""
for parametergroup, parameters in self.parameters: #pylint: disable=unused-variable
for parameter in parameters:
if parameter.id == parameter_id:
... | Return the specified global parameter (the entire object, not just the value) | Below is the the instruction that describes the task:
### Input:
Return the specified global parameter (the entire object, not just the value)
### Response:
def parameter(self, parameter_id):
"""Return the specified global parameter (the entire object, not just the value)"""
for parametergroup, par... |
def close_connection(self): # pylint: disable=C0103
"""
Closes serial port connection.
:return: Nothing
"""
if self.port:
self.stop()
self.logger.debug("Close port '%s'" % self.comport,
extra={'type': '<->'})
sel... | Closes serial port connection.
:return: Nothing | Below is the the instruction that describes the task:
### Input:
Closes serial port connection.
:return: Nothing
### Response:
def close_connection(self): # pylint: disable=C0103
"""
Closes serial port connection.
:return: Nothing
"""
if self.port:
sel... |
def plot_series_residuals(self, xres, varied_data, varied_idx, params, **kwargs):
""" Analogous to :meth:`plot_series` but will plot residuals. """
nf = len(self.f_cb(*self.pre_process(xres[0], params)))
xerr = np.empty((xres.shape[0], nf))
new_params = np.array(params)
for idx,... | Analogous to :meth:`plot_series` but will plot residuals. | Below is the the instruction that describes the task:
### Input:
Analogous to :meth:`plot_series` but will plot residuals.
### Response:
def plot_series_residuals(self, xres, varied_data, varied_idx, params, **kwargs):
""" Analogous to :meth:`plot_series` but will plot residuals. """
nf = len(self.... |
def signal_optimiser(d, analytes, min_points=5,
threshold_mode='kde_first_max',
threshold_mult=1., x_bias=0,
weights=None, ind=None, mode='minimise'):
"""
Optimise data selection based on specified analytes.
Identifies the longest possible cont... | Optimise data selection based on specified analytes.
Identifies the longest possible contiguous data region in
the signal where the relative standard deviation (std) and
concentration of all analytes is minimised.
Optimisation is performed via a grid search of all possible
contiguous data regions... | Below is the the instruction that describes the task:
### Input:
Optimise data selection based on specified analytes.
Identifies the longest possible contiguous data region in
the signal where the relative standard deviation (std) and
concentration of all analytes is minimised.
Optimisation is pe... |
def pad_batch(features, batch_multiple):
"""Pad batch dim of features to nearest multiple of batch_multiple."""
feature = list(features.items())[0][1]
batch_size = tf.shape(feature)[0]
mod = batch_size % batch_multiple
has_mod = tf.cast(tf.cast(mod, tf.bool), tf.int32)
batch_padding = batch_multiple * has_m... | Pad batch dim of features to nearest multiple of batch_multiple. | Below is the the instruction that describes the task:
### Input:
Pad batch dim of features to nearest multiple of batch_multiple.
### Response:
def pad_batch(features, batch_multiple):
"""Pad batch dim of features to nearest multiple of batch_multiple."""
feature = list(features.items())[0][1]
batch_size = t... |
def deep_reload_hook(m):
"""Replacement for reload()."""
if not isinstance(m, ModuleType):
raise TypeError("reload() argument must be module")
name = m.__name__
if name not in sys.modules:
raise ImportError("reload(): module %.200s not in sys.modules" % name)
global modules_reload... | Replacement for reload(). | Below is the the instruction that describes the task:
### Input:
Replacement for reload().
### Response:
def deep_reload_hook(m):
"""Replacement for reload()."""
if not isinstance(m, ModuleType):
raise TypeError("reload() argument must be module")
name = m.__name__
if name not in sys.modu... |
def check_password(raw_password, enc_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
encryption formats behind the scenes.
"""
algo, salt, hsh = enc_password.split('$')
return enc_password == encrypt_password(raw_password, algorithm=algo,
... | Returns a boolean of whether the raw_password was correct. Handles
encryption formats behind the scenes. | Below is the the instruction that describes the task:
### Input:
Returns a boolean of whether the raw_password was correct. Handles
encryption formats behind the scenes.
### Response:
def check_password(raw_password, enc_password):
"""
Returns a boolean of whether the raw_password was correct. Handles
... |
def readinto(self, data):
"""Read data from the ring buffer into a user-provided buffer.
This advances the read index after reading;
calling :meth:`advance_read_index` is *not* necessary.
:param data: The memory where the data should be stored.
:type data: CData pointer or buff... | Read data from the ring buffer into a user-provided buffer.
This advances the read index after reading;
calling :meth:`advance_read_index` is *not* necessary.
:param data: The memory where the data should be stored.
:type data: CData pointer or buffer
:returns: The number of e... | Below is the the instruction that describes the task:
### Input:
Read data from the ring buffer into a user-provided buffer.
This advances the read index after reading;
calling :meth:`advance_read_index` is *not* necessary.
:param data: The memory where the data should be stored.
:... |
def _parse_uri(uri_as_string):
"""
Parse the given URI from a string.
Supported URI schemes are:
* file
* hdfs
* http
* https
* s3
* s3a
* s3n
* s3u
* webhdfs
.s3, s3a and s3n are treated the same way. s3u is s3 but without SSL.
Valid URI ex... | Parse the given URI from a string.
Supported URI schemes are:
* file
* hdfs
* http
* https
* s3
* s3a
* s3n
* s3u
* webhdfs
.s3, s3a and s3n are treated the same way. s3u is s3 but without SSL.
Valid URI examples::
* s3://my_bucket/my_key
... | Below is the the instruction that describes the task:
### Input:
Parse the given URI from a string.
Supported URI schemes are:
* file
* hdfs
* http
* https
* s3
* s3a
* s3n
* s3u
* webhdfs
.s3, s3a and s3n are treated the same way. s3u is s3 but with... |
def open(self):
"""
Calls SetupDiGetClassDevs to obtain a handle to an opaque device
information set that describes the device interfaces supported by all
the USB collections currently installed in the system. The
application should specify DIGCF.PRESENT and DIGCF.INTERFACED... | Calls SetupDiGetClassDevs to obtain a handle to an opaque device
information set that describes the device interfaces supported by all
the USB collections currently installed in the system. The
application should specify DIGCF.PRESENT and DIGCF.INTERFACEDEVICE
in the Flags parameter ... | Below is the the instruction that describes the task:
### Input:
Calls SetupDiGetClassDevs to obtain a handle to an opaque device
information set that describes the device interfaces supported by all
the USB collections currently installed in the system. The
application should specify DIG... |
def start(self, origin):
"""
Start this Tracer.
Return a Python function suitable for use with sys.settrace().
"""
self.start_time = time.time()
self.pause_until = None
self.data.update(self._get_struct(origin, 'origin'))
self.data_stack.append(self.data)... | Start this Tracer.
Return a Python function suitable for use with sys.settrace(). | Below is the the instruction that describes the task:
### Input:
Start this Tracer.
Return a Python function suitable for use with sys.settrace().
### Response:
def start(self, origin):
"""
Start this Tracer.
Return a Python function suitable for use with sys.settrace().
"... |
def insert_seperator_results(results):
"""Given a sequence of BenchmarkResults,
return a new sequence where a "seperator" BenchmarkResult has been placed
between differing benchmarks to provide a visual difference."""
sepbench = BenchmarkResult(*[' ' * w for w in COLUMN_WIDTHS])
last_bm = None
f... | Given a sequence of BenchmarkResults,
return a new sequence where a "seperator" BenchmarkResult has been placed
between differing benchmarks to provide a visual difference. | Below is the the instruction that describes the task:
### Input:
Given a sequence of BenchmarkResults,
return a new sequence where a "seperator" BenchmarkResult has been placed
between differing benchmarks to provide a visual difference.
### Response:
def insert_seperator_results(results):
"""Given a s... |
def getCoeff(self, name, light=None, date=None):
'''
try to get calibration for right light source, but
use another if they is none existent
'''
d = self.coeffs[name]
try:
c = d[light]
except KeyError:
try:
k, i ... | try to get calibration for right light source, but
use another if they is none existent | Below is the the instruction that describes the task:
### Input:
try to get calibration for right light source, but
use another if they is none existent
### Response:
def getCoeff(self, name, light=None, date=None):
'''
try to get calibration for right light source, but
use anot... |
def read(self):
"""
Read buffer out as a single stream.
.. warning::
Avoid using this function!
**Why?** This is a *convenience* function; it doesn't encourage good
memory management.
All memory required for a mesh is duplicated, and returned a... | Read buffer out as a single stream.
.. warning::
Avoid using this function!
**Why?** This is a *convenience* function; it doesn't encourage good
memory management.
All memory required for a mesh is duplicated, and returned as a
single :class:`str`.... | Below is the the instruction that describes the task:
### Input:
Read buffer out as a single stream.
.. warning::
Avoid using this function!
**Why?** This is a *convenience* function; it doesn't encourage good
memory management.
All memory required for a m... |
def _update_pwm(self):
"""Update the pwm values of the driver regarding the current state."""
if self._is_on:
values = self._get_pwm_values()
else:
values = [0] * len(self._driver.pins)
self._driver.set_pwm(values) | Update the pwm values of the driver regarding the current state. | Below is the the instruction that describes the task:
### Input:
Update the pwm values of the driver regarding the current state.
### Response:
def _update_pwm(self):
"""Update the pwm values of the driver regarding the current state."""
if self._is_on:
values = self._get_pwm_values()
... |
def eotvos(target, k, temperature='pore.temperature',
critical_temperature='pore.critical_temperature',
molar_density='pore.molar_density'):
r"""
Missing description
Parameters
----------
target : OpenPNM Object
The object for which these values are being calculated. ... | r"""
Missing description
Parameters
----------
target : OpenPNM Object
The object for which these values are being calculated. This
controls the length of the calculated array, and also provides
access to other necessary thermofluid properties.
k : float
Constant p... | Below is the the instruction that describes the task:
### Input:
r"""
Missing description
Parameters
----------
target : OpenPNM Object
The object for which these values are being calculated. This
controls the length of the calculated array, and also provides
access to othe... |
def arrow_table_from_vaex_df(ds, column_names=None, selection=None, strings=True, virtual=False):
"""Implementation of Dataset.to_arrow_table"""
names = []
arrays = []
for name, array in ds.to_items(column_names=column_names, selection=selection, strings=strings, virtual=virtual):
names.append(n... | Implementation of Dataset.to_arrow_table | Below is the the instruction that describes the task:
### Input:
Implementation of Dataset.to_arrow_table
### Response:
def arrow_table_from_vaex_df(ds, column_names=None, selection=None, strings=True, virtual=False):
"""Implementation of Dataset.to_arrow_table"""
names = []
arrays = []
for name, a... |
def image_predict_proba(self, X):
"""
Predicts class probabilities for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_samples, n... | Predicts class probabilities for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_samples, n_pixels_x, n_pixels_y, n_classes]
Target pr... | Below is the the instruction that describes the task:
### Input:
Predicts class probabilities for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_x, n_pixels_y, n_bands]
Array of training images
y: array, shape = [n_samples] or ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.