code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def make_100gaussians_image(noise=True):
"""
Make an example image containing 100 2D Gaussians plus a constant
background.
The background has a mean of 5.
If ``noise`` is `True`, then Gaussian noise with a mean of 0 and a
standard deviation of 2 is added to the output image.
Parameters
... | Make an example image containing 100 2D Gaussians plus a constant
background.
The background has a mean of 5.
If ``noise`` is `True`, then Gaussian noise with a mean of 0 and a
standard deviation of 2 is added to the output image.
Parameters
----------
noise : bool, optional
Wheth... | Below is the the instruction that describes the task:
### Input:
Make an example image containing 100 2D Gaussians plus a constant
background.
The background has a mean of 5.
If ``noise`` is `True`, then Gaussian noise with a mean of 0 and a
standard deviation of 2 is added to the output image.
... |
def _unicode_decode_extracted_tb(extracted_tb):
"""Return a traceback with the string elements translated into Unicode."""
return [(_decode(file), line_number, _decode(function), _decode(text))
for file, line_number, function, text in extracted_tb] | Return a traceback with the string elements translated into Unicode. | Below is the the instruction that describes the task:
### Input:
Return a traceback with the string elements translated into Unicode.
### Response:
def _unicode_decode_extracted_tb(extracted_tb):
"""Return a traceback with the string elements translated into Unicode."""
return [(_decode(file), line_number,... |
def read(self, filename, binary_mode=False, size=None, offset=None):
"""Reads contents of a file to a string.
Args:
filename: string, a path
binary_mode: bool, read as binary if True, otherwise text
size: int, number of bytes or characters to read, otherwise
... | Reads contents of a file to a string.
Args:
filename: string, a path
binary_mode: bool, read as binary if True, otherwise text
size: int, number of bytes or characters to read, otherwise
read all the contents of the file from the offset
offset: in... | Below is the the instruction that describes the task:
### Input:
Reads contents of a file to a string.
Args:
filename: string, a path
binary_mode: bool, read as binary if True, otherwise text
size: int, number of bytes or characters to read, otherwise
rea... |
def print_action(self, test_succeed, action):
'''
Print the detailed info of failed or always print tests.
'''
#self.info_print(">>> {0}",action.keys())
if not test_succeed or action['info']['always_show_run_output']:
output = action['output'].strip()
if o... | Print the detailed info of failed or always print tests. | Below is the the instruction that describes the task:
### Input:
Print the detailed info of failed or always print tests.
### Response:
def print_action(self, test_succeed, action):
'''
Print the detailed info of failed or always print tests.
'''
#self.info_print(">>> {0}",action.ke... |
def qteRemoveAppletFromLayout(self, applet: (QtmacsApplet, str)):
"""
Remove ``applet`` from the window layout.
This method removes ``applet`` and implicitly deletes
obsolete (ie. half-full) splitters in the process. If
``applet`` is the only visible applet in the layout then it... | Remove ``applet`` from the window layout.
This method removes ``applet`` and implicitly deletes
obsolete (ie. half-full) splitters in the process. If
``applet`` is the only visible applet in the layout then it
will be replaced with the first invisible applet. If no
invisible app... | Below is the the instruction that describes the task:
### Input:
Remove ``applet`` from the window layout.
This method removes ``applet`` and implicitly deletes
obsolete (ie. half-full) splitters in the process. If
``applet`` is the only visible applet in the layout then it
will be ... |
def inverse_jacobian(self, maps):
"""Returns the Jacobian for transforming mass1 and mass2 to
mchirp and eta.
"""
m1 = maps[parameters.mass1]
m2 = maps[parameters.mass2]
mchirp = conversions.mchirp_from_mass1_mass2(m1, m2)
eta = conversions.eta_from_mass1_mass2(m1... | Returns the Jacobian for transforming mass1 and mass2 to
mchirp and eta. | Below is the the instruction that describes the task:
### Input:
Returns the Jacobian for transforming mass1 and mass2 to
mchirp and eta.
### Response:
def inverse_jacobian(self, maps):
"""Returns the Jacobian for transforming mass1 and mass2 to
mchirp and eta.
"""
m1 = maps... |
def distance_to(self, other):
"""
Returns the size of the gap between intervals, or 0
if they touch or overlap.
:param other: Interval or point
:return: distance
:rtype: Number
"""
if self.overlaps(other):
return 0
try:
if ... | Returns the size of the gap between intervals, or 0
if they touch or overlap.
:param other: Interval or point
:return: distance
:rtype: Number | Below is the the instruction that describes the task:
### Input:
Returns the size of the gap between intervals, or 0
if they touch or overlap.
:param other: Interval or point
:return: distance
:rtype: Number
### Response:
def distance_to(self, other):
"""
Returns th... |
def formfield_for_dbfield(self, db_field, **kwargs):
"""
Adds the "Send to Twitter" checkbox after the "status" field,
provided by any ``Displayable`` models. The approach here is
quite a hack, however the sane approach of using a custom
form with a boolean field defined, and the... | Adds the "Send to Twitter" checkbox after the "status" field,
provided by any ``Displayable`` models. The approach here is
quite a hack, however the sane approach of using a custom
form with a boolean field defined, and then adding it to the
formssets attribute of the admin class fell ap... | Below is the the instruction that describes the task:
### Input:
Adds the "Send to Twitter" checkbox after the "status" field,
provided by any ``Displayable`` models. The approach here is
quite a hack, however the sane approach of using a custom
form with a boolean field defined, and then ad... |
def _set_port_sec_violation(self, v, load=False):
"""
Setter method for port_sec_violation, mapped from YANG variable /interface/port_channel/switchport/port_security/port_sec_violation (port-sec-violation)
If this variable is read-only (config: false) in the
source YANG file, then _set_port_sec_violati... | Setter method for port_sec_violation, mapped from YANG variable /interface/port_channel/switchport/port_security/port_sec_violation (port-sec-violation)
If this variable is read-only (config: false) in the
source YANG file, then _set_port_sec_violation is considered as a private
method. Backends looking to ... | Below is the the instruction that describes the task:
### Input:
Setter method for port_sec_violation, mapped from YANG variable /interface/port_channel/switchport/port_security/port_sec_violation (port-sec-violation)
If this variable is read-only (config: false) in the
source YANG file, then _set_port_sec_... |
def evaluate(self, password=''):
"""Evaluates the development set.
The passwords is sent as plain text.
:return: the evaluation results.
"""
# Make a copy only keeping the development set
dev_submission = self
if self['metadata'].get('evaluation_setting', {}).g... | Evaluates the development set.
The passwords is sent as plain text.
:return: the evaluation results. | Below is the the instruction that describes the task:
### Input:
Evaluates the development set.
The passwords is sent as plain text.
:return: the evaluation results.
### Response:
def evaluate(self, password=''):
"""Evaluates the development set.
The passwords is sent as plain te... |
def read_msh(path):
"""
Reads a GMSH MSH file and returns a :class:`Mesh` instance.
:arg path: path to MSH file.
:type path: str
"""
elementMap = { 15:"point1",
1:"line2",
2:"tri3",
3:"quad4",
4:"tetra4",
5:"hexa8",
... | Reads a GMSH MSH file and returns a :class:`Mesh` instance.
:arg path: path to MSH file.
:type path: str | Below is the the instruction that describes the task:
### Input:
Reads a GMSH MSH file and returns a :class:`Mesh` instance.
:arg path: path to MSH file.
:type path: str
### Response:
def read_msh(path):
"""
Reads a GMSH MSH file and returns a :class:`Mesh` instance.
:arg path: path to MSH file.
... |
def cond(A):
"""Return condition number of A.
Parameters
----------
A : {dense or sparse matrix}
e.g. array, matrix, csr_matrix, ...
Returns
-------
2-norm condition number through use of the SVD
Use for small to moderate sized dense matrices.
For large sparse matrices, u... | Return condition number of A.
Parameters
----------
A : {dense or sparse matrix}
e.g. array, matrix, csr_matrix, ...
Returns
-------
2-norm condition number through use of the SVD
Use for small to moderate sized dense matrices.
For large sparse matrices, use condest.
Not... | Below is the the instruction that describes the task:
### Input:
Return condition number of A.
Parameters
----------
A : {dense or sparse matrix}
e.g. array, matrix, csr_matrix, ...
Returns
-------
2-norm condition number through use of the SVD
Use for small to moderate sized... |
def AnalizarAjuste(self, aut, base=True):
"Método interno para analizar la respuesta de AFIP (ajustes)"
self.__ajuste_base = None
self.__ajuste_debito = None
self.__ajuste_credito = None
# para compatibilidad con la generacion de PDF (completo datos)
if hasattr(... | Método interno para analizar la respuesta de AFIP (ajustes) | Below is the the instruction that describes the task:
### Input:
Método interno para analizar la respuesta de AFIP (ajustes)
### Response:
def AnalizarAjuste(self, aut, base=True):
"Método interno para analizar la respuesta de AFIP (ajustes)"
self.__ajuste_base = None
self.__ajuste_debito ... |
def _process_token(cls, token):
"""Preprocess the token component of a token definition."""
assert type(token) is _TokenType or callable(token), \
'token type must be simple type or callable, not %r' % (token,)
return token | Preprocess the token component of a token definition. | Below is the the instruction that describes the task:
### Input:
Preprocess the token component of a token definition.
### Response:
def _process_token(cls, token):
"""Preprocess the token component of a token definition."""
assert type(token) is _TokenType or callable(token), \
'token ... |
def run(self):
"""Process events such as incoming data.
This method blocks indefinitely. It will only return after the
connection to the server is closed.
"""
self._stop = False # Allow re-starting the event loop
while not self._stop:
try:
sel... | Process events such as incoming data.
This method blocks indefinitely. It will only return after the
connection to the server is closed. | Below is the the instruction that describes the task:
### Input:
Process events such as incoming data.
This method blocks indefinitely. It will only return after the
connection to the server is closed.
### Response:
def run(self):
"""Process events such as incoming data.
This meth... |
def from_csv(filename_or_buffer, copy_index=True, **kwargs):
"""Shortcut to read a csv file using pandas and convert to a DataFrame directly.
:rtype: DataFrame
"""
import pandas as pd
return from_pandas(pd.read_csv(filename_or_buffer, **kwargs), copy_index=copy_index) | Shortcut to read a csv file using pandas and convert to a DataFrame directly.
:rtype: DataFrame | Below is the the instruction that describes the task:
### Input:
Shortcut to read a csv file using pandas and convert to a DataFrame directly.
:rtype: DataFrame
### Response:
def from_csv(filename_or_buffer, copy_index=True, **kwargs):
"""Shortcut to read a csv file using pandas and convert to a DataFrame... |
def tokml(self):
"""Generate a KML Placemark element subtree.
Returns:
etree.Element: KML Placemark element
"""
placemark = create_elem('Placemark')
if self.name:
placemark.set('id', self.name)
placemark.name = create_elem('name', text=self.na... | Generate a KML Placemark element subtree.
Returns:
etree.Element: KML Placemark element | Below is the the instruction that describes the task:
### Input:
Generate a KML Placemark element subtree.
Returns:
etree.Element: KML Placemark element
### Response:
def tokml(self):
"""Generate a KML Placemark element subtree.
Returns:
etree.Element: KML Placemar... |
def territory(self):
""" Return the cached territory occupied by the piece. """
cache_key = (
self.board.length, self.board.height, self.uid, self.index)
if cache_key not in self.territory_cache:
vector = self.compute_territory()
self.territory_cache[cache_key... | Return the cached territory occupied by the piece. | Below is the the instruction that describes the task:
### Input:
Return the cached territory occupied by the piece.
### Response:
def territory(self):
""" Return the cached territory occupied by the piece. """
cache_key = (
self.board.length, self.board.height, self.uid, self.index)
... |
def import_from_api(request):
"""
Import a part of a source site's page tree via a direct API request from
this Wagtail Admin to the source site
The source site's base url and the source page id of the point in the
tree to import defined what to import and the destination parent page
defines wh... | Import a part of a source site's page tree via a direct API request from
this Wagtail Admin to the source site
The source site's base url and the source page id of the point in the
tree to import defined what to import and the destination parent page
defines where to import it to. | Below is the the instruction that describes the task:
### Input:
Import a part of a source site's page tree via a direct API request from
this Wagtail Admin to the source site
The source site's base url and the source page id of the point in the
tree to import defined what to import and the destination... |
def iterplayables():
''' fast iterator of playable file object/dicts found on disk '''
ls = DirScanner(stripdot=True)
## filter out just mp3 files (and dirs to support recursion)
filt = lambda x: ( os.path.isdir(x) or x[-4:].lower() in ALLOWED_TYPES )
## take the last two segments of the path as the... | fast iterator of playable file object/dicts found on disk | Below is the the instruction that describes the task:
### Input:
fast iterator of playable file object/dicts found on disk
### Response:
def iterplayables():
''' fast iterator of playable file object/dicts found on disk '''
ls = DirScanner(stripdot=True)
## filter out just mp3 files (and dirs to suppor... |
def initOptions(self, options):
"""
Initializes the edit with the inputed options data set.
:param options | <XScintillaEditOptions>
"""
self.setAutoIndent( options.value('autoIndent'))
self.setIndentationsUseTabs( options.value('indentationsU... | Initializes the edit with the inputed options data set.
:param options | <XScintillaEditOptions> | Below is the the instruction that describes the task:
### Input:
Initializes the edit with the inputed options data set.
:param options | <XScintillaEditOptions>
### Response:
def initOptions(self, options):
"""
Initializes the edit with the inputed options data set.
... |
def table(self, snrthresh=5.5):
"""Represent this `QPlane` as an `EventTable`
Parameters
----------
snrthresh : `float`, optional
lower inclusive threshold on individual tile SNR to keep in the
table, default: 5.5
Returns
-------
out : `~... | Represent this `QPlane` as an `EventTable`
Parameters
----------
snrthresh : `float`, optional
lower inclusive threshold on individual tile SNR to keep in the
table, default: 5.5
Returns
-------
out : `~gwpy.table.EventTable`
a table ... | Below is the the instruction that describes the task:
### Input:
Represent this `QPlane` as an `EventTable`
Parameters
----------
snrthresh : `float`, optional
lower inclusive threshold on individual tile SNR to keep in the
table, default: 5.5
Returns
... |
def new_model(self, template_name='<None>'):
"""Append a new model from .rft entry to the journal.
This instructs Revit to create a new model based on the
provided .rft template.
Args:
template_name (str): optional full path to .rft template
... | Append a new model from .rft entry to the journal.
This instructs Revit to create a new model based on the
provided .rft template.
Args:
template_name (str): optional full path to .rft template
to be used. default value is <None> | Below is the the instruction that describes the task:
### Input:
Append a new model from .rft entry to the journal.
This instructs Revit to create a new model based on the
provided .rft template.
Args:
template_name (str): optional full path to .rft template
... |
def _restore_constructor(self, cls):
"""
Restore the original constructor, lose track of class.
"""
cls.__init__ = self._observers[cls].init
del self._observers[cls] | Restore the original constructor, lose track of class. | Below is the the instruction that describes the task:
### Input:
Restore the original constructor, lose track of class.
### Response:
def _restore_constructor(self, cls):
"""
Restore the original constructor, lose track of class.
"""
cls.__init__ = self._observers[cls].init
... |
def set_exception(self, exception):
''' set the exception message and set the status to failed '''
logger.error("%s : %s" % (exception.__class__.__name__, str(exception)))
self._set_status(enumAsperaControllerStatus.FAILED, exception) | set the exception message and set the status to failed | Below is the the instruction that describes the task:
### Input:
set the exception message and set the status to failed
### Response:
def set_exception(self, exception):
''' set the exception message and set the status to failed '''
logger.error("%s : %s" % (exception.__class__.__name__, str(except... |
def ordered_dict_intersection(first_dict: Mapping[K, V],
second_dict: Mapping[K, V],
compat: Callable[[V, V], bool] = equivalent
) -> MutableMapping[K, V]:
"""Return the intersection of two dictionaries as a new OrderedDict.
... | Return the intersection of two dictionaries as a new OrderedDict.
Items are retained if their keys are found in both dictionaries and the
values are compatible.
Parameters
----------
first_dict, second_dict : dict-like
Mappings to merge.
compat : function, optional
Binary opera... | Below is the the instruction that describes the task:
### Input:
Return the intersection of two dictionaries as a new OrderedDict.
Items are retained if their keys are found in both dictionaries and the
values are compatible.
Parameters
----------
first_dict, second_dict : dict-like
Ma... |
def GetFrequencyStartTimes(self):
"""Return a list of start time for each headway-based run.
Returns:
a sorted list of seconds since midnight, the start time of each run. If
this trip doesn't have headways returns an empty list."""
start_times = []
# for each headway period of the trip
... | Return a list of start time for each headway-based run.
Returns:
a sorted list of seconds since midnight, the start time of each run. If
this trip doesn't have headways returns an empty list. | Below is the the instruction that describes the task:
### Input:
Return a list of start time for each headway-based run.
Returns:
a sorted list of seconds since midnight, the start time of each run. If
this trip doesn't have headways returns an empty list.
### Response:
def GetFrequencyStartTimes(... |
def random_size_crop(src, size, min_area=0.25, ratio=(3.0/4.0, 4.0/3.0)):
"""Randomly crop src with size. Randomize area and aspect ratio"""
h, w, _ = src.shape
area = w*h
for _ in range(10):
new_area = random.uniform(min_area, 1.0) * area
new_ratio = random.uniform(*ratio)
new_w... | Randomly crop src with size. Randomize area and aspect ratio | Below is the the instruction that describes the task:
### Input:
Randomly crop src with size. Randomize area and aspect ratio
### Response:
def random_size_crop(src, size, min_area=0.25, ratio=(3.0/4.0, 4.0/3.0)):
"""Randomly crop src with size. Randomize area and aspect ratio"""
h, w, _ = src.shape
ar... |
def write(self, model:nn.Module, iteration:int, tbwriter:SummaryWriter, name:str='model')->None:
"Writes model histograms to Tensorboard."
request = HistogramTBRequest(model=model, iteration=iteration, tbwriter=tbwriter, name=name)
asyncTBWriter.request_write(request) | Writes model histograms to Tensorboard. | Below is the the instruction that describes the task:
### Input:
Writes model histograms to Tensorboard.
### Response:
def write(self, model:nn.Module, iteration:int, tbwriter:SummaryWriter, name:str='model')->None:
"Writes model histograms to Tensorboard."
request = HistogramTBRequest(model=model,... |
def _decode_preferred_encoding(s):
"""Decode the supplied byte string using the preferred encoding
for the locale (`locale.getpreferredencoding`) or, if the default encoding
is invalid, fall back first on utf-8, then on latin-1 if the message cannot
be decoded with utf-8.
"""
enc = locale.getpr... | Decode the supplied byte string using the preferred encoding
for the locale (`locale.getpreferredencoding`) or, if the default encoding
is invalid, fall back first on utf-8, then on latin-1 if the message cannot
be decoded with utf-8. | Below is the the instruction that describes the task:
### Input:
Decode the supplied byte string using the preferred encoding
for the locale (`locale.getpreferredencoding`) or, if the default encoding
is invalid, fall back first on utf-8, then on latin-1 if the message cannot
be decoded with utf-8.
### ... |
def process_call(self, addr, cmd, val):
"""process_call(addr, cmd, val)
Perform SMBus Process Call transaction.
Note: although i2c_smbus_process_call returns a value, according to
smbusmodule.c this method does not return a value by default.
Set _compat = False on the SMBus in... | process_call(addr, cmd, val)
Perform SMBus Process Call transaction.
Note: although i2c_smbus_process_call returns a value, according to
smbusmodule.c this method does not return a value by default.
Set _compat = False on the SMBus instance to get a return value. | Below is the the instruction that describes the task:
### Input:
process_call(addr, cmd, val)
Perform SMBus Process Call transaction.
Note: although i2c_smbus_process_call returns a value, according to
smbusmodule.c this method does not return a value by default.
Set _compat = Fal... |
def controller(self, *paths, **query_kwargs):
"""create a new url object using the controller path as a base
if you have a controller `foo.BarController` then this would create a new
Url instance with `host/foo/bar` as the base path, so any *paths will be
appended to `/foo/bar`
... | create a new url object using the controller path as a base
if you have a controller `foo.BarController` then this would create a new
Url instance with `host/foo/bar` as the base path, so any *paths will be
appended to `/foo/bar`
:example:
# controller foo.BarController
... | Below is the the instruction that describes the task:
### Input:
create a new url object using the controller path as a base
if you have a controller `foo.BarController` then this would create a new
Url instance with `host/foo/bar` as the base path, so any *paths will be
appended to `/foo/b... |
def add(self, dn: str, mod_list: dict) -> None:
"""
Add a DN to the LDAP database; See ldap module. Doesn't return a result
if transactions enabled.
"""
_debug("add", self, dn, mod_list)
# if rollback of add required, delete it
def on_commit(obj):
ob... | Add a DN to the LDAP database; See ldap module. Doesn't return a result
if transactions enabled. | Below is the the instruction that describes the task:
### Input:
Add a DN to the LDAP database; See ldap module. Doesn't return a result
if transactions enabled.
### Response:
def add(self, dn: str, mod_list: dict) -> None:
"""
Add a DN to the LDAP database; See ldap module. Doesn't return ... |
def syscall_generator(generator):
'''
Directly process events from a generator function. This should never be used for normal events.
'''
def _syscall(scheduler, processor):
for e in generator():
processor(e)
return _syscall | Directly process events from a generator function. This should never be used for normal events. | Below is the the instruction that describes the task:
### Input:
Directly process events from a generator function. This should never be used for normal events.
### Response:
def syscall_generator(generator):
'''
Directly process events from a generator function. This should never be used for normal events... |
def getx(self, name, *args):
"""
Return value of one of parameter(s) or NULL is it has no value (or was not specified)
"""
return lib.zargs_getx(self._as_parameter_, name, *args) | Return value of one of parameter(s) or NULL is it has no value (or was not specified) | Below is the the instruction that describes the task:
### Input:
Return value of one of parameter(s) or NULL is it has no value (or was not specified)
### Response:
def getx(self, name, *args):
"""
Return value of one of parameter(s) or NULL is it has no value (or was not specified)
"""
... |
def add_relation(self, parent, child, level, parent_func=None,
child_func=None):
"""
Manually add relations to the database.
Parameters
----------
parent : str or Feature instance
Parent feature to add.
child : str or Feature instance
... | Manually add relations to the database.
Parameters
----------
parent : str or Feature instance
Parent feature to add.
child : str or Feature instance
Child feature to add
level : int
Level of the relation. For example, if parent is a gene ... | Below is the the instruction that describes the task:
### Input:
Manually add relations to the database.
Parameters
----------
parent : str or Feature instance
Parent feature to add.
child : str or Feature instance
Child feature to add
level : int
... |
def stage_tc_batch_xid(xid_type, xid_value, owner):
"""Create an xid for a batch job.
Args:
xid_type (str): [description]
xid_value (str): [description]
owner (str): [description]
Returns:
[type]: [description]
"""
xid_string = '{... | Create an xid for a batch job.
Args:
xid_type (str): [description]
xid_value (str): [description]
owner (str): [description]
Returns:
[type]: [description] | Below is the the instruction that describes the task:
### Input:
Create an xid for a batch job.
Args:
xid_type (str): [description]
xid_value (str): [description]
owner (str): [description]
Returns:
[type]: [description]
### Response:
def stage_tc_b... |
def gen_properties(output, ascii_props=False, append=False):
"""Generate the property table and dump it to the provided file."""
files = {
'gc': os.path.join(output, 'generalcategory.py'),
'blk': os.path.join(output, 'block.py'),
'sc': os.path.join(output, 'script.py'),
'bc': os... | Generate the property table and dump it to the provided file. | Below is the the instruction that describes the task:
### Input:
Generate the property table and dump it to the provided file.
### Response:
def gen_properties(output, ascii_props=False, append=False):
"""Generate the property table and dump it to the provided file."""
files = {
'gc': os.path.join... |
def get_commits(self, sha=github.GithubObject.NotSet, path=github.GithubObject.NotSet, since=github.GithubObject.NotSet, until=github.GithubObject.NotSet, author=github.GithubObject.NotSet):
"""
:calls: `GET /repos/:owner/:repo/commits <http://developer.github.com/v3/repos/commits>`_
:param sha:... | :calls: `GET /repos/:owner/:repo/commits <http://developer.github.com/v3/repos/commits>`_
:param sha: string
:param path: string
:param since: datetime.datetime
:param until: datetime.datetime
:param author: string or :class:`github.NamedUser.NamedUser` or :class:`github.Authenti... | Below is the the instruction that describes the task:
### Input:
:calls: `GET /repos/:owner/:repo/commits <http://developer.github.com/v3/repos/commits>`_
:param sha: string
:param path: string
:param since: datetime.datetime
:param until: datetime.datetime
:param author: str... |
def generate_params(n_items, interval=5.0, ordered=False):
r"""Generate random model parameters.
This function samples a parameter independently and uniformly for each
item. ``interval`` defines the width of the uniform distribution.
Parameters
----------
n_items : int
Number of distin... | r"""Generate random model parameters.
This function samples a parameter independently and uniformly for each
item. ``interval`` defines the width of the uniform distribution.
Parameters
----------
n_items : int
Number of distinct items.
interval : float
Sampling interval.
o... | Below is the the instruction that describes the task:
### Input:
r"""Generate random model parameters.
This function samples a parameter independently and uniformly for each
item. ``interval`` defines the width of the uniform distribution.
Parameters
----------
n_items : int
Number of ... |
def on_return(self, channel, method, properties, body):
"""Invoked by RabbitMQ when it returns a message that was published.
:param channel: The channel the message was delivered on
:type channel: pika.channel.Channel
:param method: The AMQP method frame
:type method: pika.frame... | Invoked by RabbitMQ when it returns a message that was published.
:param channel: The channel the message was delivered on
:type channel: pika.channel.Channel
:param method: The AMQP method frame
:type method: pika.frame.Frame
:param properties: The AMQP message properties
... | Below is the the instruction that describes the task:
### Input:
Invoked by RabbitMQ when it returns a message that was published.
:param channel: The channel the message was delivered on
:type channel: pika.channel.Channel
:param method: The AMQP method frame
:type method: pika.fra... |
def redraw_current_line(self):
""" Redraw the highlighted line """
if self.no_streams:
return
row = self.pads[self.current_pad].getyx()[0]
s = self.filtered_streams[row]
pad = self.pads['streams']
pad.move(row, 0)
pad.clrtoeol()
pad.addstr(row,... | Redraw the highlighted line | Below is the the instruction that describes the task:
### Input:
Redraw the highlighted line
### Response:
def redraw_current_line(self):
""" Redraw the highlighted line """
if self.no_streams:
return
row = self.pads[self.current_pad].getyx()[0]
s = self.filtered_streams... |
def service_messages(self, short_name):
"""Get the messages stored for a service.
Args:
short_name (string): The short name of the service to get messages for
Returns:
list(ServiceMessage): A list of the ServiceMessages stored for this service
"""
if sh... | Get the messages stored for a service.
Args:
short_name (string): The short name of the service to get messages for
Returns:
list(ServiceMessage): A list of the ServiceMessages stored for this service | Below is the the instruction that describes the task:
### Input:
Get the messages stored for a service.
Args:
short_name (string): The short name of the service to get messages for
Returns:
list(ServiceMessage): A list of the ServiceMessages stored for this service
### Resp... |
def set_user(uid=None, username=None, password=None, priv=None, status=None):
'''
Sets a CIMC user with specified configurations.
.. versionadded:: 2019.2.0
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The... | Sets a CIMC user with specified configurations.
.. versionadded:: 2019.2.0
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password of the user.
priv(str): The privilege level of the user.
... | Below is the the instruction that describes the task:
### Input:
Sets a CIMC user with specified configurations.
.. versionadded:: 2019.2.0
Args:
uid(int): The user ID slot to create the user account in.
username(str): The name of the user.
password(str): The clear text password ... |
def subst_list(self, string, raw=0, target=None, source=None, conv=None, executor=None):
"""Calls through to SCons.Subst.scons_subst_list(). See
the documentation for that function."""
gvars = self.gvars()
lvars = self.lvars()
lvars['__env__'] = self
if executor:
... | Calls through to SCons.Subst.scons_subst_list(). See
the documentation for that function. | Below is the the instruction that describes the task:
### Input:
Calls through to SCons.Subst.scons_subst_list(). See
the documentation for that function.
### Response:
def subst_list(self, string, raw=0, target=None, source=None, conv=None, executor=None):
"""Calls through to SCons.Subst.scons_su... |
def nStepsForParam(self, param):
"""Gets the number of steps *parameter* will yeild
:param param: parameter to get the expansion count for
:type param: dict
"""
if param['parameter'] == 'filename':
return len(param['names'])
else:
if param['step']... | Gets the number of steps *parameter* will yeild
:param param: parameter to get the expansion count for
:type param: dict | Below is the the instruction that describes the task:
### Input:
Gets the number of steps *parameter* will yeild
:param param: parameter to get the expansion count for
:type param: dict
### Response:
def nStepsForParam(self, param):
"""Gets the number of steps *parameter* will yeild
... |
def _getPWMFrequency(self, device, message):
"""
Get the PWM frequency stored on the hardware device.
:Parameters:
device : `int`
The device is the integer number of the hardware devices ID and
is only used with the Pololu Protocol.
message : `bool`
... | Get the PWM frequency stored on the hardware device.
:Parameters:
device : `int`
The device is the integer number of the hardware devices ID and
is only used with the Pololu Protocol.
message : `bool`
If set to `True` a text message will be returned, if s... | Below is the the instruction that describes the task:
### Input:
Get the PWM frequency stored on the hardware device.
:Parameters:
device : `int`
The device is the integer number of the hardware devices ID and
is only used with the Pololu Protocol.
message : `boo... |
def vdcnn(embedding_size, maxlen, max_features,
filter_nr, kernel_size, repeat_block, dense_size, repeat_dense, output_size, output_activation,
max_pooling, mean_pooling, weighted_average_attention, concat_mode,
dropout_embedding, conv_dropout, dense_dropout, dropout_mode,
conv_k... | Note:
Implementation of http://www.aclweb.org/anthology/E17-1104
We didn't use k-max pooling but GlobalMaxPool1D at the end and didn't explore it in the
intermediate layers. | Below is the the instruction that describes the task:
### Input:
Note:
Implementation of http://www.aclweb.org/anthology/E17-1104
We didn't use k-max pooling but GlobalMaxPool1D at the end and didn't explore it in the
intermediate layers.
### Response:
def vdcnn(embedding_size, maxlen, max_... |
def profile(event_type, extra_data=None):
"""Profile a span of time so that it appears in the timeline visualization.
Note that this only works in the raylet code path.
This function can be used as follows (both on the driver or within a task).
.. code-block:: python
with ray.profile("custom... | Profile a span of time so that it appears in the timeline visualization.
Note that this only works in the raylet code path.
This function can be used as follows (both on the driver or within a task).
.. code-block:: python
with ray.profile("custom event", extra_data={'key': 'value'}):
... | Below is the the instruction that describes the task:
### Input:
Profile a span of time so that it appears in the timeline visualization.
Note that this only works in the raylet code path.
This function can be used as follows (both on the driver or within a task).
.. code-block:: python
with... |
def _read_body_by_chunk(self, response, file, raw=False):
'''Read the connection using chunked transfer encoding.
Coroutine.
'''
reader = ChunkedTransferReader(self._connection)
file_is_async = hasattr(file, 'drain')
while True:
chunk_size, data = yield fro... | Read the connection using chunked transfer encoding.
Coroutine. | Below is the the instruction that describes the task:
### Input:
Read the connection using chunked transfer encoding.
Coroutine.
### Response:
def _read_body_by_chunk(self, response, file, raw=False):
'''Read the connection using chunked transfer encoding.
Coroutine.
'''
r... |
def job(func_or_queue, connection=None, *args, **kwargs):
"""This decorator does all what django_rq's one, plus
it group all logged messages using uuid and sets
job_name field as well."""
decorated_func = _job(func_or_queue, connection=connection, *args, **kwargs)
if callable(func_or_queue):
... | This decorator does all what django_rq's one, plus
it group all logged messages using uuid and sets
job_name field as well. | Below is the the instruction that describes the task:
### Input:
This decorator does all what django_rq's one, plus
it group all logged messages using uuid and sets
job_name field as well.
### Response:
def job(func_or_queue, connection=None, *args, **kwargs):
"""This decorator does all what django_rq'... |
def get_banks_by_assessment_offered(self, assessment_offered_id):
"""Gets the list of ``Banks`` mapped to an ``AssessmentOffered``.
arg: assessment_offered_id (osid.id.Id): ``Id`` of an
``AssessmentOffered``
return: (osid.assessment.BankList) - list of banks
raise: N... | Gets the list of ``Banks`` mapped to an ``AssessmentOffered``.
arg: assessment_offered_id (osid.id.Id): ``Id`` of an
``AssessmentOffered``
return: (osid.assessment.BankList) - list of banks
raise: NotFound - ``assessment_offered_id`` is not found
raise: NullArgument... | Below is the the instruction that describes the task:
### Input:
Gets the list of ``Banks`` mapped to an ``AssessmentOffered``.
arg: assessment_offered_id (osid.id.Id): ``Id`` of an
``AssessmentOffered``
return: (osid.assessment.BankList) - list of banks
raise: NotFound ... |
def mvn(*args, **kwargs):
"""Convenience function to efficiently construct a MultivariateNormalDiag."""
# Faster than using `tfd.MultivariateNormalDiag`.
return tfd.Independent(tfd.Normal(*args, **kwargs),
reinterpreted_batch_ndims=1) | Convenience function to efficiently construct a MultivariateNormalDiag. | Below is the the instruction that describes the task:
### Input:
Convenience function to efficiently construct a MultivariateNormalDiag.
### Response:
def mvn(*args, **kwargs):
"""Convenience function to efficiently construct a MultivariateNormalDiag."""
# Faster than using `tfd.MultivariateNormalDiag`.
retu... |
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
# Download the full MNIST Database
filenames = {
"train_data": _MNIST_TRAIN_DATA_FILENAME,
"train_labels": _MNIST_TRAIN_LABELS_FILENAME,
"test_data": _MNIST_TEST_DATA_FILENAME,
"test_labels": _MNIST_TEST_... | Returns SplitGenerators. | Below is the the instruction that describes the task:
### Input:
Returns SplitGenerators.
### Response:
def _split_generators(self, dl_manager):
"""Returns SplitGenerators."""
# Download the full MNIST Database
filenames = {
"train_data": _MNIST_TRAIN_DATA_FILENAME,
"train_labels": _MNI... |
def rename_rater(self, test_name=None, test_new_name=None):
"""action: create dialog to rename event type."""
if test_name and test_new_name:
name = test_name, True
new_name = test_new_name, True
else:
name = QInputDialog.getText(self, 'Rename Rater',
... | action: create dialog to rename event type. | Below is the the instruction that describes the task:
### Input:
action: create dialog to rename event type.
### Response:
def rename_rater(self, test_name=None, test_new_name=None):
"""action: create dialog to rename event type."""
if test_name and test_new_name:
name = test_name, True... |
def open(path, mode=None, ac_parser=None, **options):
"""
Open given configuration file with appropriate open flag.
:param path: Configuration file path
:param mode:
Can be 'r' and 'rb' for reading (default) or 'w', 'wb' for writing.
Please note that even if you specify 'r' or 'w', it w... | Open given configuration file with appropriate open flag.
:param path: Configuration file path
:param mode:
Can be 'r' and 'rb' for reading (default) or 'w', 'wb' for writing.
Please note that even if you specify 'r' or 'w', it will be changed to
'rb' or 'wb' if selected backend, xml an... | Below is the the instruction that describes the task:
### Input:
Open given configuration file with appropriate open flag.
:param path: Configuration file path
:param mode:
Can be 'r' and 'rb' for reading (default) or 'w', 'wb' for writing.
Please note that even if you specify 'r' or 'w', i... |
def login(self, email=None, password=None):
"""
Interactive login using the `cloudgenix.API` object. This function is more robust and handles SAML and MSP accounts.
Expects interactive capability. if this is not available, use `cloudenix.API.post.login` directly.
**Parameters:**:
... | Interactive login using the `cloudgenix.API` object. This function is more robust and handles SAML and MSP accounts.
Expects interactive capability. if this is not available, use `cloudenix.API.post.login` directly.
**Parameters:**:
- **email**: Email to log in for, will prompt if not entere... | Below is the the instruction that describes the task:
### Input:
Interactive login using the `cloudgenix.API` object. This function is more robust and handles SAML and MSP accounts.
Expects interactive capability. if this is not available, use `cloudenix.API.post.login` directly.
**Parameters:**:
... |
def QA_indicator_shadow(DataFrame):
"""
上下影线指标
"""
return {
'LOW': lower_shadow(DataFrame), 'UP': upper_shadow(DataFrame),
'BODY': body(DataFrame), 'BODY_ABS': body_abs(DataFrame), 'PRICE_PCG': price_pcg(DataFrame)
} | 上下影线指标 | Below is the the instruction that describes the task:
### Input:
上下影线指标
### Response:
def QA_indicator_shadow(DataFrame):
"""
上下影线指标
"""
return {
'LOW': lower_shadow(DataFrame), 'UP': upper_shadow(DataFrame),
'BODY': body(DataFrame), 'BODY_ABS': body_abs(DataFrame), 'PRICE_PCG': pri... |
def read_stats(self, *stats):
""" Read stream statistics from chassis.
:param stats: list of requested statistics to read, if empty - read all statistics.
"""
from ixexplorer.ixe_stream import IxePacketGroupStream
sleep_time = 0.1 # in cases we only want few counters but very f... | Read stream statistics from chassis.
:param stats: list of requested statistics to read, if empty - read all statistics. | Below is the the instruction that describes the task:
### Input:
Read stream statistics from chassis.
:param stats: list of requested statistics to read, if empty - read all statistics.
### Response:
def read_stats(self, *stats):
""" Read stream statistics from chassis.
:param stats: list... |
def with_scopes_if_required(credentials, scopes):
"""Creates a copy of the credentials with scopes if scoping is required.
This helper function is useful when you do not know (or care to know) the
specific type of credentials you are using (such as when you use
:func:`google.auth.default`). This functi... | Creates a copy of the credentials with scopes if scoping is required.
This helper function is useful when you do not know (or care to know) the
specific type of credentials you are using (such as when you use
:func:`google.auth.default`). This function will call
:meth:`Scoped.with_scopes` if the creden... | Below is the the instruction that describes the task:
### Input:
Creates a copy of the credentials with scopes if scoping is required.
This helper function is useful when you do not know (or care to know) the
specific type of credentials you are using (such as when you use
:func:`google.auth.default`).... |
def get_data_files_recursively(*rel_root_path, **kwargs):
""" Adds all files of the specified path to a data_files compatible list
:param tuple rel_root_path: List of path elements pointing to a directory of files
:return: list of tuples of install directory and list of source files
:rtype: list(tuple(... | Adds all files of the specified path to a data_files compatible list
:param tuple rel_root_path: List of path elements pointing to a directory of files
:return: list of tuples of install directory and list of source files
:rtype: list(tuple(str, [str])) | Below is the the instruction that describes the task:
### Input:
Adds all files of the specified path to a data_files compatible list
:param tuple rel_root_path: List of path elements pointing to a directory of files
:return: list of tuples of install directory and list of source files
:rtype: list(tup... |
def delete_question(self, publisher_name, extension_name, question_id):
"""DeleteQuestion.
[Preview API] Deletes an existing question and all its associated responses for an extension. (soft delete)
:param str publisher_name: Name of the publisher who published the extension.
:param str ... | DeleteQuestion.
[Preview API] Deletes an existing question and all its associated responses for an extension. (soft delete)
:param str publisher_name: Name of the publisher who published the extension.
:param str extension_name: Name of the extension.
:param long question_id: Identifier ... | Below is the the instruction that describes the task:
### Input:
DeleteQuestion.
[Preview API] Deletes an existing question and all its associated responses for an extension. (soft delete)
:param str publisher_name: Name of the publisher who published the extension.
:param str extension_name... |
def register(self, slug, bundle, order=1, title=None):
"""
Registers the bundle for a certain slug.
If a slug is already registered, this will raise AlreadyRegistered.
:param slug: The slug to register.
:param bundle: The bundle instance being registered.
:param order: ... | Registers the bundle for a certain slug.
If a slug is already registered, this will raise AlreadyRegistered.
:param slug: The slug to register.
:param bundle: The bundle instance being registered.
:param order: An integer that controls where this bundle's \
dashboard links appe... | Below is the the instruction that describes the task:
### Input:
Registers the bundle for a certain slug.
If a slug is already registered, this will raise AlreadyRegistered.
:param slug: The slug to register.
:param bundle: The bundle instance being registered.
:param order: An int... |
def tensor_jacobian_product(fun, argnum=0):
"""Builds a function that returns the exact tensor-Jacobian product, that
is the Jacobian matrix left-multiplied by tensor. The returned function
has arguments (*args, tensor, **kwargs)."""
def vector_dot_fun(*args, **kwargs):
args, vector = args[:-1],... | Builds a function that returns the exact tensor-Jacobian product, that
is the Jacobian matrix left-multiplied by tensor. The returned function
has arguments (*args, tensor, **kwargs). | Below is the the instruction that describes the task:
### Input:
Builds a function that returns the exact tensor-Jacobian product, that
is the Jacobian matrix left-multiplied by tensor. The returned function
has arguments (*args, tensor, **kwargs).
### Response:
def tensor_jacobian_product(fun, argnum=0):
... |
def luhn_checksum(num: str) -> str:
"""Calculate a checksum for num using the Luhn algorithm.
:param num: The number to calculate a checksum for as a string.
:return: Checksum for number.
"""
check = 0
for i, s in enumerate(reversed(num)):
sx = int(s)
sx = sx * 2 if i % 2 == 0 e... | Calculate a checksum for num using the Luhn algorithm.
:param num: The number to calculate a checksum for as a string.
:return: Checksum for number. | Below is the the instruction that describes the task:
### Input:
Calculate a checksum for num using the Luhn algorithm.
:param num: The number to calculate a checksum for as a string.
:return: Checksum for number.
### Response:
def luhn_checksum(num: str) -> str:
"""Calculate a checksum for num using ... |
def web_error_and_result(f):
"""
Same as error_and_result decorator, except:
If no exception was raised during task execution, ONLY IN CASE OF WEB
REQUEST formats task result into json dictionary {'data': task return value}
"""
@wraps(f)
def web_error_and_result_decorator(*args, **kwargs):
... | Same as error_and_result decorator, except:
If no exception was raised during task execution, ONLY IN CASE OF WEB
REQUEST formats task result into json dictionary {'data': task return value} | Below is the the instruction that describes the task:
### Input:
Same as error_and_result decorator, except:
If no exception was raised during task execution, ONLY IN CASE OF WEB
REQUEST formats task result into json dictionary {'data': task return value}
### Response:
def web_error_and_result(f):
"""
... |
def _is_saccharide_arrow(self, before, after):
"""Return True if the arrow is in a chemical name."""
if (before and after and before[-1].isdigit() and after[0].isdigit() and
before.rstrip('0123456789').endswith('(') and after.lstrip('0123456789').startswith(')-')):
return True
... | Return True if the arrow is in a chemical name. | Below is the the instruction that describes the task:
### Input:
Return True if the arrow is in a chemical name.
### Response:
def _is_saccharide_arrow(self, before, after):
"""Return True if the arrow is in a chemical name."""
if (before and after and before[-1].isdigit() and after[0].isdigit() an... |
def slots_class_sealer(fields, defaults):
"""
This sealer makes a container class that uses ``__slots__`` (it uses :func:`class_sealer` internally).
The resulting class has a metaclass that forcibly sets ``__slots__`` on subclasses.
"""
class __slots_meta__(type):
def __new__(mcs, name, bas... | This sealer makes a container class that uses ``__slots__`` (it uses :func:`class_sealer` internally).
The resulting class has a metaclass that forcibly sets ``__slots__`` on subclasses. | Below is the the instruction that describes the task:
### Input:
This sealer makes a container class that uses ``__slots__`` (it uses :func:`class_sealer` internally).
The resulting class has a metaclass that forcibly sets ``__slots__`` on subclasses.
### Response:
def slots_class_sealer(fields, defaults):
... |
def _patch_tcpserver():
"""
Patch shutdown_request to open blocking interaction after the end of the
request
"""
shutdown_request = TCPServer.shutdown_request
def shutdown_request_patched(*args, **kwargs):
thread = current_thread()
shutdown_request(*args, **kwargs)
if th... | Patch shutdown_request to open blocking interaction after the end of the
request | Below is the the instruction that describes the task:
### Input:
Patch shutdown_request to open blocking interaction after the end of the
request
### Response:
def _patch_tcpserver():
"""
Patch shutdown_request to open blocking interaction after the end of the
request
"""
shutdown_request =... |
def display(self):
"""
Returns the best name to display for this host. Uses the instance
name if available; else just the public IP.
:rtype: ``str``
"""
if isinstance(self.name, six.string_types) and len(self.name) > 0:
return '{0} ({1})'.format(self.name, se... | Returns the best name to display for this host. Uses the instance
name if available; else just the public IP.
:rtype: ``str`` | Below is the the instruction that describes the task:
### Input:
Returns the best name to display for this host. Uses the instance
name if available; else just the public IP.
:rtype: ``str``
### Response:
def display(self):
"""
Returns the best name to display for this host. Uses t... |
def aes_cbc_no_padding_decrypt(key, data, iv):
"""
Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no
padding.
:param key:
The encryption key - a byte string either 16, 24 or 32 bytes long
:param data:
The ciphertext - a byte string
:param iv:
T... | Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no
padding.
:param key:
The encryption key - a byte string either 16, 24 or 32 bytes long
:param data:
The ciphertext - a byte string
:param iv:
The initialization vector - a byte string 16-bytes long
... | Below is the the instruction that describes the task:
### Input:
Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no
padding.
:param key:
The encryption key - a byte string either 16, 24 or 32 bytes long
:param data:
The ciphertext - a byte string
:param iv:... |
def _log_matrix_vector(ms, vs):
"""Multiply tensor of matrices by vectors assuming values stored are logs."""
return tf.reduce_logsumexp(input_tensor=ms + vs[..., tf.newaxis, :], axis=-1) | Multiply tensor of matrices by vectors assuming values stored are logs. | Below is the the instruction that describes the task:
### Input:
Multiply tensor of matrices by vectors assuming values stored are logs.
### Response:
def _log_matrix_vector(ms, vs):
"""Multiply tensor of matrices by vectors assuming values stored are logs."""
return tf.reduce_logsumexp(input_tensor=ms + vs[.... |
def locateChild(self, context, segments):
"""
Return a statically defined child or a child defined by a sessionless
site root plugin or an avatar from guard.
"""
shortcut = getattr(self, 'child_' + segments[0], None)
if shortcut:
res = shortcut(context)
... | Return a statically defined child or a child defined by a sessionless
site root plugin or an avatar from guard. | Below is the the instruction that describes the task:
### Input:
Return a statically defined child or a child defined by a sessionless
site root plugin or an avatar from guard.
### Response:
def locateChild(self, context, segments):
"""
Return a statically defined child or a child defined b... |
def remove_preconstraints(self, to_composite_solver=True, simplify=True):
"""
Remove the preconstraints from the state.
If you are using the zen plugin, this will also use that to filter the constraints.
:param to_composite_solver: Whether to convert the replacement solver to a com... | Remove the preconstraints from the state.
If you are using the zen plugin, this will also use that to filter the constraints.
:param to_composite_solver: Whether to convert the replacement solver to a composite solver. You probably
want this if you're switch... | Below is the the instruction that describes the task:
### Input:
Remove the preconstraints from the state.
If you are using the zen plugin, this will also use that to filter the constraints.
:param to_composite_solver: Whether to convert the replacement solver to a composite solver. You probab... |
def clear_collection(self, *classes):
''' Clear all objects from the collections associated with the
objects in `*cls`. **use with caution!**'''
for c in classes:
self.queue.append(ClearCollectionOp(self.transaction_id, self, c))
if self.autoflush:
self.flush() | Clear all objects from the collections associated with the
objects in `*cls`. **use with caution!** | Below is the the instruction that describes the task:
### Input:
Clear all objects from the collections associated with the
objects in `*cls`. **use with caution!**
### Response:
def clear_collection(self, *classes):
''' Clear all objects from the collections associated with the
objects in `*cls`. **use wi... |
async def _get_full_user(self) -> Dict:
"""
Sometimes Telegram does not provide all the user info with the message.
In order to get the full profile (aka the language code) you need to
call this method which will make sure that the full User object is
loaded.
The result ... | Sometimes Telegram does not provide all the user info with the message.
In order to get the full profile (aka the language code) you need to
call this method which will make sure that the full User object is
loaded.
The result is cached for the lifetime of the object, so if the function... | Below is the the instruction that describes the task:
### Input:
Sometimes Telegram does not provide all the user info with the message.
In order to get the full profile (aka the language code) you need to
call this method which will make sure that the full User object is
loaded.
Th... |
def get_data(service, cache_data, trigger_id):
"""
get the data from the cache
:param service: the service name
:param cache_data: the data from the cache
:type trigger_id: integer
:return: Return the data from the cache
:rtype: object
... | get the data from the cache
:param service: the service name
:param cache_data: the data from the cache
:type trigger_id: integer
:return: Return the data from the cache
:rtype: object | Below is the the instruction that describes the task:
### Input:
get the data from the cache
:param service: the service name
:param cache_data: the data from the cache
:type trigger_id: integer
:return: Return the data from the cache
:rtype: object
### Re... |
def lint_directory(source, target):
"""Adds a linted version of each document in the source directory to the target directory
:param str source: Path to directory to lint
:param str target: Path to directory to output
"""
for path in os.listdir(source):
if not path.endswith('.bel'):
... | Adds a linted version of each document in the source directory to the target directory
:param str source: Path to directory to lint
:param str target: Path to directory to output | Below is the the instruction that describes the task:
### Input:
Adds a linted version of each document in the source directory to the target directory
:param str source: Path to directory to lint
:param str target: Path to directory to output
### Response:
def lint_directory(source, target):
"""Adds ... |
def _wf_to_dict(wf):
"""Parse a workflow into cwl2wdl style dictionary.
"""
inputs, outputs = _get_wf_inout(wf)
out = {"name": _id_to_name(wf.tool["id"]).replace("-", "_"), "inputs": inputs,
"outputs": outputs, "steps": [], "subworkflows": [],
"requirements": []}
for step in wf... | Parse a workflow into cwl2wdl style dictionary. | Below is the the instruction that describes the task:
### Input:
Parse a workflow into cwl2wdl style dictionary.
### Response:
def _wf_to_dict(wf):
"""Parse a workflow into cwl2wdl style dictionary.
"""
inputs, outputs = _get_wf_inout(wf)
out = {"name": _id_to_name(wf.tool["id"]).replace("-", "_"),... |
def pq(self) -> PyQuery:
"""`PyQuery <https://pythonhosted.org/pyquery/>`_ representation
of the :class:`Element <Element>` or :class:`HTML <HTML>`.
"""
if self._pq is None:
self._pq = PyQuery(self.raw_xml)
return self._pq | `PyQuery <https://pythonhosted.org/pyquery/>`_ representation
of the :class:`Element <Element>` or :class:`HTML <HTML>`. | Below is the the instruction that describes the task:
### Input:
`PyQuery <https://pythonhosted.org/pyquery/>`_ representation
of the :class:`Element <Element>` or :class:`HTML <HTML>`.
### Response:
def pq(self) -> PyQuery:
"""`PyQuery <https://pythonhosted.org/pyquery/>`_ representation
o... |
def ekntab():
"""
Return the number of loaded EK tables.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekntab_c.html
:return: The number of loaded EK tables.
:rtype: int
"""
n = ctypes.c_int(0)
libspice.ekntab_c(ctypes.byref(n))
return n.value | Return the number of loaded EK tables.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekntab_c.html
:return: The number of loaded EK tables.
:rtype: int | Below is the the instruction that describes the task:
### Input:
Return the number of loaded EK tables.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekntab_c.html
:return: The number of loaded EK tables.
:rtype: int
### Response:
def ekntab():
"""
Return the number of loaded EK tab... |
def rssi_bars(self) -> int:
"""Received Signal Strength Indication, from 0 to 4 bars."""
rssi_db = self.rssi_db
if rssi_db < 45:
return 0
elif rssi_db < 60:
return 1
elif rssi_db < 75:
return 2
elif rssi_db < 90:
return 3
... | Received Signal Strength Indication, from 0 to 4 bars. | Below is the the instruction that describes the task:
### Input:
Received Signal Strength Indication, from 0 to 4 bars.
### Response:
def rssi_bars(self) -> int:
"""Received Signal Strength Indication, from 0 to 4 bars."""
rssi_db = self.rssi_db
if rssi_db < 45:
return 0
... |
def tmpfile(root=TEMPS_DIR, prefix=TEMPS_PREFIX, suffix=TEMPS_SUFFIX):
'''
For use in a with statement, this function returns a context manager that
yields a path directly under root guaranteed to be unique by using the uuid
module. This path is not created. However if the path is an existing file
... | For use in a with statement, this function returns a context manager that
yields a path directly under root guaranteed to be unique by using the uuid
module. This path is not created. However if the path is an existing file
when the with statement is exited, the file will be removed.
This function is... | Below is the the instruction that describes the task:
### Input:
For use in a with statement, this function returns a context manager that
yields a path directly under root guaranteed to be unique by using the uuid
module. This path is not created. However if the path is an existing file
when the with... |
def remove_empty_dirs(path=None):
"""
Recursively delete empty directories; return True if everything was deleted.
"""
if not path:
path = settings.MEDIA_ROOT
if not os.path.isdir(path):
return False
listdir = [os.path.join(path, filename) for filename in os.listdir(path)]... | Recursively delete empty directories; return True if everything was deleted. | Below is the the instruction that describes the task:
### Input:
Recursively delete empty directories; return True if everything was deleted.
### Response:
def remove_empty_dirs(path=None):
"""
Recursively delete empty directories; return True if everything was deleted.
"""
if not path:
... |
def get_apps(self):
"""
Get the list of installed apps
and return the apps that have
an emails module
"""
templates = []
for app in settings.INSTALLED_APPS:
try:
app = import_module(app + '.emails')
templates += self.get... | Get the list of installed apps
and return the apps that have
an emails module | Below is the the instruction that describes the task:
### Input:
Get the list of installed apps
and return the apps that have
an emails module
### Response:
def get_apps(self):
"""
Get the list of installed apps
and return the apps that have
an emails module
... |
def litecoin_withdrawal(self, amount, address):
"""
Send litecoins to another litecoin wallet specified by address.
"""
data = {'amount': amount, 'address': address}
return self._post("ltc_withdrawal/", data=data, return_json=True,
version=2) | Send litecoins to another litecoin wallet specified by address. | Below is the the instruction that describes the task:
### Input:
Send litecoins to another litecoin wallet specified by address.
### Response:
def litecoin_withdrawal(self, amount, address):
"""
Send litecoins to another litecoin wallet specified by address.
"""
data = {'amount': am... |
def unload(self):
"""GUI breakdown procedure (for QGIS plugin api).
.. note:: Don't change the name of this method from unload!
This method is called by QGIS and should be used to *remove*
any graphical user interface elements that should appear in QGIS.
"""
# Remove th... | GUI breakdown procedure (for QGIS plugin api).
.. note:: Don't change the name of this method from unload!
This method is called by QGIS and should be used to *remove*
any graphical user interface elements that should appear in QGIS. | Below is the the instruction that describes the task:
### Input:
GUI breakdown procedure (for QGIS plugin api).
.. note:: Don't change the name of this method from unload!
This method is called by QGIS and should be used to *remove*
any graphical user interface elements that should appear ... |
def as_bytes(self) -> bytes:
"""
Returns BLS entity bytes representation.
:return: BLS entity bytes representation
"""
logger = logging.getLogger(__name__)
logger.debug("BlsEntity.as_bytes: >>> self: %r", self)
xbytes = POINTER(c_ubyte)()
xbytes_len = c_s... | Returns BLS entity bytes representation.
:return: BLS entity bytes representation | Below is the the instruction that describes the task:
### Input:
Returns BLS entity bytes representation.
:return: BLS entity bytes representation
### Response:
def as_bytes(self) -> bytes:
"""
Returns BLS entity bytes representation.
:return: BLS entity bytes representation
... |
def split(self, points):
'''Splits the list of time intervals in the specified points
The function assumes that the time intervals do not overlap and ignores
points that are not inside of any interval.
Parameters
==========
points: list of datetime
'''
f... | Splits the list of time intervals in the specified points
The function assumes that the time intervals do not overlap and ignores
points that are not inside of any interval.
Parameters
==========
points: list of datetime | Below is the the instruction that describes the task:
### Input:
Splits the list of time intervals in the specified points
The function assumes that the time intervals do not overlap and ignores
points that are not inside of any interval.
Parameters
==========
points: list ... |
def correct_bitstring_probs(p, assignment_probabilities):
"""
Given a 2d array of corrupted bitstring probabilities (outer axis iterates over shots, inner
axis over bits) and a list of assignment probability matrices (one for each bit in the readout)
compute the corrected probabilities.
:param np.a... | Given a 2d array of corrupted bitstring probabilities (outer axis iterates over shots, inner
axis over bits) and a list of assignment probability matrices (one for each bit in the readout)
compute the corrected probabilities.
:param np.array p: An array that enumerates bitstring probabilities. When
... | Below is the the instruction that describes the task:
### Input:
Given a 2d array of corrupted bitstring probabilities (outer axis iterates over shots, inner
axis over bits) and a list of assignment probability matrices (one for each bit in the readout)
compute the corrected probabilities.
:param np.ar... |
def residue_distances(res_1_num, res_1_chain, res_2_num, res_2_chain, model):
"""Distance between the last atom of 2 residues"""
res1 = model[res_1_chain][res_1_num].child_list[-1]
res2 = model[res_2_chain][res_2_num].child_list[-1]
distance = res1 - res2
return distance | Distance between the last atom of 2 residues | Below is the the instruction that describes the task:
### Input:
Distance between the last atom of 2 residues
### Response:
def residue_distances(res_1_num, res_1_chain, res_2_num, res_2_chain, model):
"""Distance between the last atom of 2 residues"""
res1 = model[res_1_chain][res_1_num].child_list[-1]
... |
def generate(self, **kwargs):
'''
Generate a :term:`URI` based on parameters passed.
:param id: The id of the concept or collection.
:param type: What we're generating a :term:`URI` for: `concept`
or `collection`.
:rtype: string
'''
if kwargs['type'] ... | Generate a :term:`URI` based on parameters passed.
:param id: The id of the concept or collection.
:param type: What we're generating a :term:`URI` for: `concept`
or `collection`.
:rtype: string | Below is the the instruction that describes the task:
### Input:
Generate a :term:`URI` based on parameters passed.
:param id: The id of the concept or collection.
:param type: What we're generating a :term:`URI` for: `concept`
or `collection`.
:rtype: string
### Response:
def ... |
def fulfill_order(self, request, pk):
"""Mark the order specified by pk as fulfilled
"""
order = Order.objects.get(id=pk)
order.fulfill()
return Response(status=status.HTTP_204_NO_CONTENT) | Mark the order specified by pk as fulfilled | Below is the the instruction that describes the task:
### Input:
Mark the order specified by pk as fulfilled
### Response:
def fulfill_order(self, request, pk):
"""Mark the order specified by pk as fulfilled
"""
order = Order.objects.get(id=pk)
order.fulfill()
return Respons... |
def __extend_uri(prefixes, short):
"""
Extend a prefixed uri with the help of a specific dictionary of prefixes
:param prefixes: Dictionary of prefixes
:param short: Prefixed uri to be extended
:return:
"""
for prefix in prefixes:
if short.startswith(prefix):
return short... | Extend a prefixed uri with the help of a specific dictionary of prefixes
:param prefixes: Dictionary of prefixes
:param short: Prefixed uri to be extended
:return: | Below is the the instruction that describes the task:
### Input:
Extend a prefixed uri with the help of a specific dictionary of prefixes
:param prefixes: Dictionary of prefixes
:param short: Prefixed uri to be extended
:return:
### Response:
def __extend_uri(prefixes, short):
"""
Extend a pref... |
def GetExpandedPaths(
args):
"""Expands given path patterns.
Args:
args: A `FileFinderArgs` instance that dictates the behaviour of the path
expansion.
Yields:
Absolute paths (as string objects) derived from input patterns.
Raises:
ValueError: For unsupported path types.
"""
if args... | Expands given path patterns.
Args:
args: A `FileFinderArgs` instance that dictates the behaviour of the path
expansion.
Yields:
Absolute paths (as string objects) derived from input patterns.
Raises:
ValueError: For unsupported path types. | Below is the the instruction that describes the task:
### Input:
Expands given path patterns.
Args:
args: A `FileFinderArgs` instance that dictates the behaviour of the path
expansion.
Yields:
Absolute paths (as string objects) derived from input patterns.
Raises:
ValueError: For unsuppor... |
def add_class_button_status(self):
"""Function to enable or disable add class button."""
if self.class_form.text() and self.radius_form.value() >= 0:
self.add_class_button.setEnabled(True)
else:
self.add_class_button.setEnabled(False) | Function to enable or disable add class button. | Below is the the instruction that describes the task:
### Input:
Function to enable or disable add class button.
### Response:
def add_class_button_status(self):
"""Function to enable or disable add class button."""
if self.class_form.text() and self.radius_form.value() >= 0:
self.add_c... |
def _events_available_in_scheduled_slot(events, slots, X, **kwargs):
"""
Constraint that ensures that an event is scheduled in slots for which it is
available
"""
slot_availability_array = lpu.slot_availability_array(slots=slots,
events=event... | Constraint that ensures that an event is scheduled in slots for which it is
available | Below is the the instruction that describes the task:
### Input:
Constraint that ensures that an event is scheduled in slots for which it is
available
### Response:
def _events_available_in_scheduled_slot(events, slots, X, **kwargs):
"""
Constraint that ensures that an event is scheduled in slots for w... |
def get_holding_change_list(self, code, holder_type, start=None, end=None):
"""
获取大股东持股变动列表,只提供美股数据
:param code: 股票代码. 例如:'US.AAPL'
:param holder_type: 持有者类别,StockHolder_
:param start: 开始时间. 例如:'2016-10-01'
:param end: 结束时间,例如:'2017-10-01'。
start与end的组合如下:
... | 获取大股东持股变动列表,只提供美股数据
:param code: 股票代码. 例如:'US.AAPL'
:param holder_type: 持有者类别,StockHolder_
:param start: 开始时间. 例如:'2016-10-01'
:param end: 结束时间,例如:'2017-10-01'。
start与end的组合如下:
========== ========== ========================================
star... | Below is the the instruction that describes the task:
### Input:
获取大股东持股变动列表,只提供美股数据
:param code: 股票代码. 例如:'US.AAPL'
:param holder_type: 持有者类别,StockHolder_
:param start: 开始时间. 例如:'2016-10-01'
:param end: 结束时间,例如:'2017-10-01'。
start与end的组合如下:
========== ===... |
def _parse(self, lines, grammar, ignore_comments=False):
""" Given a type and a list, parse it using the more detailed
parse grammar.
"""
results = []
for c in lines:
if c != '' and not (ignore_comments and c[0] == '#'):
try:
result... | Given a type and a list, parse it using the more detailed
parse grammar. | Below is the the instruction that describes the task:
### Input:
Given a type and a list, parse it using the more detailed
parse grammar.
### Response:
def _parse(self, lines, grammar, ignore_comments=False):
""" Given a type and a list, parse it using the more detailed
parse grammar.
... |
def build_one(self, package_dir, filename, source_map=False):
"""Builds one Sass/SCSS file.
:param package_dir: the path of package directory
:type package_dir: :class:`str`, :class:`basestring`
:param filename: the filename of Sass/SCSS source to compile
:type filename: :class:... | Builds one Sass/SCSS file.
:param package_dir: the path of package directory
:type package_dir: :class:`str`, :class:`basestring`
:param filename: the filename of Sass/SCSS source to compile
:type filename: :class:`str`, :class:`basestring`
:param source_map: whether to use sour... | Below is the the instruction that describes the task:
### Input:
Builds one Sass/SCSS file.
:param package_dir: the path of package directory
:type package_dir: :class:`str`, :class:`basestring`
:param filename: the filename of Sass/SCSS source to compile
:type filename: :class:`str... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.