code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def filter_rows(self, filters, rows):
'''returns rows as filtered by filters'''
ret = []
for row in rows:
if not self.row_is_filtered(row, filters):
ret.append(row)
return ret | returns rows as filtered by filters | Below is the the instruction that describes the task:
### Input:
returns rows as filtered by filters
### Response:
def filter_rows(self, filters, rows):
'''returns rows as filtered by filters'''
ret = []
for row in rows:
if not self.row_is_filtered(row, filters):
... |
def gateway_snapshot(self, indices=None):
"""
Gateway snapshot one or more indices
(See :ref:`es-guide-reference-api-admin-indices-gateway-snapshot`)
:keyword indices: a list of indices or None for default configured.
"""
path = self.conn._make_path(indices, (), '_gatewa... | Gateway snapshot one or more indices
(See :ref:`es-guide-reference-api-admin-indices-gateway-snapshot`)
:keyword indices: a list of indices or None for default configured. | Below is the the instruction that describes the task:
### Input:
Gateway snapshot one or more indices
(See :ref:`es-guide-reference-api-admin-indices-gateway-snapshot`)
:keyword indices: a list of indices or None for default configured.
### Response:
def gateway_snapshot(self, indices=None):
... |
def setDatastreamVersionable(self, pid, dsID, versionable):
'''Update datastream versionable setting.
:param pid: object pid
:param dsID: datastream id
:param versionable: boolean
:returns: boolean success
'''
# /objects/{pid}/datastreams/{dsID} ? [versionable]
... | Update datastream versionable setting.
:param pid: object pid
:param dsID: datastream id
:param versionable: boolean
:returns: boolean success | Below is the the instruction that describes the task:
### Input:
Update datastream versionable setting.
:param pid: object pid
:param dsID: datastream id
:param versionable: boolean
:returns: boolean success
### Response:
def setDatastreamVersionable(self, pid, dsID, versionable):
... |
def get_application_choices():
"""
Get the select options for the application selector
:return:
"""
result = []
keys = set()
for ct in ContentType.objects.order_by('app_label', 'model'):
try:
if issubclass(ct.model_class(), TranslatableModel) and ct.app_label not in keys... | Get the select options for the application selector
:return: | Below is the the instruction that describes the task:
### Input:
Get the select options for the application selector
:return:
### Response:
def get_application_choices():
"""
Get the select options for the application selector
:return:
"""
result = []
keys = set()
for ct in Conten... |
def handle_Sample(self, instance):
"""If this sample has a single AR, go there.
If the sample has 0 or >1 ARs, go to the sample's view URL.
"""
ars = instance.getAnalysisRequests()
if len(ars) == 1:
return self.handle_AnalysisRequest(ars[0])
else:
... | If this sample has a single AR, go there.
If the sample has 0 or >1 ARs, go to the sample's view URL. | Below is the the instruction that describes the task:
### Input:
If this sample has a single AR, go there.
If the sample has 0 or >1 ARs, go to the sample's view URL.
### Response:
def handle_Sample(self, instance):
"""If this sample has a single AR, go there.
If the sample has 0 or >1 ARs,... |
def excel_synthese(fct, df, excel_file):
"""
Enregistre dans un fichier Excel une synthèse des calculs réglementaires en
fournissant les valeurs calculées suivant les réglementations définies dans
chaque fonction de calcul et un tableau de nombre de dépassement.
Les résultats sont enregistrés
P... | Enregistre dans un fichier Excel une synthèse des calculs réglementaires en
fournissant les valeurs calculées suivant les réglementations définies dans
chaque fonction de calcul et un tableau de nombre de dépassement.
Les résultats sont enregistrés
Paramètres:
fct: fonction renvoyant les éléments c... | Below is the the instruction that describes the task:
### Input:
Enregistre dans un fichier Excel une synthèse des calculs réglementaires en
fournissant les valeurs calculées suivant les réglementations définies dans
chaque fonction de calcul et un tableau de nombre de dépassement.
Les résultats sont en... |
def stats(self, topic=None, channel=None, text=False):
"""Return internal instrumented statistics.
:param topic: (optional) filter to topic
:param channel: (optional) filter to channel
:param text: return the stats as a string (default: ``False``)
"""
if text:
... | Return internal instrumented statistics.
:param topic: (optional) filter to topic
:param channel: (optional) filter to channel
:param text: return the stats as a string (default: ``False``) | Below is the the instruction that describes the task:
### Input:
Return internal instrumented statistics.
:param topic: (optional) filter to topic
:param channel: (optional) filter to channel
:param text: return the stats as a string (default: ``False``)
### Response:
def stats(self, top... |
def create_autosummary_file(modules, opts):
# type: (List[unicode], Any, unicode) -> None
"""Create the module's index."""
lines = [
'API Reference',
'=============',
'',
'.. autosummary::',
' :template: api_module.rst',
' :toctree: {}'.format(opts.destdir... | Create the module's index. | Below is the the instruction that describes the task:
### Input:
Create the module's index.
### Response:
def create_autosummary_file(modules, opts):
# type: (List[unicode], Any, unicode) -> None
"""Create the module's index."""
lines = [
'API Reference',
'=============',
'',
... |
def mounted(name,
device,
fstype,
mkmnt=False,
opts='defaults',
dump=0,
pass_num=0,
config='/etc/fstab',
persist=True,
mount=True,
user=None,
match_on='auto',
device_name_regex... | Verify that a device is mounted
name
The path to the location where the device is to be mounted
device
The device name, typically the device node, such as ``/dev/sdb1``
or ``UUID=066e0200-2867-4ebe-b9e6-f30026ca2314`` or ``LABEL=DATA``
fstype
The filesystem type, this will... | Below is the the instruction that describes the task:
### Input:
Verify that a device is mounted
name
The path to the location where the device is to be mounted
device
The device name, typically the device node, such as ``/dev/sdb1``
or ``UUID=066e0200-2867-4ebe-b9e6-f30026ca2314``... |
async def write_close_frame(self, data: bytes = b"") -> None:
"""
Write a close frame if and only if the connection state is OPEN.
This dedicated coroutine must be used for writing close frames to
ensure that at most one close frame is sent on a given connection.
"""
# ... | Write a close frame if and only if the connection state is OPEN.
This dedicated coroutine must be used for writing close frames to
ensure that at most one close frame is sent on a given connection. | Below is the the instruction that describes the task:
### Input:
Write a close frame if and only if the connection state is OPEN.
This dedicated coroutine must be used for writing close frames to
ensure that at most one close frame is sent on a given connection.
### Response:
async def write_close... |
def tokenize_punctuation_command(text):
"""Process command that augments or modifies punctuation.
This is important to the tokenization of a string, as opening or closing
punctuation is not supposed to match.
:param Buffer text: iterator over text, with current position
"""
if text.peek() == '... | Process command that augments or modifies punctuation.
This is important to the tokenization of a string, as opening or closing
punctuation is not supposed to match.
:param Buffer text: iterator over text, with current position | Below is the the instruction that describes the task:
### Input:
Process command that augments or modifies punctuation.
This is important to the tokenization of a string, as opening or closing
punctuation is not supposed to match.
:param Buffer text: iterator over text, with current position
### Respo... |
def OnTextColorDialog(self, event):
"""Event handler for launching text color dialog"""
dlg = wx.ColourDialog(self.main_window)
# Ensure the full colour dialog is displayed,
# not the abbreviated version.
dlg.GetColourData().SetChooseFull(True)
if dlg.ShowModal() == wx... | Event handler for launching text color dialog | Below is the the instruction that describes the task:
### Input:
Event handler for launching text color dialog
### Response:
def OnTextColorDialog(self, event):
"""Event handler for launching text color dialog"""
dlg = wx.ColourDialog(self.main_window)
# Ensure the full colour dialog is d... |
def addDataModels(self, mods):
'''
Adds a model definition (same format as input to Model.addDataModels and output of Model.getModelDef).
'''
# Load all the universal properties
for _, mdef in mods:
for univname, _, _ in mdef.get('univs', ()):
self.add... | Adds a model definition (same format as input to Model.addDataModels and output of Model.getModelDef). | Below is the the instruction that describes the task:
### Input:
Adds a model definition (same format as input to Model.addDataModels and output of Model.getModelDef).
### Response:
def addDataModels(self, mods):
'''
Adds a model definition (same format as input to Model.addDataModels and output of... |
def countinputs(inputlist):
"""
Determine the number of inputfiles provided by the user and the
number of those files that are association tables
Parameters
----------
inputlist : string
the user input
Returns
-------
numInputs: int
number of inputs provided by th... | Determine the number of inputfiles provided by the user and the
number of those files that are association tables
Parameters
----------
inputlist : string
the user input
Returns
-------
numInputs: int
number of inputs provided by the user
numASNfiles: int
numb... | Below is the the instruction that describes the task:
### Input:
Determine the number of inputfiles provided by the user and the
number of those files that are association tables
Parameters
----------
inputlist : string
the user input
Returns
-------
numInputs: int
nu... |
def version(self):
"""
Get Kubernetes API version
"""
response = self.get(version="", base="/version")
response.raise_for_status()
data = response.json()
return (data["major"], data["minor"]) | Get Kubernetes API version | Below is the the instruction that describes the task:
### Input:
Get Kubernetes API version
### Response:
def version(self):
"""
Get Kubernetes API version
"""
response = self.get(version="", base="/version")
response.raise_for_status()
data = response.json()
... |
def map_providers(self, query='list_nodes', cached=False):
'''
Return a mapping of what named VMs are running on what VM providers
based on what providers are defined in the configuration and VMs
'''
if cached is True and query in self.__cached_provider_queries:
retur... | Return a mapping of what named VMs are running on what VM providers
based on what providers are defined in the configuration and VMs | Below is the the instruction that describes the task:
### Input:
Return a mapping of what named VMs are running on what VM providers
based on what providers are defined in the configuration and VMs
### Response:
def map_providers(self, query='list_nodes', cached=False):
'''
Return a mapping... |
def get_randomized_guid_sample(self, item_count):
""" Fetch a subset of randomzied GUIDs from the whitelist """
dataset = self.get_whitelist()
random.shuffle(dataset)
return dataset[:item_count] | Fetch a subset of randomzied GUIDs from the whitelist | Below is the the instruction that describes the task:
### Input:
Fetch a subset of randomzied GUIDs from the whitelist
### Response:
def get_randomized_guid_sample(self, item_count):
""" Fetch a subset of randomzied GUIDs from the whitelist """
dataset = self.get_whitelist()
random.shuffle(... |
def classical(group, src_filter, gsims, param, monitor=Monitor()):
"""
Compute the hazard curves for a set of sources belonging to the same
tectonic region type for all the GSIMs associated to that TRT.
The arguments are the same as in :func:`calc_hazard_curves`, except
for ``gsims``, which is a lis... | Compute the hazard curves for a set of sources belonging to the same
tectonic region type for all the GSIMs associated to that TRT.
The arguments are the same as in :func:`calc_hazard_curves`, except
for ``gsims``, which is a list of GSIM instances.
:returns:
a dictionary {grp_id: pmap} with at... | Below is the the instruction that describes the task:
### Input:
Compute the hazard curves for a set of sources belonging to the same
tectonic region type for all the GSIMs associated to that TRT.
The arguments are the same as in :func:`calc_hazard_curves`, except
for ``gsims``, which is a list of GSIM ... |
def getEventTypeNameFromEnum(self, eType):
"""returns the name of an EVREvent enum value"""
fn = self.function_table.getEventTypeNameFromEnum
result = fn(eType)
return result | returns the name of an EVREvent enum value | Below is the the instruction that describes the task:
### Input:
returns the name of an EVREvent enum value
### Response:
def getEventTypeNameFromEnum(self, eType):
"""returns the name of an EVREvent enum value"""
fn = self.function_table.getEventTypeNameFromEnum
result = fn(eType)
... |
def isa_from_graph(graph: nx.Graph, oneq_type='Xhalves', twoq_type='CZ') -> ISA:
"""
Generate an ISA object from a NetworkX graph.
:param graph: The graph
:param oneq_type: The type of 1-qubit gate. Currently 'Xhalves'
:param twoq_type: The type of 2-qubit gate. One of 'CZ' or 'CPHASE'.
"""
... | Generate an ISA object from a NetworkX graph.
:param graph: The graph
:param oneq_type: The type of 1-qubit gate. Currently 'Xhalves'
:param twoq_type: The type of 2-qubit gate. One of 'CZ' or 'CPHASE'. | Below is the the instruction that describes the task:
### Input:
Generate an ISA object from a NetworkX graph.
:param graph: The graph
:param oneq_type: The type of 1-qubit gate. Currently 'Xhalves'
:param twoq_type: The type of 2-qubit gate. One of 'CZ' or 'CPHASE'.
### Response:
def isa_from_graph(g... |
def make_roi(cls, sources=None):
"""Build and return a `fermipy.roi_model.ROIModel` object from
a dict with information about the sources
"""
if sources is None:
sources = {}
src_fact = cls()
src_fact.add_sources(sources)
ret_model = roi_model.ROIModel... | Build and return a `fermipy.roi_model.ROIModel` object from
a dict with information about the sources | Below is the the instruction that describes the task:
### Input:
Build and return a `fermipy.roi_model.ROIModel` object from
a dict with information about the sources
### Response:
def make_roi(cls, sources=None):
"""Build and return a `fermipy.roi_model.ROIModel` object from
a dict with in... |
def robust_isinstance(inst, typ) -> bool:
"""
Similar to isinstance, but if 'typ' is a parametrized generic Type, it is first transformed into its base generic
class so that the instance check works. It is also robust to Union and Any.
:param inst:
:param typ:
:return:
"""
if typ is Any... | Similar to isinstance, but if 'typ' is a parametrized generic Type, it is first transformed into its base generic
class so that the instance check works. It is also robust to Union and Any.
:param inst:
:param typ:
:return: | Below is the the instruction that describes the task:
### Input:
Similar to isinstance, but if 'typ' is a parametrized generic Type, it is first transformed into its base generic
class so that the instance check works. It is also robust to Union and Any.
:param inst:
:param typ:
:return:
### Respon... |
def _get_id(self, file_path):
''' a helper method for retrieving id of file or folder '''
title = '%s._get_id' % self.__class__.__name__
# construct request kwargs
list_kwargs = {
'spaces': self.drive_space,
'fields': 'files(id, parents)'
... | a helper method for retrieving id of file or folder | Below is the the instruction that describes the task:
### Input:
a helper method for retrieving id of file or folder
### Response:
def _get_id(self, file_path):
''' a helper method for retrieving id of file or folder '''
title = '%s._get_id' % self.__class__.__name__
... |
def insert_entry(self, entry):
"""!
@brief Insert new clustering feature to the leaf node.
@param[in] entry (cfentry): Clustering feature.
"""
self.feature += entry;
self.entries.append(entry); | !
@brief Insert new clustering feature to the leaf node.
@param[in] entry (cfentry): Clustering feature. | Below is the the instruction that describes the task:
### Input:
!
@brief Insert new clustering feature to the leaf node.
@param[in] entry (cfentry): Clustering feature.
### Response:
def insert_entry(self, entry):
"""!
@brief Insert new clustering feature to the leaf ... |
def set_mime_type(self, mime_type):
"""
Update the highlighter lexer based on a mime type.
:param mime_type: mime type of the new lexer to setup.
"""
try:
self.set_lexer_from_mime_type(mime_type)
except ClassNotFound:
_logger().exception('failed t... | Update the highlighter lexer based on a mime type.
:param mime_type: mime type of the new lexer to setup. | Below is the the instruction that describes the task:
### Input:
Update the highlighter lexer based on a mime type.
:param mime_type: mime type of the new lexer to setup.
### Response:
def set_mime_type(self, mime_type):
"""
Update the highlighter lexer based on a mime type.
:para... |
def track_file_ident_desc(self, file_ident):
# type: (UDFFileIdentifierDescriptor) -> None
'''
A method to start tracking a UDF File Identifier descriptor in this
UDF File Entry. Both 'tracking' and 'addition' add the identifier to
the list of file identifiers, but tracking doee... | A method to start tracking a UDF File Identifier descriptor in this
UDF File Entry. Both 'tracking' and 'addition' add the identifier to
the list of file identifiers, but tracking doees not expand or
otherwise modify the UDF File Entry.
Parameters:
file_ident - The UDF File Id... | Below is the the instruction that describes the task:
### Input:
A method to start tracking a UDF File Identifier descriptor in this
UDF File Entry. Both 'tracking' and 'addition' add the identifier to
the list of file identifiers, but tracking doees not expand or
otherwise modify the UDF F... |
def get_run_on_node_mask():
"""
Returns the mask of nodes that the current thread is allowed to run on.
@return: node mask
@rtype: C{set}
"""
bitmask = libnuma.numa_get_run_node_mask()
nodemask = nodemask_t()
libnuma.copy_bitmask_to_nodemask(bitmask, byref(nodemask))
libnuma.numa_bi... | Returns the mask of nodes that the current thread is allowed to run on.
@return: node mask
@rtype: C{set} | Below is the the instruction that describes the task:
### Input:
Returns the mask of nodes that the current thread is allowed to run on.
@return: node mask
@rtype: C{set}
### Response:
def get_run_on_node_mask():
"""
Returns the mask of nodes that the current thread is allowed to run on.
@ret... |
def main():
"""
Reads stdin jboss output, writes json on output
:return:
"""
buff = ''
for line in fileinput.input():
buff += line
parser = jbossparser.JbossParser()
result = parser.parse(buff)
print(json.dumps(result)) | Reads stdin jboss output, writes json on output
:return: | Below is the the instruction that describes the task:
### Input:
Reads stdin jboss output, writes json on output
:return:
### Response:
def main():
"""
Reads stdin jboss output, writes json on output
:return:
"""
buff = ''
for line in fileinput.input():
buff += line
parser ... |
def aws_syncr_spec(self):
"""Spec for aws_syncr options"""
formatted_string = formatted(string_spec(), MergedOptionStringFormatter, expected_type=string_types)
return create_spec(AwsSyncr
, extra = defaulted(formatted_string, "")
, stage = defaulted(formatted_string, "")
... | Spec for aws_syncr options | Below is the the instruction that describes the task:
### Input:
Spec for aws_syncr options
### Response:
def aws_syncr_spec(self):
"""Spec for aws_syncr options"""
formatted_string = formatted(string_spec(), MergedOptionStringFormatter, expected_type=string_types)
return create_spec(AwsSyn... |
def gaps(args):
"""
%prog gaps A_vs_B.blast
Find distribution of gap sizes betwen adjacent HSPs.
"""
p = OptionParser(gaps.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
blastfile, = args
blast = BlastSlow(blastfile)
logging.de... | %prog gaps A_vs_B.blast
Find distribution of gap sizes betwen adjacent HSPs. | Below is the the instruction that describes the task:
### Input:
%prog gaps A_vs_B.blast
Find distribution of gap sizes betwen adjacent HSPs.
### Response:
def gaps(args):
"""
%prog gaps A_vs_B.blast
Find distribution of gap sizes betwen adjacent HSPs.
"""
p = OptionParser(gaps.__doc__)
... |
def set_volume(self, percent, update_group=True):
"""Set client volume percent."""
if percent not in range(0, 101):
raise ValueError('Volume percent out of range')
new_volume = self._client['config']['volume']
new_volume['percent'] = percent
self._client['config']['vo... | Set client volume percent. | Below is the the instruction that describes the task:
### Input:
Set client volume percent.
### Response:
def set_volume(self, percent, update_group=True):
"""Set client volume percent."""
if percent not in range(0, 101):
raise ValueError('Volume percent out of range')
new_volum... |
def _add_variant_gene_relationship(self, patient_var_map, gene_coordinate_map):
"""
Right now it is unclear the best approach on how to connect
variants to genes. In most cases has_affected_locus/GENO:0000418
is accurate; however, there are cases where a variant is in the intron
... | Right now it is unclear the best approach on how to connect
variants to genes. In most cases has_affected_locus/GENO:0000418
is accurate; however, there are cases where a variant is in the intron
on one gene and is purported to causally affect another gene down or
upstream. In these ca... | Below is the the instruction that describes the task:
### Input:
Right now it is unclear the best approach on how to connect
variants to genes. In most cases has_affected_locus/GENO:0000418
is accurate; however, there are cases where a variant is in the intron
on one gene and is purported t... |
def xreload(mod):
"""Reload a module in place, updating classes, methods and functions.
mod: a module object
Returns a boolean indicating whether a change was done.
"""
r = Reload(mod)
r.apply()
found_change = r.found_change
r = None
pydevd_dont_trace.clear_trace_filter_cache()
... | Reload a module in place, updating classes, methods and functions.
mod: a module object
Returns a boolean indicating whether a change was done. | Below is the the instruction that describes the task:
### Input:
Reload a module in place, updating classes, methods and functions.
mod: a module object
Returns a boolean indicating whether a change was done.
### Response:
def xreload(mod):
"""Reload a module in place, updating classes, methods and f... |
def get_peers_in_established(self):
"""Returns list of peers in established state."""
est_peers = []
for peer in self._peers.values():
if peer.in_established:
est_peers.append(peer)
return est_peers | Returns list of peers in established state. | Below is the the instruction that describes the task:
### Input:
Returns list of peers in established state.
### Response:
def get_peers_in_established(self):
"""Returns list of peers in established state."""
est_peers = []
for peer in self._peers.values():
if peer.in_establishe... |
def print_extended_help():
"""
Prints an extended help message.
"""
# initiate TextWrapper class, which will handle all of the string formatting
w = textwrap.TextWrapper()
w.expand_tabs = False
w.width=110
w.initial_indent = ' '
w.subsequent_indent = ' '
print('')
print(te... | Prints an extended help message. | Below is the the instruction that describes the task:
### Input:
Prints an extended help message.
### Response:
def print_extended_help():
"""
Prints an extended help message.
"""
# initiate TextWrapper class, which will handle all of the string formatting
w = textwrap.TextWrapper()
w.expand_tabs... |
def affected_files(self):
"""
Get's a fast accessible file changes for given changeset
"""
added, modified, deleted = self._changes_cache
return list(added.union(modified).union(deleted)) | Get's a fast accessible file changes for given changeset | Below is the the instruction that describes the task:
### Input:
Get's a fast accessible file changes for given changeset
### Response:
def affected_files(self):
"""
Get's a fast accessible file changes for given changeset
"""
added, modified, deleted = self._changes_cache
r... |
def getSuccessors(jobGraph, alreadySeenSuccessors, jobStore):
"""
Gets successors of the given job by walking the job graph recursively.
Any successor in alreadySeenSuccessors is ignored and not traversed.
Returns the set of found successors. This set is added to alreadySeenSuccessors.
... | Gets successors of the given job by walking the job graph recursively.
Any successor in alreadySeenSuccessors is ignored and not traversed.
Returns the set of found successors. This set is added to alreadySeenSuccessors. | Below is the the instruction that describes the task:
### Input:
Gets successors of the given job by walking the job graph recursively.
Any successor in alreadySeenSuccessors is ignored and not traversed.
Returns the set of found successors. This set is added to alreadySeenSuccessors.
### Response: ... |
def to_netcdf4(self, fname=None, base_instrument=None, epoch_name='Epoch',
zlib=False, complevel=4, shuffle=True):
"""Stores loaded data into a netCDF4 file.
Parameters
----------
fname : string
full path to save instrument object to
base_i... | Stores loaded data into a netCDF4 file.
Parameters
----------
fname : string
full path to save instrument object to
base_instrument : pysat.Instrument
used as a comparison, only attributes that are present with
self and not on base_instrument ... | Below is the the instruction that describes the task:
### Input:
Stores loaded data into a netCDF4 file.
Parameters
----------
fname : string
full path to save instrument object to
base_instrument : pysat.Instrument
used as a comparison, only attribut... |
def _compute_ndim(row_loc, col_loc):
"""Compute the ndim of result from locators
"""
row_scaler = is_scalar(row_loc)
col_scaler = is_scalar(col_loc)
if row_scaler and col_scaler:
ndim = 0
elif row_scaler ^ col_scaler:
ndim = 1
else:
ndim = 2
return ndim | Compute the ndim of result from locators | Below is the the instruction that describes the task:
### Input:
Compute the ndim of result from locators
### Response:
def _compute_ndim(row_loc, col_loc):
"""Compute the ndim of result from locators
"""
row_scaler = is_scalar(row_loc)
col_scaler = is_scalar(col_loc)
if row_scaler and col_sca... |
def _check_delete_fw(self, tenant_id, drvr_name):
"""Deletes the Firewall, if all conditioms are met.
This function after modifying the DB with delete operation status,
calls the routine to remove the fabric cfg from DB and unconfigure
the device.
"""
fw_dict = self.fwid... | Deletes the Firewall, if all conditioms are met.
This function after modifying the DB with delete operation status,
calls the routine to remove the fabric cfg from DB and unconfigure
the device. | Below is the the instruction that describes the task:
### Input:
Deletes the Firewall, if all conditioms are met.
This function after modifying the DB with delete operation status,
calls the routine to remove the fabric cfg from DB and unconfigure
the device.
### Response:
def _check_delet... |
def get_occupied_slots(instance):
"""
Return a list of slots for which values have been set.
(While a slot might be defined, if a value for that slot hasn't
been set, then it's an AttributeError to request the slot's
value.)
"""
return [slot for slot in get_all_slots(type(instance))
... | Return a list of slots for which values have been set.
(While a slot might be defined, if a value for that slot hasn't
been set, then it's an AttributeError to request the slot's
value.) | Below is the the instruction that describes the task:
### Input:
Return a list of slots for which values have been set.
(While a slot might be defined, if a value for that slot hasn't
been set, then it's an AttributeError to request the slot's
value.)
### Response:
def get_occupied_slots(instance):
... |
def build_debian(config, os_versions, os_type='ubuntu'):
"""build_debian
Builds for a specific debian operating system with os version
specified. By default, it will use os_type='ubuntu'
"""
def build_pkg(config, os_type, os_version):
result = _build_package(config, os_type, os_version)
if... | build_debian
Builds for a specific debian operating system with os version
specified. By default, it will use os_type='ubuntu' | Below is the the instruction that describes the task:
### Input:
build_debian
Builds for a specific debian operating system with os version
specified. By default, it will use os_type='ubuntu'
### Response:
def build_debian(config, os_versions, os_type='ubuntu'):
"""build_debian
Builds for a specific debian ... |
def remove_container(self, container, v=False, link=False, force=False):
"""
Remove a container. Similar to the ``docker rm`` command.
Args:
container (str): The container to remove
v (bool): Remove the volumes associated with the container
link (bool): Remov... | Remove a container. Similar to the ``docker rm`` command.
Args:
container (str): The container to remove
v (bool): Remove the volumes associated with the container
link (bool): Remove the specified link and not the underlying
container
force (bool... | Below is the the instruction that describes the task:
### Input:
Remove a container. Similar to the ``docker rm`` command.
Args:
container (str): The container to remove
v (bool): Remove the volumes associated with the container
link (bool): Remove the specified link and... |
def add_if_unique(self, name):
"""
Returns ``True`` on success.
Returns ``False`` if the name already exists in the namespace.
"""
with self.lock:
if name not in self.names:
self.names.append(name)
return True
return False | Returns ``True`` on success.
Returns ``False`` if the name already exists in the namespace. | Below is the the instruction that describes the task:
### Input:
Returns ``True`` on success.
Returns ``False`` if the name already exists in the namespace.
### Response:
def add_if_unique(self, name):
"""
Returns ``True`` on success.
Returns ``False`` if the name already exists i... |
def add_prefix(arg, opts, shell_opts):
""" Add prefix to NIPAP
"""
# sanity checks
if 'from-pool' not in opts and 'from-prefix' not in opts and 'prefix' not in opts:
print("ERROR: 'prefix', 'from-pool' or 'from-prefix' must be specified.", file=sys.stderr)
sys.exit(1)
if len([opt f... | Add prefix to NIPAP | Below is the the instruction that describes the task:
### Input:
Add prefix to NIPAP
### Response:
def add_prefix(arg, opts, shell_opts):
""" Add prefix to NIPAP
"""
# sanity checks
if 'from-pool' not in opts and 'from-prefix' not in opts and 'prefix' not in opts:
print("ERROR: 'prefix', '... |
def opt(self, x_init, f_fp=None, f=None, fp=None):
"""
Run the optimizer
"""
rcstrings = ['Converged', 'Maximum number of f evaluations reached', 'Error']
assert f_fp != None, "BFGS requires f_fp"
opt_dict = {}
if self.xtol is not None:
print("WARNI... | Run the optimizer | Below is the the instruction that describes the task:
### Input:
Run the optimizer
### Response:
def opt(self, x_init, f_fp=None, f=None, fp=None):
"""
Run the optimizer
"""
rcstrings = ['Converged', 'Maximum number of f evaluations reached', 'Error']
assert f_fp != None, ... |
def fit(self, X, y, sample_weight=None, eval_set=None, eval_metric=None,
early_stopping_rounds=None, verbose=True, xgb_model=None,
sample_weight_eval_set=None, callbacks=None):
# pylint: disable=missing-docstring,invalid-name,attribute-defined-outside-init
"""
Fit the gra... | Fit the gradient boosting model
Parameters
----------
X : array_like
Feature matrix
y : array_like
Labels
sample_weight : array_like
instance weights
eval_set : list, optional
A list of (X, y) tuple pairs to use as a valida... | Below is the the instruction that describes the task:
### Input:
Fit the gradient boosting model
Parameters
----------
X : array_like
Feature matrix
y : array_like
Labels
sample_weight : array_like
instance weights
eval_set : list,... |
def _is_idempotent(self, output):
"""
Parses the output of the provisioning for changed and returns a bool.
:param output: A string containing the output of the ansible run.
:return: bool
"""
# Remove blank lines to make regex matches easier
output = re.sub(r'\n... | Parses the output of the provisioning for changed and returns a bool.
:param output: A string containing the output of the ansible run.
:return: bool | Below is the the instruction that describes the task:
### Input:
Parses the output of the provisioning for changed and returns a bool.
:param output: A string containing the output of the ansible run.
:return: bool
### Response:
def _is_idempotent(self, output):
"""
Parses the outp... |
def getCatalog(instance, field='UID'):
"""
Returns the catalog that stores objects of instance passed in type.
If an object is indexed by more than one catalog, the first match
will be returned.
:param instance: A single object
:type instance: ATContentType
:returns: The first catalog that ... | Returns the catalog that stores objects of instance passed in type.
If an object is indexed by more than one catalog, the first match
will be returned.
:param instance: A single object
:type instance: ATContentType
:returns: The first catalog that stores the type of object passed in | Below is the the instruction that describes the task:
### Input:
Returns the catalog that stores objects of instance passed in type.
If an object is indexed by more than one catalog, the first match
will be returned.
:param instance: A single object
:type instance: ATContentType
:returns: The f... |
def get_tasks(self, thread_name):
"""
Args:
thread_name (str): name of the thread to get the tasks for
Returns:
OrderedDict of str, Task: list of task names and log records for
each for the given thread
"""
if thread_name not in self.tasks... | Args:
thread_name (str): name of the thread to get the tasks for
Returns:
OrderedDict of str, Task: list of task names and log records for
each for the given thread | Below is the the instruction that describes the task:
### Input:
Args:
thread_name (str): name of the thread to get the tasks for
Returns:
OrderedDict of str, Task: list of task names and log records for
each for the given thread
### Response:
def get_tasks(self, th... |
def isplaybook(obj):
'''
Inspects the object and returns if it is a playbook
Args:
obj (object): The object to be inspected by this function
Returns:
boolean: True if the object is a list and False if it is not
'''
return isinstance(obj, Iterable) and (not isinstance(obj, strin... | Inspects the object and returns if it is a playbook
Args:
obj (object): The object to be inspected by this function
Returns:
boolean: True if the object is a list and False if it is not | Below is the the instruction that describes the task:
### Input:
Inspects the object and returns if it is a playbook
Args:
obj (object): The object to be inspected by this function
Returns:
boolean: True if the object is a list and False if it is not
### Response:
def isplaybook(obj):
... |
def prepend_zeros_to_lists(ls):
"""
Takes a list of lists and appends 0s to the beggining of each sub_list
until they are all the same length. Used for sign-extending binary numbers.
"""
longest = max([len(l) for l in ls])
for i in range(len(ls)):
while len(ls[i]) < longest:
... | Takes a list of lists and appends 0s to the beggining of each sub_list
until they are all the same length. Used for sign-extending binary numbers. | Below is the the instruction that describes the task:
### Input:
Takes a list of lists and appends 0s to the beggining of each sub_list
until they are all the same length. Used for sign-extending binary numbers.
### Response:
def prepend_zeros_to_lists(ls):
"""
Takes a list of lists and appends 0s to t... |
def on_delete(self, forced):
"""Session expiration callback
`forced`
If session item explicitly deleted, forced will be set to True. If
item expired, will be set to False.
"""
# Do not remove connection if it was not forced and there's running connection
... | Session expiration callback
`forced`
If session item explicitly deleted, forced will be set to True. If
item expired, will be set to False. | Below is the the instruction that describes the task:
### Input:
Session expiration callback
`forced`
If session item explicitly deleted, forced will be set to True. If
item expired, will be set to False.
### Response:
def on_delete(self, forced):
"""Session expiration call... |
def search_information(adjacency, transform=None, has_memory=False):
"""
Calculates search information of `adjacency`
Computes the amount of information (measured in bits) that a random walker
needs to follow the shortest path between a given pair of nodes.
Parameters
----------
adjacency ... | Calculates search information of `adjacency`
Computes the amount of information (measured in bits) that a random walker
needs to follow the shortest path between a given pair of nodes.
Parameters
----------
adjacency : (N x N) array_like
Weighted/unweighted, direct/undirected connection we... | Below is the the instruction that describes the task:
### Input:
Calculates search information of `adjacency`
Computes the amount of information (measured in bits) that a random walker
needs to follow the shortest path between a given pair of nodes.
Parameters
----------
adjacency : (N x N) ar... |
def ParseOptions(cls, options, output_module):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
output_module (OutputModule): output module to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
BadConfigOption... | Parses and validates options.
Args:
options (argparse.Namespace): parser options.
output_module (OutputModule): output module to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
BadConfigOption: when a configuration parameter fails validation. | Below is the the instruction that describes the task:
### Input:
Parses and validates options.
Args:
options (argparse.Namespace): parser options.
output_module (OutputModule): output module to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
... |
def connect(self):
"""
Method automatically called by the run() method of the AgentProxyThread
"""
if ('SSH_AUTH_SOCK' in os.environ) and (sys.platform != 'win32'):
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
retry_on_signal(lambd... | Method automatically called by the run() method of the AgentProxyThread | Below is the the instruction that describes the task:
### Input:
Method automatically called by the run() method of the AgentProxyThread
### Response:
def connect(self):
"""
Method automatically called by the run() method of the AgentProxyThread
"""
if ('SSH_AUTH_SOCK' in os.environ... |
def dropna(self, drop_nan=True, drop_masked=True, column_names=None):
"""Create a shallow copy of a DataFrame, with filtering set using select_non_missing.
:param drop_nan: drop rows when there is a NaN in any of the columns (will only affect float values)
:param drop_masked: drop rows when the... | Create a shallow copy of a DataFrame, with filtering set using select_non_missing.
:param drop_nan: drop rows when there is a NaN in any of the columns (will only affect float values)
:param drop_masked: drop rows when there is a masked value in any of the columns
:param column_names: The colum... | Below is the the instruction that describes the task:
### Input:
Create a shallow copy of a DataFrame, with filtering set using select_non_missing.
:param drop_nan: drop rows when there is a NaN in any of the columns (will only affect float values)
:param drop_masked: drop rows when there is a mask... |
def password(self, value):
"""gets/sets the current password"""
if isinstance(value, str):
self._password = value
self._handler = None | gets/sets the current password | Below is the the instruction that describes the task:
### Input:
gets/sets the current password
### Response:
def password(self, value):
"""gets/sets the current password"""
if isinstance(value, str):
self._password = value
self._handler = None |
def import_args_from_dict(value, args, config):
"""Replaces some arguments by those specified by a key-value dictionary.
This function will be recursively called on a dictionary looking for any
value containing a "$" variable. If found, the value will be replaced
by the attribute in "args" of the same name.
... | Replaces some arguments by those specified by a key-value dictionary.
This function will be recursively called on a dictionary looking for any
value containing a "$" variable. If found, the value will be replaced
by the attribute in "args" of the same name.
It is used to load arguments from the CLI and any ex... | Below is the the instruction that describes the task:
### Input:
Replaces some arguments by those specified by a key-value dictionary.
This function will be recursively called on a dictionary looking for any
value containing a "$" variable. If found, the value will be replaced
by the attribute in "args" of t... |
def Join(self, Id):
"""Joins with another call to form a conference.
:Parameters:
Id : int
Call Id of the other call to join to the conference.
:return: Conference object.
:rtype: `Conference`
"""
#self._Alter('JOIN_CONFERENCE', Id)
reply =... | Joins with another call to form a conference.
:Parameters:
Id : int
Call Id of the other call to join to the conference.
:return: Conference object.
:rtype: `Conference` | Below is the the instruction that describes the task:
### Input:
Joins with another call to form a conference.
:Parameters:
Id : int
Call Id of the other call to join to the conference.
:return: Conference object.
:rtype: `Conference`
### Response:
def Join(self, Id)... |
def apply_update(self, value, index):
"""
Record an opendnp3 data value (Analog, Binary, etc.) in the outstation's database.
The data value gets sent to the Master as a side-effect.
:param value: An instance of Analog, Binary, or another opendnp3 data value.
:param inde... | Record an opendnp3 data value (Analog, Binary, etc.) in the outstation's database.
The data value gets sent to the Master as a side-effect.
:param value: An instance of Analog, Binary, or another opendnp3 data value.
:param index: (integer) Index of the data definition in the opendnp3 data... | Below is the the instruction that describes the task:
### Input:
Record an opendnp3 data value (Analog, Binary, etc.) in the outstation's database.
The data value gets sent to the Master as a side-effect.
:param value: An instance of Analog, Binary, or another opendnp3 data value.
:par... |
def update_index(model_items, model_name, action='index', bulk_size=100, num_docs=-1, start_date=None, end_date=None, refresh=True):
'''
Updates the index for the provided model_items.
:param model_items: a list of model_items (django Model instances, or proxy instances) which are to be indexed/updated or d... | Updates the index for the provided model_items.
:param model_items: a list of model_items (django Model instances, or proxy instances) which are to be indexed/updated or deleted.
If action is 'index', the model_items must be serializable objects. If action is 'delete', the model_items must be primary keys
c... | Below is the the instruction that describes the task:
### Input:
Updates the index for the provided model_items.
:param model_items: a list of model_items (django Model instances, or proxy instances) which are to be indexed/updated or deleted.
If action is 'index', the model_items must be serializable objec... |
def read_union(fo, writer_schema, reader_schema=None):
"""A union is encoded by first writing a long value indicating the
zero-based position within the union of the schema of its value.
The value is then encoded per the indicated schema within the union.
"""
# schema resolution
index = read_lo... | A union is encoded by first writing a long value indicating the
zero-based position within the union of the schema of its value.
The value is then encoded per the indicated schema within the union. | Below is the the instruction that describes the task:
### Input:
A union is encoded by first writing a long value indicating the
zero-based position within the union of the schema of its value.
The value is then encoded per the indicated schema within the union.
### Response:
def read_union(fo, writer_sch... |
def facility(self, column=None, value=None, **kwargs):
"""
Check information related to Radiation facilities.
>>> RADInfo().facility('state_code', 'CA')
"""
return self._resolve_call('RAD_FACILITY', column, value, **kwargs) | Check information related to Radiation facilities.
>>> RADInfo().facility('state_code', 'CA') | Below is the the instruction that describes the task:
### Input:
Check information related to Radiation facilities.
>>> RADInfo().facility('state_code', 'CA')
### Response:
def facility(self, column=None, value=None, **kwargs):
"""
Check information related to Radiation facilities.
... |
def get_instance(self, payload):
"""
Build an instance of RecordingInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.call.recording.RecordingInstance
:rtype: twilio.rest.api.v2010.account.call.recording.RecordingInstance
... | Build an instance of RecordingInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.call.recording.RecordingInstance
:rtype: twilio.rest.api.v2010.account.call.recording.RecordingInstance | Below is the the instruction that describes the task:
### Input:
Build an instance of RecordingInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.call.recording.RecordingInstance
:rtype: twilio.rest.api.v2010.account.call.recording.Recording... |
def _array_handler(self, _cursor_type):
"""
Handles all array types.
Resolves it's element type and makes a Array typedesc.
"""
# The element type has been previously declared
# we need to get the canonical typedef, in some cases
_type = _cursor_type.get_canonical... | Handles all array types.
Resolves it's element type and makes a Array typedesc. | Below is the the instruction that describes the task:
### Input:
Handles all array types.
Resolves it's element type and makes a Array typedesc.
### Response:
def _array_handler(self, _cursor_type):
"""
Handles all array types.
Resolves it's element type and makes a Array typedesc.
... |
def get_automation(self, automation_id, refresh=False):
"""Get a single automation."""
if self._automations is None:
self.get_automations()
refresh = False
automation = self._automations.get(str(automation_id))
if automation and refresh:
automation.r... | Get a single automation. | Below is the the instruction that describes the task:
### Input:
Get a single automation.
### Response:
def get_automation(self, automation_id, refresh=False):
"""Get a single automation."""
if self._automations is None:
self.get_automations()
refresh = False
automa... |
def inicializar_y_capturar_excepciones_simple(func):
"Decorador para inicializar y capturar errores (versión básica indep.)"
@functools.wraps(func)
def capturar_errores_wrapper(self, *args, **kwargs):
self.inicializar()
try:
return func(self, *args, **kwargs)
except:
... | Decorador para inicializar y capturar errores (versión básica indep.) | Below is the the instruction that describes the task:
### Input:
Decorador para inicializar y capturar errores (versión básica indep.)
### Response:
def inicializar_y_capturar_excepciones_simple(func):
"Decorador para inicializar y capturar errores (versión básica indep.)"
@functools.wraps(func)
def ca... |
def dmag_magic(in_file="measurements.txt", dir_path=".", input_dir_path="",
spec_file="specimens.txt", samp_file="samples.txt",
site_file="sites.txt", loc_file="locations.txt",
plot_by="loc", LT="AF", norm=True, XLP="",
save_plots=True, fmt="svg"):
"""
plots intensity decay ... | plots intensity decay curves for demagnetization experiments
Parameters
----------
in_file : str, default "measurements.txt"
dir_path : str
output directory, default "."
input_dir_path : str
input file directory (if different from dir_path), default ""
spec_file : str
in... | Below is the the instruction that describes the task:
### Input:
plots intensity decay curves for demagnetization experiments
Parameters
----------
in_file : str, default "measurements.txt"
dir_path : str
output directory, default "."
input_dir_path : str
input file directory (i... |
def icnr(x, scale=2, init=nn.init.kaiming_normal_):
"ICNR init of `x`, with `scale` and `init` function."
ni,nf,h,w = x.shape
ni2 = int(ni/(scale**2))
k = init(torch.zeros([ni2,nf,h,w])).transpose(0, 1)
k = k.contiguous().view(ni2, nf, -1)
k = k.repeat(1, 1, scale**2)
k = k.contiguous().view... | ICNR init of `x`, with `scale` and `init` function. | Below is the the instruction that describes the task:
### Input:
ICNR init of `x`, with `scale` and `init` function.
### Response:
def icnr(x, scale=2, init=nn.init.kaiming_normal_):
"ICNR init of `x`, with `scale` and `init` function."
ni,nf,h,w = x.shape
ni2 = int(ni/(scale**2))
k = init(torch.ze... |
def vra(self,*args,**kwargs):
"""
NAME:
vra
PURPOSE:
return velocity in right ascension (km/s)
INPUT:
t - (optional) time at which to get vra (can be Quantity)
obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer
... | NAME:
vra
PURPOSE:
return velocity in right ascension (km/s)
INPUT:
t - (optional) time at which to get vra (can be Quantity)
obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observer
in the Galactocentric frame
... | Below is the the instruction that describes the task:
### Input:
NAME:
vra
PURPOSE:
return velocity in right ascension (km/s)
INPUT:
t - (optional) time at which to get vra (can be Quantity)
obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of ... |
def p_tag_ref(self, p):
'tag_ref : ID'
p[0] = AstTagRef(self.path, p.lineno(1), p.lexpos(1), p[1]) | tag_ref : ID | Below is the the instruction that describes the task:
### Input:
tag_ref : ID
### Response:
def p_tag_ref(self, p):
'tag_ref : ID'
p[0] = AstTagRef(self.path, p.lineno(1), p.lexpos(1), p[1]) |
def is_ipython_notebook(file_name):
"""
Return True if file_name matches a regexp for an ipython notebook. False otherwise.
:param file_name: file to test
"""
if (not re.match("^.*checkpoint\.ipynb$", file_name)) and re.match("^.*\.ipynb$", file_name): return True
return False | Return True if file_name matches a regexp for an ipython notebook. False otherwise.
:param file_name: file to test | Below is the the instruction that describes the task:
### Input:
Return True if file_name matches a regexp for an ipython notebook. False otherwise.
:param file_name: file to test
### Response:
def is_ipython_notebook(file_name):
"""
Return True if file_name matches a regexp for an ipython notebook. ... |
def write(self, file_or_filename):
""" Writes case data to file in Excel format.
"""
self.book = Workbook()
self._write_data(None)
self.book.save(file_or_filename) | Writes case data to file in Excel format. | Below is the the instruction that describes the task:
### Input:
Writes case data to file in Excel format.
### Response:
def write(self, file_or_filename):
""" Writes case data to file in Excel format.
"""
self.book = Workbook()
self._write_data(None)
self.book.save(file_or_... |
def get_s3_client():
"""
A DRY place to make sure AWS credentials in settings override
environment based credentials. Boto3 will fall back to:
http://boto3.readthedocs.io/en/latest/guide/configuration.html
"""
session_kwargs = {}
if hasattr(settings, 'AWS_ACCESS_KEY_ID'):
session_kw... | A DRY place to make sure AWS credentials in settings override
environment based credentials. Boto3 will fall back to:
http://boto3.readthedocs.io/en/latest/guide/configuration.html | Below is the the instruction that describes the task:
### Input:
A DRY place to make sure AWS credentials in settings override
environment based credentials. Boto3 will fall back to:
http://boto3.readthedocs.io/en/latest/guide/configuration.html
### Response:
def get_s3_client():
"""
A DRY place t... |
def token_expired(self):
"""Provide access to flag indicating if token has expired."""
if self._token_timer is None:
return True
return timeutil.is_newer_than(self._token_timer, timeutil.ONE_HOUR) | Provide access to flag indicating if token has expired. | Below is the the instruction that describes the task:
### Input:
Provide access to flag indicating if token has expired.
### Response:
def token_expired(self):
"""Provide access to flag indicating if token has expired."""
if self._token_timer is None:
return True
return timeutil... |
def economic_qs(K, epsilon=sqrt(finfo(float).eps)):
r"""Economic eigen decomposition for symmetric matrices.
A symmetric matrix ``K`` can be decomposed in
:math:`\mathrm Q_0 \mathrm S_0 \mathrm Q_0^\intercal + \mathrm Q_1\
\mathrm S_1 \mathrm Q_1^ \intercal`, where :math:`\mathrm S_1` is a zero
mat... | r"""Economic eigen decomposition for symmetric matrices.
A symmetric matrix ``K`` can be decomposed in
:math:`\mathrm Q_0 \mathrm S_0 \mathrm Q_0^\intercal + \mathrm Q_1\
\mathrm S_1 \mathrm Q_1^ \intercal`, where :math:`\mathrm S_1` is a zero
matrix with size determined by ``K``'s rank deficiency.
... | Below is the the instruction that describes the task:
### Input:
r"""Economic eigen decomposition for symmetric matrices.
A symmetric matrix ``K`` can be decomposed in
:math:`\mathrm Q_0 \mathrm S_0 \mathrm Q_0^\intercal + \mathrm Q_1\
\mathrm S_1 \mathrm Q_1^ \intercal`, where :math:`\mathrm S_1` is a... |
def sngl_ifo_job_setup(workflow, ifo, out_files, curr_exe_job, science_segs,
datafind_outs, parents=None,
link_job_instance=None, allow_overlap=True,
compatibility_mode=True):
""" This function sets up a set of single ifo jobs. A basic overview of... | This function sets up a set of single ifo jobs. A basic overview of how this
works is as follows:
* (1) Identify the length of data that each job needs to read in, and what
part of that data the job is valid for.
* START LOOPING OVER SCIENCE SEGMENTS
* (2) Identify how many jobs are needed (if an... | Below is the the instruction that describes the task:
### Input:
This function sets up a set of single ifo jobs. A basic overview of how this
works is as follows:
* (1) Identify the length of data that each job needs to read in, and what
part of that data the job is valid for.
* START LOOPING OVE... |
def obfn_reg(self):
"""Compute regularisation term and contribution to objective
function.
"""
rl1 = np.linalg.norm((self.wl1 * self.obfn_gvar()).ravel(), 1)
return (self.lmbda*rl1, rl1) | Compute regularisation term and contribution to objective
function. | Below is the the instruction that describes the task:
### Input:
Compute regularisation term and contribution to objective
function.
### Response:
def obfn_reg(self):
"""Compute regularisation term and contribution to objective
function.
"""
rl1 = np.linalg.norm((self.wl1 *... |
def get_post(self):
""" Returns the considered post if applicable. """
pk = self.kwargs.get(self.post_pk_url_kwarg, None)
if not pk:
return
if not hasattr(self, '_forum_post'):
self._forum_post = get_object_or_404(Post, pk=pk)
return self._forum_post | Returns the considered post if applicable. | Below is the the instruction that describes the task:
### Input:
Returns the considered post if applicable.
### Response:
def get_post(self):
""" Returns the considered post if applicable. """
pk = self.kwargs.get(self.post_pk_url_kwarg, None)
if not pk:
return
if not ha... |
def read_csv(csvfile, options):
"""
Read csv and return molList, a list of mol objects
"""
# open file or exit
name, ext = os.path.splitext(csvfile)
try:
if ext == '.gz':
f = gzip.open(csvfile, 'rb')
else:
f = open(csvfile, 'rU')
except IOError:
pri... | Read csv and return molList, a list of mol objects | Below is the the instruction that describes the task:
### Input:
Read csv and return molList, a list of mol objects
### Response:
def read_csv(csvfile, options):
"""
Read csv and return molList, a list of mol objects
"""
# open file or exit
name, ext = os.path.splitext(csvfile)
try:
if e... |
def location_2_json(self):
"""
transform ariane_clip3 location object to Ariane server JSON obj
:return: Ariane JSON obj
"""
LOGGER.debug("Location.location_2_json")
json_obj = {
'locationID': self.id,
'locationName': self.name,
'locati... | transform ariane_clip3 location object to Ariane server JSON obj
:return: Ariane JSON obj | Below is the the instruction that describes the task:
### Input:
transform ariane_clip3 location object to Ariane server JSON obj
:return: Ariane JSON obj
### Response:
def location_2_json(self):
"""
transform ariane_clip3 location object to Ariane server JSON obj
:return: Ariane JS... |
def calculate_size(name, sequence):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += LONG_SIZE_IN_BYTES
return data_size | Calculates the request payload size | Below is the the instruction that describes the task:
### Input:
Calculates the request payload size
### Response:
def calculate_size(name, sequence):
""" Calculates the request payload size"""
data_size = 0
data_size += calculate_size_str(name)
data_size += LONG_SIZE_IN_BYTES
return data_size |
def saccadic_momentum_effect(durations, forward_angle,
summary_stat=nanmean):
"""
Computes the mean fixation duration at forward angles.
"""
durations_per_da = np.nan * np.ones((len(e_angle) - 1,))
for i, (bo, b1) in enumerate(zip(e_angle[:-1], e_angle[1:])):
idx... | Computes the mean fixation duration at forward angles. | Below is the the instruction that describes the task:
### Input:
Computes the mean fixation duration at forward angles.
### Response:
def saccadic_momentum_effect(durations, forward_angle,
summary_stat=nanmean):
"""
Computes the mean fixation duration at forward angles.
"""... |
def get_json_body(self, required=None, validators=None):
"""Get JSON from the request body
:param required: optionally provide a list of keys that should be
in the JSON body (raises a 400 HTTPError if any are missing)
:param validator: optionally provide a dictionary of items that shoul... | Get JSON from the request body
:param required: optionally provide a list of keys that should be
in the JSON body (raises a 400 HTTPError if any are missing)
:param validator: optionally provide a dictionary of items that should
be in the body with a method that validates the item.
... | Below is the the instruction that describes the task:
### Input:
Get JSON from the request body
:param required: optionally provide a list of keys that should be
in the JSON body (raises a 400 HTTPError if any are missing)
:param validator: optionally provide a dictionary of items that shou... |
def detection_multiplot(stream, template, times, streamcolour='k',
templatecolour='r', size=(10.5, 7.5), **kwargs):
"""
Plot a stream of data with a template on top of it at detection times.
:type stream: obspy.core.stream.Stream
:param stream: Stream of data to be plotted as th... | Plot a stream of data with a template on top of it at detection times.
:type stream: obspy.core.stream.Stream
:param stream: Stream of data to be plotted as the background.
:type template: obspy.core.stream.Stream
:param template: Template to be plotted on top of the base stream.
:type times: list
... | Below is the the instruction that describes the task:
### Input:
Plot a stream of data with a template on top of it at detection times.
:type stream: obspy.core.stream.Stream
:param stream: Stream of data to be plotted as the background.
:type template: obspy.core.stream.Stream
:param template: Tem... |
def add_items(self, items):
'''Adds ListItems to the XBMC interface. Each item in the
provided list should either be instances of xbmcswift2.ListItem,
or regular dictionaries that will be passed to
xbmcswift2.ListItem.from_dict. Returns the list of ListItems.
:param items: An it... | Adds ListItems to the XBMC interface. Each item in the
provided list should either be instances of xbmcswift2.ListItem,
or regular dictionaries that will be passed to
xbmcswift2.ListItem.from_dict. Returns the list of ListItems.
:param items: An iterable of items where each item is eith... | Below is the the instruction that describes the task:
### Input:
Adds ListItems to the XBMC interface. Each item in the
provided list should either be instances of xbmcswift2.ListItem,
or regular dictionaries that will be passed to
xbmcswift2.ListItem.from_dict. Returns the list of ListItems... |
def get_template_names(self):
"""
Return a list of template names to be used for the view.
"""
year = self.get_archive_part_value('year')
week = self.get_archive_part_value('week')
month = self.get_archive_part_value('month')
day = self.get_archive_part_value('day... | Return a list of template names to be used for the view. | Below is the the instruction that describes the task:
### Input:
Return a list of template names to be used for the view.
### Response:
def get_template_names(self):
"""
Return a list of template names to be used for the view.
"""
year = self.get_archive_part_value('year')
w... |
def node_set_to_surface(self, tag):
"""
Converts a node set to surface.
"""
# Create a dummy node with label 0
nodes = self.nodes.copy()
dummy = nodes.iloc[0].copy()
dummy["coords"] *= np.nan
dummy["sets"] = True
nodes.loc[0] = dummy
# Getting element surfaces
element_surface... | Converts a node set to surface. | Below is the the instruction that describes the task:
### Input:
Converts a node set to surface.
### Response:
def node_set_to_surface(self, tag):
"""
Converts a node set to surface.
"""
# Create a dummy node with label 0
nodes = self.nodes.copy()
dummy = nodes.iloc[0].copy()
dummy["coo... |
def copy(self, empty=False):
""" Create a copy of the graph (by default with nodes and edges).
"""
g = graph(self.layout.n, self.distance, self.layout.type)
g.layout = self.layout.copy(g)
g.styles = self.styles.copy(g)
g.events = self.events.copy(g)
... | Create a copy of the graph (by default with nodes and edges). | Below is the the instruction that describes the task:
### Input:
Create a copy of the graph (by default with nodes and edges).
### Response:
def copy(self, empty=False):
""" Create a copy of the graph (by default with nodes and edges).
"""
g = graph(self.layout.n, self.dis... |
def get_X_gradients(self, X):
"""Get the gradients of the posterior distribution of X in its specific form."""
return X.mean.gradient, X.variance.gradient, X.binary_prob.gradient | Get the gradients of the posterior distribution of X in its specific form. | Below is the the instruction that describes the task:
### Input:
Get the gradients of the posterior distribution of X in its specific form.
### Response:
def get_X_gradients(self, X):
"""Get the gradients of the posterior distribution of X in its specific form."""
return X.mean.gradient, X.variance... |
def add_inspection(name):
"""
Add a Jishaku object inspection
"""
# create the real decorator
def inspection_inner(func):
"""
Jishaku inspection decorator
"""
# pylint: disable=inconsistent-return-statements
# create an encapsulated version of the inspectio... | Add a Jishaku object inspection | Below is the the instruction that describes the task:
### Input:
Add a Jishaku object inspection
### Response:
def add_inspection(name):
"""
Add a Jishaku object inspection
"""
# create the real decorator
def inspection_inner(func):
"""
Jishaku inspection decorator
"""
... |
def gen_cannon_grad_spec(choose, coeffs, pivots):
""" Generate Cannon gradient spectra
Parameters
----------
labels: default values for [teff, logg, feh, cfe, nfe, afe, ak]
choose: val of cfe or nfe, whatever you're varying
low: lowest val of cfe or nfe, whatever you're varying
high: highes... | Generate Cannon gradient spectra
Parameters
----------
labels: default values for [teff, logg, feh, cfe, nfe, afe, ak]
choose: val of cfe or nfe, whatever you're varying
low: lowest val of cfe or nfe, whatever you're varying
high: highest val of cfe or nfe, whatever you're varying | Below is the the instruction that describes the task:
### Input:
Generate Cannon gradient spectra
Parameters
----------
labels: default values for [teff, logg, feh, cfe, nfe, afe, ak]
choose: val of cfe or nfe, whatever you're varying
low: lowest val of cfe or nfe, whatever you're varying
h... |
def inferURILocalSymbol(aUri):
"""
From a URI returns a tuple (namespace, uri-last-bit)
Eg
from <'http://www.w3.org/2008/05/skos#something'>
==> ('something', 'http://www.w3.org/2008/05/skos')
from <'http://www.w3.org/2003/01/geo/wgs84_pos'> we extract
==> ('wgs84_pos', 'http://www.... | From a URI returns a tuple (namespace, uri-last-bit)
Eg
from <'http://www.w3.org/2008/05/skos#something'>
==> ('something', 'http://www.w3.org/2008/05/skos')
from <'http://www.w3.org/2003/01/geo/wgs84_pos'> we extract
==> ('wgs84_pos', 'http://www.w3.org/2003/01/geo/') | Below is the the instruction that describes the task:
### Input:
From a URI returns a tuple (namespace, uri-last-bit)
Eg
from <'http://www.w3.org/2008/05/skos#something'>
==> ('something', 'http://www.w3.org/2008/05/skos')
from <'http://www.w3.org/2003/01/geo/wgs84_pos'> we extract
==> ... |
def get_dict(self, name, default=None):
"""Retrieves an environment variable value as a dictionary.
Args:
name (str): The case-insensitive, unprefixed variable name.
default: If provided, a default value will be returned
instead of throwing ``EnvironmentError``.
... | Retrieves an environment variable value as a dictionary.
Args:
name (str): The case-insensitive, unprefixed variable name.
default: If provided, a default value will be returned
instead of throwing ``EnvironmentError``.
Returns:
dict: The environment... | Below is the the instruction that describes the task:
### Input:
Retrieves an environment variable value as a dictionary.
Args:
name (str): The case-insensitive, unprefixed variable name.
default: If provided, a default value will be returned
instead of throwing ``En... |
def export(self):
"""
Returns a dictionary with all album information.
Use the :meth:`from_export` method to recreate the
:class:`Album` object.
"""
return {'id' : self.id, 'name' : self.name, 'artist' : self._artist_name, 'artist_id' : self._artist_id, 'cover' : self._co... | Returns a dictionary with all album information.
Use the :meth:`from_export` method to recreate the
:class:`Album` object. | Below is the the instruction that describes the task:
### Input:
Returns a dictionary with all album information.
Use the :meth:`from_export` method to recreate the
:class:`Album` object.
### Response:
def export(self):
"""
Returns a dictionary with all album information.
Us... |
def make_optimize_tensor(self, model, session=None, var_list=None, **kwargs):
"""
Make SciPy optimization tensor.
The `make_optimize_tensor` method builds optimization tensor and initializes
all necessary variables created by optimizer.
:param model: GPflow model.
... | Make SciPy optimization tensor.
The `make_optimize_tensor` method builds optimization tensor and initializes
all necessary variables created by optimizer.
:param model: GPflow model.
:param session: Tensorflow session.
:param var_list: List of variables for training.... | Below is the the instruction that describes the task:
### Input:
Make SciPy optimization tensor.
The `make_optimize_tensor` method builds optimization tensor and initializes
all necessary variables created by optimizer.
:param model: GPflow model.
:param session: Tensorflow ... |
def get_private_endpoint(id: str, guid: str) -> str:
"""Get remote endpoint for delivering private payloads."""
_username, domain = id.split("@")
return "https://%s/receive/users/%s" % (domain, guid) | Get remote endpoint for delivering private payloads. | Below is the the instruction that describes the task:
### Input:
Get remote endpoint for delivering private payloads.
### Response:
def get_private_endpoint(id: str, guid: str) -> str:
"""Get remote endpoint for delivering private payloads."""
_username, domain = id.split("@")
return "https://%s/receiv... |
def load_plume_package(package, plume_dir, accept_defaults):
"""Loads a canari package into Plume."""
from canari.commands.load_plume_package import load_plume_package
load_plume_package(package, plume_dir, accept_defaults) | Loads a canari package into Plume. | Below is the the instruction that describes the task:
### Input:
Loads a canari package into Plume.
### Response:
def load_plume_package(package, plume_dir, accept_defaults):
"""Loads a canari package into Plume."""
from canari.commands.load_plume_package import load_plume_package
load_plume_package(pa... |
def _parse_time_to_freeze(time_to_freeze_str):
"""Parses all the possible inputs for freeze_time
:returns: a naive ``datetime.datetime`` object
"""
if time_to_freeze_str is None:
time_to_freeze_str = datetime.datetime.utcnow()
if isinstance(time_to_freeze_str, datetime.datetime):
ti... | Parses all the possible inputs for freeze_time
:returns: a naive ``datetime.datetime`` object | Below is the the instruction that describes the task:
### Input:
Parses all the possible inputs for freeze_time
:returns: a naive ``datetime.datetime`` object
### Response:
def _parse_time_to_freeze(time_to_freeze_str):
"""Parses all the possible inputs for freeze_time
:returns: a naive ``datetime.date... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.