code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def serialize_to_xml(root, block):
"""
Serialize the Peer Instruction XBlock's content to XML.
Args:
block (PeerInstructionXBlock): The peer instruction block to serialize.
root (etree.Element): The XML root node to update.
Returns:
etree.Element
"""
root.tag = 'ubcpi'... | Serialize the Peer Instruction XBlock's content to XML.
Args:
block (PeerInstructionXBlock): The peer instruction block to serialize.
root (etree.Element): The XML root node to update.
Returns:
etree.Element | Below is the the instruction that describes the task:
### Input:
Serialize the Peer Instruction XBlock's content to XML.
Args:
block (PeerInstructionXBlock): The peer instruction block to serialize.
root (etree.Element): The XML root node to update.
Returns:
etree.Element
### Respo... |
def request(self,
method,
url,
params=None,
data=None,
files=None,
json=None,
timeout=5,
headers=None,
skip_auth=False):
"""
Execute the request using requests ... | Execute the request using requests library | Below is the the instruction that describes the task:
### Input:
Execute the request using requests library
### Response:
def request(self,
method,
url,
params=None,
data=None,
files=None,
json=None,
tim... |
def make_2d_block_raster_mask(query_shape, memory_flange):
"""Creates a mask for 2d block raster scan.
The query mask can look to the left, top left, top, and top right, but
not to the right. Inside the query, we have the standard raster scan
masking.
Args:
query_shape: A tuple of ints (query_height, que... | Creates a mask for 2d block raster scan.
The query mask can look to the left, top left, top, and top right, but
not to the right. Inside the query, we have the standard raster scan
masking.
Args:
query_shape: A tuple of ints (query_height, query_width)
memory_flange: A tuple of ints
(memory_flang... | Below is the the instruction that describes the task:
### Input:
Creates a mask for 2d block raster scan.
The query mask can look to the left, top left, top, and top right, but
not to the right. Inside the query, we have the standard raster scan
masking.
Args:
query_shape: A tuple of ints (query_height... |
def dumps_xml(props, comment=None, sort_keys=False):
"""
Convert a series ``props`` of key-value pairs to a text string containing
an XML properties document. The document will include a doctype
declaration but not an XML declaration.
:param props: A mapping or iterable of ``(key, value)`` pairs t... | Convert a series ``props`` of key-value pairs to a text string containing
an XML properties document. The document will include a doctype
declaration but not an XML declaration.
:param props: A mapping or iterable of ``(key, value)`` pairs to serialize.
All keys and values in ``props`` must be tex... | Below is the the instruction that describes the task:
### Input:
Convert a series ``props`` of key-value pairs to a text string containing
an XML properties document. The document will include a doctype
declaration but not an XML declaration.
:param props: A mapping or iterable of ``(key, value)`` pai... |
def get_state_by_id(cls, state_id, **kwargs):
"""Find State
Return single instance of State by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_state_by_id(state_id, async=True)
... | Find State
Return single instance of State by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_state_by_id(state_id, async=True)
>>> result = thread.get()
:param async bool... | Below is the the instruction that describes the task:
### Input:
Find State
Return single instance of State by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_state_by_id(state_id, asy... |
def register(self, new_calc, *args, **kwargs):
"""
Register calculations and meta data.
* ``dependencies`` - list of prerequisite calculations
* ``always_calc`` - ``True`` if calculation ignores thresholds
* ``frequency`` - frequency of calculation in intervals or units of time
... | Register calculations and meta data.
* ``dependencies`` - list of prerequisite calculations
* ``always_calc`` - ``True`` if calculation ignores thresholds
* ``frequency`` - frequency of calculation in intervals or units of time
:param new_calc: register new calculation | Below is the the instruction that describes the task:
### Input:
Register calculations and meta data.
* ``dependencies`` - list of prerequisite calculations
* ``always_calc`` - ``True`` if calculation ignores thresholds
* ``frequency`` - frequency of calculation in intervals or units of tim... |
def unpack(self, key, value):
"""Unpack and return value only if it is fresh."""
value, freshness = value
if not self.is_fresh(freshness):
raise KeyError('{} (stale)'.format(key))
return value | Unpack and return value only if it is fresh. | Below is the the instruction that describes the task:
### Input:
Unpack and return value only if it is fresh.
### Response:
def unpack(self, key, value):
"""Unpack and return value only if it is fresh."""
value, freshness = value
if not self.is_fresh(freshness):
raise KeyError('... |
def generate_hash(filepath):
"""Public function that reads a local file and generates a SHA256 hash digest for it"""
fr = FileReader(filepath)
data = fr.read_bin()
return _calculate_sha256(data) | Public function that reads a local file and generates a SHA256 hash digest for it | Below is the the instruction that describes the task:
### Input:
Public function that reads a local file and generates a SHA256 hash digest for it
### Response:
def generate_hash(filepath):
"""Public function that reads a local file and generates a SHA256 hash digest for it"""
fr = FileReader(filepath)
... |
def _from_dict(cls, _dict):
"""Initialize a SpeechRecognitionResult object from a json dictionary."""
args = {}
if 'final' in _dict or 'final_results' in _dict:
args['final_results'] = _dict.get('final') or _dict.get(
'final_results')
else:
raise V... | Initialize a SpeechRecognitionResult object from a json dictionary. | Below is the the instruction that describes the task:
### Input:
Initialize a SpeechRecognitionResult object from a json dictionary.
### Response:
def _from_dict(cls, _dict):
"""Initialize a SpeechRecognitionResult object from a json dictionary."""
args = {}
if 'final' in _dict or 'final_re... |
def to_json_str(self):
"""Convert data to json string representation.
Returns:
json representation as string.
"""
_json = self.to_json()
try:
return json.dumps(_json, sort_keys=True, cls=JsonEncoder)
except:
logging.exception("Could not serialize JSON: %r", _json)
raise | Convert data to json string representation.
Returns:
json representation as string. | Below is the the instruction that describes the task:
### Input:
Convert data to json string representation.
Returns:
json representation as string.
### Response:
def to_json_str(self):
"""Convert data to json string representation.
Returns:
json representation as string.
"""
_jso... |
def neuron(layer_name, channel_n, x=None, y=None, batch=None):
"""Visualize a single neuron of a single channel.
Defaults to the center neuron. When width and height are even numbers, we
choose the neuron in the bottom right of the center 2x2 neurons.
Odd width & height: Even width & height:
... | Visualize a single neuron of a single channel.
Defaults to the center neuron. When width and height are even numbers, we
choose the neuron in the bottom right of the center 2x2 neurons.
Odd width & height: Even width & height:
+---+---+---+ +---+---+---+---+
| | | | ... | Below is the the instruction that describes the task:
### Input:
Visualize a single neuron of a single channel.
Defaults to the center neuron. When width and height are even numbers, we
choose the neuron in the bottom right of the center 2x2 neurons.
Odd width & height: Even width & height:
... |
def _encode_auth(auth):
"""
A function compatible with Python 2.3-3.3 that will encode
auth from a URL suitable for an HTTP header.
>>> str(_encode_auth('username%3Apassword'))
'dXNlcm5hbWU6cGFzc3dvcmQ='
Long auth strings should not cause a newline to be inserted.
>>> long_auth = 'username:... | A function compatible with Python 2.3-3.3 that will encode
auth from a URL suitable for an HTTP header.
>>> str(_encode_auth('username%3Apassword'))
'dXNlcm5hbWU6cGFzc3dvcmQ='
Long auth strings should not cause a newline to be inserted.
>>> long_auth = 'username:' + 'password'*10
>>> chr(10) in... | Below is the the instruction that describes the task:
### Input:
A function compatible with Python 2.3-3.3 that will encode
auth from a URL suitable for an HTTP header.
>>> str(_encode_auth('username%3Apassword'))
'dXNlcm5hbWU6cGFzc3dvcmQ='
Long auth strings should not cause a newline to be inserte... |
def server_version(self):
"""
Special method for getting server version.
Because of different behaviour on different versions of
server, we have to pass different headers to the endpoints.
This method requests the version from server and caches it
in internal variable, s... | Special method for getting server version.
Because of different behaviour on different versions of
server, we have to pass different headers to the endpoints.
This method requests the version from server and caches it
in internal variable, so other resources could use it.
:retu... | Below is the the instruction that describes the task:
### Input:
Special method for getting server version.
Because of different behaviour on different versions of
server, we have to pass different headers to the endpoints.
This method requests the version from server and caches it
... |
def cluster(self, matrix=None, level=None, sequence=None):
"""
Perform hierarchical clustering.
:param matrix: The 2D list that is currently under processing. The
matrix contains the distances of each item with each other
:param level: The current level of clustering
... | Perform hierarchical clustering.
:param matrix: The 2D list that is currently under processing. The
matrix contains the distances of each item with each other
:param level: The current level of clustering
:param sequence: The sequence number of the clustering | Below is the the instruction that describes the task:
### Input:
Perform hierarchical clustering.
:param matrix: The 2D list that is currently under processing. The
matrix contains the distances of each item with each other
:param level: The current level of clustering
:param se... |
def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args):
'''
Delete a tenant (keystone tenant-delete)
CLI Examples:
.. code-block:: bash
salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082
salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c... | Delete a tenant (keystone tenant-delete)
CLI Examples:
.. code-block:: bash
salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082
salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082
salt '*' keystone.tenant_delete name=demo | Below is the the instruction that describes the task:
### Input:
Delete a tenant (keystone tenant-delete)
CLI Examples:
.. code-block:: bash
salt '*' keystone.tenant_delete c965f79c4f864eaaa9c3b41904e67082
salt '*' keystone.tenant_delete tenant_id=c965f79c4f864eaaa9c3b41904e67082
... |
def _parse_weights(weight_args, default_weight=0.6):
"""Parse list of weight assignments."""
weights_dict = {}
r_group_weight = default_weight
for weight_arg in weight_args:
for weight_assignment in weight_arg.split(','):
if '=' not in weight_assignment:
raise ValueEr... | Parse list of weight assignments. | Below is the the instruction that describes the task:
### Input:
Parse list of weight assignments.
### Response:
def _parse_weights(weight_args, default_weight=0.6):
"""Parse list of weight assignments."""
weights_dict = {}
r_group_weight = default_weight
for weight_arg in weight_args:
for ... |
def stripIEConditionals(contents, addHtmlIfMissing=True):
'''
stripIEConditionals - Strips Internet Explorer conditional statements.
@param contents <str> - Contents String
@param addHtmlIfMissing <bool> - Since these normally encompass the "html" element, optionally add it back if missing.... | stripIEConditionals - Strips Internet Explorer conditional statements.
@param contents <str> - Contents String
@param addHtmlIfMissing <bool> - Since these normally encompass the "html" element, optionally add it back if missing. | Below is the the instruction that describes the task:
### Input:
stripIEConditionals - Strips Internet Explorer conditional statements.
@param contents <str> - Contents String
@param addHtmlIfMissing <bool> - Since these normally encompass the "html" element, optionally add it back if missing.
### ... |
def filter_instance(self, inst, plist):
"""Remove properties from an instance that aren't in the PropertyList
inst -- The pywbem.CIMInstance
plist -- The property List, or None. The list items must be all
lowercase.
"""
if plist is not None:
for pname ... | Remove properties from an instance that aren't in the PropertyList
inst -- The pywbem.CIMInstance
plist -- The property List, or None. The list items must be all
lowercase. | Below is the the instruction that describes the task:
### Input:
Remove properties from an instance that aren't in the PropertyList
inst -- The pywbem.CIMInstance
plist -- The property List, or None. The list items must be all
lowercase.
### Response:
def filter_instance(self, inst, p... |
def _generate_citation_dict(graph: BELGraph) -> Mapping[str, Mapping[Tuple[BaseEntity, BaseEntity], str]]:
"""Prepare a citation data dictionary from a graph.
:return: A dictionary of dictionaries {citation type: {(source, target): citation reference}
"""
results = defaultdict(lambda: defaultdict(set))... | Prepare a citation data dictionary from a graph.
:return: A dictionary of dictionaries {citation type: {(source, target): citation reference} | Below is the the instruction that describes the task:
### Input:
Prepare a citation data dictionary from a graph.
:return: A dictionary of dictionaries {citation type: {(source, target): citation reference}
### Response:
def _generate_citation_dict(graph: BELGraph) -> Mapping[str, Mapping[Tuple[BaseEntity, Ba... |
async def run_node(menv, log_folder):
"""Run :class:`~creamas.mp.MultiEnvironment` until its manager's
:meth:`~aiomas.subproc.Manager.stop` is called.
:param menv: :class:`~creamas.mp.MultiEnvironment` to wait for.
:param str log_folder:
Logging folder to be passed down to
:meth:`~cream... | Run :class:`~creamas.mp.MultiEnvironment` until its manager's
:meth:`~aiomas.subproc.Manager.stop` is called.
:param menv: :class:`~creamas.mp.MultiEnvironment` to wait for.
:param str log_folder:
Logging folder to be passed down to
:meth:`~creamas.mp.MultiEnvironment.destroy` after :meth:`... | Below is the the instruction that describes the task:
### Input:
Run :class:`~creamas.mp.MultiEnvironment` until its manager's
:meth:`~aiomas.subproc.Manager.stop` is called.
:param menv: :class:`~creamas.mp.MultiEnvironment` to wait for.
:param str log_folder:
Logging folder to be passed down ... |
def matches(self, *args, **kwargs):
"""Test if a request matches a :ref:`message spec <message spec>`.
Returns ``True`` or ``False``.
"""
request = make_prototype_request(*args, **kwargs)
if self._prototype.opcode not in (None, request.opcode):
return False
i... | Test if a request matches a :ref:`message spec <message spec>`.
Returns ``True`` or ``False``. | Below is the the instruction that describes the task:
### Input:
Test if a request matches a :ref:`message spec <message spec>`.
Returns ``True`` or ``False``.
### Response:
def matches(self, *args, **kwargs):
"""Test if a request matches a :ref:`message spec <message spec>`.
Returns ``Tr... |
def _setup_segments(self):
"""
Parses the database file to determine what kind of database is
being used and setup segment sizes and start points that will
be used by the seek*() methods later.
"""
self._databaseType = const.COUNTRY_EDITION
self._recordLength = co... | Parses the database file to determine what kind of database is
being used and setup segment sizes and start points that will
be used by the seek*() methods later. | Below is the the instruction that describes the task:
### Input:
Parses the database file to determine what kind of database is
being used and setup segment sizes and start points that will
be used by the seek*() methods later.
### Response:
def _setup_segments(self):
"""
Parses the... |
def generate_harvester_config(self, catalogs=None, harvest='valid',
report=None, export_path=None):
"""Genera un archivo de configuración del harvester a partir de un
reporte, o de un conjunto de catálogos y un criterio de cosecha
(`harvest`).
Args:
... | Genera un archivo de configuración del harvester a partir de un
reporte, o de un conjunto de catálogos y un criterio de cosecha
(`harvest`).
Args:
catalogs (str, dict o list): Uno (str o dict) o varios (list de
strs y/o dicts) catálogos.
harvest (str): Cr... | Below is the the instruction that describes the task:
### Input:
Genera un archivo de configuración del harvester a partir de un
reporte, o de un conjunto de catálogos y un criterio de cosecha
(`harvest`).
Args:
catalogs (str, dict o list): Uno (str o dict) o varios (list de
... |
def bed_generator(bed_path):
"""Iterates through a BED file yielding parsed BED lines.
Parameters
----------
bed_path : str
path to BED file
Yields
------
BedLine(line) : BedLine
A BedLine object which has parsed the individual line in
a BED file.
"""
with o... | Iterates through a BED file yielding parsed BED lines.
Parameters
----------
bed_path : str
path to BED file
Yields
------
BedLine(line) : BedLine
A BedLine object which has parsed the individual line in
a BED file. | Below is the the instruction that describes the task:
### Input:
Iterates through a BED file yielding parsed BED lines.
Parameters
----------
bed_path : str
path to BED file
Yields
------
BedLine(line) : BedLine
A BedLine object which has parsed the individual line in
... |
def config(self):
""" Returns a dictionary for the loaded configuration """
return {
key: self.__dict__[key]
for key in dir(self)
if key.isupper()
} | Returns a dictionary for the loaded configuration | Below is the the instruction that describes the task:
### Input:
Returns a dictionary for the loaded configuration
### Response:
def config(self):
""" Returns a dictionary for the loaded configuration """
return {
key: self.__dict__[key]
for key in dir(self)
if k... |
def get_current_ontology_date():
"""Get the release date of the current Gene Ontolgo release."""
with closing(requests.get(
'http://geneontology.org/ontology/go-basic.obo',
stream=True)) as r:
for i, l in enumerate(r.iter_lines(decode_unicode=True)):
if i == 1:
... | Get the release date of the current Gene Ontolgo release. | Below is the the instruction that describes the task:
### Input:
Get the release date of the current Gene Ontolgo release.
### Response:
def get_current_ontology_date():
"""Get the release date of the current Gene Ontolgo release."""
with closing(requests.get(
'http://geneontology.org/ontology/... |
def keys(self):
""" Returns all row keys
:raise NotImplementedError: if all rows aren't keyed
:return: all row keys
"""
if len(self._row_name_list) != len(self._rows):
raise NotImplementedError("You can't get row keys for a FVM that doesn't have all rows keyed")
... | Returns all row keys
:raise NotImplementedError: if all rows aren't keyed
:return: all row keys | Below is the the instruction that describes the task:
### Input:
Returns all row keys
:raise NotImplementedError: if all rows aren't keyed
:return: all row keys
### Response:
def keys(self):
""" Returns all row keys
:raise NotImplementedError: if all rows aren't keyed
:ret... |
def convert(self, text):
"""
convert Finglish(or whatever you'd like to call) to Persian.
gets and returns string.
"""
url = self.API_URL
encoding = self.ENCODING
headers = self.HEADERS
data = urlencode({
'farsi': str(text)
}).encode(encoding)
request = Request(url=url... | convert Finglish(or whatever you'd like to call) to Persian.
gets and returns string. | Below is the the instruction that describes the task:
### Input:
convert Finglish(or whatever you'd like to call) to Persian.
gets and returns string.
### Response:
def convert(self, text):
"""
convert Finglish(or whatever you'd like to call) to Persian.
gets and returns string.
"""
url = ... |
def from_phononwfkq_work(cls, phononwfkq_work, nscf_vars={}, remove_wfkq=True, with_ddk=True, manager=None):
"""
Construct a `GKKPWork` from a `PhononWfkqWork` object.
The WFQ are the ones used for PhononWfkqWork so in principle have only valence bands
"""
# Get list of qpoints f... | Construct a `GKKPWork` from a `PhononWfkqWork` object.
The WFQ are the ones used for PhononWfkqWork so in principle have only valence bands | Below is the the instruction that describes the task:
### Input:
Construct a `GKKPWork` from a `PhononWfkqWork` object.
The WFQ are the ones used for PhononWfkqWork so in principle have only valence bands
### Response:
def from_phononwfkq_work(cls, phononwfkq_work, nscf_vars={}, remove_wfkq=True, with_ddk=... |
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
if qreg.name in self.qregs:
raise DAGCircuitError("duplicate register %s" % qreg.name)
self.qreg... | Add all wires in a quantum register. | Below is the the instruction that describes the task:
### Input:
Add all wires in a quantum register.
### Response:
def add_qreg(self, qreg):
"""Add all wires in a quantum register."""
if not isinstance(qreg, QuantumRegister):
raise DAGCircuitError("not a QuantumRegister instance.")
... |
def forward(self, actions, batch_info):
""" Return model step after applying noise """
while len(self.processes) < actions.shape[0]:
len_action_space = self.action_space.shape[-1]
self.processes.append(
OrnsteinUhlenbeckNoiseProcess(
np.zeros(... | Return model step after applying noise | Below is the the instruction that describes the task:
### Input:
Return model step after applying noise
### Response:
def forward(self, actions, batch_info):
""" Return model step after applying noise """
while len(self.processes) < actions.shape[0]:
len_action_space = self.action_space... |
def _parse_normalizations(normalizations):
"""Parse and yield normalizations.
Parse normalizations parameter that yield all normalizations and
arguments found on it.
Args:
normalizations: List of normalizations.
Yields:
A tuple with a parsed normalizati... | Parse and yield normalizations.
Parse normalizations parameter that yield all normalizations and
arguments found on it.
Args:
normalizations: List of normalizations.
Yields:
A tuple with a parsed normalization. The first item will
contain the normal... | Below is the the instruction that describes the task:
### Input:
Parse and yield normalizations.
Parse normalizations parameter that yield all normalizations and
arguments found on it.
Args:
normalizations: List of normalizations.
Yields:
A tuple with a par... |
def parse(self, packet):
"""
There are two formats for headers
old style
---------
Old style headers can be 1, 2, 3, or 6 octets long and are composed of a Tag and a Length.
If the header length is 1 octet (length_type == 3), then there is no Length field.
new ... | There are two formats for headers
old style
---------
Old style headers can be 1, 2, 3, or 6 octets long and are composed of a Tag and a Length.
If the header length is 1 octet (length_type == 3), then there is no Length field.
new style
---------
New style he... | Below is the the instruction that describes the task:
### Input:
There are two formats for headers
old style
---------
Old style headers can be 1, 2, 3, or 6 octets long and are composed of a Tag and a Length.
If the header length is 1 octet (length_type == 3), then there is no Len... |
async def add_reaction(self, emoji):
"""|coro|
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
You must have the :attr:`~Permissions.read_message_history` permission
to use this. If nobody else has reacted to the message using ... | |coro|
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
You must have the :attr:`~Permissions.read_message_history` permission
to use this. If nobody else has reacted to the message using this
emoji, the :attr:`~Permissions.add_... | Below is the the instruction that describes the task:
### Input:
|coro|
Add a reaction to the message.
The emoji may be a unicode emoji or a custom guild :class:`Emoji`.
You must have the :attr:`~Permissions.read_message_history` permission
to use this. If nobody else has reacted ... |
def add_error_handlers(app):
"""Add custom error handlers for PyMacaronCoreExceptions to the app"""
def handle_validation_error(error):
response = jsonify({'message': str(error)})
response.status_code = error.status_code
return response
app.errorhandler(ValidationError)(handle_vali... | Add custom error handlers for PyMacaronCoreExceptions to the app | Below is the the instruction that describes the task:
### Input:
Add custom error handlers for PyMacaronCoreExceptions to the app
### Response:
def add_error_handlers(app):
"""Add custom error handlers for PyMacaronCoreExceptions to the app"""
def handle_validation_error(error):
response = jsonify... |
def _dct_from_mro(cls: type, attr_name: str) -> dict:
""""Get a merged dictionary from `cls` bases attribute `attr_name`. MRO defines importance (closest = strongest)."""
d = {}
for c in reversed(cls.mro()):
d.update(getattr(c, attr_name, {}))
return d | Get a merged dictionary from `cls` bases attribute `attr_name`. MRO defines importance (closest = strongest). | Below is the the instruction that describes the task:
### Input:
Get a merged dictionary from `cls` bases attribute `attr_name`. MRO defines importance (closest = strongest).
### Response:
def _dct_from_mro(cls: type, attr_name: str) -> dict:
""""Get a merged dictionary from `cls` bases attribute `attr_name`. ... |
def _get_title(self):
"""According to http://support.microsoft.com/kb/124103 the buffer
size is 1024
Does not support unicode, only ANSI"""
#TODO: unicode support
strbuffer = self.ctypes.create_string_buffer(1024)
size = self.ctypes.c_short(1024)
#unicode... | According to http://support.microsoft.com/kb/124103 the buffer
size is 1024
Does not support unicode, only ANSI | Below is the the instruction that describes the task:
### Input:
According to http://support.microsoft.com/kb/124103 the buffer
size is 1024
Does not support unicode, only ANSI
### Response:
def _get_title(self):
"""According to http://support.microsoft.com/kb/124103 the buffer
... |
def QA_indicator_DMI(DataFrame, M1=14, M2=6):
"""
趋向指标 DMI
"""
HIGH = DataFrame.high
LOW = DataFrame.low
CLOSE = DataFrame.close
OPEN = DataFrame.open
TR = SUM(MAX(MAX(HIGH-LOW, ABS(HIGH-REF(CLOSE, 1))),
ABS(LOW-REF(CLOSE, 1))), M1)
HD = HIGH-REF(HIGH, 1)
LD = R... | 趋向指标 DMI | Below is the the instruction that describes the task:
### Input:
趋向指标 DMI
### Response:
def QA_indicator_DMI(DataFrame, M1=14, M2=6):
"""
趋向指标 DMI
"""
HIGH = DataFrame.high
LOW = DataFrame.low
CLOSE = DataFrame.close
OPEN = DataFrame.open
TR = SUM(MAX(MAX(HIGH-LOW, ABS(HIGH-REF(CLO... |
def apps():
'''
Return a list of the currently installed app ids.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.apps
'''
response = salt.utils.http.query(
"{0}/v2/apps".format(_base_url()),
decode_type='json',
decode=True,
)
return ... | Return a list of the currently installed app ids.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.apps | Below is the the instruction that describes the task:
### Input:
Return a list of the currently installed app ids.
CLI Example:
.. code-block:: bash
salt marathon-minion-id marathon.apps
### Response:
def apps():
'''
Return a list of the currently installed app ids.
CLI Example:
... |
def append_tz_timestamp(self, tag, timestamp=None, precision=3,
header=False):
"""Append a field with a TZTimestamp value, derived from local time.
:param tag: Integer or string FIX tag number.
:param timestamp: Time value, see below.
:param precision: Number... | Append a field with a TZTimestamp value, derived from local time.
:param tag: Integer or string FIX tag number.
:param timestamp: Time value, see below.
:param precision: Number of decimal places: 0, 3 (ms) or 6 (us).
:param header: Append to FIX header if True; default to body.
... | Below is the the instruction that describes the task:
### Input:
Append a field with a TZTimestamp value, derived from local time.
:param tag: Integer or string FIX tag number.
:param timestamp: Time value, see below.
:param precision: Number of decimal places: 0, 3 (ms) or 6 (us).
... |
def clean_for_doc(nb):
"""
Cleans the notebook to be suitable for inclusion in the docs.
"""
new_cells = []
for cell in nb.worksheets[0].cells:
# Remove the pylab inline line.
if "input" in cell and cell["input"].strip() == "%pylab inline":
continue
# Remove outpu... | Cleans the notebook to be suitable for inclusion in the docs. | Below is the the instruction that describes the task:
### Input:
Cleans the notebook to be suitable for inclusion in the docs.
### Response:
def clean_for_doc(nb):
"""
Cleans the notebook to be suitable for inclusion in the docs.
"""
new_cells = []
for cell in nb.worksheets[0].cells:
# ... |
def subslice(inner,outer,section):
'helper for rediff\
outer is a slice (2-tuple, not an official python slice) in global coordinates\
inner is a slice (2-tuple) on that slice\
returns the result of sub-slicing outer by inner'
# todo: think about constraints here. inner and outer ordered, inner[1] less t... | helper for rediff\
outer is a slice (2-tuple, not an official python slice) in global coordinates\
inner is a slice (2-tuple) on that slice\
returns the result of sub-slicing outer by inner | Below is the the instruction that describes the task:
### Input:
helper for rediff\
outer is a slice (2-tuple, not an official python slice) in global coordinates\
inner is a slice (2-tuple) on that slice\
returns the result of sub-slicing outer by inner
### Response:
def subslice(inner,outer,section):
... |
def _unjsonify(x, isattributes=False):
"""Convert JSON string to an ordered defaultdict."""
if isattributes:
obj = json.loads(x)
return dict_class(obj)
return json.loads(x) | Convert JSON string to an ordered defaultdict. | Below is the the instruction that describes the task:
### Input:
Convert JSON string to an ordered defaultdict.
### Response:
def _unjsonify(x, isattributes=False):
"""Convert JSON string to an ordered defaultdict."""
if isattributes:
obj = json.loads(x)
return dict_class(obj)
return js... |
def date_time_string(self, timestamp=None):
"""Return the current date and time formatted for a message header."""
if timestamp is None:
timestamp = time.time()
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
... | Return the current date and time formatted for a message header. | Below is the the instruction that describes the task:
### Input:
Return the current date and time formatted for a message header.
### Response:
def date_time_string(self, timestamp=None):
"""Return the current date and time formatted for a message header."""
if timestamp is None:
timest... |
def make_service_hooks_update_groups_action(service):
"""
Make a admin action for the given service
:param service: services.hooks.ServicesHook
:return: fn to update services groups for the selected users
"""
def update_service_groups(modeladmin, request, queryset):
for user in queryset:... | Make a admin action for the given service
:param service: services.hooks.ServicesHook
:return: fn to update services groups for the selected users | Below is the the instruction that describes the task:
### Input:
Make a admin action for the given service
:param service: services.hooks.ServicesHook
:return: fn to update services groups for the selected users
### Response:
def make_service_hooks_update_groups_action(service):
"""
Make a admin ac... |
def hash_of_file(path):
"""Return the hash of a downloaded file."""
with open(path, 'rb') as archive:
sha = sha256()
while True:
data = archive.read(2 ** 20)
if not data:
break
sha.update(data)
return encoded_hash(sha) | Return the hash of a downloaded file. | Below is the the instruction that describes the task:
### Input:
Return the hash of a downloaded file.
### Response:
def hash_of_file(path):
"""Return the hash of a downloaded file."""
with open(path, 'rb') as archive:
sha = sha256()
while True:
data = archive.read(2 ** 20)
... |
def list_all(prefix=None, app=None, owner=None, description_contains=None,
name_not_contains=None, profile="splunk"):
'''
Get all splunk search details. Produces results that can be used to create
an sls file.
if app or owner are specified, results will be limited to matching saved
sea... | Get all splunk search details. Produces results that can be used to create
an sls file.
if app or owner are specified, results will be limited to matching saved
searches.
if description_contains is specified, results will be limited to those
where "description_contains in description" is true if n... | Below is the the instruction that describes the task:
### Input:
Get all splunk search details. Produces results that can be used to create
an sls file.
if app or owner are specified, results will be limited to matching saved
searches.
if description_contains is specified, results will be limited ... |
def StringEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a string field."""
tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
local_len = len
assert not is_packed
if is_repeated:
def EncodeRepeatedField(write, value):
... | Returns an encoder for a string field. | Below is the the instruction that describes the task:
### Input:
Returns an encoder for a string field.
### Response:
def StringEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a string field."""
tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint =... |
def can_view(self, user):
"""Return whether or not `user` can view the submission."""
return user in self.group.users or self.project.can_view(user) | Return whether or not `user` can view the submission. | Below is the the instruction that describes the task:
### Input:
Return whether or not `user` can view the submission.
### Response:
def can_view(self, user):
"""Return whether or not `user` can view the submission."""
return user in self.group.users or self.project.can_view(user) |
def clear_last_check(self):
"""Clear the checksum of the file."""
with db.session.begin_nested():
self.last_check = None
self.last_check_at = datetime.utcnow()
return self | Clear the checksum of the file. | Below is the the instruction that describes the task:
### Input:
Clear the checksum of the file.
### Response:
def clear_last_check(self):
"""Clear the checksum of the file."""
with db.session.begin_nested():
self.last_check = None
self.last_check_at = datetime.utcnow()
... |
def unique_id(self):
"""Creates a unique ID for the `Atom` based on its parents.
Returns
-------
unique_id : (str, str, str)
(polymer.id, residue.id, atom.id)
"""
chain = self.ampal_parent.ampal_parent.id
residue = self.ampal_parent.id
return ... | Creates a unique ID for the `Atom` based on its parents.
Returns
-------
unique_id : (str, str, str)
(polymer.id, residue.id, atom.id) | Below is the the instruction that describes the task:
### Input:
Creates a unique ID for the `Atom` based on its parents.
Returns
-------
unique_id : (str, str, str)
(polymer.id, residue.id, atom.id)
### Response:
def unique_id(self):
"""Creates a unique ID for the `Ato... |
def create_pvsm_file(vtk_files, pvsm_filename, relative_paths=True):
"""
Create paraview status file (.pvsm) based on input vtk files.
:param vtk_files:
:param pvsm_filename:
:param relative_paths:
:return:
"""
from xml.etree.ElementTree import Element, SubElement, Comment
import os.... | Create paraview status file (.pvsm) based on input vtk files.
:param vtk_files:
:param pvsm_filename:
:param relative_paths:
:return: | Below is the the instruction that describes the task:
### Input:
Create paraview status file (.pvsm) based on input vtk files.
:param vtk_files:
:param pvsm_filename:
:param relative_paths:
:return:
### Response:
def create_pvsm_file(vtk_files, pvsm_filename, relative_paths=True):
"""
Creat... |
def get_signal_level(cell):
""" Gets the signal level of a network / cell.
@param string cell
A network / cell from iwlist scan.
@return string
The signal level of the network.
"""
signal = matching_line(cell, "Signal level=")
if signal is None:
return ""
signal = sig... | Gets the signal level of a network / cell.
@param string cell
A network / cell from iwlist scan.
@return string
The signal level of the network. | Below is the the instruction that describes the task:
### Input:
Gets the signal level of a network / cell.
@param string cell
A network / cell from iwlist scan.
@return string
The signal level of the network.
### Response:
def get_signal_level(cell):
""" Gets the signal level of a net... |
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
'''
for fn_ in os.listdir(__opts__['pki_dir']):
path = os.path.join(__opts__['pki_dir'], fn_)
try:
os.remove(path)
except os.err... | Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys | Below is the the instruction that describes the task:
### Input:
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
salt '*' saltutil.regen_keys
### Response:
def regen_keys():
'''
Used to regenerate the minion keys.
CLI Example:
.. code-block:: bash
... |
async def _get_response(self, msg):
"""Perform the request, get the response."""
try:
protocol = await self._get_protocol()
pr = protocol.request(msg)
r = await pr.response
return pr, r
except ConstructionRenderableError as e:
raise Cli... | Perform the request, get the response. | Below is the the instruction that describes the task:
### Input:
Perform the request, get the response.
### Response:
async def _get_response(self, msg):
"""Perform the request, get the response."""
try:
protocol = await self._get_protocol()
pr = protocol.request(msg)
... |
def applet_describe(object_id, input_params={}, always_retry=True, **kwargs):
"""
Invokes the /applet-xxxx/describe API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Applets-and-Entry-Points#API-method%3A-%2Fapplet-xxxx%2Fdescribe
"""
return DXHTTPRequest('/%s/descr... | Invokes the /applet-xxxx/describe API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Applets-and-Entry-Points#API-method%3A-%2Fapplet-xxxx%2Fdescribe | Below is the the instruction that describes the task:
### Input:
Invokes the /applet-xxxx/describe API method.
For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Applets-and-Entry-Points#API-method%3A-%2Fapplet-xxxx%2Fdescribe
### Response:
def applet_describe(object_id, input_params={}, a... |
def previous_page_url(self):
"""
:return str: Returns a link to the previous_page_url or None if doesn't exist.
"""
if 'meta' in self._payload and 'previous_page_url' in self._payload['meta']:
return self._payload['meta']['previous_page_url']
elif 'previous_page_uri' ... | :return str: Returns a link to the previous_page_url or None if doesn't exist. | Below is the the instruction that describes the task:
### Input:
:return str: Returns a link to the previous_page_url or None if doesn't exist.
### Response:
def previous_page_url(self):
"""
:return str: Returns a link to the previous_page_url or None if doesn't exist.
"""
if 'meta'... |
def _make_content_item(node, mime_type=None, alternate_data=None):
"""Create a ContentItem from a node in the spinn3r data tree.
The ContentItem is created with raw data set to ``node.data``,
decompressed if the node's encoding is 'zlib', and UTF-8
normalized, with a MIME type from ``node.mime_type``.
... | Create a ContentItem from a node in the spinn3r data tree.
The ContentItem is created with raw data set to ``node.data``,
decompressed if the node's encoding is 'zlib', and UTF-8
normalized, with a MIME type from ``node.mime_type``.
``node``
the actual node from the spinn3r protobuf data
``m... | Below is the the instruction that describes the task:
### Input:
Create a ContentItem from a node in the spinn3r data tree.
The ContentItem is created with raw data set to ``node.data``,
decompressed if the node's encoding is 'zlib', and UTF-8
normalized, with a MIME type from ``node.mime_type``.
... |
def get_jobs_url(self, job_id):
# type: (Text) -> Text
"""
Returns the URL to check job status.
:param job_id:
The ID of the job to check.
"""
return compat.urllib_parse.urlunsplit((
self.uri.scheme,
self.uri.netloc,
self.u... | Returns the URL to check job status.
:param job_id:
The ID of the job to check. | Below is the the instruction that describes the task:
### Input:
Returns the URL to check job status.
:param job_id:
The ID of the job to check.
### Response:
def get_jobs_url(self, job_id):
# type: (Text) -> Text
"""
Returns the URL to check job status.
:param... |
def phenotypes_actions(institute_id, case_name):
"""Perform actions on multiple phenotypes."""
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
case_url = url_for('.case', institute_id=institute_id, case_name=case_name)
action = request.form['action']
hpo_ids = request.fo... | Perform actions on multiple phenotypes. | Below is the the instruction that describes the task:
### Input:
Perform actions on multiple phenotypes.
### Response:
def phenotypes_actions(institute_id, case_name):
"""Perform actions on multiple phenotypes."""
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
case_url = u... |
def markdown_media_css():
""" Add css requirements to HTML.
:returns: Editor template context.
"""
return dict(
CSS_SET=posixpath.join(
settings.MARKDOWN_SET_PATH, settings.MARKDOWN_SET_NAME, 'style.css'
),
CSS_SKIN=posixpath.join(
'django_markdown', 'sk... | Add css requirements to HTML.
:returns: Editor template context. | Below is the the instruction that describes the task:
### Input:
Add css requirements to HTML.
:returns: Editor template context.
### Response:
def markdown_media_css():
""" Add css requirements to HTML.
:returns: Editor template context.
"""
return dict(
CSS_SET=posixpath.join(
... |
def _init_client(self, from_archive=False):
"""Init client"""
return ConfluenceClient(self.url, archive=self.archive, from_archive=from_archive) | Init client | Below is the the instruction that describes the task:
### Input:
Init client
### Response:
def _init_client(self, from_archive=False):
"""Init client"""
return ConfluenceClient(self.url, archive=self.archive, from_archive=from_archive) |
def value(self):
"""
Return the value of this SpinBox.
"""
if self.opts['int']:
return int(self.val)
else:
return float(self.val) | Return the value of this SpinBox. | Below is the the instruction that describes the task:
### Input:
Return the value of this SpinBox.
### Response:
def value(self):
"""
Return the value of this SpinBox.
"""
if self.opts['int']:
return int(self.val)
else:
return float(self.val) |
def labels(self):
"""
Construct a dictionary of string -> labels
Returns:
--------
OrderedDict<str, int> : string label pairs.
"""
labelings = OrderedDict()
for tree in self:
for label, line in tree.to_labeled_lines():
labe... | Construct a dictionary of string -> labels
Returns:
--------
OrderedDict<str, int> : string label pairs. | Below is the the instruction that describes the task:
### Input:
Construct a dictionary of string -> labels
Returns:
--------
OrderedDict<str, int> : string label pairs.
### Response:
def labels(self):
"""
Construct a dictionary of string -> labels
Returns:
... |
def moon_phase(self, date=None, rtype=int):
"""Calculates the moon phase for a specific date.
:param date: The date to calculate the phase for.
If ommitted the current date is used.
:type date: :class:`datetime.date`
:returns:
A number designating the p... | Calculates the moon phase for a specific date.
:param date: The date to calculate the phase for.
If ommitted the current date is used.
:type date: :class:`datetime.date`
:returns:
A number designating the phase
| 0 = New moon
|... | Below is the the instruction that describes the task:
### Input:
Calculates the moon phase for a specific date.
:param date: The date to calculate the phase for.
If ommitted the current date is used.
:type date: :class:`datetime.date`
:returns:
A number des... |
def _lmowfv1(password):
"""
[MS-NLMP] v28.0 2016-07-14
3.3.1 NTLM v1 Authentication
Same function as LMOWFv1 in document to create a one way hash of the
password. Only used in NTLMv1 auth without session security
:param password: The password or hash of the user we are trying to
authen... | [MS-NLMP] v28.0 2016-07-14
3.3.1 NTLM v1 Authentication
Same function as LMOWFv1 in document to create a one way hash of the
password. Only used in NTLMv1 auth without session security
:param password: The password or hash of the user we are trying to
authenticate with
:return res: A Lan M... | Below is the the instruction that describes the task:
### Input:
[MS-NLMP] v28.0 2016-07-14
3.3.1 NTLM v1 Authentication
Same function as LMOWFv1 in document to create a one way hash of the
password. Only used in NTLMv1 auth without session security
:param password: The password or hash of the use... |
def normalize_init_values(cls, release, species, server):
"""
Normalizes the arguments which uniquely specify an EnsemblRelease
genome.
"""
release = check_release_number(release)
species = check_species_object(species)
return (release, species, server) | Normalizes the arguments which uniquely specify an EnsemblRelease
genome. | Below is the the instruction that describes the task:
### Input:
Normalizes the arguments which uniquely specify an EnsemblRelease
genome.
### Response:
def normalize_init_values(cls, release, species, server):
"""
Normalizes the arguments which uniquely specify an EnsemblRelease
ge... |
def copy_sqla_object(obj: object,
omit_fk: bool = True,
omit_pk: bool = True,
omit_attrs: List[str] = None,
debug: bool = False) -> object:
"""
Given an SQLAlchemy object, creates a new object (FOR WHICH THE OBJECT
MUST SUPP... | Given an SQLAlchemy object, creates a new object (FOR WHICH THE OBJECT
MUST SUPPORT CREATION USING ``__init__()`` WITH NO PARAMETERS), and copies
across all attributes, omitting PKs (by default), FKs (by default), and
relationship attributes (always omitted).
Args:
obj: the object to copy
... | Below is the the instruction that describes the task:
### Input:
Given an SQLAlchemy object, creates a new object (FOR WHICH THE OBJECT
MUST SUPPORT CREATION USING ``__init__()`` WITH NO PARAMETERS), and copies
across all attributes, omitting PKs (by default), FKs (by default), and
relationship attribut... |
def filters(self, *filters):
"""
Add a list of Filter ingredients to the query. These can either be
Filter objects or strings representing filters on the service's shelf.
``.filters()`` are additive, calling .filters() more than once will add
to the list of filters being used by ... | Add a list of Filter ingredients to the query. These can either be
Filter objects or strings representing filters on the service's shelf.
``.filters()`` are additive, calling .filters() more than once will add
to the list of filters being used by the recipe.
The Filter expression will b... | Below is the the instruction that describes the task:
### Input:
Add a list of Filter ingredients to the query. These can either be
Filter objects or strings representing filters on the service's shelf.
``.filters()`` are additive, calling .filters() more than once will add
to the list of fi... |
def results(self, query_name):
"""
Gets a single saved query with a 'result' object for a project from the
Keen IO API given a query name.
Read or Master key must be set.
"""
url = "{0}/{1}/result".format(self.saved_query_url, query_name)
response = self._get_jso... | Gets a single saved query with a 'result' object for a project from the
Keen IO API given a query name.
Read or Master key must be set. | Below is the the instruction that describes the task:
### Input:
Gets a single saved query with a 'result' object for a project from the
Keen IO API given a query name.
Read or Master key must be set.
### Response:
def results(self, query_name):
"""
Gets a single saved query with a ... |
def _HashFile(self, fd):
"""Look for the required hashes in the file."""
hashes = data_store_utils.GetFileHashEntry(fd)
if hashes:
found_all = True
for fingerprint_type, hash_types in iteritems(self.HASH_TYPES):
for hash_type in hash_types:
if fingerprint_type == "pecoff":
... | Look for the required hashes in the file. | Below is the the instruction that describes the task:
### Input:
Look for the required hashes in the file.
### Response:
def _HashFile(self, fd):
"""Look for the required hashes in the file."""
hashes = data_store_utils.GetFileHashEntry(fd)
if hashes:
found_all = True
for fingerprint_type, ... |
def on(self, event: str) -> Callable:
""" Decorator for subscribing a function to a specific event.
:param event: Name of the event to subscribe to.
:type event: str
:return: The outer function.
:rtype: Callable
"""
def outer(func):
self.add_event(f... | Decorator for subscribing a function to a specific event.
:param event: Name of the event to subscribe to.
:type event: str
:return: The outer function.
:rtype: Callable | Below is the the instruction that describes the task:
### Input:
Decorator for subscribing a function to a specific event.
:param event: Name of the event to subscribe to.
:type event: str
:return: The outer function.
:rtype: Callable
### Response:
def on(self, event: str) -> Call... |
def table_is_subset_of(entries_a, entries_b):
"""Check that every key matched by every entry in one table results in the
same route when checked against the other table.
For example, the table::
>>> from rig.routing_table import Routes
>>> table = [
... RoutingTableEntry({Route... | Check that every key matched by every entry in one table results in the
same route when checked against the other table.
For example, the table::
>>> from rig.routing_table import Routes
>>> table = [
... RoutingTableEntry({Routes.north, Routes.north_east}, 0x0, 0xf),
... ... | Below is the the instruction that describes the task:
### Input:
Check that every key matched by every entry in one table results in the
same route when checked against the other table.
For example, the table::
>>> from rig.routing_table import Routes
>>> table = [
... RoutingT... |
def _default_ctx(self):
""" Return the package config or context and normalize some of the
values
"""
if not self.in_app_directory:
print("Warning: {} does not exist. Using the default.".format(
self.package))
ctx = {}
else:
... | Return the package config or context and normalize some of the
values | Below is the the instruction that describes the task:
### Input:
Return the package config or context and normalize some of the
values
### Response:
def _default_ctx(self):
""" Return the package config or context and normalize some of the
values
"""
if not self.... |
def cast_in(self, element):
"""encode the element into the internal tag list."""
if _debug: SequenceOfAny._debug("cast_in %r", element)
# make sure it is a list
if not isinstance(element, List):
raise EncodingError("%r is not a list" % (element,))
t = TagList()
... | encode the element into the internal tag list. | Below is the the instruction that describes the task:
### Input:
encode the element into the internal tag list.
### Response:
def cast_in(self, element):
"""encode the element into the internal tag list."""
if _debug: SequenceOfAny._debug("cast_in %r", element)
# make sure it is a list
... |
async def _body_callback(self, h11_connection):
'''
A callback func to be supplied if the user wants to do something
directly with the response body's stream.
'''
# pylint: disable=not-callable
while True:
next_event = await self._recv_event(h11_connection)
... | A callback func to be supplied if the user wants to do something
directly with the response body's stream. | Below is the the instruction that describes the task:
### Input:
A callback func to be supplied if the user wants to do something
directly with the response body's stream.
### Response:
async def _body_callback(self, h11_connection):
'''
A callback func to be supplied if the user wants to d... |
def create(p_class, p_todo, p_id_width=4):
"""
Creates a TodoWidget instance for the given todo. Widgets are
cached, the same object is returned for the same todo item.
"""
def parent_progress_may_have_changed(p_todo):
"""
Returns True when a todo's progr... | Creates a TodoWidget instance for the given todo. Widgets are
cached, the same object is returned for the same todo item. | Below is the the instruction that describes the task:
### Input:
Creates a TodoWidget instance for the given todo. Widgets are
cached, the same object is returned for the same todo item.
### Response:
def create(p_class, p_todo, p_id_width=4):
"""
Creates a TodoWidget instance for the given... |
def set_printed_time(self, sample):
"""Updates the printed time of the last results report from the sample
"""
if api.get_workflow_status_of(sample) != "published":
return False
reports = sample.objectValues("ARReport")
reports = sorted(reports, key=lambda report: rep... | Updates the printed time of the last results report from the sample | Below is the the instruction that describes the task:
### Input:
Updates the printed time of the last results report from the sample
### Response:
def set_printed_time(self, sample):
"""Updates the printed time of the last results report from the sample
"""
if api.get_workflow_status_of(sam... |
def get_field_mapping(self):
"""Obtain metadata from current state of the widget.
:returns: Dictionary of values by type in this format:
{'fields': {}, 'values': {}}.
:rtype: dict
"""
fields = {}
values = {}
for tab in self.tabs:
parameter... | Obtain metadata from current state of the widget.
:returns: Dictionary of values by type in this format:
{'fields': {}, 'values': {}}.
:rtype: dict | Below is the the instruction that describes the task:
### Input:
Obtain metadata from current state of the widget.
:returns: Dictionary of values by type in this format:
{'fields': {}, 'values': {}}.
:rtype: dict
### Response:
def get_field_mapping(self):
"""Obtain metadata fro... |
def example_lab_to_xyz():
"""
This function shows a simple conversion of an Lab color to an XYZ color.
"""
print("=== Simple Example: Lab->XYZ ===")
# Instantiate an Lab color object with the given values.
lab = LabColor(0.903, 16.296, -2.22)
# Show a string representation.
print(lab)
... | This function shows a simple conversion of an Lab color to an XYZ color. | Below is the the instruction that describes the task:
### Input:
This function shows a simple conversion of an Lab color to an XYZ color.
### Response:
def example_lab_to_xyz():
"""
This function shows a simple conversion of an Lab color to an XYZ color.
"""
print("=== Simple Example: Lab->XYZ ===... |
def __get_cfg_pkgs_rpm(self):
'''
Get packages with configuration files on RPM systems.
'''
out, err = self._syscall('rpm', None, None, '-qa', '--configfiles',
'--queryformat', '%{name}-%{version}-%{release}\\n')
data = dict()
pkg_name = N... | Get packages with configuration files on RPM systems. | Below is the the instruction that describes the task:
### Input:
Get packages with configuration files on RPM systems.
### Response:
def __get_cfg_pkgs_rpm(self):
'''
Get packages with configuration files on RPM systems.
'''
out, err = self._syscall('rpm', None, None, '-qa', '--conf... |
def fcs(args):
"""
%prog fcs fcsfile
Process the results from Genbank contaminant screen. An example of the file
looks like:
contig name, length, span(s), apparent source
contig0746 11760 1..141 vector
contig0751 14226 13476..14226 vector
contig0800 124133 30512... | %prog fcs fcsfile
Process the results from Genbank contaminant screen. An example of the file
looks like:
contig name, length, span(s), apparent source
contig0746 11760 1..141 vector
contig0751 14226 13476..14226 vector
contig0800 124133 30512..30559 primer/adapter | Below is the the instruction that describes the task:
### Input:
%prog fcs fcsfile
Process the results from Genbank contaminant screen. An example of the file
looks like:
contig name, length, span(s), apparent source
contig0746 11760 1..141 vector
contig0751 14226 13476..14226 ... |
def _record_revisit(self, payload_offset: int):
'''Record the revisit if possible.'''
fields = self._response_record.fields
ref_record_id = self._url_table.get_revisit_id(
fields['WARC-Target-URI'],
fields.get('WARC-Payload-Digest', '').upper().replace('SHA1:', '')
... | Record the revisit if possible. | Below is the the instruction that describes the task:
### Input:
Record the revisit if possible.
### Response:
def _record_revisit(self, payload_offset: int):
'''Record the revisit if possible.'''
fields = self._response_record.fields
ref_record_id = self._url_table.get_revisit_id(
... |
def pack_paths(paths, sheet_size=None):
"""
Pack a list of Path2D objects into a rectangle.
Parameters
------------
paths: (n,) Path2D
Geometry to be packed
Returns
------------
packed : trimesh.path.Path2D
Object containing input geometry
inserted : (m,) int
Inde... | Pack a list of Path2D objects into a rectangle.
Parameters
------------
paths: (n,) Path2D
Geometry to be packed
Returns
------------
packed : trimesh.path.Path2D
Object containing input geometry
inserted : (m,) int
Indexes of paths inserted into result | Below is the the instruction that describes the task:
### Input:
Pack a list of Path2D objects into a rectangle.
Parameters
------------
paths: (n,) Path2D
Geometry to be packed
Returns
------------
packed : trimesh.path.Path2D
Object containing input geometry
inserted : (m... |
def get_context(namespace, context_id):
"""Get stored context object."""
context_obj = get_state(context_id, namespace=namespace)
if not context_obj:
raise ContextError("Context '{}' not found in namespace '{}'".format(
context_id, namespace))
return context_obj | Get stored context object. | Below is the the instruction that describes the task:
### Input:
Get stored context object.
### Response:
def get_context(namespace, context_id):
"""Get stored context object."""
context_obj = get_state(context_id, namespace=namespace)
if not context_obj:
raise ContextError("Context '{}' not fo... |
def generate_slides(self, infile):
""" Process a file of rest and yield dictionaries """
state = 0
# each slide is a dict
slide = {}
last_heading = 0
for item in self.generate_lines(infile):
line = item['line']
heading = item['heading']
... | Process a file of rest and yield dictionaries | Below is the the instruction that describes the task:
### Input:
Process a file of rest and yield dictionaries
### Response:
def generate_slides(self, infile):
""" Process a file of rest and yield dictionaries """
state = 0
# each slide is a dict
slide = {}
last_heading =... |
def _get_cache_key(self, obj):
"""Derive cache key for given object."""
if obj is not None:
# Make sure that key is REALLY unique.
return '{}-{}'.format(id(self), obj.pk)
return "{}-None".format(id(self)) | Derive cache key for given object. | Below is the the instruction that describes the task:
### Input:
Derive cache key for given object.
### Response:
def _get_cache_key(self, obj):
"""Derive cache key for given object."""
if obj is not None:
# Make sure that key is REALLY unique.
return '{}-{}'.format(id(self)... |
def projectEmitter(target, source, env):
"""Sets up the DSP dependencies."""
# todo: Not sure what sets source to what user has passed as target,
# but this is what happens. When that is fixed, we also won't have
# to make the user always append env['MSVSPROJECTSUFFIX'] to target.
if source[0] == t... | Sets up the DSP dependencies. | Below is the the instruction that describes the task:
### Input:
Sets up the DSP dependencies.
### Response:
def projectEmitter(target, source, env):
"""Sets up the DSP dependencies."""
# todo: Not sure what sets source to what user has passed as target,
# but this is what happens. When that is fixed,... |
def wait(self, dwMilliseconds = None):
"""
Wait for the Win32 object to be signaled.
@type dwMilliseconds: int
@param dwMilliseconds: (Optional) Timeout value in milliseconds.
Use C{INFINITE} or C{None} for no timeout.
"""
if self.value is None:
... | Wait for the Win32 object to be signaled.
@type dwMilliseconds: int
@param dwMilliseconds: (Optional) Timeout value in milliseconds.
Use C{INFINITE} or C{None} for no timeout. | Below is the the instruction that describes the task:
### Input:
Wait for the Win32 object to be signaled.
@type dwMilliseconds: int
@param dwMilliseconds: (Optional) Timeout value in milliseconds.
Use C{INFINITE} or C{None} for no timeout.
### Response:
def wait(self, dwMilliseconds ... |
def add_fields(input_array, arrays, names=None, assubarray=False):
"""Adds the given array(s) as new field(s) to the given input array.
Returns a new instance of the input_array with the new fields added.
Parameters
----------
input_array : instance of a numpy.ndarray or numpy recarray
The ... | Adds the given array(s) as new field(s) to the given input array.
Returns a new instance of the input_array with the new fields added.
Parameters
----------
input_array : instance of a numpy.ndarray or numpy recarray
The array to to add the fields to.
arrays : (list of) numpy array(s)
... | Below is the the instruction that describes the task:
### Input:
Adds the given array(s) as new field(s) to the given input array.
Returns a new instance of the input_array with the new fields added.
Parameters
----------
input_array : instance of a numpy.ndarray or numpy recarray
The array... |
def gpio_set(self, pins, states):
"""Sets the state for one or more user-controllable GPIOs.
For each of the given pins, sets the the corresponding state based on
the index.
Args:
self (JLink): the ``JLink`` instance
pins (list): list of GPIO indices
state... | Sets the state for one or more user-controllable GPIOs.
For each of the given pins, sets the the corresponding state based on
the index.
Args:
self (JLink): the ``JLink`` instance
pins (list): list of GPIO indices
states (list): list of states to set
Retu... | Below is the the instruction that describes the task:
### Input:
Sets the state for one or more user-controllable GPIOs.
For each of the given pins, sets the the corresponding state based on
the index.
Args:
self (JLink): the ``JLink`` instance
pins (list): list of GPIO... |
def createMultipleL4L2Columns(network, networkConfig):
"""
Create a network consisting of multiple columns. Each column contains one L4
and one L2, is identical in structure to the network created by
createL4L2Column. In addition all the L2 columns are fully connected to each
other through their lateral inpu... | Create a network consisting of multiple columns. Each column contains one L4
and one L2, is identical in structure to the network created by
createL4L2Column. In addition all the L2 columns are fully connected to each
other through their lateral inputs.
Region names have a column number appended as in externa... | Below is the the instruction that describes the task:
### Input:
Create a network consisting of multiple columns. Each column contains one L4
and one L2, is identical in structure to the network created by
createL4L2Column. In addition all the L2 columns are fully connected to each
other through their latera... |
def get_line(self, position):
'Returns the line number that the given string position is found on'
datalen = len(self.data)
count = len(self.data[0])
line = 1
while count < position:
if line >= datalen:
break
count += len(self.data[line]) ... | Returns the line number that the given string position is found on | Below is the the instruction that describes the task:
### Input:
Returns the line number that the given string position is found on
### Response:
def get_line(self, position):
'Returns the line number that the given string position is found on'
datalen = len(self.data)
count = len(self.dat... |
def get_collection(self, **kwargs):
"""Get an iterator of Python ``Resource`` objects that represent URIs.
The returned objects are Pythonic `Resource`s that map to the most
recently `refreshed` state of uris-resources published by the device.
In order to instantiate the correct types, ... | Get an iterator of Python ``Resource`` objects that represent URIs.
The returned objects are Pythonic `Resource`s that map to the most
recently `refreshed` state of uris-resources published by the device.
In order to instantiate the correct types, the concrete subclass must
populate its... | Below is the the instruction that describes the task:
### Input:
Get an iterator of Python ``Resource`` objects that represent URIs.
The returned objects are Pythonic `Resource`s that map to the most
recently `refreshed` state of uris-resources published by the device.
In order to instantia... |
def schedule_job(self, j):
"""
Add the job given by j to the job queue.
Note: Does not actually run the job.
"""
job_id = uuid.uuid4().hex
j.job_id = job_id
session = self.sessionmaker()
orm_job = ORMJob(
id=job_id,
state=j.state,... | Add the job given by j to the job queue.
Note: Does not actually run the job. | Below is the the instruction that describes the task:
### Input:
Add the job given by j to the job queue.
Note: Does not actually run the job.
### Response:
def schedule_job(self, j):
"""
Add the job given by j to the job queue.
Note: Does not actually run the job.
"""
... |
def _check_timeindex(self, timeseries):
"""
Raises an error if time index of storage time series does not
comply with the time index of load and feed-in time series.
Parameters
-----------
timeseries : :pandas:`pandas.DataFrame<dataframe>`
DataFrame containin... | Raises an error if time index of storage time series does not
comply with the time index of load and feed-in time series.
Parameters
-----------
timeseries : :pandas:`pandas.DataFrame<dataframe>`
DataFrame containing active power the storage is charged (negative)
... | Below is the the instruction that describes the task:
### Input:
Raises an error if time index of storage time series does not
comply with the time index of load and feed-in time series.
Parameters
-----------
timeseries : :pandas:`pandas.DataFrame<dataframe>`
DataFrame ... |
def with_query(self, *args, **kwargs):
"""Return a new URL with query part replaced.
Accepts any Mapping (e.g. dict, multidict.MultiDict instances)
or str, autoencode the argument if needed.
A sequence of (key, value) pairs is supported as well.
It also can take an arbitrary n... | Return a new URL with query part replaced.
Accepts any Mapping (e.g. dict, multidict.MultiDict instances)
or str, autoencode the argument if needed.
A sequence of (key, value) pairs is supported as well.
It also can take an arbitrary number of keyword arguments.
Clear query i... | Below is the the instruction that describes the task:
### Input:
Return a new URL with query part replaced.
Accepts any Mapping (e.g. dict, multidict.MultiDict instances)
or str, autoencode the argument if needed.
A sequence of (key, value) pairs is supported as well.
It also can ... |
def raw_datastream_old(request, pid, dsid, type=None, repo=None,
headers=None, accept_range_request=False,
as_of_date=None, streaming=False):
'''
.. NOTE::
This version of :meth:`raw_datastream` is deprecated, and you
should update to the new :meth:... | .. NOTE::
This version of :meth:`raw_datastream` is deprecated, and you
should update to the new :meth:`raw_datastream`. This version
is still available if you are using a version of Fedora
prior to 3.7 and need the additional functionality.
View to display a raw datastream that b... | Below is the the instruction that describes the task:
### Input:
.. NOTE::
This version of :meth:`raw_datastream` is deprecated, and you
should update to the new :meth:`raw_datastream`. This version
is still available if you are using a version of Fedora
prior to 3.7 and need the a... |
def eval_string_value(self, element, value):
"""Evaluate parsed string.
Returns a list of current and delayed values.
"""
strval = ''
vals = []
for term in value:
if type(term) is ast.WhitespaceToken:
pass
elif type(term) is ast.... | Evaluate parsed string.
Returns a list of current and delayed values. | Below is the the instruction that describes the task:
### Input:
Evaluate parsed string.
Returns a list of current and delayed values.
### Response:
def eval_string_value(self, element, value):
"""Evaluate parsed string.
Returns a list of current and delayed values.
"""
st... |
def match_pattern(regex):
"""
Return a value check function which raises a ValueError if the value does
not match the supplied regular expression, see also `re.match`.
"""
prog = re.compile(regex)
def checker(v):
result = prog.match(v)
if result is None:
raise Value... | Return a value check function which raises a ValueError if the value does
not match the supplied regular expression, see also `re.match`. | Below is the the instruction that describes the task:
### Input:
Return a value check function which raises a ValueError if the value does
not match the supplied regular expression, see also `re.match`.
### Response:
def match_pattern(regex):
"""
Return a value check function which raises a ValueError ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.