code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def exportUsufy(data, ext, fileH):
"""
Method that exports the different structures onto different formats.
Args:
-----
data: Data to export.
ext: One of the following: csv, excel, json, ods.
fileH: Fileheader for the output files.
Returns:
--------
Performs the... | Method that exports the different structures onto different formats.
Args:
-----
data: Data to export.
ext: One of the following: csv, excel, json, ods.
fileH: Fileheader for the output files.
Returns:
--------
Performs the export as requested by parameter. | Below is the the instruction that describes the task:
### Input:
Method that exports the different structures onto different formats.
Args:
-----
data: Data to export.
ext: One of the following: csv, excel, json, ods.
fileH: Fileheader for the output files.
Returns:
-------... |
def _determine_representative_chains(self):
''' Quotient the chains to get equivalence classes of chains. These will be used for the actual mapping.'''
# todo: This logic should be moved into the FASTA class or a more general module (maybe a fast exists which uses a C/C++ library?) but at present it is ... | Quotient the chains to get equivalence classes of chains. These will be used for the actual mapping. | Below is the the instruction that describes the task:
### Input:
Quotient the chains to get equivalence classes of chains. These will be used for the actual mapping.
### Response:
def _determine_representative_chains(self):
''' Quotient the chains to get equivalence classes of chains. These will be used fo... |
def native_description(self):
""" todo document
"""
if self._session is None:
return None
res = self._session.res_info
if res:
return res.native_descr
else:
return None | todo document | Below is the the instruction that describes the task:
### Input:
todo document
### Response:
def native_description(self):
""" todo document
"""
if self._session is None:
return None
res = self._session.res_info
if res:
return res.native_descr
... |
def _readString(self, length_fmt="H"):
"""
Reads a serialized string
:param length_fmt: Structure format of the string length (H or Q)
:return: The deserialized string
:raise RuntimeError: Unexpected end of stream
"""
(length,) = self._readStruct(">{0}".format(le... | Reads a serialized string
:param length_fmt: Structure format of the string length (H or Q)
:return: The deserialized string
:raise RuntimeError: Unexpected end of stream | Below is the the instruction that describes the task:
### Input:
Reads a serialized string
:param length_fmt: Structure format of the string length (H or Q)
:return: The deserialized string
:raise RuntimeError: Unexpected end of stream
### Response:
def _readString(self, length_fmt="H"):
... |
def current_frame(self):
"""
Compute the number of the current frame (0-indexed)
"""
if not self._pause_level:
return (
int((self._clock() + self._offset) * self.frames_per_second)
% len(self._frames)
)
else:
ret... | Compute the number of the current frame (0-indexed) | Below is the the instruction that describes the task:
### Input:
Compute the number of the current frame (0-indexed)
### Response:
def current_frame(self):
"""
Compute the number of the current frame (0-indexed)
"""
if not self._pause_level:
return (
int(... |
def _extract_id_token(id_token):
"""Extract the JSON payload from a JWT.
Does the extraction w/o checking the signature.
Args:
id_token: string or bytestring, OAuth 2.0 id_token.
Returns:
object, The deserialized JSON payload.
"""
if type(id_token) == bytes:
segments =... | Extract the JSON payload from a JWT.
Does the extraction w/o checking the signature.
Args:
id_token: string or bytestring, OAuth 2.0 id_token.
Returns:
object, The deserialized JSON payload. | Below is the the instruction that describes the task:
### Input:
Extract the JSON payload from a JWT.
Does the extraction w/o checking the signature.
Args:
id_token: string or bytestring, OAuth 2.0 id_token.
Returns:
object, The deserialized JSON payload.
### Response:
def _extract_i... |
def run(self, data, runtime_dir, argv):
"""Select a concrete connector and run the process through it.
:param data: The :class:`~resolwe.flow.models.Data` object that
is to be run.
:param runtime_dir: The directory the executor is run from.
:param argv: The argument vector u... | Select a concrete connector and run the process through it.
:param data: The :class:`~resolwe.flow.models.Data` object that
is to be run.
:param runtime_dir: The directory the executor is run from.
:param argv: The argument vector used to spawn the executor. | Below is the the instruction that describes the task:
### Input:
Select a concrete connector and run the process through it.
:param data: The :class:`~resolwe.flow.models.Data` object that
is to be run.
:param runtime_dir: The directory the executor is run from.
:param argv: The... |
def get_gan_loss(self, true_frames, gen_frames, name):
"""Get the discriminator + generator loss at every step.
This performs an 1:1 update of the discriminator and generator at every
step.
Args:
true_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C)
Assumed to be g... | Get the discriminator + generator loss at every step.
This performs an 1:1 update of the discriminator and generator at every
step.
Args:
true_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C)
Assumed to be ground truth.
gen_frames: 5-D Tensor of shape (num_steps,... | Below is the the instruction that describes the task:
### Input:
Get the discriminator + generator loss at every step.
This performs an 1:1 update of the discriminator and generator at every
step.
Args:
true_frames: 5-D Tensor of shape (num_steps, batch_size, H, W, C)
Assumed ... |
def _set_sitematrix(self):
"""
capture API sitematrix data in data attribute
"""
data = self._load_response('sitematrix')
self.params.update({'title': self.COMMONS})
matrix = data.get('sitematrix')
if matrix:
self.data['sites'] = self._sitelist(matri... | capture API sitematrix data in data attribute | Below is the the instruction that describes the task:
### Input:
capture API sitematrix data in data attribute
### Response:
def _set_sitematrix(self):
"""
capture API sitematrix data in data attribute
"""
data = self._load_response('sitematrix')
self.params.update({'title'... |
def float2json(value):
"""
CONVERT NUMBER TO JSON STRING, WITH BETTER CONTROL OVER ACCURACY
:param value: float, int, long, Decimal
:return: unicode
"""
if value == 0:
return u'0'
try:
sign = "-" if value < 0 else ""
value = abs(value)
sci = value.__format__("... | CONVERT NUMBER TO JSON STRING, WITH BETTER CONTROL OVER ACCURACY
:param value: float, int, long, Decimal
:return: unicode | Below is the the instruction that describes the task:
### Input:
CONVERT NUMBER TO JSON STRING, WITH BETTER CONTROL OVER ACCURACY
:param value: float, int, long, Decimal
:return: unicode
### Response:
def float2json(value):
"""
CONVERT NUMBER TO JSON STRING, WITH BETTER CONTROL OVER ACCURACY
:p... |
def get_line_value(self, context_type):
"""
Get the values defined on this line.
:param context_type: "ENV" or "LABEL"
:return: values of given type defined on this line
"""
if context_type.upper() == "ENV":
return self.line_envs
elif context_type.upp... | Get the values defined on this line.
:param context_type: "ENV" or "LABEL"
:return: values of given type defined on this line | Below is the the instruction that describes the task:
### Input:
Get the values defined on this line.
:param context_type: "ENV" or "LABEL"
:return: values of given type defined on this line
### Response:
def get_line_value(self, context_type):
"""
Get the values defined on this li... |
def set_field(self, state, field_name, field_type, value):
"""
Sets an instance field.
"""
field_ref = SimSootValue_InstanceFieldRef.get_ref(state=state,
obj_alloc_id=self.heap_alloc_id,
... | Sets an instance field. | Below is the the instruction that describes the task:
### Input:
Sets an instance field.
### Response:
def set_field(self, state, field_name, field_type, value):
"""
Sets an instance field.
"""
field_ref = SimSootValue_InstanceFieldRef.get_ref(state=state,
... |
def rel_posterior_mass(logx, logl):
"""Calculate the relative posterior mass for some array of logx values
given the likelihood, prior and number of dimensions.
The posterior mass at each logX value is proportional to L(X)X, where L(X)
is the likelihood.
The weight is returned normalized so that the... | Calculate the relative posterior mass for some array of logx values
given the likelihood, prior and number of dimensions.
The posterior mass at each logX value is proportional to L(X)X, where L(X)
is the likelihood.
The weight is returned normalized so that the integral of the weight with
respect to... | Below is the the instruction that describes the task:
### Input:
Calculate the relative posterior mass for some array of logx values
given the likelihood, prior and number of dimensions.
The posterior mass at each logX value is proportional to L(X)X, where L(X)
is the likelihood.
The weight is retur... |
def get_roc_values(motif, fg_file, bg_file):
"""Calculate ROC AUC values for ROC plots."""
#print(calc_stats(motif, fg_file, bg_file, stats=["roc_values"], ncpus=1))
#["roc_values"])
try:
# fg_result = motif.pwm_scan_score(Fasta(fg_file), cutoff=0.0, nreport=1)
# fg_vals = [sorted(x)[... | Calculate ROC AUC values for ROC plots. | Below is the the instruction that describes the task:
### Input:
Calculate ROC AUC values for ROC plots.
### Response:
def get_roc_values(motif, fg_file, bg_file):
"""Calculate ROC AUC values for ROC plots."""
#print(calc_stats(motif, fg_file, bg_file, stats=["roc_values"], ncpus=1))
#["roc_values"])
... |
def filter_keys(self, **kwargs):
"Return a set of keys filtered according to the given arguments."
self._used_index = False
keys = set(self.data.keys())
for key_filter, v_filter in kwargs.items():
if key_filter in self.indexes:
self._used_index = True
... | Return a set of keys filtered according to the given arguments. | Below is the the instruction that describes the task:
### Input:
Return a set of keys filtered according to the given arguments.
### Response:
def filter_keys(self, **kwargs):
"Return a set of keys filtered according to the given arguments."
self._used_index = False
keys = set(self.data.key... |
def expand_folder(files):
"""Return a clone of file list files where all directories are recursively replaced with their contents."""
expfiles = []
for file in files:
if os.path.isdir(file):
for dirpath, dirnames, filenames in os.walk(file):
for filename in filenames:
... | Return a clone of file list files where all directories are recursively replaced with their contents. | Below is the the instruction that describes the task:
### Input:
Return a clone of file list files where all directories are recursively replaced with their contents.
### Response:
def expand_folder(files):
"""Return a clone of file list files where all directories are recursively replaced with their contents.... |
def predict(self, recording, result_format=None):
"""Predict the class of the given recording.
Parameters
----------
recording : string
Recording of a single handwritten dataset in JSON format.
result_format : string, optional
If it is 'LaTeX', then only ... | Predict the class of the given recording.
Parameters
----------
recording : string
Recording of a single handwritten dataset in JSON format.
result_format : string, optional
If it is 'LaTeX', then only the latex code will be returned
Returns
----... | Below is the the instruction that describes the task:
### Input:
Predict the class of the given recording.
Parameters
----------
recording : string
Recording of a single handwritten dataset in JSON format.
result_format : string, optional
If it is 'LaTeX', th... |
def environ(on=os, **kw):
"""Update one or more environment variables.
Preserves the previous environment variable (if available) and can be
applied to remote connections that offer an @environ@ attribute using the
@on@ argument.
"""
originals = list()
for key in kw:
o... | Update one or more environment variables.
Preserves the previous environment variable (if available) and can be
applied to remote connections that offer an @environ@ attribute using the
@on@ argument. | Below is the the instruction that describes the task:
### Input:
Update one or more environment variables.
Preserves the previous environment variable (if available) and can be
applied to remote connections that offer an @environ@ attribute using the
@on@ argument.
### Response:
def environ(on=os,... |
def ekcii(table, cindex, lenout=_default_len_out):
"""
Return attribute information about a column belonging to a loaded
EK table, specifying the column by table and index.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekcii_c.html
:param table: Name of table containing column.
:type... | Return attribute information about a column belonging to a loaded
EK table, specifying the column by table and index.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekcii_c.html
:param table: Name of table containing column.
:type table: str
:param cindex: Index of column whose attributes... | Below is the the instruction that describes the task:
### Input:
Return attribute information about a column belonging to a loaded
EK table, specifying the column by table and index.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ekcii_c.html
:param table: Name of table containing column.
... |
def set_lang(prefix):
'''
Change the language of the API being requested.
Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_.
After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared... | Change the language of the API being requested.
Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_.
After setting the language, the cache for ``search``, ``suggest``, and ``summary`` will be cleared.
.. note:: Make sure you s... | Below is the the instruction that describes the task:
### Input:
Change the language of the API being requested.
Set `prefix` to one of the two letter prefixes found on the `list of all Wikipedias <http://meta.wikimedia.org/wiki/List_of_Wikipedias>`_.
After setting the language, the cache for ``search``, ``sug... |
def split_address(address):
"""
Returns (host, port) with an integer port from the specified address
string. (None, None) is returned if the address is invalid.
"""
invalid = None, None
if not address and address != 0:
return invalid
components = str(address).split(':')
if len(... | Returns (host, port) with an integer port from the specified address
string. (None, None) is returned if the address is invalid. | Below is the the instruction that describes the task:
### Input:
Returns (host, port) with an integer port from the specified address
string. (None, None) is returned if the address is invalid.
### Response:
def split_address(address):
"""
Returns (host, port) with an integer port from the specified ad... |
def db_from_hass_config(path=None, **kwargs):
"""Initialize a database from HASS config."""
if path is None:
path = config.find_hass_config()
url = config.db_url_from_hass_config(path)
return HassDatabase(url, **kwargs) | Initialize a database from HASS config. | Below is the the instruction that describes the task:
### Input:
Initialize a database from HASS config.
### Response:
def db_from_hass_config(path=None, **kwargs):
"""Initialize a database from HASS config."""
if path is None:
path = config.find_hass_config()
url = config.db_url_from_hass_con... |
def render(self):
"""Render reply from Python object to XML string"""
tpl = '<xml>\n{data}\n</xml>'
nodes = []
msg_type = '<MsgType><![CDATA[{msg_type}]]></MsgType>'.format(
msg_type=self.type
)
nodes.append(msg_type)
for name, field in self._fields.it... | Render reply from Python object to XML string | Below is the the instruction that describes the task:
### Input:
Render reply from Python object to XML string
### Response:
def render(self):
"""Render reply from Python object to XML string"""
tpl = '<xml>\n{data}\n</xml>'
nodes = []
msg_type = '<MsgType><![CDATA[{msg_type}]]></Ms... |
def render_config(data,ctx):
"""Render the given config data using Django's template system.
This function takes a config data string and a dict of context variables,
renders the data through Django's template system, and returns the result.
"""
djsupervisor_tags.current_context = ctx
data = "{... | Render the given config data using Django's template system.
This function takes a config data string and a dict of context variables,
renders the data through Django's template system, and returns the result. | Below is the the instruction that describes the task:
### Input:
Render the given config data using Django's template system.
This function takes a config data string and a dict of context variables,
renders the data through Django's template system, and returns the result.
### Response:
def render_config... |
def index_delete(self, index):
'''
Delets the specified index
> search = ElasticSearch()
> search.index_delete('twitter')
{"ok" : True, "acknowledged" : True }
'''
request = self.session
url = 'http://%s:%s/%s' % (self.host, self.port, index)
res... | Delets the specified index
> search = ElasticSearch()
> search.index_delete('twitter')
{"ok" : True, "acknowledged" : True } | Below is the the instruction that describes the task:
### Input:
Delets the specified index
> search = ElasticSearch()
> search.index_delete('twitter')
{"ok" : True, "acknowledged" : True }
### Response:
def index_delete(self, index):
'''
Delets the specified index
... |
def delete_core_element_of_model(model, raise_exceptions=False, recursive=True, destroy=True, force=False):
"""Deletes respective core element of handed model of its state machine
If the model is one of state, data flow or transition, it is tried to delete that model together with its
data from the corresp... | Deletes respective core element of handed model of its state machine
If the model is one of state, data flow or transition, it is tried to delete that model together with its
data from the corresponding state machine.
:param model: The model of respective core element to delete
:param bool raise_excep... | Below is the the instruction that describes the task:
### Input:
Deletes respective core element of handed model of its state machine
If the model is one of state, data flow or transition, it is tried to delete that model together with its
data from the corresponding state machine.
:param model: The m... |
def plot_phase_plane(self, indices=None, **kwargs):
""" Plots a phase portrait from last integration.
This method will be deprecated. Please use :meth:`Result.plot_phase_plane`.
See :func:`pyodesys.plotting.plot_phase_plane`
"""
return self._plot(plot_phase_plane, indices=indice... | Plots a phase portrait from last integration.
This method will be deprecated. Please use :meth:`Result.plot_phase_plane`.
See :func:`pyodesys.plotting.plot_phase_plane` | Below is the the instruction that describes the task:
### Input:
Plots a phase portrait from last integration.
This method will be deprecated. Please use :meth:`Result.plot_phase_plane`.
See :func:`pyodesys.plotting.plot_phase_plane`
### Response:
def plot_phase_plane(self, indices=None, **kwargs)... |
def ascii2h5(dat_fname, h5_fname):
"""
Converts from the original ASCII format of the Chen+ (2014) 3D dust map to
the HDF5 format.
Args:
dat_fname (:obj:`str`): Filename of the original ASCII .dat file.
h5_fname (:obj:`str`): Output filename to write the resulting HDF5 file to.
"""
... | Converts from the original ASCII format of the Chen+ (2014) 3D dust map to
the HDF5 format.
Args:
dat_fname (:obj:`str`): Filename of the original ASCII .dat file.
h5_fname (:obj:`str`): Output filename to write the resulting HDF5 file to. | Below is the the instruction that describes the task:
### Input:
Converts from the original ASCII format of the Chen+ (2014) 3D dust map to
the HDF5 format.
Args:
dat_fname (:obj:`str`): Filename of the original ASCII .dat file.
h5_fname (:obj:`str`): Output filename to write the resulting ... |
def set_log_level(self, level, keep=True):
"""
Set the log level. If keep is True, then it will not change along with
global log changes.
"""
self._set_log_level(level)
self._log_level_set_explicitly = keep | Set the log level. If keep is True, then it will not change along with
global log changes. | Below is the the instruction that describes the task:
### Input:
Set the log level. If keep is True, then it will not change along with
global log changes.
### Response:
def set_log_level(self, level, keep=True):
"""
Set the log level. If keep is True, then it will not change along with
... |
def create_virtualenv(venv=VENV, install_pip=False):
"""Creates the virtual environment and installs PIP only into the
virtual environment
"""
print 'Creating venv...',
install = ['virtualenv', '-q', venv]
run_command(install)
print 'done.'
print 'Installing pip in virtualenv...',
... | Creates the virtual environment and installs PIP only into the
virtual environment | Below is the the instruction that describes the task:
### Input:
Creates the virtual environment and installs PIP only into the
virtual environment
### Response:
def create_virtualenv(venv=VENV, install_pip=False):
"""Creates the virtual environment and installs PIP only into the
virtual environment
... |
def content_create(self, key, model, contentid, meta, protected=False):
"""Creates a content entity bucket with the given `contentid`.
This method maps to
https://github.com/exosite/docs/tree/master/provision#post---create-content-entity.
Args:
key: The CIK or Token for the... | Creates a content entity bucket with the given `contentid`.
This method maps to
https://github.com/exosite/docs/tree/master/provision#post---create-content-entity.
Args:
key: The CIK or Token for the device
model:
contentid: The ID used to name the entity bu... | Below is the the instruction that describes the task:
### Input:
Creates a content entity bucket with the given `contentid`.
This method maps to
https://github.com/exosite/docs/tree/master/provision#post---create-content-entity.
Args:
key: The CIK or Token for the device
... |
def calculate_leaf_paths(self):
"""Build map of reverse xrefs then traverse backwards marking path to leaf for all leaves.
"""
reverse_xref = {}
leaves = set()
for v in self.value.values():
if v.leaf:
leaves.add(v)
for xref in v.value_xref:... | Build map of reverse xrefs then traverse backwards marking path to leaf for all leaves. | Below is the the instruction that describes the task:
### Input:
Build map of reverse xrefs then traverse backwards marking path to leaf for all leaves.
### Response:
def calculate_leaf_paths(self):
"""Build map of reverse xrefs then traverse backwards marking path to leaf for all leaves.
"""
... |
def _set_sflow(self, v, load=False):
"""
Setter method for sflow, mapped from YANG variable /overlay_gateway/sflow (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_sflow is considered as a private
method. Backends looking to populate this variable should
do... | Setter method for sflow, mapped from YANG variable /overlay_gateway/sflow (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_sflow is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sflow() directly. | Below is the the instruction that describes the task:
### Input:
Setter method for sflow, mapped from YANG variable /overlay_gateway/sflow (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_sflow is considered as a private
method. Backends looking to populate this va... |
def coalesce(self):
"""Coalesce the segments for this flag.
This method does two things:
- `coalesces <SegmentList.coalesce>` the `~DataQualityFlag.known` and
`~DataQualityFlag.active` segment lists
- forces the `active` segments to be a proper subset of the `known`
... | Coalesce the segments for this flag.
This method does two things:
- `coalesces <SegmentList.coalesce>` the `~DataQualityFlag.known` and
`~DataQualityFlag.active` segment lists
- forces the `active` segments to be a proper subset of the `known`
segments
.. note::
... | Below is the the instruction that describes the task:
### Input:
Coalesce the segments for this flag.
This method does two things:
- `coalesces <SegmentList.coalesce>` the `~DataQualityFlag.known` and
`~DataQualityFlag.active` segment lists
- forces the `active` segments to be a ... |
def parse_cookie(header, charset='utf-8', errors='ignore'):
"""Parse a cookie.
:param header: the header to be used to parse the cookie.
:param charset: the charset for the cookie values.
:param errors: the error behavior for the charset decoding.
"""
cookie = _ExtendedCookie()
if header:
... | Parse a cookie.
:param header: the header to be used to parse the cookie.
:param charset: the charset for the cookie values.
:param errors: the error behavior for the charset decoding. | Below is the the instruction that describes the task:
### Input:
Parse a cookie.
:param header: the header to be used to parse the cookie.
:param charset: the charset for the cookie values.
:param errors: the error behavior for the charset decoding.
### Response:
def parse_cookie(header, charset='utf-... |
def blotto_game(h, t, rho, mu=0, random_state=None):
"""
Return a NormalFormGame instance of a 2-player non-zero sum Colonel
Blotto game (Hortala-Vallve and Llorente-Saguer, 2012), where the
players have an equal number `t` of troops to assign to `h` hills
(so that the number of actions for each pla... | Return a NormalFormGame instance of a 2-player non-zero sum Colonel
Blotto game (Hortala-Vallve and Llorente-Saguer, 2012), where the
players have an equal number `t` of troops to assign to `h` hills
(so that the number of actions for each player is equal to
(t+h-1) choose (h-1) = (t+h-1)!/(t!*(h-1)!)).... | Below is the the instruction that describes the task:
### Input:
Return a NormalFormGame instance of a 2-player non-zero sum Colonel
Blotto game (Hortala-Vallve and Llorente-Saguer, 2012), where the
players have an equal number `t` of troops to assign to `h` hills
(so that the number of actions for each... |
def git_commentchar():
""" Shortcut for retrieving comment char from git config """
commentchar = _git("config", "--get", "core.commentchar", _ok_code=[1])
# git will return an exit code of 1 if it can't find a config value, in this case we fall-back to # as commentchar
if hasattr(commentchar, 'exit_cod... | Shortcut for retrieving comment char from git config | Below is the the instruction that describes the task:
### Input:
Shortcut for retrieving comment char from git config
### Response:
def git_commentchar():
""" Shortcut for retrieving comment char from git config """
commentchar = _git("config", "--get", "core.commentchar", _ok_code=[1])
# git will retu... |
def generate_function(info, method=False):
"""Creates a Python callable for a GIFunctionInfo instance"""
assert isinstance(info, GIFunctionInfo)
arg_infos = list(info.get_args())
arg_types = [a.get_type() for a in arg_infos]
return_type = info.get_return_type()
func = None
messages = []
... | Creates a Python callable for a GIFunctionInfo instance | Below is the the instruction that describes the task:
### Input:
Creates a Python callable for a GIFunctionInfo instance
### Response:
def generate_function(info, method=False):
"""Creates a Python callable for a GIFunctionInfo instance"""
assert isinstance(info, GIFunctionInfo)
arg_infos = list(info... |
def read_cz_lsminfo(fh, byteorder, dtype, count, offsetsize):
"""Read CZ_LSMINFO tag from file and return as dict."""
assert byteorder == '<'
magic_number, structure_size = struct.unpack('<II', fh.read(8))
if magic_number not in (50350412, 67127628):
raise ValueError('invalid CZ_LSMINFO structur... | Read CZ_LSMINFO tag from file and return as dict. | Below is the the instruction that describes the task:
### Input:
Read CZ_LSMINFO tag from file and return as dict.
### Response:
def read_cz_lsminfo(fh, byteorder, dtype, count, offsetsize):
"""Read CZ_LSMINFO tag from file and return as dict."""
assert byteorder == '<'
magic_number, structure_size = s... |
def _init_map(self):
"""call these all manually because non-cooperative"""
DecimalAnswerFormRecord._init_map(self)
DecimalValuesFormRecord._init_map(self)
TextAnswerFormRecord._init_map(self)
TextsFormRecord._init_map(self)
super(edXNumericResponseAnswerFormRecord, self).... | call these all manually because non-cooperative | Below is the the instruction that describes the task:
### Input:
call these all manually because non-cooperative
### Response:
def _init_map(self):
"""call these all manually because non-cooperative"""
DecimalAnswerFormRecord._init_map(self)
DecimalValuesFormRecord._init_map(self)
T... |
def stop_watching(self, cluster):
"""
Causes the thread that launched the watch of the cluster path
to end by setting the proper stop event found in `self.stop_events`.
"""
znode_path = "/".join([self.base_path, cluster.name])
if znode_path in self.stop_events:
... | Causes the thread that launched the watch of the cluster path
to end by setting the proper stop event found in `self.stop_events`. | Below is the the instruction that describes the task:
### Input:
Causes the thread that launched the watch of the cluster path
to end by setting the proper stop event found in `self.stop_events`.
### Response:
def stop_watching(self, cluster):
"""
Causes the thread that launched the watch o... |
def get_stp_mst_detail_output_msti_port_rx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
config = get_stp_mst_detail
output = ET.SubElement(get_stp_mst_detail, "output")
m... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_stp_mst_detail_output_msti_port_rx_bpdu_count(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_stp_mst_detail = ET.Element("get_stp_mst_detail")
... |
def do_exit(self, arg):
"""Exit the shell session."""
if self.current:
self.current.close()
self.resource_manager.close()
del self.resource_manager
return True | Exit the shell session. | Below is the the instruction that describes the task:
### Input:
Exit the shell session.
### Response:
def do_exit(self, arg):
"""Exit the shell session."""
if self.current:
self.current.close()
self.resource_manager.close()
del self.resource_manager
return True |
def add_user(self, username, email, **kwargs):
"""Create a new user with provided details.
Add user example:
.. code-block:: python
account_management_api = AccountManagementAPI()
# Add user
user = {
"username": "test_user",
... | Create a new user with provided details.
Add user example:
.. code-block:: python
account_management_api = AccountManagementAPI()
# Add user
user = {
"username": "test_user",
"email": "test@gmail.com",
"phone_number":... | Below is the the instruction that describes the task:
### Input:
Create a new user with provided details.
Add user example:
.. code-block:: python
account_management_api = AccountManagementAPI()
# Add user
user = {
"username": "test_user",
... |
def get_version(cls, path, memo={}):
"""
Return a string describing the version of the repository at ``path`` if
possible, otherwise throws ``subprocess.CalledProcessError``.
(Note: memoizes the result in the ``memo`` parameter)
"""
if path not in memo:
memo[... | Return a string describing the version of the repository at ``path`` if
possible, otherwise throws ``subprocess.CalledProcessError``.
(Note: memoizes the result in the ``memo`` parameter) | Below is the the instruction that describes the task:
### Input:
Return a string describing the version of the repository at ``path`` if
possible, otherwise throws ``subprocess.CalledProcessError``.
(Note: memoizes the result in the ``memo`` parameter)
### Response:
def get_version(cls, path, memo... |
def attention_lm_ae_extended():
"""Experiment with the exp_factor params."""
hparams = attention_lm_moe_base_long_seq()
hparams.attention_layers = "eeee"
hparams.attention_local = True
# hparams.factored_logits=1 # Necessary when the number of expert grow bigger
hparams.attention_moe_k = 2
hparams.attent... | Experiment with the exp_factor params. | Below is the the instruction that describes the task:
### Input:
Experiment with the exp_factor params.
### Response:
def attention_lm_ae_extended():
"""Experiment with the exp_factor params."""
hparams = attention_lm_moe_base_long_seq()
hparams.attention_layers = "eeee"
hparams.attention_local = True
# ... |
def update_index(self, key, value):
"Update the index with the new key/values."
for k, v in value.items():
if k in self.indexes:
# A non-string index value switches it into a lazy one.
if not isinstance(v, six.string_types):
self.index_defs... | Update the index with the new key/values. | Below is the the instruction that describes the task:
### Input:
Update the index with the new key/values.
### Response:
def update_index(self, key, value):
"Update the index with the new key/values."
for k, v in value.items():
if k in self.indexes:
# A non-string index ... |
def is_invalid_params_py2(func, *args, **kwargs):
""" Check, whether function 'func' accepts parameters 'args', 'kwargs'.
NOTE: Method is called after funct(*args, **kwargs) generated TypeError,
it is aimed to destinguish TypeError because of invalid parameters from
TypeError from inside the function.
... | Check, whether function 'func' accepts parameters 'args', 'kwargs'.
NOTE: Method is called after funct(*args, **kwargs) generated TypeError,
it is aimed to destinguish TypeError because of invalid parameters from
TypeError from inside the function.
.. versionadded: 1.9.0 | Below is the the instruction that describes the task:
### Input:
Check, whether function 'func' accepts parameters 'args', 'kwargs'.
NOTE: Method is called after funct(*args, **kwargs) generated TypeError,
it is aimed to destinguish TypeError because of invalid parameters from
TypeError from inside the... |
def get_template(self, template_name):
'''
Retrieves a template object from the pattern "app_name/template.html".
This is one of the required methods of Django template engines.
Because DMP templates are always app-specific (Django only searches
a global set of directories), the... | Retrieves a template object from the pattern "app_name/template.html".
This is one of the required methods of Django template engines.
Because DMP templates are always app-specific (Django only searches
a global set of directories), the template_name MUST be in the format:
"app_name/tem... | Below is the the instruction that describes the task:
### Input:
Retrieves a template object from the pattern "app_name/template.html".
This is one of the required methods of Django template engines.
Because DMP templates are always app-specific (Django only searches
a global set of directo... |
def handle_termination(cls, pid, is_cancel=True):
'''
Internal method to terminate a subprocess spawned by `pexpect` representing an invocation of runner.
:param pid: the process id of the running the job.
:param is_cancel: flag showing whether this termination is caused by
... | Internal method to terminate a subprocess spawned by `pexpect` representing an invocation of runner.
:param pid: the process id of the running the job.
:param is_cancel: flag showing whether this termination is caused by
instance's cancel_flag. | Below is the the instruction that describes the task:
### Input:
Internal method to terminate a subprocess spawned by `pexpect` representing an invocation of runner.
:param pid: the process id of the running the job.
:param is_cancel: flag showing whether this termination is caused by
... |
def validate_args(api_key, *, rate="informers", **kwargs):
"Проверяет и формирует аргументы для запроса"
rate = Rate.validate(rate)
headers = {"X-Yandex-API-Key": api_key}
url = "https://api.weather.yandex.ru/v1/{}".format(rate)
if rate == "informers":
params = ARGS_SCHEMA(kwargs)
else:
... | Проверяет и формирует аргументы для запроса | Below is the the instruction that describes the task:
### Input:
Проверяет и формирует аргументы для запроса
### Response:
def validate_args(api_key, *, rate="informers", **kwargs):
"Проверяет и формирует аргументы для запроса"
rate = Rate.validate(rate)
headers = {"X-Yandex-API-Key": api_key}
url ... |
def getElementsByTagName(self, tagName, root='root'):
'''
getElementsByTagName - Searches and returns all elements with a specific tag name.
@param tagName <lowercase str> - A lowercase string of the tag name.
@param root <AdvancedTag/'root'> - Search... | getElementsByTagName - Searches and returns all elements with a specific tag name.
@param tagName <lowercase str> - A lowercase string of the tag name.
@param root <AdvancedTag/'root'> - Search starting at a specific node, if provided. if string 'root', the root of the p... | Below is the the instruction that describes the task:
### Input:
getElementsByTagName - Searches and returns all elements with a specific tag name.
@param tagName <lowercase str> - A lowercase string of the tag name.
@param root <AdvancedTag/'root'> - Search starting... |
def responsive(self):
""" bool: Whether the server for this app is up and responsive. """
if self.server_thread and self.server_thread.join(0):
return False
try:
# Try to fetch the endpoint added by the middleware.
identify_url = "http://{0}:{1}/__identify__... | bool: Whether the server for this app is up and responsive. | Below is the the instruction that describes the task:
### Input:
bool: Whether the server for this app is up and responsive.
### Response:
def responsive(self):
""" bool: Whether the server for this app is up and responsive. """
if self.server_thread and self.server_thread.join(0):
ret... |
def random_chain(generators):
"""Generator to generate a set of keys from
from a set of generators, each generator is selected
at random and consumed to exhaustion.
"""
while generators:
g = random.choice(generators)
try:
v = g.next()
if v is None:
... | Generator to generate a set of keys from
from a set of generators, each generator is selected
at random and consumed to exhaustion. | Below is the the instruction that describes the task:
### Input:
Generator to generate a set of keys from
from a set of generators, each generator is selected
at random and consumed to exhaustion.
### Response:
def random_chain(generators):
"""Generator to generate a set of keys from
from a set of ... |
def set_public_domain(self, public_domain):
"""Sets the public domain flag.
arg: public_domain (boolean): the public domain status
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
# Implemented f... | Sets the public domain flag.
arg: public_domain (boolean): the public domain status
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Sets the public domain flag.
arg: public_domain (boolean): the public domain status
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
### Response:
def set... |
def _selectView( self ):
"""
Matches the view selection to the trees selection.
"""
scene = self.uiGanttVIEW.scene()
scene.blockSignals(True)
scene.clearSelection()
for item in self.uiGanttTREE.selectedItems():
item.viewItem().setSelected(True)... | Matches the view selection to the trees selection. | Below is the the instruction that describes the task:
### Input:
Matches the view selection to the trees selection.
### Response:
def _selectView( self ):
"""
Matches the view selection to the trees selection.
"""
scene = self.uiGanttVIEW.scene()
scene.blockSignals(True... |
def common(self, other):
'''
Return the common part of these two mults. This is the largest mult
which can be safely subtracted from both the originals. The multiplier
on this mult could be zero: this is the case if, for example, the
multiplicands disagree.
'''
if self.multiplicand == other.multiplica... | Return the common part of these two mults. This is the largest mult
which can be safely subtracted from both the originals. The multiplier
on this mult could be zero: this is the case if, for example, the
multiplicands disagree. | Below is the the instruction that describes the task:
### Input:
Return the common part of these two mults. This is the largest mult
which can be safely subtracted from both the originals. The multiplier
on this mult could be zero: this is the case if, for example, the
multiplicands disagree.
### Response:... |
async def encrypt(self, message: bytes, authn: bool = False, recip: str = None) -> bytes:
"""
Encrypt plaintext for owner of DID or verification key, anonymously or via
authenticated encryption scheme. If given DID, first check wallet and then pool
for corresponding verification key.
... | Encrypt plaintext for owner of DID or verification key, anonymously or via
authenticated encryption scheme. If given DID, first check wallet and then pool
for corresponding verification key.
Raise WalletState if the wallet is closed. Given a recipient DID not in the wallet,
raise Absent... | Below is the the instruction that describes the task:
### Input:
Encrypt plaintext for owner of DID or verification key, anonymously or via
authenticated encryption scheme. If given DID, first check wallet and then pool
for corresponding verification key.
Raise WalletState if the wallet is ... |
def list_databases(self, name):
'''
List the SQL databases defined on the specified server name
'''
response = self._perform_get(self._get_list_databases_path(name),
None)
return _MinidomXmlToObject.parse_service_resources_response(
... | List the SQL databases defined on the specified server name | Below is the the instruction that describes the task:
### Input:
List the SQL databases defined on the specified server name
### Response:
def list_databases(self, name):
'''
List the SQL databases defined on the specified server name
'''
response = self._perform_get(self._get_list_... |
def regex_in_package_file(regex, filename, package_name, return_match=False):
""" Search for a regex in a file contained within the package directory
If return_match is True, return the found object instead of a boolean
"""
filepath = package_file_path(filename, package_name)
return regex_in_file(r... | Search for a regex in a file contained within the package directory
If return_match is True, return the found object instead of a boolean | Below is the the instruction that describes the task:
### Input:
Search for a regex in a file contained within the package directory
If return_match is True, return the found object instead of a boolean
### Response:
def regex_in_package_file(regex, filename, package_name, return_match=False):
""" Search ... |
def get_instance(self, payload):
"""
Build an instance of AssistantInitiationActionsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsInstance
:rtype: twilio.rest... | Build an instance of AssistantInitiationActionsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsInstance
:rtype: twilio.rest.preview.understand.assistant.assistant_initiation_ac... | Below is the the instruction that describes the task:
### Input:
Build an instance of AssistantInitiationActionsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.preview.understand.assistant.assistant_initiation_actions.AssistantInitiationActionsInstance
:rt... |
def bootstrapping_dtrajs(dtrajs, lag, N_full, nbs=10000, active_set=None):
"""
Perform trajectory based re-sampling.
Parameters
----------
dtrajs : list of discrete trajectories
lag : int
lag time
N_full : int
Number of states in discrete trajectories.
nbs : int, optio... | Perform trajectory based re-sampling.
Parameters
----------
dtrajs : list of discrete trajectories
lag : int
lag time
N_full : int
Number of states in discrete trajectories.
nbs : int, optional
Number of bootstrapping samples
active_set : ndarray
Indices of... | Below is the the instruction that describes the task:
### Input:
Perform trajectory based re-sampling.
Parameters
----------
dtrajs : list of discrete trajectories
lag : int
lag time
N_full : int
Number of states in discrete trajectories.
nbs : int, optional
Number... |
def extract_source_geom(dstore, srcidxs):
"""
Extract the geometry of a given sources
Example:
http://127.0.0.1:8800/v1/calc/30/extract/source_geom/1,2,3
"""
for i in srcidxs.split(','):
rec = dstore['source_info'][int(i)]
geom = dstore['source_geom'][rec['gidx1']:rec['gidx2']]
... | Extract the geometry of a given sources
Example:
http://127.0.0.1:8800/v1/calc/30/extract/source_geom/1,2,3 | Below is the the instruction that describes the task:
### Input:
Extract the geometry of a given sources
Example:
http://127.0.0.1:8800/v1/calc/30/extract/source_geom/1,2,3
### Response:
def extract_source_geom(dstore, srcidxs):
"""
Extract the geometry of a given sources
Example:
http://12... |
def resolve_blocks(template, context):
'''
Return a BlockContext instance of all the {% block %} tags in the template.
If template is a string, it will be resolved through get_template
'''
try:
blocks = context.render_context[BLOCK_CONTEXT_KEY]
except KeyError:
blocks = context.... | Return a BlockContext instance of all the {% block %} tags in the template.
If template is a string, it will be resolved through get_template | Below is the the instruction that describes the task:
### Input:
Return a BlockContext instance of all the {% block %} tags in the template.
If template is a string, it will be resolved through get_template
### Response:
def resolve_blocks(template, context):
'''
Return a BlockContext instance of all ... |
def rpc(ctx, call, arguments, api):
""" Construct RPC call directly
\b
You can specify which API to send the call to:
peerplays rpc --api bookie get_matched_bets_for_bettor 1.2.0
You can also specify lists using
peerplays rpc get_objects "['2.0.0', '2.1.0']"
"... | Construct RPC call directly
\b
You can specify which API to send the call to:
peerplays rpc --api bookie get_matched_bets_for_bettor 1.2.0
You can also specify lists using
peerplays rpc get_objects "['2.0.0', '2.1.0']" | Below is the the instruction that describes the task:
### Input:
Construct RPC call directly
\b
You can specify which API to send the call to:
peerplays rpc --api bookie get_matched_bets_for_bettor 1.2.0
You can also specify lists using
peerplays rpc get_objects "[... |
def process_service_check_result(self, service, return_code, plugin_output):
"""Process service check result
Format of the line that triggers function call::
PROCESS_SERVICE_CHECK_RESULT;<host_name>;<service_description>;<return_code>;<plugin_output>
:param service: service to process ... | Process service check result
Format of the line that triggers function call::
PROCESS_SERVICE_CHECK_RESULT;<host_name>;<service_description>;<return_code>;<plugin_output>
:param service: service to process check to
:type service: alignak.objects.service.Service
:param return_co... | Below is the the instruction that describes the task:
### Input:
Process service check result
Format of the line that triggers function call::
PROCESS_SERVICE_CHECK_RESULT;<host_name>;<service_description>;<return_code>;<plugin_output>
:param service: service to process check to
:t... |
def _request_tls(self):
"""Request a TLS-encrypted connection.
[initiating entity only]"""
self.requested = True
element = ElementTree.Element(STARTTLS_TAG)
self.stream.write_element(element) | Request a TLS-encrypted connection.
[initiating entity only] | Below is the the instruction that describes the task:
### Input:
Request a TLS-encrypted connection.
[initiating entity only]
### Response:
def _request_tls(self):
"""Request a TLS-encrypted connection.
[initiating entity only]"""
self.requested = True
element = ElementTre... |
def serialize_args(self):
"""Returns (args, kwargs) to be used when deserializing this parameter."""
args, kwargs = super(MultiParameter, self).serialize_args()
args.insert(0, [[t.id, t.serialize_args()] for t in self.types])
return args, kwargs | Returns (args, kwargs) to be used when deserializing this parameter. | Below is the the instruction that describes the task:
### Input:
Returns (args, kwargs) to be used when deserializing this parameter.
### Response:
def serialize_args(self):
"""Returns (args, kwargs) to be used when deserializing this parameter."""
args, kwargs = super(MultiParameter, self).serial... |
def get_root(w):
"""
Simple method to access root for a widget
"""
next_level = w
while next_level.master:
next_level = next_level.master
return next_level | Simple method to access root for a widget | Below is the the instruction that describes the task:
### Input:
Simple method to access root for a widget
### Response:
def get_root(w):
"""
Simple method to access root for a widget
"""
next_level = w
while next_level.master:
next_level = next_level.master
return next_level |
def tag_fig_ordinal(tag):
"""
Meant for finding the position of fig tags with respect to whether
they are for a main figure or a child figure
"""
tag_count = 0
if 'specific-use' not in tag.attrs:
# Look for tags with no "specific-use" attribute
return len(list(filter(lambda tag: ... | Meant for finding the position of fig tags with respect to whether
they are for a main figure or a child figure | Below is the the instruction that describes the task:
### Input:
Meant for finding the position of fig tags with respect to whether
they are for a main figure or a child figure
### Response:
def tag_fig_ordinal(tag):
"""
Meant for finding the position of fig tags with respect to whether
they are fo... |
def set_header_align(self, array):
"""Set the desired header alignment
- the elements of the array should be either "l", "c" or "r":
* "l": column flushed left
* "c": column centered
* "r": column flushed right
"""
self._check_row_size(array)
... | Set the desired header alignment
- the elements of the array should be either "l", "c" or "r":
* "l": column flushed left
* "c": column centered
* "r": column flushed right | Below is the the instruction that describes the task:
### Input:
Set the desired header alignment
- the elements of the array should be either "l", "c" or "r":
* "l": column flushed left
* "c": column centered
* "r": column flushed right
### Response:
def set_header_al... |
def line_width(default_width=DEFAULT_LINE_WIDTH, max_width=MAX_LINE_WIDTH):
"""
Return the ideal column width for the output from :func:`see.see`, taking
the terminal width into account to avoid wrapping.
"""
width = term_width()
if width: # pragma: no cover (no terminal info in Travis CI)
... | Return the ideal column width for the output from :func:`see.see`, taking
the terminal width into account to avoid wrapping. | Below is the the instruction that describes the task:
### Input:
Return the ideal column width for the output from :func:`see.see`, taking
the terminal width into account to avoid wrapping.
### Response:
def line_width(default_width=DEFAULT_LINE_WIDTH, max_width=MAX_LINE_WIDTH):
"""
Return the ideal co... |
def parse_value_refarray(self, tup_tree):
"""
Parse a VALUE.REFARRAY element and return the array of instance paths
or class paths it represents as a list of CIMInstanceName or
CIMClassName objects, respectively.
::
<!ELEMENT VALUE.REFARRAY (VALUE.REFERENCE | VALU... | Parse a VALUE.REFARRAY element and return the array of instance paths
or class paths it represents as a list of CIMInstanceName or
CIMClassName objects, respectively.
::
<!ELEMENT VALUE.REFARRAY (VALUE.REFERENCE | VALUE.NULL)*> | Below is the the instruction that describes the task:
### Input:
Parse a VALUE.REFARRAY element and return the array of instance paths
or class paths it represents as a list of CIMInstanceName or
CIMClassName objects, respectively.
::
<!ELEMENT VALUE.REFARRAY (VALUE.REFERENCE... |
def parse_args(self, ap_mac, ssid, passphrase,
channel=None,
# KRACK attack options
double_3handshake=True,
encrypt_3handshake=True,
wait_3handshake=0,
double_gtk_refresh=True,
arp_target... | Mandatory arguments:
@iface: interface to use (must be in monitor mode)
@ap_mac: AP's MAC
@ssid: AP's SSID
@passphrase: AP's Passphrase (min 8 char.)
Optional arguments:
@channel: used by the interface. Default 6, autodetected on windows
Krack attacks options:
... | Below is the the instruction that describes the task:
### Input:
Mandatory arguments:
@iface: interface to use (must be in monitor mode)
@ap_mac: AP's MAC
@ssid: AP's SSID
@passphrase: AP's Passphrase (min 8 char.)
Optional arguments:
@channel: used by the interface.... |
def _srm(self, data):
"""Expectation-Maximization algorithm for fitting the probabilistic SRM.
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
Returns
-... | Expectation-Maximization algorithm for fitting the probabilistic SRM.
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
Returns
-------
sigma_s : array, ... | Below is the the instruction that describes the task:
### Input:
Expectation-Maximization algorithm for fitting the probabilistic SRM.
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one ... |
def H9(self):
"Entropy."
if not hasattr(self, '_H9'):
self._H9 = -(self.P * np.log(self.P + self.eps)).sum(2).sum(1)
return self._H9 | Entropy. | Below is the the instruction that describes the task:
### Input:
Entropy.
### Response:
def H9(self):
"Entropy."
if not hasattr(self, '_H9'):
self._H9 = -(self.P * np.log(self.P + self.eps)).sum(2).sum(1)
return self._H9 |
def as_sql(self, compiler, connection):
"""Compiles this expression into SQL."""
sql, params = super().as_sql(compiler, connection)
return 'EXTRACT(epoch FROM {})'.format(sql), params | Compiles this expression into SQL. | Below is the the instruction that describes the task:
### Input:
Compiles this expression into SQL.
### Response:
def as_sql(self, compiler, connection):
"""Compiles this expression into SQL."""
sql, params = super().as_sql(compiler, connection)
return 'EXTRACT(epoch FROM {})'.format(sql),... |
def write_record(self, event_str):
"""Writes a serialized event to file."""
header = struct.pack('Q', len(event_str))
header += struct.pack('I', masked_crc32c(header))
footer = struct.pack('I', masked_crc32c(event_str))
self._writer.write(header + event_str + footer) | Writes a serialized event to file. | Below is the the instruction that describes the task:
### Input:
Writes a serialized event to file.
### Response:
def write_record(self, event_str):
"""Writes a serialized event to file."""
header = struct.pack('Q', len(event_str))
header += struct.pack('I', masked_crc32c(header))
f... |
def _ensure_index_cache(self, db_uri, db_name, collection_name):
"""Adds a collections index entries to the cache if not present"""
if not self._check_indexes or db_uri is None:
return {'indexes': None}
if db_name not in self.get_cache():
self._internal_map[db_name] = {}
... | Adds a collections index entries to the cache if not present | Below is the the instruction that describes the task:
### Input:
Adds a collections index entries to the cache if not present
### Response:
def _ensure_index_cache(self, db_uri, db_name, collection_name):
"""Adds a collections index entries to the cache if not present"""
if not self._check_indexes ... |
def _build_parser(self):
"""Build command line argument parser.
Returns:
:class:`argparse.ArgumentParser`: the command line argument parser.
You probably won't need to use it directly. To parse command line
arguments and update the :class:`ConfigurationManager` insta... | Build command line argument parser.
Returns:
:class:`argparse.ArgumentParser`: the command line argument parser.
You probably won't need to use it directly. To parse command line
arguments and update the :class:`ConfigurationManager` instance
accordingly, use the... | Below is the the instruction that describes the task:
### Input:
Build command line argument parser.
Returns:
:class:`argparse.ArgumentParser`: the command line argument parser.
You probably won't need to use it directly. To parse command line
arguments and update the :c... |
def initialize_ui(self):
"""
Initializes the Component ui.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Initializing '{0}' Component ui.".format(self.__class__.__name__))
self.__Port_spinBox_set_ui()
self.__Address_lineEdit_set_ui()
... | Initializes the Component ui.
:return: Method success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Initializes the Component ui.
:return: Method success.
:rtype: bool
### Response:
def initialize_ui(self):
"""
Initializes the Component ui.
:return: Method success.
:rtype: bool
"""
... |
def get_post(post_id, username, password):
"""
metaWeblog.getPost(post_id, username, password)
=> post structure
"""
user = authenticate(username, password)
site = Site.objects.get_current()
return post_structure(Entry.objects.get(id=post_id, authors=user), site) | metaWeblog.getPost(post_id, username, password)
=> post structure | Below is the the instruction that describes the task:
### Input:
metaWeblog.getPost(post_id, username, password)
=> post structure
### Response:
def get_post(post_id, username, password):
"""
metaWeblog.getPost(post_id, username, password)
=> post structure
"""
user = authenticate(username,... |
def get_resources(cls):
"""Returns Ext Resources."""
job_controller = JobsController(
directory.get_plugin())
resources = []
resources.append(extensions.ResourceExtension(
Jobs.get_alias(),
job_controller))
return reso... | Returns Ext Resources. | Below is the the instruction that describes the task:
### Input:
Returns Ext Resources.
### Response:
def get_resources(cls):
"""Returns Ext Resources."""
job_controller = JobsController(
directory.get_plugin())
resources = []
resources.append(extensions.ResourceExtensio... |
def extended_cigar(aligned_template, aligned_query):
''' Convert mutation annotations to extended cigar format
https://github.com/lh3/minimap2#the-cs-optional-tag
USAGE:
>>> template = 'CGATCGATAAATAGAGTAG---GAATAGCA'
>>> query = 'CGATCG---AATAGAGTAGGTCGAATtGCA'
>>> extended_cigar(tem... | Convert mutation annotations to extended cigar format
https://github.com/lh3/minimap2#the-cs-optional-tag
USAGE:
>>> template = 'CGATCGATAAATAGAGTAG---GAATAGCA'
>>> query = 'CGATCG---AATAGAGTAGGTCGAATtGCA'
>>> extended_cigar(template, query) == ':6-ata:10+gtc:4*at:3'
True | Below is the the instruction that describes the task:
### Input:
Convert mutation annotations to extended cigar format
https://github.com/lh3/minimap2#the-cs-optional-tag
USAGE:
>>> template = 'CGATCGATAAATAGAGTAG---GAATAGCA'
>>> query = 'CGATCG---AATAGAGTAGGTCGAATtGCA'
>>> extended_... |
def intf_up(self, interface):
'''
Can be called when an interface is put in service.
FIXME: not currently used; more needs to be done to
correctly put a new intf into service.
'''
if interface.name not in self._devinfo:
self._devinfo[interface.name] = interfac... | Can be called when an interface is put in service.
FIXME: not currently used; more needs to be done to
correctly put a new intf into service. | Below is the the instruction that describes the task:
### Input:
Can be called when an interface is put in service.
FIXME: not currently used; more needs to be done to
correctly put a new intf into service.
### Response:
def intf_up(self, interface):
'''
Can be called when an interf... |
def bind(self, *targets):
"""
Tries to bind the PV to one of the supplied targets. Targets are inspected according to
the order in which they are supplied.
:param targets: Objects to inspect from.
:return: BoundPV instance with the PV bound to the target property.
"""
... | Tries to bind the PV to one of the supplied targets. Targets are inspected according to
the order in which they are supplied.
:param targets: Objects to inspect from.
:return: BoundPV instance with the PV bound to the target property. | Below is the the instruction that describes the task:
### Input:
Tries to bind the PV to one of the supplied targets. Targets are inspected according to
the order in which they are supplied.
:param targets: Objects to inspect from.
:return: BoundPV instance with the PV bound to the target p... |
def get_annotation(cls, fn):
"""Find the _schema_annotation attribute for the given function.
This will descend through decorators until it finds something that has
the attribute. If it doesn't find it anywhere, it will return None.
:param func fn: Find the attribute on this function.
... | Find the _schema_annotation attribute for the given function.
This will descend through decorators until it finds something that has
the attribute. If it doesn't find it anywhere, it will return None.
:param func fn: Find the attribute on this function.
:returns: an instance of
... | Below is the the instruction that describes the task:
### Input:
Find the _schema_annotation attribute for the given function.
This will descend through decorators until it finds something that has
the attribute. If it doesn't find it anywhere, it will return None.
:param func fn: Find the... |
def _compute_value(power, wg):
"""Return the weight corresponding to single power."""
if power not in wg:
p1, p2 = power
# y power
if p1 == 0:
yy = wg[(0, -1)]
wg[power] = numpy.power(yy, p2 / 2).sum() / len(yy)
# x power
else:
xx = wg[... | Return the weight corresponding to single power. | Below is the the instruction that describes the task:
### Input:
Return the weight corresponding to single power.
### Response:
def _compute_value(power, wg):
"""Return the weight corresponding to single power."""
if power not in wg:
p1, p2 = power
# y power
if p1 == 0:
... |
def read_stats(self):
""" Read current statistics from chassis.
:return: dictionary {stream: {tx: {stat name: stat value}} rx: {tpld: {stat group {stat name: value}}}}
"""
self.tx_statistics = TgnObjectsDict()
for port in self.session.ports.values():
for stream in p... | Read current statistics from chassis.
:return: dictionary {stream: {tx: {stat name: stat value}} rx: {tpld: {stat group {stat name: value}}}} | Below is the the instruction that describes the task:
### Input:
Read current statistics from chassis.
:return: dictionary {stream: {tx: {stat name: stat value}} rx: {tpld: {stat group {stat name: value}}}}
### Response:
def read_stats(self):
""" Read current statistics from chassis.
:ret... |
def stem(self, word):
"""Return CLEF German stem.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> stmr = CLEFGerman()
>>> stmr.stem('lesen')
'l... | Return CLEF German stem.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> stmr = CLEFGerman()
>>> stmr.stem('lesen')
'lese'
>>> stmr.stem('graue... | Below is the the instruction that describes the task:
### Input:
Return CLEF German stem.
Parameters
----------
word : str
The word to stem
Returns
-------
str
Word stem
Examples
--------
>>> stmr = CLEFGerman()
... |
def _fused_batch_norm_op(self, input_batch, mean, variance, use_batch_stats):
"""Creates a fused batch normalization op."""
# Store the original shape of the mean and variance.
mean_shape = mean.get_shape()
variance_shape = variance.get_shape()
# The fused batch norm expects the mean, variance, gamm... | Creates a fused batch normalization op. | Below is the the instruction that describes the task:
### Input:
Creates a fused batch normalization op.
### Response:
def _fused_batch_norm_op(self, input_batch, mean, variance, use_batch_stats):
"""Creates a fused batch normalization op."""
# Store the original shape of the mean and variance.
mean_sh... |
def _get_param_types_maxint(params):
"""
Returns characteristics of parameters
:param params: dictionary of pairs
it must have parameter_name:list of possible values:
params = {"kernel": ["rbf"],
"C" : [1,2,3,4,5,6,7,8],
"gamma" : np.logspace(-9, 9, num=... | Returns characteristics of parameters
:param params: dictionary of pairs
it must have parameter_name:list of possible values:
params = {"kernel": ["rbf"],
"C" : [1,2,3,4,5,6,7,8],
"gamma" : np.logspace(-9, 9, num=25, base=10)}
:return: name_values pairs - li... | Below is the the instruction that describes the task:
### Input:
Returns characteristics of parameters
:param params: dictionary of pairs
it must have parameter_name:list of possible values:
params = {"kernel": ["rbf"],
"C" : [1,2,3,4,5,6,7,8],
"gamma" : np.... |
def get_minkowski_red(structure):
"""
Get a minkowski reduced structure
"""
output = run_aconvasp_command(["aconvasp", "--kpath"], structure)
started = False
poscar_string = ""
if "ERROR" in output[1]:
raise AconvaspError(output[1])
for line in output[0].split("\n"):
if s... | Get a minkowski reduced structure | Below is the the instruction that describes the task:
### Input:
Get a minkowski reduced structure
### Response:
def get_minkowski_red(structure):
"""
Get a minkowski reduced structure
"""
output = run_aconvasp_command(["aconvasp", "--kpath"], structure)
started = False
poscar_string = ""
... |
def _set_clock_foreign_masters(self, v, load=False):
"""
Setter method for clock_foreign_masters, mapped from YANG variable /ptp_state/clock_foreign_masters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_clock_foreign_masters is considered as a private
m... | Setter method for clock_foreign_masters, mapped from YANG variable /ptp_state/clock_foreign_masters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_clock_foreign_masters is considered as a private
method. Backends looking to populate this variable should
do s... | Below is the the instruction that describes the task:
### Input:
Setter method for clock_foreign_masters, mapped from YANG variable /ptp_state/clock_foreign_masters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_clock_foreign_masters is considered as a private
... |
def predict_w(self, data3d, voxelsize_mm, weight, label0=0, label1=1):
"""
segmentation with weight factor
:param data3d:
:param voxelsize_mm:
:param weight:
:return:
"""
scores = self.scores(data3d, voxelsize_mm)
out = scores[label1] > (weight * s... | segmentation with weight factor
:param data3d:
:param voxelsize_mm:
:param weight:
:return: | Below is the the instruction that describes the task:
### Input:
segmentation with weight factor
:param data3d:
:param voxelsize_mm:
:param weight:
:return:
### Response:
def predict_w(self, data3d, voxelsize_mm, weight, label0=0, label1=1):
"""
segmentation with wei... |
def transform_system(principal_vec, principal_default, other_vecs,
matrix=None):
"""Transform vectors with either ``matrix`` or based on ``principal_vec``.
The logic of this function is as follows:
- If ``matrix`` is not ``None``, transform ``principal_vec`` and
all vectors in `... | Transform vectors with either ``matrix`` or based on ``principal_vec``.
The logic of this function is as follows:
- If ``matrix`` is not ``None``, transform ``principal_vec`` and
all vectors in ``other_vecs`` by ``matrix``, ignoring
``principal_default``.
- If ``matrix`` is ``None``, compute t... | Below is the the instruction that describes the task:
### Input:
Transform vectors with either ``matrix`` or based on ``principal_vec``.
The logic of this function is as follows:
- If ``matrix`` is not ``None``, transform ``principal_vec`` and
all vectors in ``other_vecs`` by ``matrix``, ignoring
... |
def fit(self, trX, trY, batch_size=64, n_epochs=1, len_filter=LenFilter(), snapshot_freq=1, path=None):
"""Train model on given training examples and return the list of costs after each minibatch is processed.
Args:
trX (list) -- Inputs
trY (list) -- Outputs
batch_size (in... | Train model on given training examples and return the list of costs after each minibatch is processed.
Args:
trX (list) -- Inputs
trY (list) -- Outputs
batch_size (int, optional) -- number of examples in a minibatch (default 64)
n_epochs (int, optional) -- number of epo... | Below is the the instruction that describes the task:
### Input:
Train model on given training examples and return the list of costs after each minibatch is processed.
Args:
trX (list) -- Inputs
trY (list) -- Outputs
batch_size (int, optional) -- number of examples in a miniba... |
def open_icmp_firewall(host):
"""Temporarily open the ICMP firewall. Tricks Windows into allowing
ICMP packets for a short period of time (~ 1 minute)"""
# We call ping with a timeout of 1ms: will return instantly
with open(os.devnull, 'wb') as DEVNULL:
return subprocess.Popen("ping -4 -w 1 -n 1... | Temporarily open the ICMP firewall. Tricks Windows into allowing
ICMP packets for a short period of time (~ 1 minute) | Below is the the instruction that describes the task:
### Input:
Temporarily open the ICMP firewall. Tricks Windows into allowing
ICMP packets for a short period of time (~ 1 minute)
### Response:
def open_icmp_firewall(host):
"""Temporarily open the ICMP firewall. Tricks Windows into allowing
ICMP pac... |
def normalize_jr(jr, url=None):
""" normalize JSON reference, also fix
implicit reference of JSON pointer.
input:
- #/definitions/User
- http://test.com/swagger.json#/definitions/User
output:
- http://test.com/swagger.json#/definitions/User
input:
- some_folder/User.json
output:... | normalize JSON reference, also fix
implicit reference of JSON pointer.
input:
- #/definitions/User
- http://test.com/swagger.json#/definitions/User
output:
- http://test.com/swagger.json#/definitions/User
input:
- some_folder/User.json
output:
- http://test.com/some_folder/User.... | Below is the the instruction that describes the task:
### Input:
normalize JSON reference, also fix
implicit reference of JSON pointer.
input:
- #/definitions/User
- http://test.com/swagger.json#/definitions/User
output:
- http://test.com/swagger.json#/definitions/User
input:
- some... |
def extend(self, iterable):
"""
Add each item from iterable to the end of the list
"""
with self.lock:
for item in iterable:
self.append(item) | Add each item from iterable to the end of the list | Below is the the instruction that describes the task:
### Input:
Add each item from iterable to the end of the list
### Response:
def extend(self, iterable):
"""
Add each item from iterable to the end of the list
"""
with self.lock:
for item in iterable:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.