code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def visitValueSetValue(self, ctx: ShExDocParser.ValueSetValueContext):
""" valueSetValue: iriRange | literalRange | languageRange |
'.' (iriExclusion+ | literalExclusion+ | languageExclusion+) """
if ctx.iriRange() or ctx.literalRange() or ctx.languageRange():
self.visitChildren... | valueSetValue: iriRange | literalRange | languageRange |
'.' (iriExclusion+ | literalExclusion+ | languageExclusion+) | Below is the the instruction that describes the task:
### Input:
valueSetValue: iriRange | literalRange | languageRange |
'.' (iriExclusion+ | literalExclusion+ | languageExclusion+)
### Response:
def visitValueSetValue(self, ctx: ShExDocParser.ValueSetValueContext):
""" valueSetValue: iriRang... |
def list_dir(root, prefix=False):
"""List all directories at a given root
Args:
root (str): Path to directory whose folders need to be listed
prefix (bool, optional): If true, prepends the path to each result, otherwise
only returns the name of the directories found
"""
root... | List all directories at a given root
Args:
root (str): Path to directory whose folders need to be listed
prefix (bool, optional): If true, prepends the path to each result, otherwise
only returns the name of the directories found | Below is the the instruction that describes the task:
### Input:
List all directories at a given root
Args:
root (str): Path to directory whose folders need to be listed
prefix (bool, optional): If true, prepends the path to each result, otherwise
only returns the name of the direct... |
def get_alias(self):
"""
Gets the alias for the table or the auto_alias if one is set.
If there isn't any kind of alias, None is returned.
:returns: The table alias, auto_alias, or None
:rtype: str or None
"""
alias = None
if self.alias:
alias... | Gets the alias for the table or the auto_alias if one is set.
If there isn't any kind of alias, None is returned.
:returns: The table alias, auto_alias, or None
:rtype: str or None | Below is the the instruction that describes the task:
### Input:
Gets the alias for the table or the auto_alias if one is set.
If there isn't any kind of alias, None is returned.
:returns: The table alias, auto_alias, or None
:rtype: str or None
### Response:
def get_alias(self):
"... |
def check_array(array, *args, **kwargs):
"""Validate inputs
Parameters
----------
accept_dask_array : bool, default True
accept_dask_dataframe : bool, default False
accept_unknown_chunks : bool, default False
For dask Arrays, whether to allow the `.chunks` attribute to contain
a... | Validate inputs
Parameters
----------
accept_dask_array : bool, default True
accept_dask_dataframe : bool, default False
accept_unknown_chunks : bool, default False
For dask Arrays, whether to allow the `.chunks` attribute to contain
any unknown values
accept_multiple_blocks : b... | Below is the the instruction that describes the task:
### Input:
Validate inputs
Parameters
----------
accept_dask_array : bool, default True
accept_dask_dataframe : bool, default False
accept_unknown_chunks : bool, default False
For dask Arrays, whether to allow the `.chunks` attribute... |
def get_icon(name, as_qicon=False):
"""Returns a `QPixmap` containing the given image, or a QIcon if `as_qicon`
is True"""
filename = name + ".png"
icon = icons.get(filename)
if not icon:
path = os.path.dirname(__file__)
path = os.path.join(path, "icons")
filepath = os.path.j... | Returns a `QPixmap` containing the given image, or a QIcon if `as_qicon`
is True | Below is the the instruction that describes the task:
### Input:
Returns a `QPixmap` containing the given image, or a QIcon if `as_qicon`
is True
### Response:
def get_icon(name, as_qicon=False):
"""Returns a `QPixmap` containing the given image, or a QIcon if `as_qicon`
is True"""
filename = name ... |
def export(self, name, columns, points):
"""Write the points to the Prometheus exporter using Gauge."""
logger.debug("Export {} stats to Prometheus exporter".format(name))
# Remove non number stats and convert all to float (for Boolean)
data = {k: float(v) for (k, v) in iteritems(dict(z... | Write the points to the Prometheus exporter using Gauge. | Below is the the instruction that describes the task:
### Input:
Write the points to the Prometheus exporter using Gauge.
### Response:
def export(self, name, columns, points):
"""Write the points to the Prometheus exporter using Gauge."""
logger.debug("Export {} stats to Prometheus exporter".forma... |
def dict_has_all_keys(self, keys):
"""
Create a boolean SArray by checking the keys of an SArray of
dictionaries. An element of the output SArray is True if the
corresponding input element's dictionary has all of the given keys.
Fails on SArrays whose data type is not ``dict``.
... | Create a boolean SArray by checking the keys of an SArray of
dictionaries. An element of the output SArray is True if the
corresponding input element's dictionary has all of the given keys.
Fails on SArrays whose data type is not ``dict``.
Parameters
----------
keys : li... | Below is the the instruction that describes the task:
### Input:
Create a boolean SArray by checking the keys of an SArray of
dictionaries. An element of the output SArray is True if the
corresponding input element's dictionary has all of the given keys.
Fails on SArrays whose data type is n... |
def allVariantAnnotationSets(self):
"""
Return an iterator over all variant annotation sets
in the data repo
"""
for dataset in self.getDatasets():
for variantSet in dataset.getVariantSets():
for vaSet in variantSet.getVariantAnnotationSets():
... | Return an iterator over all variant annotation sets
in the data repo | Below is the the instruction that describes the task:
### Input:
Return an iterator over all variant annotation sets
in the data repo
### Response:
def allVariantAnnotationSets(self):
"""
Return an iterator over all variant annotation sets
in the data repo
"""
for da... |
def lv_load_areas(self):
""" #TODO: description
"""
for lv_load_area in self._grid._graph.nodes():
if isinstance(lv_load_area, LVLoadAreaDing0):
if lv_load_area.ring == self:
yield lv_load_area | #TODO: description | Below is the the instruction that describes the task:
### Input:
#TODO: description
### Response:
def lv_load_areas(self):
""" #TODO: description
"""
for lv_load_area in self._grid._graph.nodes():
if isinstance(lv_load_area, LVLoadAreaDing0):
if lv_load_area.ring... |
def number(items):
"""Maps numbering onto given values"""
n = len(items)
if n == 0:
return items
places = str(int(math.log10(n) // 1 + 1))
format = '[{0[0]:' + str(int(places)) + 'd}] {0[1]}'
return map(
lambda x: format.format(x),
enumerate(items)
) | Maps numbering onto given values | Below is the the instruction that describes the task:
### Input:
Maps numbering onto given values
### Response:
def number(items):
"""Maps numbering onto given values"""
n = len(items)
if n == 0:
return items
places = str(int(math.log10(n) // 1 + 1))
format = '[{0[0]:' + str(int(places)... |
def get_entity(self, ilx_id: str) -> dict:
""" Gets full meta data (expect their annotations and relationships) from is ILX ID """
ilx_id = self.fix_ilx(ilx_id)
url = self.base_url + "ilx/search/identifier/{identifier}?key={api_key}".format(
identifier = ilx_id,
api_key =... | Gets full meta data (expect their annotations and relationships) from is ILX ID | Below is the the instruction that describes the task:
### Input:
Gets full meta data (expect their annotations and relationships) from is ILX ID
### Response:
def get_entity(self, ilx_id: str) -> dict:
""" Gets full meta data (expect their annotations and relationships) from is ILX ID """
ilx_id = ... |
def nfa_dot_importer(input_file: str) -> dict:
""" Imports a NFA from a DOT file.
Of .dot files are recognized the following attributes
• nodeX shape=doublecircle -> accepting node;
• nodeX root=true -> initial node;
• edgeX label="a" -> action in alphabet;
• fakeX style=invisi... | Imports a NFA from a DOT file.
Of .dot files are recognized the following attributes
• nodeX shape=doublecircle -> accepting node;
• nodeX root=true -> initial node;
• edgeX label="a" -> action in alphabet;
• fakeX style=invisible -> dummy invisible nodes pointing
t... | Below is the the instruction that describes the task:
### Input:
Imports a NFA from a DOT file.
Of .dot files are recognized the following attributes
• nodeX shape=doublecircle -> accepting node;
• nodeX root=true -> initial node;
• edgeX label="a" -> action in alphabet;
• fakeX ... |
def result(self, result):
"""
Query result post processing.
@param result: A query result.
@type result: L{sxbase.SchemaObject}
"""
if result is None:
log.debug('%s, not-found', self.ref)
return
if self.resolved:
result = result... | Query result post processing.
@param result: A query result.
@type result: L{sxbase.SchemaObject} | Below is the the instruction that describes the task:
### Input:
Query result post processing.
@param result: A query result.
@type result: L{sxbase.SchemaObject}
### Response:
def result(self, result):
"""
Query result post processing.
@param result: A query result.
... |
def schedule_to_proto_dicts(schedule: Schedule) -> Iterable[Dict]:
"""Convert a schedule into an iterable of proto dictionaries.
Args:
schedule: The schedule to convert to a proto dict. Must contain only
gates that can be cast to xmon gates.
Yields:
A proto dictionary correspon... | Convert a schedule into an iterable of proto dictionaries.
Args:
schedule: The schedule to convert to a proto dict. Must contain only
gates that can be cast to xmon gates.
Yields:
A proto dictionary corresponding to an Operation proto. | Below is the the instruction that describes the task:
### Input:
Convert a schedule into an iterable of proto dictionaries.
Args:
schedule: The schedule to convert to a proto dict. Must contain only
gates that can be cast to xmon gates.
Yields:
A proto dictionary corresponding ... |
def from_string(string):
"""
Construct an AdfKey object from the string.
Parameters
----------
string : str
A string.
Returns
-------
adfkey : AdfKey
An AdfKey object recovered from the string.
Raises
------
... | Construct an AdfKey object from the string.
Parameters
----------
string : str
A string.
Returns
-------
adfkey : AdfKey
An AdfKey object recovered from the string.
Raises
------
ValueError
Currently nested su... | Below is the the instruction that describes the task:
### Input:
Construct an AdfKey object from the string.
Parameters
----------
string : str
A string.
Returns
-------
adfkey : AdfKey
An AdfKey object recovered from the string.
Rai... |
def inverted(self):
"""Return the inverse of the transform."""
# This is a bit of hackery so that we can put a single "inverse"
# function here. If we just made "self._inverse_type" point to the class
# in question, it wouldn't be defined yet. This way, it's done at
# at runtime ... | Return the inverse of the transform. | Below is the the instruction that describes the task:
### Input:
Return the inverse of the transform.
### Response:
def inverted(self):
"""Return the inverse of the transform."""
# This is a bit of hackery so that we can put a single "inverse"
# function here. If we just made "self._inverse... |
def call_fan(tstat):
"""
Toggles the fan
"""
old_fan = tstat.fan
tstat.write({
'fan': not old_fan,
})
def restore():
tstat.write({
'fan': old_fan,
})
return restore | Toggles the fan | Below is the the instruction that describes the task:
### Input:
Toggles the fan
### Response:
def call_fan(tstat):
"""
Toggles the fan
"""
old_fan = tstat.fan
tstat.write({
'fan': not old_fan,
})
def restore():
tstat.write({
'fan': old_fan,
})
... |
def get_field_type(field):
"""
Returns field type/possible values.
"""
if isinstance(field, core_filters.MappedMultipleChoiceFilter):
return ' | '.join(['"%s"' % f for f in sorted(field.mapped_to_model)])
if isinstance(field, OrderingFilter) or isinstance(field, ChoiceFilter):
return... | Returns field type/possible values. | Below is the the instruction that describes the task:
### Input:
Returns field type/possible values.
### Response:
def get_field_type(field):
"""
Returns field type/possible values.
"""
if isinstance(field, core_filters.MappedMultipleChoiceFilter):
return ' | '.join(['"%s"' % f for f in sor... |
def kl_divergence(self, logits_q, logits_p):
"""
Categorical distribution KL divergence calculation
KL(Q || P) = sum Q_i log (Q_i / P_i)
When talking about logits this is:
sum exp(Q_i) * (Q_i - P_i)
"""
return (torch.exp(logits_q) * (logits_q - logits_p)).sum(1, k... | Categorical distribution KL divergence calculation
KL(Q || P) = sum Q_i log (Q_i / P_i)
When talking about logits this is:
sum exp(Q_i) * (Q_i - P_i) | Below is the the instruction that describes the task:
### Input:
Categorical distribution KL divergence calculation
KL(Q || P) = sum Q_i log (Q_i / P_i)
When talking about logits this is:
sum exp(Q_i) * (Q_i - P_i)
### Response:
def kl_divergence(self, logits_q, logits_p):
"""
... |
def delete_files_and_sync_sources(self, owner, id, name, **kwargs):
"""
Delete files
Delete one or more files from a dataset by their name, including files added via URL. **Batching** Note that the `name` parameter can be include multiple times in the query string, once for each file that ... | Delete files
Delete one or more files from a dataset by their name, including files added via URL. **Batching** Note that the `name` parameter can be include multiple times in the query string, once for each file that is to be deleted together in a single request.
This method makes a synchronous H... | Below is the the instruction that describes the task:
### Input:
Delete files
Delete one or more files from a dataset by their name, including files added via URL. **Batching** Note that the `name` parameter can be include multiple times in the query string, once for each file that is to be deleted to... |
def get_form_context(self, obj, ns=None):
"""Return a dict: form instance, action button, submit url...
Used by macro m_tags_form(entity)
"""
return {
"url": url_for("entity_tags.edit", object_id=obj.id),
"form": self.entity_tags_form(obj)(obj=obj, ns=ns),
... | Return a dict: form instance, action button, submit url...
Used by macro m_tags_form(entity) | Below is the the instruction that describes the task:
### Input:
Return a dict: form instance, action button, submit url...
Used by macro m_tags_form(entity)
### Response:
def get_form_context(self, obj, ns=None):
"""Return a dict: form instance, action button, submit url...
Used by macro... |
def _drag_col(self, event):
"""Continue dragging a column"""
x = self._dx + event.x # get dragged column new left x coordinate
self._visual_drag.place_configure(x=x) # update column preview position
# if one border of the dragged column is beyon the middle of the
# neighboring ... | Continue dragging a column | Below is the the instruction that describes the task:
### Input:
Continue dragging a column
### Response:
def _drag_col(self, event):
"""Continue dragging a column"""
x = self._dx + event.x # get dragged column new left x coordinate
self._visual_drag.place_configure(x=x) # update column p... |
def _generate_cfgnode(self, cfg_job, current_function_addr):
"""
Generate a CFGNode that starts at `cfg_job.addr`.
Since lifting machine code to IRSBs is slow, self._nodes is used as a cache of CFGNodes.
If the current architecture is ARM, this method will try to lift the block in the ... | Generate a CFGNode that starts at `cfg_job.addr`.
Since lifting machine code to IRSBs is slow, self._nodes is used as a cache of CFGNodes.
If the current architecture is ARM, this method will try to lift the block in the mode specified by the address
(determined by the parity of the address: e... | Below is the the instruction that describes the task:
### Input:
Generate a CFGNode that starts at `cfg_job.addr`.
Since lifting machine code to IRSBs is slow, self._nodes is used as a cache of CFGNodes.
If the current architecture is ARM, this method will try to lift the block in the mode specifi... |
def payload_element_name(element_name):
"""Class decorator generator for decorationg
`StanzaPayload` subclasses.
:Parameters:
- `element_name`: XML element qname handled by the class
:Types:
- `element_name`: `unicode`
"""
def decorator(klass):
"""The payload_element_nam... | Class decorator generator for decorationg
`StanzaPayload` subclasses.
:Parameters:
- `element_name`: XML element qname handled by the class
:Types:
- `element_name`: `unicode` | Below is the the instruction that describes the task:
### Input:
Class decorator generator for decorationg
`StanzaPayload` subclasses.
:Parameters:
- `element_name`: XML element qname handled by the class
:Types:
- `element_name`: `unicode`
### Response:
def payload_element_name(elemen... |
def _chi_lr(self,r, phi, nl,nr,beta):
"""
computes the generalized polar basis function in the convention of Massey&Refregier eqn 8
:param nl: left basis
:type nl: int
:param nr: right basis
:type nr: int
:param beta: beta --the characteristic scale typically cho... | computes the generalized polar basis function in the convention of Massey&Refregier eqn 8
:param nl: left basis
:type nl: int
:param nr: right basis
:type nr: int
:param beta: beta --the characteristic scale typically choosen to be close to the size of the object.
:type ... | Below is the the instruction that describes the task:
### Input:
computes the generalized polar basis function in the convention of Massey&Refregier eqn 8
:param nl: left basis
:type nl: int
:param nr: right basis
:type nr: int
:param beta: beta --the characteristic scale ty... |
def set_widgets(self):
"""Set widgets on the LayerMode tab."""
self.clear_further_steps()
# Set widgets
self.lblBandSelector.setText(tr(
'Please select which band that contains the data that you want to '
'use for this layer.'))
self.lstBands.clear()
... | Set widgets on the LayerMode tab. | Below is the the instruction that describes the task:
### Input:
Set widgets on the LayerMode tab.
### Response:
def set_widgets(self):
"""Set widgets on the LayerMode tab."""
self.clear_further_steps()
# Set widgets
self.lblBandSelector.setText(tr(
'Please select which ... |
def get_instance(self, payload):
"""
Build an instance of EngagementInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.studio.v1.flow.engagement.EngagementInstance
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance
"""
... | Build an instance of EngagementInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.studio.v1.flow.engagement.EngagementInstance
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance | Below is the the instruction that describes the task:
### Input:
Build an instance of EngagementInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.studio.v1.flow.engagement.EngagementInstance
:rtype: twilio.rest.studio.v1.flow.engagement.EngagementInstance
##... |
def process_values(self):
"""Takes a set of angles and converts them to the x,y,z coordinates in the internal prepresentation of the class, ready for plotting.
:param vals: the values that are being modelled."""
if self.padding>0:
channels = np.zeros((self.vals.shape[0], self.vals.... | Takes a set of angles and converts them to the x,y,z coordinates in the internal prepresentation of the class, ready for plotting.
:param vals: the values that are being modelled. | Below is the the instruction that describes the task:
### Input:
Takes a set of angles and converts them to the x,y,z coordinates in the internal prepresentation of the class, ready for plotting.
:param vals: the values that are being modelled.
### Response:
def process_values(self):
"""Takes a se... |
def import_styles(self, subs, overwrite=True):
"""
Merge in styles from other SSAFile.
Arguments:
subs (SSAFile): Subtitle file imported from.
overwrite (bool): On name conflict, use style from the other file
(default: True).
"""
if not i... | Merge in styles from other SSAFile.
Arguments:
subs (SSAFile): Subtitle file imported from.
overwrite (bool): On name conflict, use style from the other file
(default: True). | Below is the the instruction that describes the task:
### Input:
Merge in styles from other SSAFile.
Arguments:
subs (SSAFile): Subtitle file imported from.
overwrite (bool): On name conflict, use style from the other file
(default: True).
### Response:
def import_s... |
def bytes(self, count):
"""Returns a bytearray of length `count`. Works unaligned."""
if count < 0:
raise ValueError
# fast path
if self._bits == 0:
data = self._fileobj.read(count)
if len(data) != count:
raise BitReaderError("not eno... | Returns a bytearray of length `count`. Works unaligned. | Below is the the instruction that describes the task:
### Input:
Returns a bytearray of length `count`. Works unaligned.
### Response:
def bytes(self, count):
"""Returns a bytearray of length `count`. Works unaligned."""
if count < 0:
raise ValueError
# fast path
if se... |
def obfn_cns(self):
r"""Compute constraint violation measure :math:`\| P(\mathbf{y})
- \mathbf{y}\|_2`.
"""
Y = self.obfn_gvar()
return np.linalg.norm((self.Pcn(Y) - Y)) | r"""Compute constraint violation measure :math:`\| P(\mathbf{y})
- \mathbf{y}\|_2`. | Below is the the instruction that describes the task:
### Input:
r"""Compute constraint violation measure :math:`\| P(\mathbf{y})
- \mathbf{y}\|_2`.
### Response:
def obfn_cns(self):
r"""Compute constraint violation measure :math:`\| P(\mathbf{y})
- \mathbf{y}\|_2`.
"""
Y =... |
def add_module(self, ref, text, format=None,
expect_modulename=None, expect_revision=None,
expect_failure_error=True):
"""Parse a module text and add the module data to the context
`ref` is a string which is used to identify the source of
the text for... | Parse a module text and add the module data to the context
`ref` is a string which is used to identify the source of
the text for the user. used in error messages
`text` is the raw text data
`format` is one of 'yang' or 'yin'.
Returns the parsed and validated module on s... | Below is the the instruction that describes the task:
### Input:
Parse a module text and add the module data to the context
`ref` is a string which is used to identify the source of
the text for the user. used in error messages
`text` is the raw text data
`format` is one of '... |
def _strip_tag(tree, tag):
"""
Remove all tags that have the tag name ``tag``
"""
for el in tree.iter():
if el.tag == tag:
el.getparent().remove(el) | Remove all tags that have the tag name ``tag`` | Below is the the instruction that describes the task:
### Input:
Remove all tags that have the tag name ``tag``
### Response:
def _strip_tag(tree, tag):
"""
Remove all tags that have the tag name ``tag``
"""
for el in tree.iter():
if el.tag == tag:
el.getparent().remove(el) |
def writeProxy(self, obj):
"""
Encodes a proxied object to the stream.
@since: 0.6
"""
proxy = self.context.getProxyForObject(obj)
self.writeObject(proxy, is_proxy=True) | Encodes a proxied object to the stream.
@since: 0.6 | Below is the the instruction that describes the task:
### Input:
Encodes a proxied object to the stream.
@since: 0.6
### Response:
def writeProxy(self, obj):
"""
Encodes a proxied object to the stream.
@since: 0.6
"""
proxy = self.context.getProxyForObject(obj)
... |
def add_option(self, parser):
""" Add option group and all children options. """
group = parser.add_argument_group(self.name)
for stat in self.stats:
stat.add_option(group)
group.add_argument(
"--{0}".format(self.option), action="store_true", help="All above") | Add option group and all children options. | Below is the the instruction that describes the task:
### Input:
Add option group and all children options.
### Response:
def add_option(self, parser):
""" Add option group and all children options. """
group = parser.add_argument_group(self.name)
for stat in self.stats:
stat.a... |
def add_wikilink(self, title, href, **attrs):
"""
Add a Wiki link to the project and returns a :class:`WikiLink` object.
:param title: title of the :class:`WikiLink`
:param href: href of the :class:`WikiLink`
:param attrs: optional attributes for :class:`WikiLink`
"""
... | Add a Wiki link to the project and returns a :class:`WikiLink` object.
:param title: title of the :class:`WikiLink`
:param href: href of the :class:`WikiLink`
:param attrs: optional attributes for :class:`WikiLink` | Below is the the instruction that describes the task:
### Input:
Add a Wiki link to the project and returns a :class:`WikiLink` object.
:param title: title of the :class:`WikiLink`
:param href: href of the :class:`WikiLink`
:param attrs: optional attributes for :class:`WikiLink`
### Respons... |
def get_historical_klines(symbol, interval, start_str, end_str=None):
"""Get Historical Klines from Binance
See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/
If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
... | Get Historical Klines from Binance
See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/
If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
:param symbol: Name of symbol pair e.g BNBBTC
:type symbol: str
:p... | Below is the the instruction that describes the task:
### Input:
Get Historical Klines from Binance
See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/
If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
:para... |
def ReadHuntLogEntries(self,
hunt_id,
offset,
count,
with_substring=None,
cursor=None):
"""Reads hunt log entries of a given hunt using given query options."""
hunt_id_int = db_utils.Hunt... | Reads hunt log entries of a given hunt using given query options. | Below is the the instruction that describes the task:
### Input:
Reads hunt log entries of a given hunt using given query options.
### Response:
def ReadHuntLogEntries(self,
hunt_id,
offset,
count,
with_substring=No... |
def _list_dir(self, path):
"""returns absolute paths for all entries in a directory"""
try:
elements = [
os.path.join(path, x) for x in os.listdir(path)
] if os.path.isdir(path) else []
elements.sort()
except OSError:
elements = Non... | returns absolute paths for all entries in a directory | Below is the the instruction that describes the task:
### Input:
returns absolute paths for all entries in a directory
### Response:
def _list_dir(self, path):
"""returns absolute paths for all entries in a directory"""
try:
elements = [
os.path.join(path, x) for x in os... |
def clone(self, _, scene):
"""
Create a clone of this Frame into a new Screen.
:param _: ignored.
:param scene: The new Scene object to clone into.
"""
# Assume that the application creates a new set of Frames and so we need to match up the
# data from the old ob... | Create a clone of this Frame into a new Screen.
:param _: ignored.
:param scene: The new Scene object to clone into. | Below is the the instruction that describes the task:
### Input:
Create a clone of this Frame into a new Screen.
:param _: ignored.
:param scene: The new Scene object to clone into.
### Response:
def clone(self, _, scene):
"""
Create a clone of this Frame into a new Screen.
... |
def update_plan(self, updated_plan, project, id):
"""UpdatePlan.
Update the information for the specified plan
:param :class:`<UpdatePlan> <azure.devops.v5_0.work.models.UpdatePlan>` updated_plan: Plan definition to be updated
:param str project: Project ID or project name
:param... | UpdatePlan.
Update the information for the specified plan
:param :class:`<UpdatePlan> <azure.devops.v5_0.work.models.UpdatePlan>` updated_plan: Plan definition to be updated
:param str project: Project ID or project name
:param str id: Identifier of the plan
:rtype: :class:`<Plan... | Below is the the instruction that describes the task:
### Input:
UpdatePlan.
Update the information for the specified plan
:param :class:`<UpdatePlan> <azure.devops.v5_0.work.models.UpdatePlan>` updated_plan: Plan definition to be updated
:param str project: Project ID or project name
... |
def save_and_validate_logo(logo_stream, logo_filename, community_id):
"""Validate if communities logo is in limit size and save it."""
cfg = current_app.config
logos_bucket_id = cfg['COMMUNITIES_BUCKET_UUID']
logo_max_size = cfg['COMMUNITIES_LOGO_MAX_SIZE']
logos_bucket = Bucket.query.get(logos_buc... | Validate if communities logo is in limit size and save it. | Below is the the instruction that describes the task:
### Input:
Validate if communities logo is in limit size and save it.
### Response:
def save_and_validate_logo(logo_stream, logo_filename, community_id):
"""Validate if communities logo is in limit size and save it."""
cfg = current_app.config
logo... |
def Reset(self):
"""Resets the internal state of the analyzer."""
hasher_names = hashers_manager.HashersManager.GetHasherNamesFromString(
self._hasher_names_string)
self._hashers = hashers_manager.HashersManager.GetHashers(hasher_names) | Resets the internal state of the analyzer. | Below is the the instruction that describes the task:
### Input:
Resets the internal state of the analyzer.
### Response:
def Reset(self):
"""Resets the internal state of the analyzer."""
hasher_names = hashers_manager.HashersManager.GetHasherNamesFromString(
self._hasher_names_string)
self._ha... |
def fetch(url, dest, force=False):
"""Retrieve data from an url and store it into dest.
Parameters
----------
url: str
Link to the remote data
dest: str
Path where the file must be stored
force: bool (default=False)
Overwrite if the file exists
Returns
-------
... | Retrieve data from an url and store it into dest.
Parameters
----------
url: str
Link to the remote data
dest: str
Path where the file must be stored
force: bool (default=False)
Overwrite if the file exists
Returns
-------
cached: bool
True if the file a... | Below is the the instruction that describes the task:
### Input:
Retrieve data from an url and store it into dest.
Parameters
----------
url: str
Link to the remote data
dest: str
Path where the file must be stored
force: bool (default=False)
Overwrite if the file exists... |
def blocks2numList(blocks, n):
"""inverse function of numList2blocks."""
toProcess = copy.copy(blocks)
returnList = []
for numBlock in toProcess:
inner = []
for i in range(0, n):
inner.append(numBlock % 256)
numBlock >>= 8
inner.reverse()
returnLis... | inverse function of numList2blocks. | Below is the the instruction that describes the task:
### Input:
inverse function of numList2blocks.
### Response:
def blocks2numList(blocks, n):
"""inverse function of numList2blocks."""
toProcess = copy.copy(blocks)
returnList = []
for numBlock in toProcess:
inner = []
for i in ra... |
def move_datetime_week(dt, direction, num_shifts):
"""
Move datetime 1 week in the chosen direction.
unit is a no-op, to keep the API the same as the day case
"""
delta = relativedelta(weeks=+num_shifts)
return _move_datetime(dt, direction, delta) | Move datetime 1 week in the chosen direction.
unit is a no-op, to keep the API the same as the day case | Below is the the instruction that describes the task:
### Input:
Move datetime 1 week in the chosen direction.
unit is a no-op, to keep the API the same as the day case
### Response:
def move_datetime_week(dt, direction, num_shifts):
"""
Move datetime 1 week in the chosen direction.
unit is a no-op... |
def validate_response_type(self, client_id, response_type, client, request,
*args, **kwargs):
"""Ensure client is authorized to use the response type requested.
It will allow any of the two (`code`, `token`) response types by
default. Implemented `allowed_response... | Ensure client is authorized to use the response type requested.
It will allow any of the two (`code`, `token`) response types by
default. Implemented `allowed_response_types` for client object
to authorize the request. | Below is the the instruction that describes the task:
### Input:
Ensure client is authorized to use the response type requested.
It will allow any of the two (`code`, `token`) response types by
default. Implemented `allowed_response_types` for client object
to authorize the request.
### Res... |
def get_deployment_by_slot(self, service_name, deployment_slot):
'''
Returns configuration information, status, and system properties for
a deployment.
service_name:
Name of the hosted service.
deployment_slot:
The environment to which the hosted service ... | Returns configuration information, status, and system properties for
a deployment.
service_name:
Name of the hosted service.
deployment_slot:
The environment to which the hosted service is deployed. Valid
values are: staging, production | Below is the the instruction that describes the task:
### Input:
Returns configuration information, status, and system properties for
a deployment.
service_name:
Name of the hosted service.
deployment_slot:
The environment to which the hosted service is deployed. Val... |
def wheel_delta_discrete(self):
"""The delta for the wheel in discrete steps (e.g. wheel clicks) and
whether it has changed in this event.
Returns:
(int, bool): The delta of the wheel, in discrete steps, compared to
the last event and whether it has changed.
"""
delta = self._libinput. \
libinput_... | The delta for the wheel in discrete steps (e.g. wheel clicks) and
whether it has changed in this event.
Returns:
(int, bool): The delta of the wheel, in discrete steps, compared to
the last event and whether it has changed. | Below is the the instruction that describes the task:
### Input:
The delta for the wheel in discrete steps (e.g. wheel clicks) and
whether it has changed in this event.
Returns:
(int, bool): The delta of the wheel, in discrete steps, compared to
the last event and whether it has changed.
### Response:
d... |
def set_nodes_vlan(site, nodes, interface, vlan_id):
"""Set the interface of the nodes in a specific vlan.
It is assumed that the same interface name is available on the node.
Args:
site(str): site to consider
nodes(list): nodes to consider
interface(str): the network interface to ... | Set the interface of the nodes in a specific vlan.
It is assumed that the same interface name is available on the node.
Args:
site(str): site to consider
nodes(list): nodes to consider
interface(str): the network interface to put in the vlan
vlan_id(str): the id of the vlan | Below is the the instruction that describes the task:
### Input:
Set the interface of the nodes in a specific vlan.
It is assumed that the same interface name is available on the node.
Args:
site(str): site to consider
nodes(list): nodes to consider
interface(str): the network inte... |
def connection_made(self, transport: asyncio.BaseTransport) -> None:
"""
Configure write buffer limits.
The high-water limit is defined by ``self.write_limit``.
The low-water limit currently defaults to ``self.write_limit // 4`` in
:meth:`~asyncio.WriteTransport.set_write_buffe... | Configure write buffer limits.
The high-water limit is defined by ``self.write_limit``.
The low-water limit currently defaults to ``self.write_limit // 4`` in
:meth:`~asyncio.WriteTransport.set_write_buffer_limits`, which should
be all right for reasonable use cases of this library.
... | Below is the the instruction that describes the task:
### Input:
Configure write buffer limits.
The high-water limit is defined by ``self.write_limit``.
The low-water limit currently defaults to ``self.write_limit // 4`` in
:meth:`~asyncio.WriteTransport.set_write_buffer_limits`, which sho... |
def superreload(module, reload=reload, old_objects={}):
"""Enhanced version of the builtin reload function.
superreload remembers objects previously in the module, and
- upgrades the class dictionary of every old class in the module
- upgrades the code object of every old function and method
- cle... | Enhanced version of the builtin reload function.
superreload remembers objects previously in the module, and
- upgrades the class dictionary of every old class in the module
- upgrades the code object of every old function and method
- clears the module's namespace before reloading | Below is the the instruction that describes the task:
### Input:
Enhanced version of the builtin reload function.
superreload remembers objects previously in the module, and
- upgrades the class dictionary of every old class in the module
- upgrades the code object of every old function and method
... |
def _run_cell_text(self, text, line):
"""Run cell code in the console.
Cell code is run in the console by copying it to the console if
`self.run_cell_copy` is ``True`` otherwise by using the `run_cell`
function.
Parameters
----------
text : str
... | Run cell code in the console.
Cell code is run in the console by copying it to the console if
`self.run_cell_copy` is ``True`` otherwise by using the `run_cell`
function.
Parameters
----------
text : str
The code in the cell as a string.
li... | Below is the the instruction that describes the task:
### Input:
Run cell code in the console.
Cell code is run in the console by copying it to the console if
`self.run_cell_copy` is ``True`` otherwise by using the `run_cell`
function.
Parameters
----------
... |
def select_neighbors_by_layer(docgraph, node, layer, data=False):
"""
Get all neighboring nodes belonging to (any of) the given layer(s),
A neighboring node is a node that the given node connects to with an
outgoing edge.
Parameters
----------
docgraph : DiscourseDocumentGraph
docum... | Get all neighboring nodes belonging to (any of) the given layer(s),
A neighboring node is a node that the given node connects to with an
outgoing edge.
Parameters
----------
docgraph : DiscourseDocumentGraph
document graph from which the nodes will be extracted
layer : str or collection... | Below is the the instruction that describes the task:
### Input:
Get all neighboring nodes belonging to (any of) the given layer(s),
A neighboring node is a node that the given node connects to with an
outgoing edge.
Parameters
----------
docgraph : DiscourseDocumentGraph
document graph... |
def analytics(account=None, *args, **kwargs):
"""
Simple Google Analytics integration.
First looks for an ``account`` parameter. If not supplied, uses
Django ``GOOGLE_ANALYTICS_ACCOUNT`` setting. If account not set,
raises ``TemplateSyntaxError``.
:param account:
Google Analytics acco... | Simple Google Analytics integration.
First looks for an ``account`` parameter. If not supplied, uses
Django ``GOOGLE_ANALYTICS_ACCOUNT`` setting. If account not set,
raises ``TemplateSyntaxError``.
:param account:
Google Analytics account id to be used. | Below is the the instruction that describes the task:
### Input:
Simple Google Analytics integration.
First looks for an ``account`` parameter. If not supplied, uses
Django ``GOOGLE_ANALYTICS_ACCOUNT`` setting. If account not set,
raises ``TemplateSyntaxError``.
:param account:
Google Ana... |
def vol_tetra(vt1, vt2, vt3, vt4):
"""
Calculate the volume of a tetrahedron, given the four vertices of vt1,
vt2, vt3 and vt4.
Args:
vt1 (array-like): coordinates of vertex 1.
vt2 (array-like): coordinates of vertex 2.
vt3 (array-like): coordinates of vertex 3.
vt4 (arra... | Calculate the volume of a tetrahedron, given the four vertices of vt1,
vt2, vt3 and vt4.
Args:
vt1 (array-like): coordinates of vertex 1.
vt2 (array-like): coordinates of vertex 2.
vt3 (array-like): coordinates of vertex 3.
vt4 (array-like): coordinates of vertex 4.
Returns:
... | Below is the the instruction that describes the task:
### Input:
Calculate the volume of a tetrahedron, given the four vertices of vt1,
vt2, vt3 and vt4.
Args:
vt1 (array-like): coordinates of vertex 1.
vt2 (array-like): coordinates of vertex 2.
vt3 (array-like): coordinates of verte... |
def set_extra_info(self, username, extra_info):
"""Set extra info for the given user.
Raise a ServerError if an error occurs in the request process.
@param username The username for the user to update.
@param info The extra info as a JSON encoded string, or as a Python
dict... | Set extra info for the given user.
Raise a ServerError if an error occurs in the request process.
@param username The username for the user to update.
@param info The extra info as a JSON encoded string, or as a Python
dictionary like object. | Below is the the instruction that describes the task:
### Input:
Set extra info for the given user.
Raise a ServerError if an error occurs in the request process.
@param username The username for the user to update.
@param info The extra info as a JSON encoded string, or as a Python
... |
def multiple_sources(stmt):
'''Return True if statement is supported by multiple sources.
Note: this is currently not used and replaced by BeliefEngine score cutoff
'''
sources = list(set([e.source_api for e in stmt.evidence]))
if len(sources) > 1:
return True
return False | Return True if statement is supported by multiple sources.
Note: this is currently not used and replaced by BeliefEngine score cutoff | Below is the the instruction that describes the task:
### Input:
Return True if statement is supported by multiple sources.
Note: this is currently not used and replaced by BeliefEngine score cutoff
### Response:
def multiple_sources(stmt):
'''Return True if statement is supported by multiple sources.
... |
def add_javascripts(self, *js_files):
"""add javascripts files in HTML body"""
# create the script tag if don't exists
if self.main_soup.script is None:
script_tag = self.main_soup.new_tag('script')
self.main_soup.body.append(script_tag)
for js_file in js_files:
... | add javascripts files in HTML body | Below is the the instruction that describes the task:
### Input:
add javascripts files in HTML body
### Response:
def add_javascripts(self, *js_files):
"""add javascripts files in HTML body"""
# create the script tag if don't exists
if self.main_soup.script is None:
script_tag =... |
def write_sequences_to_fasta(path, seqs):
"""
Create a FASTA file listing the given sequences.
Arguments
=========
path: str or pathlib.Path
The name of the file to create.
seqs: dict
A mapping of names to sequences, which can be either protein or DNA.
"""
from Bio impo... | Create a FASTA file listing the given sequences.
Arguments
=========
path: str or pathlib.Path
The name of the file to create.
seqs: dict
A mapping of names to sequences, which can be either protein or DNA. | Below is the the instruction that describes the task:
### Input:
Create a FASTA file listing the given sequences.
Arguments
=========
path: str or pathlib.Path
The name of the file to create.
seqs: dict
A mapping of names to sequences, which can be either protein or DNA.
### Respon... |
def patch(self, request, format=None):
"""
Update an existing Channel
"""
data = request.data.copy()
# Get chat type record
try:
ct = ChatType.objects.get(id=data.pop("chat_type"))
data["chat_type"] = ct
except ChatType.DoesNotExist:
... | Update an existing Channel | Below is the the instruction that describes the task:
### Input:
Update an existing Channel
### Response:
def patch(self, request, format=None):
"""
Update an existing Channel
"""
data = request.data.copy()
# Get chat type record
try:
ct = ChatType.objec... |
def business_hours_schedule_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/schedules#create-a-schedule"
api_path = "/api/v2/business_hours/schedules.json"
return self.call(api_path, method="POST", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/schedules#create-a-schedule | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/schedules#create-a-schedule
### Response:
def business_hours_schedule_create(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/schedules#create-a-schedule"
api_pa... |
def filesavebox(msg=None, title=None, argInitialFile=None):
"""Original doc: A file to get the name of a file to save.
Returns the name of a file, or None if user chose to cancel.
if argInitialFile contains a valid filename, the dialog will
be positioned at that file when it appears.
... | Original doc: A file to get the name of a file to save.
Returns the name of a file, or None if user chose to cancel.
if argInitialFile contains a valid filename, the dialog will
be positioned at that file when it appears. | Below is the the instruction that describes the task:
### Input:
Original doc: A file to get the name of a file to save.
Returns the name of a file, or None if user chose to cancel.
if argInitialFile contains a valid filename, the dialog will
be positioned at that file when it appears.
### ... |
def badge_label(self, badge):
'''Display the badge label for a given kind'''
kind = badge.kind if isinstance(badge, Badge) else badge
return self.__badges__[kind] | Display the badge label for a given kind | Below is the the instruction that describes the task:
### Input:
Display the badge label for a given kind
### Response:
def badge_label(self, badge):
'''Display the badge label for a given kind'''
kind = badge.kind if isinstance(badge, Badge) else badge
return self.__badges__[kind] |
def verify_param(self, param, must=[], r=None):
'''return Code.ARGUMENT_MISSING if every key in must not found in param'''
if APIKEY not in param:
param[APIKEY] = self.apikey()
r = Result() if r is None else r
for p in must:
if p not in param:
r.c... | return Code.ARGUMENT_MISSING if every key in must not found in param | Below is the the instruction that describes the task:
### Input:
return Code.ARGUMENT_MISSING if every key in must not found in param
### Response:
def verify_param(self, param, must=[], r=None):
'''return Code.ARGUMENT_MISSING if every key in must not found in param'''
if APIKEY not in param:
... |
def parents(self, lhs, rhs):
"""Find nodes in rhs which have parents in lhs."""
return [node for node in rhs if node.parent in lhs] | Find nodes in rhs which have parents in lhs. | Below is the the instruction that describes the task:
### Input:
Find nodes in rhs which have parents in lhs.
### Response:
def parents(self, lhs, rhs):
"""Find nodes in rhs which have parents in lhs."""
return [node for node in rhs if node.parent in lhs] |
def _extract_hemispheric_difference(image, mask = slice(None), sigma_active = 7, sigma_reference = 7, cut_plane = 0, voxelspacing = None):
"""
Internal, single-image version of `hemispheric_difference`.
"""
# constants
INTERPOLATION_RANGE = int(10) # how many neighbouring values to take into account... | Internal, single-image version of `hemispheric_difference`. | Below is the the instruction that describes the task:
### Input:
Internal, single-image version of `hemispheric_difference`.
### Response:
def _extract_hemispheric_difference(image, mask = slice(None), sigma_active = 7, sigma_reference = 7, cut_plane = 0, voxelspacing = None):
"""
Internal, single-image ve... |
def get_table_location(self, database_name, table_name):
"""
Get the physical location of the table
:param database_name: Name of hive database (schema) @table belongs to
:type database_name: str
:param table_name: Name of hive table
:type table_name: str
:return... | Get the physical location of the table
:param database_name: Name of hive database (schema) @table belongs to
:type database_name: str
:param table_name: Name of hive table
:type table_name: str
:return: str | Below is the the instruction that describes the task:
### Input:
Get the physical location of the table
:param database_name: Name of hive database (schema) @table belongs to
:type database_name: str
:param table_name: Name of hive table
:type table_name: str
:return: str
##... |
def as_dict(self):
"""
Bson-serializable dict representation of the MultiWeightsChemenvStrategy object.
:return: Bson-serializable dict representation of the MultiWeightsChemenvStrategy object.
"""
return {"@module": self.__class__.__module__,
"@class": self.__cla... | Bson-serializable dict representation of the MultiWeightsChemenvStrategy object.
:return: Bson-serializable dict representation of the MultiWeightsChemenvStrategy object. | Below is the the instruction that describes the task:
### Input:
Bson-serializable dict representation of the MultiWeightsChemenvStrategy object.
:return: Bson-serializable dict representation of the MultiWeightsChemenvStrategy object.
### Response:
def as_dict(self):
"""
Bson-serializable ... |
def execute(self, input_data):
''' Execute the PEIndicators worker '''
raw_bytes = input_data['sample']['raw_bytes']
# Analyze the output of pefile for any anomalous conditions.
# Have the PE File module process the file
try:
self.pefile_handle = pefile.PE(data=raw_b... | Execute the PEIndicators worker | Below is the the instruction that describes the task:
### Input:
Execute the PEIndicators worker
### Response:
def execute(self, input_data):
''' Execute the PEIndicators worker '''
raw_bytes = input_data['sample']['raw_bytes']
# Analyze the output of pefile for any anomalous conditions.
... |
def preemptable(self):
"""
Whether the job can be run on a preemptable node.
"""
if self._preemptable is not None:
return self._preemptable
elif self._config is not None:
return self._config.defaultPreemptable
else:
raise AttributeError... | Whether the job can be run on a preemptable node. | Below is the the instruction that describes the task:
### Input:
Whether the job can be run on a preemptable node.
### Response:
def preemptable(self):
"""
Whether the job can be run on a preemptable node.
"""
if self._preemptable is not None:
return self._preemptable
... |
def addSubprocess(self, fds, name, factory):
"""
Public method for _addSubprocess.
Wraps reactor.adoptStreamConnection in
a simple DeferredLock to guarantee
workers play well together.
"""
self._lock.run(self._addSubprocess, self, fds, name, factory) | Public method for _addSubprocess.
Wraps reactor.adoptStreamConnection in
a simple DeferredLock to guarantee
workers play well together. | Below is the the instruction that describes the task:
### Input:
Public method for _addSubprocess.
Wraps reactor.adoptStreamConnection in
a simple DeferredLock to guarantee
workers play well together.
### Response:
def addSubprocess(self, fds, name, factory):
"""
Public met... |
def after_log(logger, log_level, sec_format="%0.3f"):
"""After call strategy that logs to some logger the finished attempt."""
log_tpl = ("Finished call to '%s' after " + str(sec_format) + "(s), "
"this was the %s time calling it.")
def log_it(retry_state):
logger.log(log_level, log_... | After call strategy that logs to some logger the finished attempt. | Below is the the instruction that describes the task:
### Input:
After call strategy that logs to some logger the finished attempt.
### Response:
def after_log(logger, log_level, sec_format="%0.3f"):
"""After call strategy that logs to some logger the finished attempt."""
log_tpl = ("Finished call to '%s' ... |
def read_follower_file(fname, min_followers=0, max_followers=1e10, blacklist=set()):
""" Read a file of follower information and return a dictionary mapping screen_name to a set of follower ids. """
result = {}
with open(fname, 'rt') as f:
for line in f:
parts = line.split()
... | Read a file of follower information and return a dictionary mapping screen_name to a set of follower ids. | Below is the the instruction that describes the task:
### Input:
Read a file of follower information and return a dictionary mapping screen_name to a set of follower ids.
### Response:
def read_follower_file(fname, min_followers=0, max_followers=1e10, blacklist=set()):
""" Read a file of follower information a... |
def _add_to_batch_list(self, TX, payment):
"""
Method to add a transaction to the batch list. The correct batch will
be determined by the payment dict and the batch will be created if
not existant. This will also add the payment amount to the respective
batch total.
"""
... | Method to add a transaction to the batch list. The correct batch will
be determined by the payment dict and the batch will be created if
not existant. This will also add the payment amount to the respective
batch total. | Below is the the instruction that describes the task:
### Input:
Method to add a transaction to the batch list. The correct batch will
be determined by the payment dict and the batch will be created if
not existant. This will also add the payment amount to the respective
batch total.
### Res... |
def _deserialize_audience(audience_map):
""" Helper method to de-serialize and populate audience map with the condition list and structure.
Args:
audience_map: Dict mapping audience ID to audience object.
Returns:
Dict additionally consisting of condition list and structure on every audience o... | Helper method to de-serialize and populate audience map with the condition list and structure.
Args:
audience_map: Dict mapping audience ID to audience object.
Returns:
Dict additionally consisting of condition list and structure on every audience object. | Below is the the instruction that describes the task:
### Input:
Helper method to de-serialize and populate audience map with the condition list and structure.
Args:
audience_map: Dict mapping audience ID to audience object.
Returns:
Dict additionally consisting of condition list and structure... |
def get_context_from_cmdln(args, desc="Run scriptworker"):
"""Create a Context object from args.
Args:
args (list): the commandline args. Generally sys.argv
Returns:
tuple: ``scriptworker.context.Context`` with populated config, and
credentials frozendict
"""
context ... | Create a Context object from args.
Args:
args (list): the commandline args. Generally sys.argv
Returns:
tuple: ``scriptworker.context.Context`` with populated config, and
credentials frozendict | Below is the the instruction that describes the task:
### Input:
Create a Context object from args.
Args:
args (list): the commandline args. Generally sys.argv
Returns:
tuple: ``scriptworker.context.Context`` with populated config, and
credentials frozendict
### Response:
def... |
def infos(self, type=None, failed=False):
"""Get infos that originate from this node.
Type must be a subclass of :class:`~dallinger.models.Info`, the default is
``Info``. Failed can be True, False or "all".
"""
if type is None:
type = Info
if not issubclass... | Get infos that originate from this node.
Type must be a subclass of :class:`~dallinger.models.Info`, the default is
``Info``. Failed can be True, False or "all". | Below is the the instruction that describes the task:
### Input:
Get infos that originate from this node.
Type must be a subclass of :class:`~dallinger.models.Info`, the default is
``Info``. Failed can be True, False or "all".
### Response:
def infos(self, type=None, failed=False):
"""Get ... |
def _verify_shape_bounds(shape, bounds):
"""Verify that shape corresponds to bounds apect ratio."""
if not isinstance(shape, (tuple, list)) or len(shape) != 2:
raise TypeError(
"shape must be a tuple or list with two elements: %s" % str(shape)
)
if not isinstance(bounds, (tuple, ... | Verify that shape corresponds to bounds apect ratio. | Below is the the instruction that describes the task:
### Input:
Verify that shape corresponds to bounds apect ratio.
### Response:
def _verify_shape_bounds(shape, bounds):
"""Verify that shape corresponds to bounds apect ratio."""
if not isinstance(shape, (tuple, list)) or len(shape) != 2:
raise T... |
def client_pause(self, timeout):
"""Stop processing commands from clients for *timeout* milliseconds.
:raises TypeError: if timeout is not int
:raises ValueError: if timeout is less than 0
"""
if not isinstance(timeout, int):
raise TypeError("timeout argument must be... | Stop processing commands from clients for *timeout* milliseconds.
:raises TypeError: if timeout is not int
:raises ValueError: if timeout is less than 0 | Below is the the instruction that describes the task:
### Input:
Stop processing commands from clients for *timeout* milliseconds.
:raises TypeError: if timeout is not int
:raises ValueError: if timeout is less than 0
### Response:
def client_pause(self, timeout):
"""Stop processing comman... |
def is_reversible(T, mu=None, tol=1e-12):
r"""Check reversibility of the given transition matrix.
Parameters
----------
T : (M, M) ndarray or scipy.sparse matrix
Transition matrix
mu : (M,) ndarray (optional)
Test reversibility with respect to this vector
tol : float (optional)... | r"""Check reversibility of the given transition matrix.
Parameters
----------
T : (M, M) ndarray or scipy.sparse matrix
Transition matrix
mu : (M,) ndarray (optional)
Test reversibility with respect to this vector
tol : float (optional)
Floating point tolerance to check wit... | Below is the the instruction that describes the task:
### Input:
r"""Check reversibility of the given transition matrix.
Parameters
----------
T : (M, M) ndarray or scipy.sparse matrix
Transition matrix
mu : (M,) ndarray (optional)
Test reversibility with respect to this vector
... |
def _record(self, value, rank, delta, successor):
"""Catalogs a sample."""
self._observations += 1
self._items += 1
return _Sample(value, rank, delta, successor) | Catalogs a sample. | Below is the the instruction that describes the task:
### Input:
Catalogs a sample.
### Response:
def _record(self, value, rank, delta, successor):
"""Catalogs a sample."""
self._observations += 1
self._items += 1
return _Sample(value, rank, delta, successor) |
def location_once_scrolled_into_view(self):
"""THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover
where on the screen an element is so that we can click it. This method
should cause the element to be scrolled into view.
Returns the top lefthand corner location on the screen,... | THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover
where on the screen an element is so that we can click it. This method
should cause the element to be scrolled into view.
Returns the top lefthand corner location on the screen, or ``None`` if
the element is not visible. | Below is the the instruction that describes the task:
### Input:
THIS PROPERTY MAY CHANGE WITHOUT WARNING. Use this to discover
where on the screen an element is so that we can click it. This method
should cause the element to be scrolled into view.
Returns the top lefthand corner location ... |
def maximum_vline_bundle(self, x0, y0, y1):
"""Compute a maximum set of vertical lines in the unit cells ``(x0,y)``
for :math:`y0 \leq y \leq y1`.
INPUTS:
y0,x0,x1: int
OUTPUT:
list of lists of qubits
"""
y_range = range(y1, y0 - 1, -1) if y0 < ... | Compute a maximum set of vertical lines in the unit cells ``(x0,y)``
for :math:`y0 \leq y \leq y1`.
INPUTS:
y0,x0,x1: int
OUTPUT:
list of lists of qubits | Below is the the instruction that describes the task:
### Input:
Compute a maximum set of vertical lines in the unit cells ``(x0,y)``
for :math:`y0 \leq y \leq y1`.
INPUTS:
y0,x0,x1: int
OUTPUT:
list of lists of qubits
### Response:
def maximum_vline_bundle(self, x... |
def create(self, name, *args, **kwargs):
"""
Create an instance of this resource type.
"""
resource_name = self._resource_name(name)
log.info(
"Creating {} '{}'...".format(self._model_name, resource_name))
resource = self.collection.create(*args, name=resource... | Create an instance of this resource type. | Below is the the instruction that describes the task:
### Input:
Create an instance of this resource type.
### Response:
def create(self, name, *args, **kwargs):
"""
Create an instance of this resource type.
"""
resource_name = self._resource_name(name)
log.info(
... |
def _parse_protocol_port(name, protocol, port):
'''
.. versionadded:: 2019.2.0
Validates and parses the protocol and port/port range from the name
if both protocol and port are not provided.
If the name is in a valid format, the protocol and port are ignored if provided
Examples: tcp/8080 or ... | .. versionadded:: 2019.2.0
Validates and parses the protocol and port/port range from the name
if both protocol and port are not provided.
If the name is in a valid format, the protocol and port are ignored if provided
Examples: tcp/8080 or udp/20-21 | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2019.2.0
Validates and parses the protocol and port/port range from the name
if both protocol and port are not provided.
If the name is in a valid format, the protocol and port are ignored if provided
Examples: tcp... |
def _is_active_model(cls, model):
""" Check is model app name is in list of INSTALLED_APPS """
# We need to use such tricky way to check because of inconsistent apps names:
# some apps are included in format "<module_name>.<app_name>" like "waldur_core.openstack"
# other apps are include... | Check is model app name is in list of INSTALLED_APPS | Below is the the instruction that describes the task:
### Input:
Check is model app name is in list of INSTALLED_APPS
### Response:
def _is_active_model(cls, model):
""" Check is model app name is in list of INSTALLED_APPS """
# We need to use such tricky way to check because of inconsistent apps n... |
def read_text(self, name):
"""Read text string from cur_dir/name using open_readable()."""
with self.open_readable(name) as fp:
res = fp.read() # StringIO or file object
# try:
# res = fp.getvalue() # StringIO returned by FtpTarget
# except Attribute... | Read text string from cur_dir/name using open_readable(). | Below is the the instruction that describes the task:
### Input:
Read text string from cur_dir/name using open_readable().
### Response:
def read_text(self, name):
"""Read text string from cur_dir/name using open_readable()."""
with self.open_readable(name) as fp:
res = fp.read() # Str... |
def show_help(command_name: str = None, raw_args: str = '') -> Response:
""" Prints the basic command help to the console """
response = Response()
cmds = fetch()
if command_name and command_name in cmds:
parser, result = parse.get_parser(
cmds[command_name],
parse.expl... | Prints the basic command help to the console | Below is the the instruction that describes the task:
### Input:
Prints the basic command help to the console
### Response:
def show_help(command_name: str = None, raw_args: str = '') -> Response:
""" Prints the basic command help to the console """
response = Response()
cmds = fetch()
if command... |
def create_setter(func, attrs):
"""Create the __set__ method for the descriptor."""
def _set(self, instance, value, name=None):
args = [getattr(self, attr) for attr in attrs]
if not func(value, *args):
raise ValueError(self.err_msg(instance, value))
return _set | Create the __set__ method for the descriptor. | Below is the the instruction that describes the task:
### Input:
Create the __set__ method for the descriptor.
### Response:
def create_setter(func, attrs):
"""Create the __set__ method for the descriptor."""
def _set(self, instance, value, name=None):
args = [getattr(self, attr) for attr in attrs]... |
def experimentVaryingSynapseSampling(expParams,
sampleSizeDistalList,
sampleSizeProximalList):
"""
Test multi-column convergence with varying amount of proximal/distal sampling
:return:
"""
numRpts = 20
df = None
args = []
for sa... | Test multi-column convergence with varying amount of proximal/distal sampling
:return: | Below is the the instruction that describes the task:
### Input:
Test multi-column convergence with varying amount of proximal/distal sampling
:return:
### Response:
def experimentVaryingSynapseSampling(expParams,
sampleSizeDistalList,
sa... |
def standardize_cell(cell,
to_primitive=False,
no_idealize=False,
symprec=1e-5,
angle_tolerance=-1.0):
"""Return standardized cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
... | Return standardized cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
to_primitive:
bool: If True, the standardized primitive cell is created.
no_idealize:
bool: If True, it is disabled to idealize lengths and angles of
... | Below is the the instruction that describes the task:
### Input:
Return standardized cell.
Args:
cell, symprec, angle_tolerance:
See the docstring of get_symmetry.
to_primitive:
bool: If True, the standardized primitive cell is created.
no_idealize:
b... |
def generate_defect_structure(self, supercell=(1, 1, 1)):
"""
Returns Defective Vacancy structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix
"""
defect_structure = self.bulk_structure.copy()
... | Returns Defective Vacancy structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix | Below is the the instruction that describes the task:
### Input:
Returns Defective Vacancy structure, decorated with charge
Args:
supercell (int, [3x1], or [[]] (3x3)): supercell integer, vector, or scaling matrix
### Response:
def generate_defect_structure(self, supercell=(1, 1, 1)):
"... |
def get_property(elt, key, ctx=None):
"""Get elt key property.
:param elt: property elt. Not None methods.
:param key: property key to get from elt.
:param ctx: elt ctx from where get properties. Equals elt if None. It
allows to get function properties related to a class or instance if
... | Get elt key property.
:param elt: property elt. Not None methods.
:param key: property key to get from elt.
:param ctx: elt ctx from where get properties. Equals elt if None. It
allows to get function properties related to a class or instance if
related function is defined in base class.
... | Below is the the instruction that describes the task:
### Input:
Get elt key property.
:param elt: property elt. Not None methods.
:param key: property key to get from elt.
:param ctx: elt ctx from where get properties. Equals elt if None. It
allows to get function properties related to a class... |
def max_projection(self, axis=2):
"""
Compute maximum projections of images along a dimension.
Parameters
----------
axis : int, optional, default = 2
Which axis to compute projection along.
"""
if axis >= size(self.value_shape):
raise Exc... | Compute maximum projections of images along a dimension.
Parameters
----------
axis : int, optional, default = 2
Which axis to compute projection along. | Below is the the instruction that describes the task:
### Input:
Compute maximum projections of images along a dimension.
Parameters
----------
axis : int, optional, default = 2
Which axis to compute projection along.
### Response:
def max_projection(self, axis=2):
"""
... |
def discombobulate(self, filehash):
""" prepare napiprojekt scrambled hash """
idx = [0xe, 0x3, 0x6, 0x8, 0x2]
mul = [2, 2, 5, 4, 3]
add = [0, 0xd, 0x10, 0xb, 0x5]
b = []
for i in xrange(len(idx)):
a = add[i]
m = mul[i]
i = idx[i]
... | prepare napiprojekt scrambled hash | Below is the the instruction that describes the task:
### Input:
prepare napiprojekt scrambled hash
### Response:
def discombobulate(self, filehash):
""" prepare napiprojekt scrambled hash """
idx = [0xe, 0x3, 0x6, 0x8, 0x2]
mul = [2, 2, 5, 4, 3]
add = [0, 0xd, 0x10, 0xb, 0x5]
... |
def _labeledInput(activeInputs, cellsPerCol=32):
"""Print the list of [column, cellIdx] indices for each of the active
cells in activeInputs.
"""
if cellsPerCol == 0:
cellsPerCol = 1
cols = activeInputs.size / cellsPerCol
activeInputs = activeInputs.reshape(cols, cellsPerCol)
(cols, cellIdxs) = active... | Print the list of [column, cellIdx] indices for each of the active
cells in activeInputs. | Below is the the instruction that describes the task:
### Input:
Print the list of [column, cellIdx] indices for each of the active
cells in activeInputs.
### Response:
def _labeledInput(activeInputs, cellsPerCol=32):
"""Print the list of [column, cellIdx] indices for each of the active
cells in activeInputs... |
def get_whois(self, asn_registry='arin', retry_count=3, server=None,
port=43, extra_blacklist=None):
"""
The function for retrieving whois or rwhois information for an IP
address via any port. Defaults to port 43/tcp (WHOIS).
Args:
asn_registry (:obj:`str`)... | The function for retrieving whois or rwhois information for an IP
address via any port. Defaults to port 43/tcp (WHOIS).
Args:
asn_registry (:obj:`str`): The NIC to run the query against.
Defaults to 'arin'.
retry_count (:obj:`int`): The number of times to retry ... | Below is the the instruction that describes the task:
### Input:
The function for retrieving whois or rwhois information for an IP
address via any port. Defaults to port 43/tcp (WHOIS).
Args:
asn_registry (:obj:`str`): The NIC to run the query against.
Defaults to 'arin'... |
def user_type_registered(self, keyspace, user_type, klass):
"""
Called by the parent Cluster instance when the user registers a new
mapping from a user-defined type to a class. Intended for internal
use only.
"""
try:
ks_meta = self.cluster.metadata.keyspaces... | Called by the parent Cluster instance when the user registers a new
mapping from a user-defined type to a class. Intended for internal
use only. | Below is the the instruction that describes the task:
### Input:
Called by the parent Cluster instance when the user registers a new
mapping from a user-defined type to a class. Intended for internal
use only.
### Response:
def user_type_registered(self, keyspace, user_type, klass):
"""
... |
def _inserts(self):
"""thwe"""
return {concat(a, c, b)
for a, b in self.slices
for c in ALPHABET} | thwe | Below is the the instruction that describes the task:
### Input:
thwe
### Response:
def _inserts(self):
"""thwe"""
return {concat(a, c, b)
for a, b in self.slices
for c in ALPHABET} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.