code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def emulate_wheel(self, data, direction, timeval):
"""Emulate rel values for the mouse wheel.
In evdev, a single click forwards of the mouse wheel is 1 and
a click back is -1. Windows uses 120 and -120. We floor divide
the Windows number by 120. This is fine for the digital scroll
... | Emulate rel values for the mouse wheel.
In evdev, a single click forwards of the mouse wheel is 1 and
a click back is -1. Windows uses 120 and -120. We floor divide
the Windows number by 120. This is fine for the digital scroll
wheels found on the vast majority of mice. It also works on... | Below is the the instruction that describes the task:
### Input:
Emulate rel values for the mouse wheel.
In evdev, a single click forwards of the mouse wheel is 1 and
a click back is -1. Windows uses 120 and -120. We floor divide
the Windows number by 120. This is fine for the digital scrol... |
def populateBufferContextMenu(self, parentMenu):
"""Populates the editing buffer context menu.
The buffer context menu shown for the current edited/viewed file
will have an item with a plugin name and subitems which are
populated here. If no items were populated then the plugin menu
... | Populates the editing buffer context menu.
The buffer context menu shown for the current edited/viewed file
will have an item with a plugin name and subitems which are
populated here. If no items were populated then the plugin menu
item will not be shown.
Note: when a buffer co... | Below is the the instruction that describes the task:
### Input:
Populates the editing buffer context menu.
The buffer context menu shown for the current edited/viewed file
will have an item with a plugin name and subitems which are
populated here. If no items were populated then the plugin... |
def mark_data_dirty(self):
""" Called from item to indicate its data or metadata has changed."""
self.__cache.set_cached_value_dirty(self.__display_item, self.__cache_property_name)
self.__initialize_cache()
self.__cached_value_dirty = True | Called from item to indicate its data or metadata has changed. | Below is the the instruction that describes the task:
### Input:
Called from item to indicate its data or metadata has changed.
### Response:
def mark_data_dirty(self):
""" Called from item to indicate its data or metadata has changed."""
self.__cache.set_cached_value_dirty(self.__display_item, sel... |
def fit(self,Params0=None,grad_threshold=1e-2):
"""
fit a variance component model with the predefined design and the initialization and returns all the results
"""
# GPVD initialization
lik = limix.CLikNormalNULL()
# Initial Params
if Params0==None:
... | fit a variance component model with the predefined design and the initialization and returns all the results | Below is the the instruction that describes the task:
### Input:
fit a variance component model with the predefined design and the initialization and returns all the results
### Response:
def fit(self,Params0=None,grad_threshold=1e-2):
"""
fit a variance component model with the predefined design a... |
def get_k8s_metadata():
"""Get kubernetes container metadata, as on GCP GKE."""
k8s_metadata = {}
gcp_cluster = (gcp_metadata_config.GcpMetadataConfig
.get_attribute(gcp_metadata_config.CLUSTER_NAME_KEY))
if gcp_cluster is not None:
k8s_metadata[CLUSTER_NAME_KEY] = gcp_cluste... | Get kubernetes container metadata, as on GCP GKE. | Below is the the instruction that describes the task:
### Input:
Get kubernetes container metadata, as on GCP GKE.
### Response:
def get_k8s_metadata():
"""Get kubernetes container metadata, as on GCP GKE."""
k8s_metadata = {}
gcp_cluster = (gcp_metadata_config.GcpMetadataConfig
.ge... |
def init0(self, dae):
"""Set initial p and q for power flow"""
self.p0 = matrix(self.p, (self.n, 1), 'd')
self.q0 = matrix(self.q, (self.n, 1), 'd') | Set initial p and q for power flow | Below is the the instruction that describes the task:
### Input:
Set initial p and q for power flow
### Response:
def init0(self, dae):
"""Set initial p and q for power flow"""
self.p0 = matrix(self.p, (self.n, 1), 'd')
self.q0 = matrix(self.q, (self.n, 1), 'd') |
def click(self):
"""
Pretends to user clicked it, sending the signal and everything.
"""
if self.is_checkable():
if self.is_checked(): self.set_checked(False)
else: self.set_checked(True)
self.signal_clicked.emit(self.is_checked... | Pretends to user clicked it, sending the signal and everything. | Below is the the instruction that describes the task:
### Input:
Pretends to user clicked it, sending the signal and everything.
### Response:
def click(self):
"""
Pretends to user clicked it, sending the signal and everything.
"""
if self.is_checkable():
if self... |
def dump(self,indent='',depth=0):
"""Diagnostic method for listing out the contents of a C{ParseResults}.
Accepts an optional C{indent} argument so that this string can be embedded
in a nested display of other data."""
out = []
out.append( indent+_ustr(self.asList()) )... | Diagnostic method for listing out the contents of a C{ParseResults}.
Accepts an optional C{indent} argument so that this string can be embedded
in a nested display of other data. | Below is the the instruction that describes the task:
### Input:
Diagnostic method for listing out the contents of a C{ParseResults}.
Accepts an optional C{indent} argument so that this string can be embedded
in a nested display of other data.
### Response:
def dump(self,indent='',depth=0):... |
def get_controller_list(self):
"""
Returns an iterable of tuples containing (index, controller_name) pairs.
Controller indexes start at 0.
You may easily transform this to a {name: index} mapping by using:
>>> controllers = {name: index for index, name in raildriver.get_contro... | Returns an iterable of tuples containing (index, controller_name) pairs.
Controller indexes start at 0.
You may easily transform this to a {name: index} mapping by using:
>>> controllers = {name: index for index, name in raildriver.get_controller_list()}
:return enumerate | Below is the the instruction that describes the task:
### Input:
Returns an iterable of tuples containing (index, controller_name) pairs.
Controller indexes start at 0.
You may easily transform this to a {name: index} mapping by using:
>>> controllers = {name: index for index, name in rai... |
def update_objective_bank(self, objective_bank_form):
"""Updates an existing objective bank.
arg: objective_bank_form (osid.learning.ObjectiveBankForm):
the form containing the elements to be updated
raise: IllegalState - ``objective_bank_form`` already used in
... | Updates an existing objective bank.
arg: objective_bank_form (osid.learning.ObjectiveBankForm):
the form containing the elements to be updated
raise: IllegalState - ``objective_bank_form`` already used in
an update transaction
raise: InvalidArgument - the fo... | Below is the the instruction that describes the task:
### Input:
Updates an existing objective bank.
arg: objective_bank_form (osid.learning.ObjectiveBankForm):
the form containing the elements to be updated
raise: IllegalState - ``objective_bank_form`` already used in
... |
def get_scopes(self, vpnid='.*'):
"""Returns a list of all the scopes from CPNR server."""
request_url = self._build_url(['Scope'], vpn=vpnid)
return self._do_request('GET', request_url) | Returns a list of all the scopes from CPNR server. | Below is the the instruction that describes the task:
### Input:
Returns a list of all the scopes from CPNR server.
### Response:
def get_scopes(self, vpnid='.*'):
"""Returns a list of all the scopes from CPNR server."""
request_url = self._build_url(['Scope'], vpn=vpnid)
return self._do_re... |
def create_usuario(self):
"""Get an instance of usuario services facade."""
return Usuario(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | Get an instance of usuario services facade. | Below is the the instruction that describes the task:
### Input:
Get an instance of usuario services facade.
### Response:
def create_usuario(self):
"""Get an instance of usuario services facade."""
return Usuario(
self.networkapi_url,
self.user,
self.password,
... |
def try_date(obj) -> Optional[datetime.date]:
"""Attempts to convert an object into a date.
If the date format is known, it's recommended to use the corresponding function
This is meant to be used in constructors.
Parameters
----------
obj: :class:`str`, :class:`datetime.datetime`, :class:`dat... | Attempts to convert an object into a date.
If the date format is known, it's recommended to use the corresponding function
This is meant to be used in constructors.
Parameters
----------
obj: :class:`str`, :class:`datetime.datetime`, :class:`datetime.date`
The object to convert.
Retur... | Below is the the instruction that describes the task:
### Input:
Attempts to convert an object into a date.
If the date format is known, it's recommended to use the corresponding function
This is meant to be used in constructors.
Parameters
----------
obj: :class:`str`, :class:`datetime.dateti... |
def create_dialog_node(self,
workspace_id,
dialog_node,
description=None,
conditions=None,
parent=None,
previous_sibling=None,
outp... | Create dialog node.
Create a new dialog node.
This operation is limited to 500 requests per 30 minutes. For more information,
see **Rate limiting**.
:param str workspace_id: Unique identifier of the workspace.
:param str dialog_node: The dialog node ID. This string must conform... | Below is the the instruction that describes the task:
### Input:
Create dialog node.
Create a new dialog node.
This operation is limited to 500 requests per 30 minutes. For more information,
see **Rate limiting**.
:param str workspace_id: Unique identifier of the workspace.
... |
def get_config(self, budget):
"""
Function to sample a new configuration
This function is called inside Hyperband to query a new configuration
Parameters:
-----------
budget: float
the budget for which this configuration is scheduled
returns: config
should return a valid configuration
... | Function to sample a new configuration
This function is called inside Hyperband to query a new configuration
Parameters:
-----------
budget: float
the budget for which this configuration is scheduled
returns: config
should return a valid configuration | Below is the the instruction that describes the task:
### Input:
Function to sample a new configuration
This function is called inside Hyperband to query a new configuration
Parameters:
-----------
budget: float
the budget for which this configuration is scheduled
returns: config
should r... |
def prepare_xml(args, parser):
"""Prepares XML files for stripping.
This process creates a single, normalised TEI XML file for each
work.
"""
if args.source == constants.TEI_SOURCE_CBETA_GITHUB:
corpus_class = tacl.TEICorpusCBETAGitHub
else:
raise Exception('Unsupported TEI sou... | Prepares XML files for stripping.
This process creates a single, normalised TEI XML file for each
work. | Below is the the instruction that describes the task:
### Input:
Prepares XML files for stripping.
This process creates a single, normalised TEI XML file for each
work.
### Response:
def prepare_xml(args, parser):
"""Prepares XML files for stripping.
This process creates a single, normalised TEI ... |
def translate(self, date_string, keep_formatting=False, settings=None):
"""
Translate the date string to its English equivalent.
:param date_string:
A string representing date and/or time in a recognizably valid format.
:type date_string: str|unicode
:param keep_for... | Translate the date string to its English equivalent.
:param date_string:
A string representing date and/or time in a recognizably valid format.
:type date_string: str|unicode
:param keep_formatting:
If True, retain formatting of the date string after translation.
... | Below is the the instruction that describes the task:
### Input:
Translate the date string to its English equivalent.
:param date_string:
A string representing date and/or time in a recognizably valid format.
:type date_string: str|unicode
:param keep_formatting:
If... |
def _generate_response_head_bytes(status_code, headers):
"""
:type status_code: int
:type headers: dict[str, str]
:rtype: bytes
"""
head_string = str(status_code) + _DELIMITER_NEWLINE
header_tuples = sorted((k, headers[k]) for k in headers)
for name, value in header_tuples:
na... | :type status_code: int
:type headers: dict[str, str]
:rtype: bytes | Below is the the instruction that describes the task:
### Input:
:type status_code: int
:type headers: dict[str, str]
:rtype: bytes
### Response:
def _generate_response_head_bytes(status_code, headers):
"""
:type status_code: int
:type headers: dict[str, str]
:rtype: bytes
"""
he... |
def ver_cmp(ver1, ver2):
"""
Compare lago versions
Args:
ver1(str): version string
ver2(str): version string
Returns:
Return negative if ver1<ver2, zero if ver1==ver2, positive if
ver1>ver2.
"""
return cmp(
pkg_resources.parse_version(ver1), pkg_resourc... | Compare lago versions
Args:
ver1(str): version string
ver2(str): version string
Returns:
Return negative if ver1<ver2, zero if ver1==ver2, positive if
ver1>ver2. | Below is the the instruction that describes the task:
### Input:
Compare lago versions
Args:
ver1(str): version string
ver2(str): version string
Returns:
Return negative if ver1<ver2, zero if ver1==ver2, positive if
ver1>ver2.
### Response:
def ver_cmp(ver1, ver2):
"""... |
def UpdateResourcesFromResFile(dstpath, srcpath, types=None, names=None,
languages=None):
"""
Update or add resources from dll/exe file srcpath in dll/exe file dstpath.
types = a list of resource types to update (None = all)
names = a list of resource names to update... | Update or add resources from dll/exe file srcpath in dll/exe file dstpath.
types = a list of resource types to update (None = all)
names = a list of resource names to update (None = all)
languages = a list of resource languages to update (None = all) | Below is the the instruction that describes the task:
### Input:
Update or add resources from dll/exe file srcpath in dll/exe file dstpath.
types = a list of resource types to update (None = all)
names = a list of resource names to update (None = all)
languages = a list of resource languages to upd... |
async def disable_digital_reporting(self, pin):
"""
Disables digital reporting. By turning reporting off for this pin,
Reporting is disabled for all 8 bits in the "port"
:param pin: Pin and all pins for this port
:returns: No return value
"""
port = pin // 8
... | Disables digital reporting. By turning reporting off for this pin,
Reporting is disabled for all 8 bits in the "port"
:param pin: Pin and all pins for this port
:returns: No return value | Below is the the instruction that describes the task:
### Input:
Disables digital reporting. By turning reporting off for this pin,
Reporting is disabled for all 8 bits in the "port"
:param pin: Pin and all pins for this port
:returns: No return value
### Response:
async def disable_digit... |
def recode_from_groupby(c, sort, ci):
"""
Reverse the codes_to_groupby to account for sort / observed.
Parameters
----------
c : Categorical
sort : boolean
The value of the sort parameter groupby was called with.
ci : CategoricalIndex
The codes / categories to recode
Re... | Reverse the codes_to_groupby to account for sort / observed.
Parameters
----------
c : Categorical
sort : boolean
The value of the sort parameter groupby was called with.
ci : CategoricalIndex
The codes / categories to recode
Returns
-------
CategoricalIndex | Below is the the instruction that describes the task:
### Input:
Reverse the codes_to_groupby to account for sort / observed.
Parameters
----------
c : Categorical
sort : boolean
The value of the sort parameter groupby was called with.
ci : CategoricalIndex
The codes / categorie... |
def create(fc_layers=None, dropout=None, pretrained=True):
""" Vel factory function """
def instantiate(**_):
return Resnet34(fc_layers, dropout, pretrained)
return ModelFactory.generic(instantiate) | Vel factory function | Below is the the instruction that describes the task:
### Input:
Vel factory function
### Response:
def create(fc_layers=None, dropout=None, pretrained=True):
""" Vel factory function """
def instantiate(**_):
return Resnet34(fc_layers, dropout, pretrained)
return ModelFactory.generic(instanti... |
def run_analyze_dimension_and_radius(data, rmin, rmax, nradii, adjacency_method='brute', adjacency_kwds = {},
fit_range=None, savefig=False, plot_name = 'dimension_plot.png'):
"""
This function is used to estimate the doubling dimension (approximately equal to the intrinsic
... | This function is used to estimate the doubling dimension (approximately equal to the intrinsic
dimension) by computing a graph of neighborhood radius versus average number of neighbors.
The "radius" refers to the truncation constant where all distances greater than
a specified radius are taken to be infini... | Below is the the instruction that describes the task:
### Input:
This function is used to estimate the doubling dimension (approximately equal to the intrinsic
dimension) by computing a graph of neighborhood radius versus average number of neighbors.
The "radius" refers to the truncation constant where all... |
def graph_coloring_qubo(graph, k):
"""
the QUBO for k-coloring a graph A is as follows:
variables:
x_{v,c} = 1 if vertex v of A gets color c; x_{v,c} = 0 otherwise
constraints:
1) each v in A gets exactly one color.
This constraint is enforced by including the term (\sum_c x_{v,c} - 1)... | the QUBO for k-coloring a graph A is as follows:
variables:
x_{v,c} = 1 if vertex v of A gets color c; x_{v,c} = 0 otherwise
constraints:
1) each v in A gets exactly one color.
This constraint is enforced by including the term (\sum_c x_{v,c} - 1)^2 in the QUBO,
which is minimized when ... | Below is the the instruction that describes the task:
### Input:
the QUBO for k-coloring a graph A is as follows:
variables:
x_{v,c} = 1 if vertex v of A gets color c; x_{v,c} = 0 otherwise
constraints:
1) each v in A gets exactly one color.
This constraint is enforced by including the ter... |
def load_engines(manager, class_name, base_module, engines, class_key='ENGINE', engine_type='engine'):
"""Load engines."""
loaded_engines = {}
for module_name_or_dict in engines:
if not isinstance(module_name_or_dict, dict):
module_name_or_dict = {
class_key: module_name... | Load engines. | Below is the the instruction that describes the task:
### Input:
Load engines.
### Response:
def load_engines(manager, class_name, base_module, engines, class_key='ENGINE', engine_type='engine'):
"""Load engines."""
loaded_engines = {}
for module_name_or_dict in engines:
if not isinstance(modu... |
def createDirStruct(paths, verbose=True):
'''Loops ait.config._datapaths from AIT_CONFIG and creates a directory.
Replaces year and doy with the respective year and day-of-year.
If neither are given as arguments, current UTC day and year are used.
Args:
paths:
[optional] list of di... | Loops ait.config._datapaths from AIT_CONFIG and creates a directory.
Replaces year and doy with the respective year and day-of-year.
If neither are given as arguments, current UTC day and year are used.
Args:
paths:
[optional] list of directory paths you would like to create.
... | Below is the the instruction that describes the task:
### Input:
Loops ait.config._datapaths from AIT_CONFIG and creates a directory.
Replaces year and doy with the respective year and day-of-year.
If neither are given as arguments, current UTC day and year are used.
Args:
paths:
[... |
def to_web(graph: BELGraph,
host: Optional[str] = None,
user: Optional[str] = None,
password: Optional[str] = None,
public: bool = False,
) -> requests.Response:
"""Send a graph to the receiver service and returns the :mod:`requests` response object.
:para... | Send a graph to the receiver service and returns the :mod:`requests` response object.
:param graph: A BEL graph
:param host: The location of the BEL Commons server. Alternatively, looks up in PyBEL config with
``PYBEL_REMOTE_HOST`` or the environment as ``PYBEL_REMOTE_HOST`` Defaults to
:data:`pybel.... | Below is the the instruction that describes the task:
### Input:
Send a graph to the receiver service and returns the :mod:`requests` response object.
:param graph: A BEL graph
:param host: The location of the BEL Commons server. Alternatively, looks up in PyBEL config with
``PYBEL_REMOTE_HOST`` or th... |
def update_project(project):
"""Update a project instance.
:param project: PYBOSSA project
:type project: PYBOSSA Project
:returns: True -- the response status code
"""
try:
project_id = project.id
project = _forbidden_attributes(project)
res = _pybossa_req('put', 'proj... | Update a project instance.
:param project: PYBOSSA project
:type project: PYBOSSA Project
:returns: True -- the response status code | Below is the the instruction that describes the task:
### Input:
Update a project instance.
:param project: PYBOSSA project
:type project: PYBOSSA Project
:returns: True -- the response status code
### Response:
def update_project(project):
"""Update a project instance.
:param project: PYBOSS... |
def _imm_dir(self):
'''
An immutable object's dir function should list not only its attributes, but also its un-cached
lazy values.
'''
dir0 = set(dir(self.__class__))
dir0.update(self.__dict__.keys())
dir0.update(six.iterkeys(_imm_value_data(self)))
return sorted(list(dir0)) | An immutable object's dir function should list not only its attributes, but also its un-cached
lazy values. | Below is the the instruction that describes the task:
### Input:
An immutable object's dir function should list not only its attributes, but also its un-cached
lazy values.
### Response:
def _imm_dir(self):
'''
An immutable object's dir function should list not only its attributes, but also its un-cach... |
def step_through(self, msg='', shutit_pexpect_child=None, level=1, print_input=True, value=True):
"""Implements a step-through function, using pause_point.
"""
shutit_global.shutit_global_object.yield_to_draw()
shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_chil... | Implements a step-through function, using pause_point. | Below is the the instruction that describes the task:
### Input:
Implements a step-through function, using pause_point.
### Response:
def step_through(self, msg='', shutit_pexpect_child=None, level=1, print_input=True, value=True):
"""Implements a step-through function, using pause_point.
"""
shutit_global.s... |
def parseSpectra(self):
""" #TODO: docstring
:returns: #TODO: docstring
"""
#Note: the spectra need to be iterated completely to save the
#metadataNode
if self._parsed:
raise TypeError('Mzml file already parsed.')
self._parsed = True
return se... | #TODO: docstring
:returns: #TODO: docstring | Below is the the instruction that describes the task:
### Input:
#TODO: docstring
:returns: #TODO: docstring
### Response:
def parseSpectra(self):
""" #TODO: docstring
:returns: #TODO: docstring
"""
#Note: the spectra need to be iterated completely to save the
#met... |
def names2dnsrepr(x):
"""
Take as input a list of DNS names or a single DNS name
and encode it in DNS format (with possible compression)
If a string that is already a DNS name in DNS format
is passed, it is returned unmodified. Result is a string.
!!! At the moment, compression is not implement... | Take as input a list of DNS names or a single DNS name
and encode it in DNS format (with possible compression)
If a string that is already a DNS name in DNS format
is passed, it is returned unmodified. Result is a string.
!!! At the moment, compression is not implemented !!! | Below is the the instruction that describes the task:
### Input:
Take as input a list of DNS names or a single DNS name
and encode it in DNS format (with possible compression)
If a string that is already a DNS name in DNS format
is passed, it is returned unmodified. Result is a string.
!!! At the m... |
def python_matches(self,text):
"""Match attributes or global python names"""
#io.rprint('Completer->python_matches, txt=%r' % text) # dbg
if "." in text:
try:
matches = self.attr_matches(text)
if text.endswith('.') and self.omit__names:
... | Match attributes or global python names | Below is the the instruction that describes the task:
### Input:
Match attributes or global python names
### Response:
def python_matches(self,text):
"""Match attributes or global python names"""
#io.rprint('Completer->python_matches, txt=%r' % text) # dbg
if "." in text:
... |
def _flush(self):
"""Write persistent dictionary to disc."""
_logger.debug("_flush()")
self._lock.acquire_write() # TODO: read access is enough?
try:
self._dict.sync()
finally:
self._lock.release() | Write persistent dictionary to disc. | Below is the the instruction that describes the task:
### Input:
Write persistent dictionary to disc.
### Response:
def _flush(self):
"""Write persistent dictionary to disc."""
_logger.debug("_flush()")
self._lock.acquire_write() # TODO: read access is enough?
try:
self... |
def peng_mant(snum):
r"""
Return the mantissa of a number represented in engineering notation.
:param snum: Number
:type snum: :ref:`EngineeringNotationNumber`
:rtype: float
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.f... | r"""
Return the mantissa of a number represented in engineering notation.
:param snum: Number
:type snum: :ref:`EngineeringNotationNumber`
:rtype: float
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generated exceptions documentation for
.. peng.functions.peng_mant
:... | Below is the the instruction that describes the task:
### Input:
r"""
Return the mantissa of a number represented in engineering notation.
:param snum: Number
:type snum: :ref:`EngineeringNotationNumber`
:rtype: float
.. [[[cog cog.out(exobj_eng.get_sphinx_autodoc()) ]]]
.. Auto-generate... |
def _write_model(self, specification, specification_set):
""" Write autogenerate specification file
"""
filename = "vspk/%s%s.cs" % (self._class_prefix, specification.entity_name)
override_content = self._extract_override_content(specification.entity_name)
superclass_name = "Re... | Write autogenerate specification file | Below is the the instruction that describes the task:
### Input:
Write autogenerate specification file
### Response:
def _write_model(self, specification, specification_set):
""" Write autogenerate specification file
"""
filename = "vspk/%s%s.cs" % (self._class_prefix, specification.entity... |
def set_dimensions(self, variables, unlimited_dims=None):
"""
This provides a centralized method to set the dimensions on the data
store.
Parameters
----------
variables : dict-like
Dictionary of key/value (variable name / xr.Variable) pairs
unlimited... | This provides a centralized method to set the dimensions on the data
store.
Parameters
----------
variables : dict-like
Dictionary of key/value (variable name / xr.Variable) pairs
unlimited_dims : list-like
List of dimension names that should be treated a... | Below is the the instruction that describes the task:
### Input:
This provides a centralized method to set the dimensions on the data
store.
Parameters
----------
variables : dict-like
Dictionary of key/value (variable name / xr.Variable) pairs
unlimited_dims : l... |
def set_value(self, key, value):
"""
Set the recent files value in QSettings.
:param key: value key
:param value: new value
"""
if value is None:
value = []
value = [os.path.normpath(pth) for pth in value]
self._settings.setValue('recent_files/... | Set the recent files value in QSettings.
:param key: value key
:param value: new value | Below is the the instruction that describes the task:
### Input:
Set the recent files value in QSettings.
:param key: value key
:param value: new value
### Response:
def set_value(self, key, value):
"""
Set the recent files value in QSettings.
:param key: value key
:... |
def build_list(self, title=None, items=None):
"""Presents the user with a vertical list of multiple items.
Allows the user to select a single item.
Selection generates a user query containing the title of the list item
*Note* Returns a completely new object,
and does not modify... | Presents the user with a vertical list of multiple items.
Allows the user to select a single item.
Selection generates a user query containing the title of the list item
*Note* Returns a completely new object,
and does not modify the existing response object
Therefore, to add i... | Below is the the instruction that describes the task:
### Input:
Presents the user with a vertical list of multiple items.
Allows the user to select a single item.
Selection generates a user query containing the title of the list item
*Note* Returns a completely new object,
and doe... |
def set_by_dotted_path(d, path, value):
"""
Set an entry in a nested dict using a dotted path.
Will create dictionaries as needed.
Examples
--------
>>> d = {'foo': {'bar': 7}}
>>> set_by_dotted_path(d, 'foo.bar', 10)
>>> d
{'foo': {'bar': 10}}
>>> set_by_dotted_path(d, 'foo.d.... | Set an entry in a nested dict using a dotted path.
Will create dictionaries as needed.
Examples
--------
>>> d = {'foo': {'bar': 7}}
>>> set_by_dotted_path(d, 'foo.bar', 10)
>>> d
{'foo': {'bar': 10}}
>>> set_by_dotted_path(d, 'foo.d.baz', 3)
>>> d
{'foo': {'bar': 10, 'd': {'ba... | Below is the the instruction that describes the task:
### Input:
Set an entry in a nested dict using a dotted path.
Will create dictionaries as needed.
Examples
--------
>>> d = {'foo': {'bar': 7}}
>>> set_by_dotted_path(d, 'foo.bar', 10)
>>> d
{'foo': {'bar': 10}}
>>> set_by_dotte... |
def soft_kill(jid, state_id=None):
'''
Set up a state run to die before executing the given state id,
this instructs a running state to safely exit at a given
state id. This needs to pass in the jid of the running state.
If a state_id is not passed then the jid referenced will be safely exited
a... | Set up a state run to die before executing the given state id,
this instructs a running state to safely exit at a given
state id. This needs to pass in the jid of the running state.
If a state_id is not passed then the jid referenced will be safely exited
at the beginning of the next state run. | Below is the the instruction that describes the task:
### Input:
Set up a state run to die before executing the given state id,
this instructs a running state to safely exit at a given
state id. This needs to pass in the jid of the running state.
If a state_id is not passed then the jid referenced will ... |
def _create_get_request(self, resource, billomat_id='', command=None, params=None):
"""
Creates a get request and return the response data
"""
if not params:
params = {}
if not command:
command = ''
else:
command = '/' + command
... | Creates a get request and return the response data | Below is the the instruction that describes the task:
### Input:
Creates a get request and return the response data
### Response:
def _create_get_request(self, resource, billomat_id='', command=None, params=None):
"""
Creates a get request and return the response data
"""
if not par... |
def reweight_by_distance(self, coords, metric='l2', copy=False):
'''Replaces existing edge weights by distances between connected vertices.
The new weight of edge (i,j) is given by: metric(coords[i], coords[j]).
coords : (num_vertices x d) array of coordinates, in vertex order
metric : str or callable, ... | Replaces existing edge weights by distances between connected vertices.
The new weight of edge (i,j) is given by: metric(coords[i], coords[j]).
coords : (num_vertices x d) array of coordinates, in vertex order
metric : str or callable, see sklearn.metrics.pairwise.paired_distances | Below is the the instruction that describes the task:
### Input:
Replaces existing edge weights by distances between connected vertices.
The new weight of edge (i,j) is given by: metric(coords[i], coords[j]).
coords : (num_vertices x d) array of coordinates, in vertex order
metric : str or callable, see... |
def create_workflow_template(
self,
parent,
template,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Creates new workflow template.
Example:
>>> from google.clo... | Creates new workflow template.
Example:
>>> from google.cloud import dataproc_v1beta2
>>>
>>> client = dataproc_v1beta2.WorkflowTemplateServiceClient()
>>>
>>> parent = client.region_path('[PROJECT]', '[REGION]')
>>>
>>> # TODO... | Below is the the instruction that describes the task:
### Input:
Creates new workflow template.
Example:
>>> from google.cloud import dataproc_v1beta2
>>>
>>> client = dataproc_v1beta2.WorkflowTemplateServiceClient()
>>>
>>> parent = client.region... |
def _set_id_variable_by_entity_key(self) -> Dict[str, str]:
'''Identify and set the good ids for the different entities'''
if self.id_variable_by_entity_key is None:
self.id_variable_by_entity_key = dict(
(entity.key, entity.key + '_id') for entity in self.tax_benefit_system.... | Identify and set the good ids for the different entities | Below is the the instruction that describes the task:
### Input:
Identify and set the good ids for the different entities
### Response:
def _set_id_variable_by_entity_key(self) -> Dict[str, str]:
'''Identify and set the good ids for the different entities'''
if self.id_variable_by_entity_key is Non... |
def make_muc_userinfo(self):
"""
Create <x xmlns="...muc#user"/> element in the stanza.
:return: the element created.
:returntype: `MucUserX`
"""
self.clear_muc_child()
self.muc_child=MucUserX(parent=self.xmlnode)
return self.muc_child | Create <x xmlns="...muc#user"/> element in the stanza.
:return: the element created.
:returntype: `MucUserX` | Below is the the instruction that describes the task:
### Input:
Create <x xmlns="...muc#user"/> element in the stanza.
:return: the element created.
:returntype: `MucUserX`
### Response:
def make_muc_userinfo(self):
"""
Create <x xmlns="...muc#user"/> element in the stanza.
... |
def sha2_crypt(key, salt, hashfunc, rounds=_ROUNDS_DEFAULT):
"""
This algorithm is insane. History can be found at
https://en.wikipedia.org/wiki/Crypt_%28C%29
"""
key = key.encode('utf-8')
h = hashfunc()
alt_h = hashfunc()
digest_size = h.digest_size
key_len = len(key)
# First, ... | This algorithm is insane. History can be found at
https://en.wikipedia.org/wiki/Crypt_%28C%29 | Below is the the instruction that describes the task:
### Input:
This algorithm is insane. History can be found at
https://en.wikipedia.org/wiki/Crypt_%28C%29
### Response:
def sha2_crypt(key, salt, hashfunc, rounds=_ROUNDS_DEFAULT):
"""
This algorithm is insane. History can be found at
https://en.... |
def transfer_to(self, cloudpath, bbox, block_size=None, compress=True):
"""
Transfer files from one storage location to another, bypassing
volume painting. This enables using a single CloudVolume instance
to transfer big volumes. In some cases, gsutil or aws s3 cli tools
may be more appropriate. Thi... | Transfer files from one storage location to another, bypassing
volume painting. This enables using a single CloudVolume instance
to transfer big volumes. In some cases, gsutil or aws s3 cli tools
may be more appropriate. This method is provided for convenience. It
may be optimized for better performance... | Below is the the instruction that describes the task:
### Input:
Transfer files from one storage location to another, bypassing
volume painting. This enables using a single CloudVolume instance
to transfer big volumes. In some cases, gsutil or aws s3 cli tools
may be more appropriate. This method is pro... |
def _get(self, end_point, params=None, **kwargs):
"""Send a HTTP GET request to a Todoist API end-point.
:param end_point: The Todoist API end-point.
:type end_point: str
:param params: The required request parameters.
:type params: dict
:param kwargs: Any optional param... | Send a HTTP GET request to a Todoist API end-point.
:param end_point: The Todoist API end-point.
:type end_point: str
:param params: The required request parameters.
:type params: dict
:param kwargs: Any optional parameters.
:type kwargs: dict
:return: The HTTP r... | Below is the the instruction that describes the task:
### Input:
Send a HTTP GET request to a Todoist API end-point.
:param end_point: The Todoist API end-point.
:type end_point: str
:param params: The required request parameters.
:type params: dict
:param kwargs: Any option... |
def hmm(args):
"""
%prog hmm workdir sample_key
Run CNV segmentation caller. The workdir must contain a subfolder called
`sample_key-cn` that contains CN for each chromosome. A `beta` directory
that contains scaler for each bin must also be present in the current
directory.
"""
p = Opti... | %prog hmm workdir sample_key
Run CNV segmentation caller. The workdir must contain a subfolder called
`sample_key-cn` that contains CN for each chromosome. A `beta` directory
that contains scaler for each bin must also be present in the current
directory. | Below is the the instruction that describes the task:
### Input:
%prog hmm workdir sample_key
Run CNV segmentation caller. The workdir must contain a subfolder called
`sample_key-cn` that contains CN for each chromosome. A `beta` directory
that contains scaler for each bin must also be present in the c... |
def calc_tc_v1(self):
"""Adjust the measured air temperature to the altitude of the
individual zones.
Required control parameters:
|NmbZones|
|TCAlt|
|ZoneZ|
|ZRelT|
Required input sequence:
|hland_inputs.T|
Calculated flux sequences:
|TC|
Basic equation:
... | Adjust the measured air temperature to the altitude of the
individual zones.
Required control parameters:
|NmbZones|
|TCAlt|
|ZoneZ|
|ZRelT|
Required input sequence:
|hland_inputs.T|
Calculated flux sequences:
|TC|
Basic equation:
:math:`TC = T - TCAlt \... | Below is the the instruction that describes the task:
### Input:
Adjust the measured air temperature to the altitude of the
individual zones.
Required control parameters:
|NmbZones|
|TCAlt|
|ZoneZ|
|ZRelT|
Required input sequence:
|hland_inputs.T|
Calculated flux seq... |
def stop_button_click_handler(self):
"""Method to handle what to do when the stop button is pressed"""
self.stop_button.setDisabled(True)
# Interrupt computations or stop debugging
if not self.shellwidget._reading:
self.interrupt_kernel()
else:
self... | Method to handle what to do when the stop button is pressed | Below is the the instruction that describes the task:
### Input:
Method to handle what to do when the stop button is pressed
### Response:
def stop_button_click_handler(self):
"""Method to handle what to do when the stop button is pressed"""
self.stop_button.setDisabled(True)
# Interrupt... |
def polyder(c, m=1, scl=1, axis=0):
'''not quite a copy of numpy's version because this was faster to implement.
'''
c = list(c)
cnt = int(m)
if cnt == 0:
return c
n = len(c)
if cnt >= n:
c = c[:1]*0
else:
for i in range(cnt):
n = n - 1
c... | not quite a copy of numpy's version because this was faster to implement. | Below is the the instruction that describes the task:
### Input:
not quite a copy of numpy's version because this was faster to implement.
### Response:
def polyder(c, m=1, scl=1, axis=0):
'''not quite a copy of numpy's version because this was faster to implement.
'''
c = list(c)
cnt = int(m)
... |
def content(self):
"""Content of the response, in bytes or unicode
(if available).
"""
if self._content is not None:
return self._content
if self._content_consumed:
raise RuntimeError('The content for this response was '
'a... | Content of the response, in bytes or unicode
(if available). | Below is the the instruction that describes the task:
### Input:
Content of the response, in bytes or unicode
(if available).
### Response:
def content(self):
"""Content of the response, in bytes or unicode
(if available).
"""
if self._content is not None:
retur... |
def remove_empty(rec):
""" Deletes sequences that were marked for deletion by convert_to_IUPAC """
for header, sequence in rec.mapping.items():
if all(char == 'X' for char in sequence):
rec.headers.remove(header)
rec.sequences.remove(sequence)
rec.update()
return rec | Deletes sequences that were marked for deletion by convert_to_IUPAC | Below is the the instruction that describes the task:
### Input:
Deletes sequences that were marked for deletion by convert_to_IUPAC
### Response:
def remove_empty(rec):
""" Deletes sequences that were marked for deletion by convert_to_IUPAC """
for header, sequence in rec.mapping.items():
if all(c... |
def on_step_end(self, step, logs):
""" Update progression bar at the end of each step """
if self.info_names is None:
self.info_names = logs['info'].keys()
values = [('reward', logs['reward'])]
if KERAS_VERSION > '2.1.3':
self.progbar.update((self.step % self.inte... | Update progression bar at the end of each step | Below is the the instruction that describes the task:
### Input:
Update progression bar at the end of each step
### Response:
def on_step_end(self, step, logs):
""" Update progression bar at the end of each step """
if self.info_names is None:
self.info_names = logs['info'].keys()
... |
def download_highlights(self,
user: Union[int, Profile],
fast_update: bool = False,
filename_target: Optional[str] = None,
storyitem_filter: Optional[Callable[[StoryItem], bool]] = None) -> None:
"""
... | Download available highlights from a user whose ID is given.
To use this, one needs to be logged in.
.. versionadded:: 4.1
:param user: ID or Profile of the user whose highlights should get downloaded.
:param fast_update: If true, abort when first already-downloaded picture is encounte... | Below is the the instruction that describes the task:
### Input:
Download available highlights from a user whose ID is given.
To use this, one needs to be logged in.
.. versionadded:: 4.1
:param user: ID or Profile of the user whose highlights should get downloaded.
:param fast_upd... |
def remove(self, task_cls):
""" Remove task from the storage. If task class are stored multiple times
(if :attr:`.WTaskRegistryStorage.__multiple_tasks_per_tag__` is True) - removes all of them.
:param task_cls: task to remove
:return: None
"""
registry_tag = task_cls.__registry_tag__
if registry_tag in ... | Remove task from the storage. If task class are stored multiple times
(if :attr:`.WTaskRegistryStorage.__multiple_tasks_per_tag__` is True) - removes all of them.
:param task_cls: task to remove
:return: None | Below is the the instruction that describes the task:
### Input:
Remove task from the storage. If task class are stored multiple times
(if :attr:`.WTaskRegistryStorage.__multiple_tasks_per_tag__` is True) - removes all of them.
:param task_cls: task to remove
:return: None
### Response:
def remove(self, tas... |
def service_delete(service_id=None, name=None, profile=None, **connection_args):
'''
Delete a service from Keystone service catalog
CLI Examples:
.. code-block:: bash
salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082
salt '*' keystone.service_delete name=nova
'''
... | Delete a service from Keystone service catalog
CLI Examples:
.. code-block:: bash
salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082
salt '*' keystone.service_delete name=nova | Below is the the instruction that describes the task:
### Input:
Delete a service from Keystone service catalog
CLI Examples:
.. code-block:: bash
salt '*' keystone.service_delete c965f79c4f864eaaa9c3b41904e67082
salt '*' keystone.service_delete name=nova
### Response:
def service_delete... |
def _get_rate(self, mag):
"""
Calculate and return the annual occurrence rate for a specific bin.
:param mag:
Magnitude value corresponding to the center of the bin of interest.
:returns:
Float number, the annual occurrence rate for the :param mag value.
... | Calculate and return the annual occurrence rate for a specific bin.
:param mag:
Magnitude value corresponding to the center of the bin of interest.
:returns:
Float number, the annual occurrence rate for the :param mag value. | Below is the the instruction that describes the task:
### Input:
Calculate and return the annual occurrence rate for a specific bin.
:param mag:
Magnitude value corresponding to the center of the bin of interest.
:returns:
Float number, the annual occurrence rate for the :pa... |
def overall_serovar_call(serovar_prediction, antigen_predictor):
"""
Predict serovar from cgMLST cluster membership analysis and antigen BLAST results.
SerovarPrediction object is assigned H1, H2 and Serogroup from the antigen BLAST results.
Antigen BLAST results will predict a particular serovar or lis... | Predict serovar from cgMLST cluster membership analysis and antigen BLAST results.
SerovarPrediction object is assigned H1, H2 and Serogroup from the antigen BLAST results.
Antigen BLAST results will predict a particular serovar or list of serovars, however,
the cgMLST membership may be able to help narrow ... | Below is the the instruction that describes the task:
### Input:
Predict serovar from cgMLST cluster membership analysis and antigen BLAST results.
SerovarPrediction object is assigned H1, H2 and Serogroup from the antigen BLAST results.
Antigen BLAST results will predict a particular serovar or list of ser... |
def _instruction_to_superop(cls, instruction):
"""Convert a QuantumCircuit or Instruction to a SuperOp."""
# Convert circuit to an instruction
if isinstance(instruction, QuantumCircuit):
instruction = instruction.to_instruction()
# Initialize an identity superoperator of the ... | Convert a QuantumCircuit or Instruction to a SuperOp. | Below is the the instruction that describes the task:
### Input:
Convert a QuantumCircuit or Instruction to a SuperOp.
### Response:
def _instruction_to_superop(cls, instruction):
"""Convert a QuantumCircuit or Instruction to a SuperOp."""
# Convert circuit to an instruction
if isinstance(i... |
def import_dashboard_config(modules):
"""Imports configuration from all the modules and merges it."""
config = collections.defaultdict(dict)
for module in modules:
for submodule in import_submodules(module).values():
if hasattr(submodule, 'DASHBOARD'):
dashboard = submodu... | Imports configuration from all the modules and merges it. | Below is the the instruction that describes the task:
### Input:
Imports configuration from all the modules and merges it.
### Response:
def import_dashboard_config(modules):
"""Imports configuration from all the modules and merges it."""
config = collections.defaultdict(dict)
for module in modules:
... |
def init_app(self, app):
"""Setup before_request, after_request handlers for tracing.
"""
app.config.setdefault("TRACY_REQUIRE_CLIENT", False)
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['restpoints'] = self
app.before_request(self._... | Setup before_request, after_request handlers for tracing. | Below is the the instruction that describes the task:
### Input:
Setup before_request, after_request handlers for tracing.
### Response:
def init_app(self, app):
"""Setup before_request, after_request handlers for tracing.
"""
app.config.setdefault("TRACY_REQUIRE_CLIENT", False)
if ... |
def _array_type_std_res(self, counts, total, colsum, rowsum):
"""Return ndarray containing standard residuals for array values.
The shape of the return value is the same as that of *counts*.
Array variables require special processing because of the
underlying math. Essentially, it boils... | Return ndarray containing standard residuals for array values.
The shape of the return value is the same as that of *counts*.
Array variables require special processing because of the
underlying math. Essentially, it boils down to the fact that the
variable dimensions are mutually indep... | Below is the the instruction that describes the task:
### Input:
Return ndarray containing standard residuals for array values.
The shape of the return value is the same as that of *counts*.
Array variables require special processing because of the
underlying math. Essentially, it boils dow... |
def close_idle_connections(self, pool_id=None):
"""close idle connections to mongo"""
if not hasattr(self, '_pools'):
return
if pool_id:
if pool_id not in self._pools:
raise ProgrammingError("pool %r does not exist" % pool_id)
else:
... | close idle connections to mongo | Below is the the instruction that describes the task:
### Input:
close idle connections to mongo
### Response:
def close_idle_connections(self, pool_id=None):
"""close idle connections to mongo"""
if not hasattr(self, '_pools'):
return
if pool_id:
if pool_id not in ... |
def pos(self):
"""A dictionary of the current walker positions.
If the sampler hasn't been run yet, returns p0.
"""
pos = self._pos
if pos is None:
return self.p0
# convert to dict
pos = {param: self._pos[..., k]
for (k, param) in enume... | A dictionary of the current walker positions.
If the sampler hasn't been run yet, returns p0. | Below is the the instruction that describes the task:
### Input:
A dictionary of the current walker positions.
If the sampler hasn't been run yet, returns p0.
### Response:
def pos(self):
"""A dictionary of the current walker positions.
If the sampler hasn't been run yet, returns p0.
... |
def _init_journal(self, permissive=True):
"""Add the initialization lines to the journal.
By default adds JrnObj variable and timestamp to the journal contents.
Args:
permissive (bool): if True most errors in journal will not
cause Revit to stop journ... | Add the initialization lines to the journal.
By default adds JrnObj variable and timestamp to the journal contents.
Args:
permissive (bool): if True most errors in journal will not
cause Revit to stop journal execution.
Some sti... | Below is the the instruction that describes the task:
### Input:
Add the initialization lines to the journal.
By default adds JrnObj variable and timestamp to the journal contents.
Args:
permissive (bool): if True most errors in journal will not
cause Rev... |
def increase(self, ubound=1, top_id=None):
"""
Increases a potential upper bound that can be imposed on the
literals in the sum of an existing :class:`ITotalizer` object to a
new value.
:param ubound: a new upper bound.
:param top_id: a new top variab... | Increases a potential upper bound that can be imposed on the
literals in the sum of an existing :class:`ITotalizer` object to a
new value.
:param ubound: a new upper bound.
:param top_id: a new top variable identifier.
:type ubound: int
:type top... | Below is the the instruction that describes the task:
### Input:
Increases a potential upper bound that can be imposed on the
literals in the sum of an existing :class:`ITotalizer` object to a
new value.
:param ubound: a new upper bound.
:param top_id: a new top vari... |
def _record2card(self, record):
"""
when we add new records they don't have a card,
this sort of fakes it up similar to what cfitsio
does, just for display purposes. e.g.
DBL = 23.299843
LNG = 3423432
KEYSNC = 'hello ... | when we add new records they don't have a card,
this sort of fakes it up similar to what cfitsio
does, just for display purposes. e.g.
DBL = 23.299843
LNG = 3423432
KEYSNC = 'hello '
KEYSC = 'hello ' / a c... | Below is the the instruction that describes the task:
### Input:
when we add new records they don't have a card,
this sort of fakes it up similar to what cfitsio
does, just for display purposes. e.g.
DBL = 23.299843
LNG = 3423432
... |
def obfuscate(cls, idStr):
"""
Mildly obfuscates the specified ID string in an easily reversible
fashion. This is not intended for security purposes, but rather to
dissuade users from depending on our internal ID structures.
"""
return unicode(base64.urlsafe_b64encode(
... | Mildly obfuscates the specified ID string in an easily reversible
fashion. This is not intended for security purposes, but rather to
dissuade users from depending on our internal ID structures. | Below is the the instruction that describes the task:
### Input:
Mildly obfuscates the specified ID string in an easily reversible
fashion. This is not intended for security purposes, but rather to
dissuade users from depending on our internal ID structures.
### Response:
def obfuscate(cls, idStr):... |
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy():
return grains
try:
(
grains['locale_info']['defaultlanguage'],
grains['locale_info']['defaul... | Provides
defaultlanguage
defaultencoding | Below is the the instruction that describes the task:
### Input:
Provides
defaultlanguage
defaultencoding
### Response:
def locale_info():
'''
Provides
defaultlanguage
defaultencoding
'''
grains = {}
grains['locale_info'] = {}
if salt.utils.platform.is_proxy... |
def select(self, template_name):
"""
Select a specific family from the party.
:type template_name: str
:param template_name: Template name of Family to select from a party.
:returns: Family
"""
return [fam for fam in self.families
if fam.template.... | Select a specific family from the party.
:type template_name: str
:param template_name: Template name of Family to select from a party.
:returns: Family | Below is the the instruction that describes the task:
### Input:
Select a specific family from the party.
:type template_name: str
:param template_name: Template name of Family to select from a party.
:returns: Family
### Response:
def select(self, template_name):
"""
Selec... |
def calc_tkor_v1(self):
"""Adjust the given air temperature values.
Required control parameters:
|NHRU|
|KT|
Required input sequence:
|TemL|
Calculated flux sequence:
|TKor|
Basic equation:
:math:`TKor = KT + TemL`
Example:
>>> from hydpy.models.lland ... | Adjust the given air temperature values.
Required control parameters:
|NHRU|
|KT|
Required input sequence:
|TemL|
Calculated flux sequence:
|TKor|
Basic equation:
:math:`TKor = KT + TemL`
Example:
>>> from hydpy.models.lland import *
>>> parameters... | Below is the the instruction that describes the task:
### Input:
Adjust the given air temperature values.
Required control parameters:
|NHRU|
|KT|
Required input sequence:
|TemL|
Calculated flux sequence:
|TKor|
Basic equation:
:math:`TKor = KT + TemL`
Example:... |
def make_complete(self):
"""
Turns the site collection into a complete one, if needed
"""
# reset the site indices from 0 to N-1 and set self.complete to self
self.array['sids'] = numpy.arange(len(self), dtype=numpy.uint32)
self.complete = self | Turns the site collection into a complete one, if needed | Below is the the instruction that describes the task:
### Input:
Turns the site collection into a complete one, if needed
### Response:
def make_complete(self):
"""
Turns the site collection into a complete one, if needed
"""
# reset the site indices from 0 to N-1 and set self.compl... |
def _parse_response_types(argspec, attrs):
"""
from the given parameters, return back the response type dictionaries.
"""
return_type = argspec.annotations.get("return") or None
type_description = attrs.parameter_descriptions.get("return", "")
response_types = attrs.respo... | from the given parameters, return back the response type dictionaries. | Below is the the instruction that describes the task:
### Input:
from the given parameters, return back the response type dictionaries.
### Response:
def _parse_response_types(argspec, attrs):
"""
from the given parameters, return back the response type dictionaries.
"""
return_type... |
def list_(
pkg=None,
user=None,
installed=False,
env=None):
'''
List packages matching a search string.
pkg
Search string for matching package names
user
The user to run cabal list with
installed
If True, only return installed packages.
en... | List packages matching a search string.
pkg
Search string for matching package names
user
The user to run cabal list with
installed
If True, only return installed packages.
env
Environment variables to set when invoking cabal. Uses the
same ``env`` format as the ... | Below is the the instruction that describes the task:
### Input:
List packages matching a search string.
pkg
Search string for matching package names
user
The user to run cabal list with
installed
If True, only return installed packages.
env
Environment variables to ... |
def zip_file(self, app_path, app_name, tmp_path):
"""Zip the App with tcex extension.
Args:
app_path (str): The path of the current project.
app_name (str): The name of the App.
tmp_path (str): The temp output path for the zip.
"""
# zip build directo... | Zip the App with tcex extension.
Args:
app_path (str): The path of the current project.
app_name (str): The name of the App.
tmp_path (str): The temp output path for the zip. | Below is the the instruction that describes the task:
### Input:
Zip the App with tcex extension.
Args:
app_path (str): The path of the current project.
app_name (str): The name of the App.
tmp_path (str): The temp output path for the zip.
### Response:
def zip_file(sel... |
def numericalize(self, arrs, device=None):
"""Convert a padded minibatch into a variable tensor.
Each item in the minibatch will be numericalized independently and the resulting
tensors will be stacked at the first dimension.
Arguments:
arr (List[List[str]]): List of tokeni... | Convert a padded minibatch into a variable tensor.
Each item in the minibatch will be numericalized independently and the resulting
tensors will be stacked at the first dimension.
Arguments:
arr (List[List[str]]): List of tokenized and padded examples.
device (str or to... | Below is the the instruction that describes the task:
### Input:
Convert a padded minibatch into a variable tensor.
Each item in the minibatch will be numericalized independently and the resulting
tensors will be stacked at the first dimension.
Arguments:
arr (List[List[str]]):... |
def create_subject_access_review(self, body, **kwargs):
"""
create a SubjectAccessReview
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_subject_access_review(body, async_req=True)
... | create a SubjectAccessReview
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_subject_access_review(body, async_req=True)
>>> result = thread.get()
:param async_req bool
:par... | Below is the the instruction that describes the task:
### Input:
create a SubjectAccessReview
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_subject_access_review(body, async_req=True)
... |
def _validate_filters_ndb(cls, filters, model_class):
"""Validate ndb.Model filters."""
if not filters:
return
properties = model_class._properties
for idx, f in enumerate(filters):
prop, ineq, val = f
if prop not in properties:
raise errors.BadReaderParamsError(
... | Validate ndb.Model filters. | Below is the the instruction that describes the task:
### Input:
Validate ndb.Model filters.
### Response:
def _validate_filters_ndb(cls, filters, model_class):
"""Validate ndb.Model filters."""
if not filters:
return
properties = model_class._properties
for idx, f in enumerate(filters):
... |
def download_file(self, bucket, key, filename, extra_args=None,
expected_size=None):
"""Downloads the object's contents to a file
:type bucket: str
:param bucket: The name of the bucket to download from
:type key: str
:param key: The name of the key to dow... | Downloads the object's contents to a file
:type bucket: str
:param bucket: The name of the bucket to download from
:type key: str
:param key: The name of the key to download from
:type filename: str
:param filename: The name of a file to download to.
:type ext... | Below is the the instruction that describes the task:
### Input:
Downloads the object's contents to a file
:type bucket: str
:param bucket: The name of the bucket to download from
:type key: str
:param key: The name of the key to download from
:type filename: str
:... |
def sflow_collector_collector_ip_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
sflow = ET.SubElement(config, "sflow", xmlns="urn:brocade.com:mgmt:brocade-sflow")
collector = ET.SubElement(sflow, "collector")
collector_port_number_key = ... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def sflow_collector_collector_ip_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
sflow = ET.SubElement(config, "sflow", xmlns="urn:brocade.com:mgmt:br... |
def compress(self, d=DEFAULT):
"""Returns a copy of d with compressed leaves."""
if d is DEFAULT:
d = self
if isinstance(d, list):
l = [v for v in (self.compress(v) for v in d)]
try:
return list(set(l))
except TypeError:
... | Returns a copy of d with compressed leaves. | Below is the the instruction that describes the task:
### Input:
Returns a copy of d with compressed leaves.
### Response:
def compress(self, d=DEFAULT):
"""Returns a copy of d with compressed leaves."""
if d is DEFAULT:
d = self
if isinstance(d, list):
l = [v for v ... |
def roleUpdated(self, *args, **kwargs):
"""
Role Updated Messages
Message that a new role has been updated.
This exchange outputs: ``v1/role-message.json#``This exchange takes the following keys:
* reserved: Space reserved for future routing-key entries, you should always mat... | Role Updated Messages
Message that a new role has been updated.
This exchange outputs: ``v1/role-message.json#``This exchange takes the following keys:
* reserved: Space reserved for future routing-key entries, you should always match this entry with `#`. As automatically done by our tooling... | Below is the the instruction that describes the task:
### Input:
Role Updated Messages
Message that a new role has been updated.
This exchange outputs: ``v1/role-message.json#``This exchange takes the following keys:
* reserved: Space reserved for future routing-key entries, you should a... |
def enable_one_shot_page_breakpoint(self, dwProcessId, address):
"""
Enables the page breakpoint at the given address for only one shot.
@see:
L{define_page_breakpoint},
L{has_page_breakpoint},
L{get_page_breakpoint},
L{enable_page_breakpoint},
... | Enables the page breakpoint at the given address for only one shot.
@see:
L{define_page_breakpoint},
L{has_page_breakpoint},
L{get_page_breakpoint},
L{enable_page_breakpoint},
L{disable_page_breakpoint}
L{erase_page_breakpoint},
@... | Below is the the instruction that describes the task:
### Input:
Enables the page breakpoint at the given address for only one shot.
@see:
L{define_page_breakpoint},
L{has_page_breakpoint},
L{get_page_breakpoint},
L{enable_page_breakpoint},
L{disa... |
async def api_request(self, url, params):
"""Make api fetch request."""
request = None
try:
with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop):
request = await self._api_session.get(
url, params=params)
if request.status... | Make api fetch request. | Below is the the instruction that describes the task:
### Input:
Make api fetch request.
### Response:
async def api_request(self, url, params):
"""Make api fetch request."""
request = None
try:
with async_timeout.timeout(DEFAULT_TIMEOUT, loop=self._event_loop):
... |
def predict(self, temp_type):
"""
Transpile the predict method.
Parameters
----------
:param temp_type : string
The kind of export type (embedded, separated, exported).
Returns
-------
:return : string
The transpiled predict metho... | Transpile the predict method.
Parameters
----------
:param temp_type : string
The kind of export type (embedded, separated, exported).
Returns
-------
:return : string
The transpiled predict method as string. | Below is the the instruction that describes the task:
### Input:
Transpile the predict method.
Parameters
----------
:param temp_type : string
The kind of export type (embedded, separated, exported).
Returns
-------
:return : string
The trans... |
def prior(self):
"""
Model prior for particular model.
Product of eclipse probability (``self.prob``),
the fraction of scenario that is allowed by the various
constraints (``self.selectfrac``), and all additional
factors in ``self.priorfactors``.
"""
pri... | Model prior for particular model.
Product of eclipse probability (``self.prob``),
the fraction of scenario that is allowed by the various
constraints (``self.selectfrac``), and all additional
factors in ``self.priorfactors``. | Below is the the instruction that describes the task:
### Input:
Model prior for particular model.
Product of eclipse probability (``self.prob``),
the fraction of scenario that is allowed by the various
constraints (``self.selectfrac``), and all additional
factors in ``self.priorfac... |
def Flash(self, partition, timeout_ms=0, info_cb=DEFAULT_MESSAGE_CALLBACK):
"""Flashes the last downloaded file to the given partition.
Args:
partition: Partition to overwrite with the new image.
timeout_ms: Optional timeout in milliseconds to wait for it to finish.
info_c... | Flashes the last downloaded file to the given partition.
Args:
partition: Partition to overwrite with the new image.
timeout_ms: Optional timeout in milliseconds to wait for it to finish.
info_cb: See Download. Usually no messages.
Returns:
Response to a downloa... | Below is the the instruction that describes the task:
### Input:
Flashes the last downloaded file to the given partition.
Args:
partition: Partition to overwrite with the new image.
timeout_ms: Optional timeout in milliseconds to wait for it to finish.
info_cb: See Download. U... |
def _node_has_modifier(graph: BELGraph, node: BaseEntity, modifier: str) -> bool:
"""Return true if over any of a nodes edges, it has a given modifier.
Modifier can be one of:
- :data:`pybel.constants.ACTIVITY`,
- :data:`pybel.constants.DEGRADATION`
- :data:`pybel.constants.TRANSLOCATION`.
... | Return true if over any of a nodes edges, it has a given modifier.
Modifier can be one of:
- :data:`pybel.constants.ACTIVITY`,
- :data:`pybel.constants.DEGRADATION`
- :data:`pybel.constants.TRANSLOCATION`.
:param modifier: One of :data:`pybel.constants.ACTIVITY`, :data:`pybel.constants.DEGRAD... | Below is the the instruction that describes the task:
### Input:
Return true if over any of a nodes edges, it has a given modifier.
Modifier can be one of:
- :data:`pybel.constants.ACTIVITY`,
- :data:`pybel.constants.DEGRADATION`
- :data:`pybel.constants.TRANSLOCATION`.
:param modifier: O... |
def has(self):
"""Whether the cache file exists in the file system."""
self._done = os.path.exists(self._cache_file)
return self._done or self._out is not None | Whether the cache file exists in the file system. | Below is the the instruction that describes the task:
### Input:
Whether the cache file exists in the file system.
### Response:
def has(self):
"""Whether the cache file exists in the file system."""
self._done = os.path.exists(self._cache_file)
return self._done or self._out is not None |
def makekey(self, *args):
""" return a binary key for the nodeid, tag and optional value """
if len(args) > 1:
args = args[:1] + (args[1].encode('utf-8'),) + args[2:]
if len(args) == 3 and type(args[-1]) == str:
# node.tag.string type keys
return struct.... | return a binary key for the nodeid, tag and optional value | Below is the the instruction that describes the task:
### Input:
return a binary key for the nodeid, tag and optional value
### Response:
def makekey(self, *args):
""" return a binary key for the nodeid, tag and optional value """
if len(args) > 1:
args = args[:1] + (args[1].encode('... |
def toc(self):
"""
Returns a rich list of texts in the catalog.
"""
output = []
for key in sorted(self.catalog.keys()):
edition = self.catalog[key]['edition']
length = len(self.catalog[key]['transliteration'])
output.append(
"Pn... | Returns a rich list of texts in the catalog. | Below is the the instruction that describes the task:
### Input:
Returns a rich list of texts in the catalog.
### Response:
def toc(self):
"""
Returns a rich list of texts in the catalog.
"""
output = []
for key in sorted(self.catalog.keys()):
edition = self.cata... |
def get_assessment_lookup_session_for_bank(self, bank_id, proxy):
"""Gets the ``OsidSession`` associated with the assessment lookup service for the given bank.
arg: bank_id (osid.id.Id): the ``Id`` of the bank
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.Assessm... | Gets the ``OsidSession`` associated with the assessment lookup service for the given bank.
arg: bank_id (osid.id.Id): the ``Id`` of the bank
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.AssessmentLookupSession) - ``an
_assessment_lookup_session``
... | Below is the the instruction that describes the task:
### Input:
Gets the ``OsidSession`` associated with the assessment lookup service for the given bank.
arg: bank_id (osid.id.Id): the ``Id`` of the bank
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.assessment.AssessmentLooku... |
def convert_from_unicode(data):
"""
converts unicode data to a string
:param data: the data to convert
:return:
"""
# if isinstance(data, basestring):
if isinstance(data, str):
return str(data)
elif isinstance(data, collectionsAbc.Mapping):
return dict(map(convert_from_... | converts unicode data to a string
:param data: the data to convert
:return: | Below is the the instruction that describes the task:
### Input:
converts unicode data to a string
:param data: the data to convert
:return:
### Response:
def convert_from_unicode(data):
"""
converts unicode data to a string
:param data: the data to convert
:return:
"""
# if isinst... |
def from_blob(cls, blob):
"""
Return a new |Image| subclass instance parsed from the image binary
contained in *blob*.
"""
stream = BytesIO(blob)
return cls._from_stream(stream, blob) | Return a new |Image| subclass instance parsed from the image binary
contained in *blob*. | Below is the the instruction that describes the task:
### Input:
Return a new |Image| subclass instance parsed from the image binary
contained in *blob*.
### Response:
def from_blob(cls, blob):
"""
Return a new |Image| subclass instance parsed from the image binary
contained in *blo... |
def get_buckets(self, timeout=None):
"""
Get the list of buckets under this bucket-type as
:class:`RiakBucket <riak.bucket.RiakBucket>` instances.
.. warning:: Do not use this in production, as it requires
traversing through all keys stored in a cluster.
.. note:: Th... | Get the list of buckets under this bucket-type as
:class:`RiakBucket <riak.bucket.RiakBucket>` instances.
.. warning:: Do not use this in production, as it requires
traversing through all keys stored in a cluster.
.. note:: This request is automatically retried :attr:`retries`
... | Below is the the instruction that describes the task:
### Input:
Get the list of buckets under this bucket-type as
:class:`RiakBucket <riak.bucket.RiakBucket>` instances.
.. warning:: Do not use this in production, as it requires
traversing through all keys stored in a cluster.
... |
def list_themes(directory=None):
"""Gets a list of the installed themes."""
repo = require_repo(directory)
path = os.path.join(repo, themes_dir)
return os.listdir(path) if os.path.isdir(path) else None | Gets a list of the installed themes. | Below is the the instruction that describes the task:
### Input:
Gets a list of the installed themes.
### Response:
def list_themes(directory=None):
"""Gets a list of the installed themes."""
repo = require_repo(directory)
path = os.path.join(repo, themes_dir)
return os.listdir(path) if os.path.isd... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.