code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def __set_timestamp(self, clock):
"""
If "clock" is None, set the time now.
This function is called self.__init__()
"""
if clock is None:
unix_timestamp = time.mktime(
datetime.datetime.now().utctimetuple()
)
timestamp = int(uni... | If "clock" is None, set the time now.
This function is called self.__init__() | Below is the the instruction that describes the task:
### Input:
If "clock" is None, set the time now.
This function is called self.__init__()
### Response:
def __set_timestamp(self, clock):
"""
If "clock" is None, set the time now.
This function is called self.__init__()
""... |
def unquote_filename(name, win32=(sys.platform=='win32')):
""" On Windows, remove leading and trailing quotes from filenames.
"""
if win32:
if name.startswith(("'", '"')) and name.endswith(("'", '"')):
name = name[1:-1]
return name | On Windows, remove leading and trailing quotes from filenames. | Below is the the instruction that describes the task:
### Input:
On Windows, remove leading and trailing quotes from filenames.
### Response:
def unquote_filename(name, win32=(sys.platform=='win32')):
""" On Windows, remove leading and trailing quotes from filenames.
"""
if win32:
if name.start... |
def switch_to_line_in(self, source=None):
""" Switch the speaker's input to line-in.
Args:
source (SoCo): The speaker whose line-in should be played.
Default is line-in from the speaker itself.
"""
if source:
uid = source.uid
else:
... | Switch the speaker's input to line-in.
Args:
source (SoCo): The speaker whose line-in should be played.
Default is line-in from the speaker itself. | Below is the the instruction that describes the task:
### Input:
Switch the speaker's input to line-in.
Args:
source (SoCo): The speaker whose line-in should be played.
Default is line-in from the speaker itself.
### Response:
def switch_to_line_in(self, source=None):
"... |
def load(self, pkcs11dll_filename=None, *init_string):
"""
load a PKCS#11 library
:type pkcs11dll_filename: string
:param pkcs11dll_filename: the library name.
If this parameter is not set then the environment variable
`PYKCS11LIB` is used instead
:returns: a... | load a PKCS#11 library
:type pkcs11dll_filename: string
:param pkcs11dll_filename: the library name.
If this parameter is not set then the environment variable
`PYKCS11LIB` is used instead
:returns: a :class:`PyKCS11Lib` object
:raises: :class:`PyKCS11Error` (-1): wh... | Below is the the instruction that describes the task:
### Input:
load a PKCS#11 library
:type pkcs11dll_filename: string
:param pkcs11dll_filename: the library name.
If this parameter is not set then the environment variable
`PYKCS11LIB` is used instead
:returns: a :clas... |
def _read_depth_image(self):
""" Reads a depth image from the device """
# read raw uint16 buffer
im_arr = self._depth_stream.read_frame()
raw_buf = im_arr.get_buffer_as_uint16()
buf_array = np.array([raw_buf[i] for i in range(PrimesenseSensor.DEPTH_IM_WIDTH * PrimesenseSensor.DE... | Reads a depth image from the device | Below is the the instruction that describes the task:
### Input:
Reads a depth image from the device
### Response:
def _read_depth_image(self):
""" Reads a depth image from the device """
# read raw uint16 buffer
im_arr = self._depth_stream.read_frame()
raw_buf = im_arr.get_buffer_a... |
def _number_zero_start_handler(c, ctx):
"""Handles numeric values that start with zero or negative zero. Branches to delegate co-routines according to
_ZERO_START_TABLE.
"""
assert c == _ZERO
assert len(ctx.value) == 0 or (len(ctx.value) == 1 and ctx.value[0] == _MINUS)
ctx.set_ion_type(IonType.... | Handles numeric values that start with zero or negative zero. Branches to delegate co-routines according to
_ZERO_START_TABLE. | Below is the the instruction that describes the task:
### Input:
Handles numeric values that start with zero or negative zero. Branches to delegate co-routines according to
_ZERO_START_TABLE.
### Response:
def _number_zero_start_handler(c, ctx):
"""Handles numeric values that start with zero or negative ze... |
def resume_sm(self, xmlstream):
"""
Resume an SM-enabled stream using the given `xmlstream`.
If the server rejects the attempt to resume stream management, a
:class:`.errors.StreamNegotiationFailure` is raised. The stream is then
in stopped state and stream management has been s... | Resume an SM-enabled stream using the given `xmlstream`.
If the server rejects the attempt to resume stream management, a
:class:`.errors.StreamNegotiationFailure` is raised. The stream is then
in stopped state and stream management has been stopped.
.. warning::
This metho... | Below is the the instruction that describes the task:
### Input:
Resume an SM-enabled stream using the given `xmlstream`.
If the server rejects the attempt to resume stream management, a
:class:`.errors.StreamNegotiationFailure` is raised. The stream is then
in stopped state and stream mana... |
def isochrone(self,age,feh=0.0,minm=None,maxm=None,dm=0.02,
return_df=True,distance=None,AV=0.0):
"""
Returns stellar models at constant age and feh, for a range of masses
:param age:
log10(age) of desired isochrone.
:param feh: (optional)
Meta... | Returns stellar models at constant age and feh, for a range of masses
:param age:
log10(age) of desired isochrone.
:param feh: (optional)
Metallicity of desired isochrone (default = 0.0)
:param minm, maxm: (optional)
Mass range of desired isochrone (will de... | Below is the the instruction that describes the task:
### Input:
Returns stellar models at constant age and feh, for a range of masses
:param age:
log10(age) of desired isochrone.
:param feh: (optional)
Metallicity of desired isochrone (default = 0.0)
:param minm, ... |
def div(x, y, context=None):
"""
Return ``x`` divided by ``y``.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_div,
(
BigFloat._implicit_convert(x),
BigFloat._implicit_convert(y),
),
context,
) | Return ``x`` divided by ``y``. | Below is the the instruction that describes the task:
### Input:
Return ``x`` divided by ``y``.
### Response:
def div(x, y, context=None):
"""
Return ``x`` divided by ``y``.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_div,
(
BigFloat._impl... |
def get(ctx):
"""Get info for current project, by project_name, or user/project_name.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
To get current project:
\b
```bash
$ polyaxon project get
```
To get a project by name
\b
```bash
$ polyaxon project get... | Get info for current project, by project_name, or user/project_name.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
To get current project:
\b
```bash
$ polyaxon project get
```
To get a project by name
\b
```bash
$ polyaxon project get user/project
``` | Below is the the instruction that describes the task:
### Input:
Get info for current project, by project_name, or user/project_name.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
To get current project:
\b
```bash
$ polyaxon project get
```
To get a project by nam... |
def parent(self):
"""Get the parent package family.
Returns:
`PackageFamily`.
"""
family = self.repository.get_parent_package_family(self.resource)
return PackageFamily(family) if family else None | Get the parent package family.
Returns:
`PackageFamily`. | Below is the the instruction that describes the task:
### Input:
Get the parent package family.
Returns:
`PackageFamily`.
### Response:
def parent(self):
"""Get the parent package family.
Returns:
`PackageFamily`.
"""
family = self.repository.get_pa... |
def interm_fluent_ordering(self) -> List[str]:
'''The list of intermediate-fluent names in canonical order.
Returns:
List[str]: A list of fluent names.
'''
interm_fluents = self.intermediate_fluents.values()
key = lambda pvar: (pvar.level, pvar.name)
return [... | The list of intermediate-fluent names in canonical order.
Returns:
List[str]: A list of fluent names. | Below is the the instruction that describes the task:
### Input:
The list of intermediate-fluent names in canonical order.
Returns:
List[str]: A list of fluent names.
### Response:
def interm_fluent_ordering(self) -> List[str]:
'''The list of intermediate-fluent names in canonical orde... |
def authenticate():
"""Authenticate via already provided configuration.
This is called once automatically per session when uploading and rendering a visualization."""
key = PyGraphistry.api_key()
#Mocks may set to True, so bypass in that case
if (key is None) and PyGraphistry._is... | Authenticate via already provided configuration.
This is called once automatically per session when uploading and rendering a visualization. | Below is the the instruction that describes the task:
### Input:
Authenticate via already provided configuration.
This is called once automatically per session when uploading and rendering a visualization.
### Response:
def authenticate():
"""Authenticate via already provided configuration.
... |
def allRoles(self, memo=None):
"""
Identify all the roles that this role is authorized to act as.
@param memo: used only for recursion. Do not pass this.
@return: an iterator of all roles that this role is a member of,
including itself.
"""
if memo is None:
... | Identify all the roles that this role is authorized to act as.
@param memo: used only for recursion. Do not pass this.
@return: an iterator of all roles that this role is a member of,
including itself. | Below is the the instruction that describes the task:
### Input:
Identify all the roles that this role is authorized to act as.
@param memo: used only for recursion. Do not pass this.
@return: an iterator of all roles that this role is a member of,
including itself.
### Response:
def all... |
def standings(date=datetime.now()):
"""Return Standings object that contains standings info
date should be a datetime object,
leave empty to get current standings
"""
data = mlbgame.info.standings(date)
return mlbgame.info.Standings(data) | Return Standings object that contains standings info
date should be a datetime object,
leave empty to get current standings | Below is the the instruction that describes the task:
### Input:
Return Standings object that contains standings info
date should be a datetime object,
leave empty to get current standings
### Response:
def standings(date=datetime.now()):
"""Return Standings object that contains standings info
da... |
def _reqs(self, tag):
""" Grab all the pull requests """
return [
(tag, i) for i in
self.client.get_pulls(*tag.split('/'))
] | Grab all the pull requests | Below is the the instruction that describes the task:
### Input:
Grab all the pull requests
### Response:
def _reqs(self, tag):
""" Grab all the pull requests """
return [
(tag, i) for i in
self.client.get_pulls(*tag.split('/'))
] |
def audio_graph(
chunksize_bytes=DEFAULT_CHUNK_SIZE,
resample_to=SR44100(),
store_fft=False):
"""
Produce a base class suitable as a starting point for many audio processing
pipelines. This class resamples all audio to a common sampling rate, and
produces a bark band spectrogram... | Produce a base class suitable as a starting point for many audio processing
pipelines. This class resamples all audio to a common sampling rate, and
produces a bark band spectrogram from overlapping short-time fourier
transform frames. It also compresses the audio into ogg vorbis format for
compact st... | Below is the the instruction that describes the task:
### Input:
Produce a base class suitable as a starting point for many audio processing
pipelines. This class resamples all audio to a common sampling rate, and
produces a bark band spectrogram from overlapping short-time fourier
transform frames. I... |
def t_LESSTHAN(self, t):
r"\<"
t.endlexpos = t.lexpos + len(t.value)
return t | r"\< | Below is the the instruction that describes the task:
### Input:
r"\<
### Response:
def t_LESSTHAN(self, t):
r"\<"
t.endlexpos = t.lexpos + len(t.value)
return t |
def addressbatch(self, data, **kwargs):
'''
Send either a CSV file or data to the addressbatch API.
According to the Census, "there is currently an upper limit of 1000 records per batch file."
If a file, must have no header and fields id,street,city,state,zip
If data, should be a... | Send either a CSV file or data to the addressbatch API.
According to the Census, "there is currently an upper limit of 1000 records per batch file."
If a file, must have no header and fields id,street,city,state,zip
If data, should be a list of dicts with the above fields (although ID is optiona... | Below is the the instruction that describes the task:
### Input:
Send either a CSV file or data to the addressbatch API.
According to the Census, "there is currently an upper limit of 1000 records per batch file."
If a file, must have no header and fields id,street,city,state,zip
If data, sh... |
def delete_connection():
"""
Stop and destroy Bloomberg connection
"""
if _CON_SYM_ in globals():
con = globals().pop(_CON_SYM_)
if not getattr(con, '_session').start(): con.stop() | Stop and destroy Bloomberg connection | Below is the the instruction that describes the task:
### Input:
Stop and destroy Bloomberg connection
### Response:
def delete_connection():
"""
Stop and destroy Bloomberg connection
"""
if _CON_SYM_ in globals():
con = globals().pop(_CON_SYM_)
if not getattr(con, '_session').start... |
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the Certificate object to a stream.
Args:
ostream (Stream): A data stream in which to encode object data,
supporting a write method; usually a BytearrayStream object.
... | Write the data encoding the Certificate object to a stream.
Args:
ostream (Stream): A data stream in which to encode object data,
supporting a write method; usually a BytearrayStream object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
ver... | Below is the the instruction that describes the task:
### Input:
Write the data encoding the Certificate object to a stream.
Args:
ostream (Stream): A data stream in which to encode object data,
supporting a write method; usually a BytearrayStream object.
kmip_versio... |
def _print_entity_intro(self, g=None, entity=None, first_time=True):
"""after a selection, prints on screen basic info about onto or entity, plus change prompt
2015-10-18: removed the sound
2016-01-18: entity is the shell wrapper around the ontospy entity
"""
if entity:
... | after a selection, prints on screen basic info about onto or entity, plus change prompt
2015-10-18: removed the sound
2016-01-18: entity is the shell wrapper around the ontospy entity | Below is the the instruction that describes the task:
### Input:
after a selection, prints on screen basic info about onto or entity, plus change prompt
2015-10-18: removed the sound
2016-01-18: entity is the shell wrapper around the ontospy entity
### Response:
def _print_entity_intro(self, g=None... |
def _variant_vc(checkpoints):
"""Add variant calling to workflow, if configured.
"""
if not checkpoints.get("vc"):
return [], []
vc_wf = [s("get_parallel_regions", "batch-split",
[["batch_rec"]],
[cwlout(["region_block"], {"type": "array", "items": "string"})],
... | Add variant calling to workflow, if configured. | Below is the the instruction that describes the task:
### Input:
Add variant calling to workflow, if configured.
### Response:
def _variant_vc(checkpoints):
"""Add variant calling to workflow, if configured.
"""
if not checkpoints.get("vc"):
return [], []
vc_wf = [s("get_parallel_regions", ... |
def new_figure_manager(num, *args, **kwargs):
"""
Create a new figure manager instance
"""
if __debug__: verbose.report('backend_agg.new_figure_manager',
'debug-annoying')
FigureClass = kwargs.pop('FigureClass', Figure)
thisFig = FigureClass(*args, **kwargs)
... | Create a new figure manager instance | Below is the the instruction that describes the task:
### Input:
Create a new figure manager instance
### Response:
def new_figure_manager(num, *args, **kwargs):
"""
Create a new figure manager instance
"""
if __debug__: verbose.report('backend_agg.new_figure_manager',
... |
def ahrs3_encode(self, roll, pitch, yaw, altitude, lat, lng, v1, v2, v3, v4):
'''
Status of third AHRS filter if available. This is for ANU research
group (Ali and Sean)
roll : Roll angle (rad) (float)
pitch ... | Status of third AHRS filter if available. This is for ANU research
group (Ali and Sean)
roll : Roll angle (rad) (float)
pitch : Pitch angle (rad) (float)
yaw : Yaw angle (rad) (float)
... | Below is the the instruction that describes the task:
### Input:
Status of third AHRS filter if available. This is for ANU research
group (Ali and Sean)
roll : Roll angle (rad) (float)
pitch : Pitch angle (rad) (float)
... |
def DEFINE_bool(self, name, default, help, constant=False):
"""A helper for defining boolean options."""
self.AddOption(
type_info.Bool(name=name, default=default, description=help),
constant=constant) | A helper for defining boolean options. | Below is the the instruction that describes the task:
### Input:
A helper for defining boolean options.
### Response:
def DEFINE_bool(self, name, default, help, constant=False):
"""A helper for defining boolean options."""
self.AddOption(
type_info.Bool(name=name, default=default, description=help)... |
def lowerbound(self, axis=0):
"""
Get the lower bound of the binning along an axis
"""
if not 0 <= axis < self.GetDimension():
raise ValueError(
"axis must be a non-negative integer less than "
"the dimensionality of the histogram")
if ... | Get the lower bound of the binning along an axis | Below is the the instruction that describes the task:
### Input:
Get the lower bound of the binning along an axis
### Response:
def lowerbound(self, axis=0):
"""
Get the lower bound of the binning along an axis
"""
if not 0 <= axis < self.GetDimension():
raise ValueError... |
def http_error_401(self, url, fp, errcode, errmsg, headers, data=None,
retry=False):
"""Error 401 -- authentication required.
This function supports Basic authentication only."""
if 'www-authenticate' not in headers:
URLopener.http_error_default(self, url, fp,
... | Error 401 -- authentication required.
This function supports Basic authentication only. | Below is the the instruction that describes the task:
### Input:
Error 401 -- authentication required.
This function supports Basic authentication only.
### Response:
def http_error_401(self, url, fp, errcode, errmsg, headers, data=None,
retry=False):
"""Error 401 -- authentication requ... |
def _recv_msg(self, mid_stream=False):
"""
:param mid_stream: are we receiving in a streaming operation?
:type mid_stream: boolean
"""
try:
msgbuf = self._recv_pkt()
except BadResource as e:
e.mid_stream = mid_stream
raise
excep... | :param mid_stream: are we receiving in a streaming operation?
:type mid_stream: boolean | Below is the the instruction that describes the task:
### Input:
:param mid_stream: are we receiving in a streaming operation?
:type mid_stream: boolean
### Response:
def _recv_msg(self, mid_stream=False):
"""
:param mid_stream: are we receiving in a streaming operation?
:type mid_s... |
def unassign_authorization_from_vault(self, authorization_id, vault_id):
"""Removes an ``Authorization`` from a ``Vault``.
arg: authorization_id (osid.id.Id): the ``Id`` of the
``Authorization``
arg: vault_id (osid.id.Id): the ``Id`` of the ``Vault``
raise: NotFou... | Removes an ``Authorization`` from a ``Vault``.
arg: authorization_id (osid.id.Id): the ``Id`` of the
``Authorization``
arg: vault_id (osid.id.Id): the ``Id`` of the ``Vault``
raise: NotFound - ``authorization_id`` or ``vault_id`` not
found or ``authorizati... | Below is the the instruction that describes the task:
### Input:
Removes an ``Authorization`` from a ``Vault``.
arg: authorization_id (osid.id.Id): the ``Id`` of the
``Authorization``
arg: vault_id (osid.id.Id): the ``Id`` of the ``Vault``
raise: NotFound - ``authoriz... |
def write_loudest_events(page, bins, onsource=False):
"""
Write injection chisq plots to markup.page object page
"""
th = ['']+['Mchirp %s - %s' % tuple(bin) for bin in bins]
td = []
plots = ['BestNR','SNR']
if onsource:
trial = 'ONSOURCE'
else:
trial = 'OFFTRIAL_... | Write injection chisq plots to markup.page object page | Below is the the instruction that describes the task:
### Input:
Write injection chisq plots to markup.page object page
### Response:
def write_loudest_events(page, bins, onsource=False):
"""
Write injection chisq plots to markup.page object page
"""
th = ['']+['Mchirp %s - %s' % tuple(bin) f... |
def _to_sky_params(self, wcs, mode='all'):
"""
Convert the pixel aperture parameters to those for a sky
aperture.
Parameters
----------
wcs : `~astropy.wcs.WCS`
The world coordinate system (WCS) transformation to use.
mode : {'all', 'wcs'}, optional
... | Convert the pixel aperture parameters to those for a sky
aperture.
Parameters
----------
wcs : `~astropy.wcs.WCS`
The world coordinate system (WCS) transformation to use.
mode : {'all', 'wcs'}, optional
Whether to do the transformation including distorti... | Below is the the instruction that describes the task:
### Input:
Convert the pixel aperture parameters to those for a sky
aperture.
Parameters
----------
wcs : `~astropy.wcs.WCS`
The world coordinate system (WCS) transformation to use.
mode : {'all', 'wcs'}, opt... |
def get_baking_statuses_sql(get_request):
""" Creates SQL to get info on baking books filtered from GET request.
All books that have ever attempted to bake will be retured if they
pass the filters in the GET request.
If a single book has been requested to bake multiple times there will
be a row for... | Creates SQL to get info on baking books filtered from GET request.
All books that have ever attempted to bake will be retured if they
pass the filters in the GET request.
If a single book has been requested to bake multiple times there will
be a row for each of the baking attempts.
By default the r... | Below is the the instruction that describes the task:
### Input:
Creates SQL to get info on baking books filtered from GET request.
All books that have ever attempted to bake will be retured if they
pass the filters in the GET request.
If a single book has been requested to bake multiple times there wi... |
def get_uuids():
"""List all bundle UUIDs in the worksheet."""
result = shell('cl ls -w {} -u'.format(worksheet))
uuids = result.split('\n')
uuids = uuids[1:-1] # trim non uuids
return uuids | List all bundle UUIDs in the worksheet. | Below is the the instruction that describes the task:
### Input:
List all bundle UUIDs in the worksheet.
### Response:
def get_uuids():
"""List all bundle UUIDs in the worksheet."""
result = shell('cl ls -w {} -u'.format(worksheet))
uuids = result.split('\n')
uuids = uuids[1:-1] # trim non uuids
... |
def cf_number_from_integer(integer):
"""
Creates a CFNumber object from an integer
:param integer:
The integer to create the CFNumber for
:return:
A CFNumber
"""
integer_as_long = c_long(integer)
return CoreFoundation.CFNumberCreate(
... | Creates a CFNumber object from an integer
:param integer:
The integer to create the CFNumber for
:return:
A CFNumber | Below is the the instruction that describes the task:
### Input:
Creates a CFNumber object from an integer
:param integer:
The integer to create the CFNumber for
:return:
A CFNumber
### Response:
def cf_number_from_integer(integer):
"""
Creates a CFNumber o... |
def schemata(self) -> list:
"""
Return list with schemata in cache.
:return: list of schemata
"""
LOGGER.debug('SchemaCache.schemata >>>')
LOGGER.debug('SchemaCache.schemata <<<')
return [self._schema_key2schema[seq_no] for seq_no in self._schema_key2schema] | Return list with schemata in cache.
:return: list of schemata | Below is the the instruction that describes the task:
### Input:
Return list with schemata in cache.
:return: list of schemata
### Response:
def schemata(self) -> list:
"""
Return list with schemata in cache.
:return: list of schemata
"""
LOGGER.debug('SchemaCache... |
def assess_angmom(X):
"""
Checks for change of sign in each component of the angular momentum.
Returns an array with ith entry 1 if no sign change in i component
and 0 if sign change.
Box = (0,0,0)
S.A loop = (0,0,1)
L.A loop = (1,0,0)
"""
L=angmom(X[0])
l... | Checks for change of sign in each component of the angular momentum.
Returns an array with ith entry 1 if no sign change in i component
and 0 if sign change.
Box = (0,0,0)
S.A loop = (0,0,1)
L.A loop = (1,0,0) | Below is the the instruction that describes the task:
### Input:
Checks for change of sign in each component of the angular momentum.
Returns an array with ith entry 1 if no sign change in i component
and 0 if sign change.
Box = (0,0,0)
S.A loop = (0,0,1)
L.A loop = (1,0,0)
#... |
def scale_ps(lat):
"""
This function calculates the scaling factor for a polar stereographic
projection (ie. SSM/I grid) to correct area calculations. The scaling
factor is defined (from Snyder, 1982, Map Projections used by the U.S.
Geological Survey) as:
k = (mc/m)*(t/tc), where:
m = cos... | This function calculates the scaling factor for a polar stereographic
projection (ie. SSM/I grid) to correct area calculations. The scaling
factor is defined (from Snyder, 1982, Map Projections used by the U.S.
Geological Survey) as:
k = (mc/m)*(t/tc), where:
m = cos(lat)/sqrt(1 - e2*sin(lat)^2)
... | Below is the the instruction that describes the task:
### Input:
This function calculates the scaling factor for a polar stereographic
projection (ie. SSM/I grid) to correct area calculations. The scaling
factor is defined (from Snyder, 1982, Map Projections used by the U.S.
Geological Survey) as:
... |
def _extract_emd(mat, filename):
"""Extract the data from the EMD substruct, given a medusa-created MNU0-mat
file
Parameters
----------
mat: matlab-imported struct
"""
emd = mat['EMD'].squeeze()
# Labview epoch
epoch = datetime.datetime(1904, 1, 1)
def convert_epoch(x):
... | Extract the data from the EMD substruct, given a medusa-created MNU0-mat
file
Parameters
----------
mat: matlab-imported struct | Below is the the instruction that describes the task:
### Input:
Extract the data from the EMD substruct, given a medusa-created MNU0-mat
file
Parameters
----------
mat: matlab-imported struct
### Response:
def _extract_emd(mat, filename):
"""Extract the data from the EMD substruct, given a m... |
def get_correlated_report_ids(self, indicators):
"""
DEPRECATED!
Retrieves a list of the IDs of all TruSTAR reports that contain the searched indicators.
:param indicators: A list of indicator values to retrieve correlated reports for.
:return: The list of IDs of reports that co... | DEPRECATED!
Retrieves a list of the IDs of all TruSTAR reports that contain the searched indicators.
:param indicators: A list of indicator values to retrieve correlated reports for.
:return: The list of IDs of reports that correlated.
Example:
>>> report_ids = ts.get_correlat... | Below is the the instruction that describes the task:
### Input:
DEPRECATED!
Retrieves a list of the IDs of all TruSTAR reports that contain the searched indicators.
:param indicators: A list of indicator values to retrieve correlated reports for.
:return: The list of IDs of reports that co... |
def get_table_names_by_filter(self, dbname, filter, max_tables):
"""
Parameters:
- dbname
- filter
- max_tables
"""
self.send_get_table_names_by_filter(dbname, filter, max_tables)
return self.recv_get_table_names_by_filter() | Parameters:
- dbname
- filter
- max_tables | Below is the the instruction that describes the task:
### Input:
Parameters:
- dbname
- filter
- max_tables
### Response:
def get_table_names_by_filter(self, dbname, filter, max_tables):
"""
Parameters:
- dbname
- filter
- max_tables
"""
self.send_get_table_names_by_fi... |
def process_delimiter(self, char):
'''Process chars while not in a part'''
if char in self.whitespace:
return
if char in self.quote_chars:
# Store the quote type (' or ") and switch to quote processing.
self.inquote = char
self.process_char = self.... | Process chars while not in a part | Below is the the instruction that describes the task:
### Input:
Process chars while not in a part
### Response:
def process_delimiter(self, char):
'''Process chars while not in a part'''
if char in self.whitespace:
return
if char in self.quote_chars:
# Store the quo... |
def get_user_blocks(session, user_text):
"""
Returns a list of blocks for a single user
"""
logger.debug("Getting user_blocks for {0}".format(user_text))
doc = session.get(action='query', list='blocks', bkusers=user_text,
bkprop=['id'])
return doc['query']['blocks'] | Returns a list of blocks for a single user | Below is the the instruction that describes the task:
### Input:
Returns a list of blocks for a single user
### Response:
def get_user_blocks(session, user_text):
"""
Returns a list of blocks for a single user
"""
logger.debug("Getting user_blocks for {0}".format(user_text))
doc = session.get(a... |
def random_peak_magnitudes(
log,
peakMagnitudeDistributions,
snTypesArray,
plot=True):
"""
*Generate a numpy array of random (distribution weighted) peak magnitudes for the given sn types.*
**Key Arguments:**
- ``log`` -- logger
- ``peakMagnitudeDistributions... | *Generate a numpy array of random (distribution weighted) peak magnitudes for the given sn types.*
**Key Arguments:**
- ``log`` -- logger
- ``peakMagnitudeDistributions`` -- yaml style dictionary of peak magnitude distributions
- ``snTypesArray`` -- the pre-generated array of random sn type... | Below is the the instruction that describes the task:
### Input:
*Generate a numpy array of random (distribution weighted) peak magnitudes for the given sn types.*
**Key Arguments:**
- ``log`` -- logger
- ``peakMagnitudeDistributions`` -- yaml style dictionary of peak magnitude distributions
... |
def open(cls, title, conn=None, google_user=None,
google_password=None):
""" Open the spreadsheet named ``title``. If no spreadsheet with
that name exists, a new one will be created. """
spreadsheet = cls.by_title(title, conn=conn, google_user=google_user,
... | Open the spreadsheet named ``title``. If no spreadsheet with
that name exists, a new one will be created. | Below is the the instruction that describes the task:
### Input:
Open the spreadsheet named ``title``. If no spreadsheet with
that name exists, a new one will be created.
### Response:
def open(cls, title, conn=None, google_user=None,
google_password=None):
""" Open the spreadsheet nam... |
def dump_view(cls, request):
"""Dumps sitetrees with items using django-smuggler.
:param request:
:return:
"""
from smuggler.views import dump_to_response
return dump_to_response(request, [MODEL_TREE, MODEL_TREE_ITEM], filename_prefix='sitetrees') | Dumps sitetrees with items using django-smuggler.
:param request:
:return: | Below is the the instruction that describes the task:
### Input:
Dumps sitetrees with items using django-smuggler.
:param request:
:return:
### Response:
def dump_view(cls, request):
"""Dumps sitetrees with items using django-smuggler.
:param request:
:return:
"""
... |
def cleanup(self):
"""
Clean up finished children.
:return: None
"""
self.lock.acquire()
logger.debug('Acquired lock in cleanup for ' + str(self))
self.children = [child for child in self.children if child.is_alive()]
self.lock.release() | Clean up finished children.
:return: None | Below is the the instruction that describes the task:
### Input:
Clean up finished children.
:return: None
### Response:
def cleanup(self):
"""
Clean up finished children.
:return: None
"""
self.lock.acquire()
logger.debug('Acquired lock in cleanup for ' + ... |
def commit(self, msg):
"""
Commit outstanding data changes
"""
self.logger.info('Commit config: {}'.format(msg))
with Dir(self.data_path):
self.cmd.check_assert('git add .')
self.cmd.check_assert('git commit --allow-empty -m "{}"'.format(msg)) | Commit outstanding data changes | Below is the the instruction that describes the task:
### Input:
Commit outstanding data changes
### Response:
def commit(self, msg):
"""
Commit outstanding data changes
"""
self.logger.info('Commit config: {}'.format(msg))
with Dir(self.data_path):
self.cmd.chec... |
def create_dcnm_out_nwk(self, tenant_id, fw_dict, is_fw_virt=False):
"""Create the DCNM OUT Network and update the result. """
tenant_name = fw_dict.get('tenant_name')
ret = self._create_service_nwk(tenant_id, tenant_name, 'out')
if ret:
res = fw_const.DCNM_OUT_NETWORK_CREATE... | Create the DCNM OUT Network and update the result. | Below is the the instruction that describes the task:
### Input:
Create the DCNM OUT Network and update the result.
### Response:
def create_dcnm_out_nwk(self, tenant_id, fw_dict, is_fw_virt=False):
"""Create the DCNM OUT Network and update the result. """
tenant_name = fw_dict.get('tenant_name')
... |
def iter_format_block(
self, text=None,
width=60, chars=False, fill=False, newlines=False,
append=None, prepend=None, strip_first=False, strip_last=False,
lstrip=False):
""" Iterate over lines in a formatted block of text.
This iterator allows you to p... | Iterate over lines in a formatted block of text.
This iterator allows you to prepend to each line.
For basic blocks see iter_block().
Arguments:
text : String to format.
width : Maximum width for each line. The prepend string
... | Below is the the instruction that describes the task:
### Input:
Iterate over lines in a formatted block of text.
This iterator allows you to prepend to each line.
For basic blocks see iter_block().
Arguments:
text : String to format.
wid... |
def run(self):
"""Start the server on the local IP at port 1400 (default).
Handling of requests is delegated to an instance of the
`EventNotifyHandler` class.
"""
listener = EventServer(self.address, EventNotifyHandler)
log.info("Event listener running on %s", listener.s... | Start the server on the local IP at port 1400 (default).
Handling of requests is delegated to an instance of the
`EventNotifyHandler` class. | Below is the the instruction that describes the task:
### Input:
Start the server on the local IP at port 1400 (default).
Handling of requests is delegated to an instance of the
`EventNotifyHandler` class.
### Response:
def run(self):
"""Start the server on the local IP at port 1400 (defau... |
def stripped_lib_dict(lib_dict, strip_prefix):
""" Return `lib_dict` with `strip_prefix` removed from start of paths
Use to give form of `lib_dict` that appears relative to some base path
given by `strip_prefix`. Particularly useful for analyzing wheels where we
unpack to a temporary path before analy... | Return `lib_dict` with `strip_prefix` removed from start of paths
Use to give form of `lib_dict` that appears relative to some base path
given by `strip_prefix`. Particularly useful for analyzing wheels where we
unpack to a temporary path before analyzing.
Parameters
----------
lib_dict : dic... | Below is the the instruction that describes the task:
### Input:
Return `lib_dict` with `strip_prefix` removed from start of paths
Use to give form of `lib_dict` that appears relative to some base path
given by `strip_prefix`. Particularly useful for analyzing wheels where we
unpack to a temporary pat... |
def posix_rename(self, oldpath, newpath):
"""
Rename a file or folder from ``oldpath`` to ``newpath``, following
posix conventions.
:param str oldpath: existing name of the file or folder
:param str newpath: new name for the file or folder, will be
overwritten if it ... | Rename a file or folder from ``oldpath`` to ``newpath``, following
posix conventions.
:param str oldpath: existing name of the file or folder
:param str newpath: new name for the file or folder, will be
overwritten if it already exists
:raises:
``IOError`` -- if... | Below is the the instruction that describes the task:
### Input:
Rename a file or folder from ``oldpath`` to ``newpath``, following
posix conventions.
:param str oldpath: existing name of the file or folder
:param str newpath: new name for the file or folder, will be
overwritten... |
def _url_parts(self, url_suffix, data, content_type):
"""
Format the url data based on config_type.
:param url_suffix: str URL path we are sending a GET/POST/PUT to
:param data: object data we are sending
:param content_type: str from ContentType that determines how we format the... | Format the url data based on config_type.
:param url_suffix: str URL path we are sending a GET/POST/PUT to
:param data: object data we are sending
:param content_type: str from ContentType that determines how we format the data
:return: complete url, formatted data, and headers for sendi... | Below is the the instruction that describes the task:
### Input:
Format the url data based on config_type.
:param url_suffix: str URL path we are sending a GET/POST/PUT to
:param data: object data we are sending
:param content_type: str from ContentType that determines how we format the data... |
def mutate(self, node, index):
"""Modify the For loop to evaluate to None"""
assert index == 0
assert isinstance(node, ForStmt)
empty_list = parso.parse(' []')
node.children[3] = empty_list
return node | Modify the For loop to evaluate to None | Below is the the instruction that describes the task:
### Input:
Modify the For loop to evaluate to None
### Response:
def mutate(self, node, index):
"""Modify the For loop to evaluate to None"""
assert index == 0
assert isinstance(node, ForStmt)
empty_list = parso.parse(' []')
... |
def addSourceAddr(self, addr):
"""None means 'system default'"""
try:
self._multiInSocket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self._makeMreq(addr))
except socket.error: # if 1 interface has more than 1 address, exception is raised for the second
pass
... | None means 'system default | Below is the the instruction that describes the task:
### Input:
None means 'system default
### Response:
def addSourceAddr(self, addr):
"""None means 'system default'"""
try:
self._multiInSocket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self._makeMreq(addr))
excep... |
def _enqueue(self, msg):
"""Push a new `msg` onto the queue, return `(success, msg)`"""
self.log.debug('queueing: %s', msg)
if self.queue.full():
self.log.warn('librato_bg queue is full')
return False, msg
self.queue.put(msg)
self.log.debug('enqueued %s.... | Push a new `msg` onto the queue, return `(success, msg)` | Below is the the instruction that describes the task:
### Input:
Push a new `msg` onto the queue, return `(success, msg)`
### Response:
def _enqueue(self, msg):
"""Push a new `msg` onto the queue, return `(success, msg)`"""
self.log.debug('queueing: %s', msg)
if self.queue.full():
... |
def extract_cookies(self, response, request):
"""Extract cookies from response, where allowable given the request."""
_debug("extract_cookies: %s", response.info())
self._cookies_lock.acquire()
try:
self._policy._now = self._now = int(time.time())
for cookie in s... | Extract cookies from response, where allowable given the request. | Below is the the instruction that describes the task:
### Input:
Extract cookies from response, where allowable given the request.
### Response:
def extract_cookies(self, response, request):
"""Extract cookies from response, where allowable given the request."""
_debug("extract_cookies: %s", respon... |
def setup_path():
"""Sets up the python include paths to include src"""
import os.path; import sys
if sys.argv[0]:
top_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
sys.path = [os.path.join(top_dir, "src")] + sys.path
pass
return | Sets up the python include paths to include src | Below is the the instruction that describes the task:
### Input:
Sets up the python include paths to include src
### Response:
def setup_path():
"""Sets up the python include paths to include src"""
import os.path; import sys
if sys.argv[0]:
top_dir = os.path.dirname(os.path.abspath(sys.argv[0... |
def init_crash_handler(self):
"""Create a crash handler, typically setting sys.excepthook to it."""
self.crash_handler = self.crash_handler_class(self)
sys.excepthook = self.excepthook
def unset_crashhandler():
sys.excepthook = sys.__excepthook__
atexit.register(unset... | Create a crash handler, typically setting sys.excepthook to it. | Below is the the instruction that describes the task:
### Input:
Create a crash handler, typically setting sys.excepthook to it.
### Response:
def init_crash_handler(self):
"""Create a crash handler, typically setting sys.excepthook to it."""
self.crash_handler = self.crash_handler_class(self)
... |
def _compile(pattern, flags):
"""Compile the pattern to regex."""
return re.compile(WcParse(pattern, flags & FLAG_MASK).parse()) | Compile the pattern to regex. | Below is the the instruction that describes the task:
### Input:
Compile the pattern to regex.
### Response:
def _compile(pattern, flags):
"""Compile the pattern to regex."""
return re.compile(WcParse(pattern, flags & FLAG_MASK).parse()) |
def get_codeblock_node(self, code, language):
"""this is copied from sphinx.directives.code.CodeBlock.run
it has been changed to accept code and language as an arguments instead
of reading from self
"""
# type: () -> List[nodes.Node]
document = self.state.document
... | this is copied from sphinx.directives.code.CodeBlock.run
it has been changed to accept code and language as an arguments instead
of reading from self | Below is the the instruction that describes the task:
### Input:
this is copied from sphinx.directives.code.CodeBlock.run
it has been changed to accept code and language as an arguments instead
of reading from self
### Response:
def get_codeblock_node(self, code, language):
"""this is copi... |
def create_dataset(self, dataset, exists_ok=False, retry=DEFAULT_RETRY):
"""API call: create the dataset via a POST request.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/insert
Args:
dataset (Union[ \
:class:`~google.cloud.bigquery.dat... | API call: create the dataset via a POST request.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/insert
Args:
dataset (Union[ \
:class:`~google.cloud.bigquery.dataset.Dataset`, \
:class:`~google.cloud.bigquery.dataset.DatasetRefer... | Below is the the instruction that describes the task:
### Input:
API call: create the dataset via a POST request.
See
https://cloud.google.com/bigquery/docs/reference/rest/v2/tables/insert
Args:
dataset (Union[ \
:class:`~google.cloud.bigquery.dataset.Dataset`, ... |
def make_link_node(rawtext, app, name, options):
"""
Create a link to the TL reference.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param name: Name of the object to link to
:param options: Options dictionary passed to role func.
"""
try:
... | Create a link to the TL reference.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param name: Name of the object to link to
:param options: Options dictionary passed to role func. | Below is the the instruction that describes the task:
### Input:
Create a link to the TL reference.
:param rawtext: Text being replaced with link node.
:param app: Sphinx application context
:param name: Name of the object to link to
:param options: Options dictionary passed to role func.
### Respo... |
def get_edges_from_parsed_data(parsed_data):
""" Taking into account fragment type (circular|linear) and retrieved gene order information translates adjacencies between blocks into edges for addition to the :class:`bg.breakpoint_graph.BreakpointGraph`
In case supplied fragment is linear (``$``) special... | Taking into account fragment type (circular|linear) and retrieved gene order information translates adjacencies between blocks into edges for addition to the :class:`bg.breakpoint_graph.BreakpointGraph`
In case supplied fragment is linear (``$``) special artificial vertices (with ``__infinity`` suffix) are int... | Below is the the instruction that describes the task:
### Input:
Taking into account fragment type (circular|linear) and retrieved gene order information translates adjacencies between blocks into edges for addition to the :class:`bg.breakpoint_graph.BreakpointGraph`
In case supplied fragment is linear (``... |
def _byteify(input):
"""
Force the given input to only use `str` instead of `bytes` or `unicode`.
This works even if the input is a dict, list,
"""
if isinstance(input, dict):
return {_byteify(key): _byteify(value) for key, value in input.items()}
elif isinstance(input, list):
re... | Force the given input to only use `str` instead of `bytes` or `unicode`.
This works even if the input is a dict, list, | Below is the the instruction that describes the task:
### Input:
Force the given input to only use `str` instead of `bytes` or `unicode`.
This works even if the input is a dict, list,
### Response:
def _byteify(input):
"""
Force the given input to only use `str` instead of `bytes` or `unicode`.
Thi... |
def _add_dynamic_field_to_model(cls, field, field_name):
"""
Add a copy of the DynamicField "field" to the current class and its
subclasses using the "field_name" name
"""
# create the new field
new_field = field._create_dynamic_version()
new_field.name = field_na... | Add a copy of the DynamicField "field" to the current class and its
subclasses using the "field_name" name | Below is the the instruction that describes the task:
### Input:
Add a copy of the DynamicField "field" to the current class and its
subclasses using the "field_name" name
### Response:
def _add_dynamic_field_to_model(cls, field, field_name):
"""
Add a copy of the DynamicField "field" to th... |
def _get_pplan_with_watch(self, topologyName, callback, isWatching):
"""
Helper function to get pplan with
a callback. The future watch is placed
only if isWatching is True.
"""
path = self.get_pplan_path(topologyName)
if isWatching:
LOG.info("Adding data watch for path: " + path)
... | Helper function to get pplan with
a callback. The future watch is placed
only if isWatching is True. | Below is the the instruction that describes the task:
### Input:
Helper function to get pplan with
a callback. The future watch is placed
only if isWatching is True.
### Response:
def _get_pplan_with_watch(self, topologyName, callback, isWatching):
"""
Helper function to get pplan with
a callba... |
async def listNamespaces(self, *args, **kwargs):
"""
List Namespaces
List the namespaces immediately under a given namespace.
This endpoint
lists up to 1000 namespaces. If more namespaces are present, a
`continuationToken` will be returned, which can be given in the nex... | List Namespaces
List the namespaces immediately under a given namespace.
This endpoint
lists up to 1000 namespaces. If more namespaces are present, a
`continuationToken` will be returned, which can be given in the next
request. For the initial request, the payload should be an ... | Below is the the instruction that describes the task:
### Input:
List Namespaces
List the namespaces immediately under a given namespace.
This endpoint
lists up to 1000 namespaces. If more namespaces are present, a
`continuationToken` will be returned, which can be given in the nex... |
def safe_add_edge(graph, u, v, key, attr_dict, **attr):
"""Adds an edge while preserving negative keys, and paying no respect to positive ones
:param pybel.BELGraph graph: A BEL Graph
:param tuple u: The source BEL node
:param tuple v: The target BEL node
:param int key: The edge key. If less than ... | Adds an edge while preserving negative keys, and paying no respect to positive ones
:param pybel.BELGraph graph: A BEL Graph
:param tuple u: The source BEL node
:param tuple v: The target BEL node
:param int key: The edge key. If less than zero, corresponds to an unqualified edge, else is disregarded
... | Below is the the instruction that describes the task:
### Input:
Adds an edge while preserving negative keys, and paying no respect to positive ones
:param pybel.BELGraph graph: A BEL Graph
:param tuple u: The source BEL node
:param tuple v: The target BEL node
:param int key: The edge key. If less... |
def create_casting_method(op, klass):
"""
Creates a new univariate special method, such as A.__float__() <=> float(A.value),
for target class. The method is called __op_name__.
"""
# This function will become the actual method.
def new_method(self, op=op):
if not check_special_methods()... | Creates a new univariate special method, such as A.__float__() <=> float(A.value),
for target class. The method is called __op_name__. | Below is the the instruction that describes the task:
### Input:
Creates a new univariate special method, such as A.__float__() <=> float(A.value),
for target class. The method is called __op_name__.
### Response:
def create_casting_method(op, klass):
"""
Creates a new univariate special method, such a... |
def getActiveJobCountForClientKey(self, clientKey):
""" Return the number of jobs for the given clientKey and a status that is
not completed.
"""
with ConnectionFactory.get() as conn:
query = 'SELECT count(job_id) ' \
'FROM %s ' \
'WHERE client_key = %%s ' \
... | Return the number of jobs for the given clientKey and a status that is
not completed. | Below is the the instruction that describes the task:
### Input:
Return the number of jobs for the given clientKey and a status that is
not completed.
### Response:
def getActiveJobCountForClientKey(self, clientKey):
""" Return the number of jobs for the given clientKey and a status that is
not complet... |
def detect_parser_type(cls, file, encoding=None):
'''Get the suitable parser type for the document.
Returns:
str
'''
is_xml = XMLDetector.is_file(file)
doctype = cls.parse_doctype(file, encoding=encoding) or ''
if not doctype and is_xml:
return '... | Get the suitable parser type for the document.
Returns:
str | Below is the the instruction that describes the task:
### Input:
Get the suitable parser type for the document.
Returns:
str
### Response:
def detect_parser_type(cls, file, encoding=None):
'''Get the suitable parser type for the document.
Returns:
str
'''
... |
def _do_anchor(self, anchor):
""" Collects preposition anchors and attachments in a dictionary.
Once the dictionary has an entry for both the anchor and the attachment, they are linked.
"""
if anchor:
for x in anchor.split("-"):
A, P = None, None
... | Collects preposition anchors and attachments in a dictionary.
Once the dictionary has an entry for both the anchor and the attachment, they are linked. | Below is the the instruction that describes the task:
### Input:
Collects preposition anchors and attachments in a dictionary.
Once the dictionary has an entry for both the anchor and the attachment, they are linked.
### Response:
def _do_anchor(self, anchor):
""" Collects preposition anchors a... |
def setModified( self, state = True ):
"""
Flags the scene as being modified based on the inputed value.
:param state <bool>
"""
if ( state == self._modified ):
return
self._modified = state
self.emitModifiedStateChanged() | Flags the scene as being modified based on the inputed value.
:param state <bool> | Below is the the instruction that describes the task:
### Input:
Flags the scene as being modified based on the inputed value.
:param state <bool>
### Response:
def setModified( self, state = True ):
"""
Flags the scene as being modified based on the inputed value.
... |
def get_methods_class(self, class_name):
"""
Return all methods of a specific class
:param class_name: the class name
:type class_name: string
:rtype: a list with :class:`EncodedMethod` objects
"""
l = []
for i in self.get_classes():
for j in... | Return all methods of a specific class
:param class_name: the class name
:type class_name: string
:rtype: a list with :class:`EncodedMethod` objects | Below is the the instruction that describes the task:
### Input:
Return all methods of a specific class
:param class_name: the class name
:type class_name: string
:rtype: a list with :class:`EncodedMethod` objects
### Response:
def get_methods_class(self, class_name):
"""
... |
def fail(self, msg, shutit_pexpect_child=None, throw_exception=False):
"""Handles a failure, pausing if a pexpect child object is passed in.
@param shutit_pexpect_child: pexpect child to work on
@param throw_exception: Whether to throw an exception.
@type throw_exception: boolean
"""
shutit_global.shutit_g... | Handles a failure, pausing if a pexpect child object is passed in.
@param shutit_pexpect_child: pexpect child to work on
@param throw_exception: Whether to throw an exception.
@type throw_exception: boolean | Below is the the instruction that describes the task:
### Input:
Handles a failure, pausing if a pexpect child object is passed in.
@param shutit_pexpect_child: pexpect child to work on
@param throw_exception: Whether to throw an exception.
@type throw_exception: boolean
### Response:
def fail(self, msg, sh... |
def generate_schema_file(config_file):
"""
Generates a basic confirm schema file from a configuration file.
"""
config = utils.load_config_from_ini_file(config_file)
schema = {}
for section_name in config:
for option_name in config[section_name]:
schema.setdefault(section_n... | Generates a basic confirm schema file from a configuration file. | Below is the the instruction that describes the task:
### Input:
Generates a basic confirm schema file from a configuration file.
### Response:
def generate_schema_file(config_file):
"""
Generates a basic confirm schema file from a configuration file.
"""
config = utils.load_config_from_ini_file(c... |
def exists(self, primary_key):
'''
a method to determine if record exists
:param primary_key: string with primary key of record
:return: boolean to indicate existence of record
'''
select_statement = self.table.select(self.table).where(... | a method to determine if record exists
:param primary_key: string with primary key of record
:return: boolean to indicate existence of record | Below is the the instruction that describes the task:
### Input:
a method to determine if record exists
:param primary_key: string with primary key of record
:return: boolean to indicate existence of record
### Response:
def exists(self, primary_key):
'''
... |
def _temporary_file(self, delete):
""":return: a temporary file where the content is dumped to."""
file = NamedTemporaryFile("w+", delete=delete,
encoding=self.__encoding)
self._file(file)
return file | :return: a temporary file where the content is dumped to. | Below is the the instruction that describes the task:
### Input:
:return: a temporary file where the content is dumped to.
### Response:
def _temporary_file(self, delete):
""":return: a temporary file where the content is dumped to."""
file = NamedTemporaryFile("w+", delete=delete,
... |
def view(model: "Model", *functions: Callable) -> Optional[Callable]:
"""A decorator for registering a callback to a model
Parameters:
model: the model object whose changes the callback should respond to.
Examples:
.. code-block:: python
from spectate import mvc
i... | A decorator for registering a callback to a model
Parameters:
model: the model object whose changes the callback should respond to.
Examples:
.. code-block:: python
from spectate import mvc
items = mvc.List()
@mvc.view(items)
def printer(items... | Below is the the instruction that describes the task:
### Input:
A decorator for registering a callback to a model
Parameters:
model: the model object whose changes the callback should respond to.
Examples:
.. code-block:: python
from spectate import mvc
items = m... |
def new(params, event_shape=(), validate_args=False, name=None):
"""Create the distribution instance from a `params` vector."""
with tf.compat.v1.name_scope(name, 'IndependentLogistic',
[params, event_shape]):
params = tf.convert_to_tensor(value=params, name='params')
... | Create the distribution instance from a `params` vector. | Below is the the instruction that describes the task:
### Input:
Create the distribution instance from a `params` vector.
### Response:
def new(params, event_shape=(), validate_args=False, name=None):
"""Create the distribution instance from a `params` vector."""
with tf.compat.v1.name_scope(name, 'Indepen... |
def _extract_package(deps_dir, pkg_path):
"""
Extract a .whl, .zip, .tar.gz or .tar.bz2 into a package path to
use when running CI tasks
:param deps_dir:
A unicode string of the directory the package should be extracted to
:param pkg_path:
A unicode string of the path to the archiv... | Extract a .whl, .zip, .tar.gz or .tar.bz2 into a package path to
use when running CI tasks
:param deps_dir:
A unicode string of the directory the package should be extracted to
:param pkg_path:
A unicode string of the path to the archive | Below is the the instruction that describes the task:
### Input:
Extract a .whl, .zip, .tar.gz or .tar.bz2 into a package path to
use when running CI tasks
:param deps_dir:
A unicode string of the directory the package should be extracted to
:param pkg_path:
A unicode string of the pat... |
def send_signal_to_gdb(self, signal_input):
"""Send signal name (case insensitive) or number to gdb subprocess
gdbmi.send_signal_to_gdb(2) # valid
gdbmi.send_signal_to_gdb('sigint') # also valid
gdbmi.send_signal_to_gdb('SIGINT') # also valid
raises ValueError if signal_input... | Send signal name (case insensitive) or number to gdb subprocess
gdbmi.send_signal_to_gdb(2) # valid
gdbmi.send_signal_to_gdb('sigint') # also valid
gdbmi.send_signal_to_gdb('SIGINT') # also valid
raises ValueError if signal_input is invalie
raises NoGdbProcessError if there i... | Below is the the instruction that describes the task:
### Input:
Send signal name (case insensitive) or number to gdb subprocess
gdbmi.send_signal_to_gdb(2) # valid
gdbmi.send_signal_to_gdb('sigint') # also valid
gdbmi.send_signal_to_gdb('SIGINT') # also valid
raises ValueError i... |
def contents(self):
"""
Returns entire contents of course page
:returns: response object
Example Usage::
>>> import muddle
>>> muddle.course(10).content()
"""
params = self.request_params
params.update({'wsfunction': 'core_course_get_contents',... | Returns entire contents of course page
:returns: response object
Example Usage::
>>> import muddle
>>> muddle.course(10).content() | Below is the the instruction that describes the task:
### Input:
Returns entire contents of course page
:returns: response object
Example Usage::
>>> import muddle
>>> muddle.course(10).content()
### Response:
def contents(self):
"""
Returns entire contents of cou... |
def listdir(self, path='/'):
"""Lists the contents of the specified path,
returning a 2-tuple of lists; the first item being
directories, the second item being files.
"""
container = self._get_bucket()
objects = self.driver.list_container_objects(container)
path =... | Lists the contents of the specified path,
returning a 2-tuple of lists; the first item being
directories, the second item being files. | Below is the the instruction that describes the task:
### Input:
Lists the contents of the specified path,
returning a 2-tuple of lists; the first item being
directories, the second item being files.
### Response:
def listdir(self, path='/'):
"""Lists the contents of the specified path,
... |
def prepare_next_tree(self):
"""Prepare conditional U matrix for next tree."""
for edge in self.edges:
copula_theta = edge.theta
if self.level == 1:
left_u = self.u_matrix[:, edge.L]
right_u = self.u_matrix[:, edge.R]
else:
... | Prepare conditional U matrix for next tree. | Below is the the instruction that describes the task:
### Input:
Prepare conditional U matrix for next tree.
### Response:
def prepare_next_tree(self):
"""Prepare conditional U matrix for next tree."""
for edge in self.edges:
copula_theta = edge.theta
if self.level == 1:
... |
def _fixed_source_line(self):
"""Attempt to find the line that this node appears on.
We need this method since not all nodes have :attr:`lineno` set.
:returns: The line number of this node,
or None if this could not be determined.
:rtype: int or None
"""
lin... | Attempt to find the line that this node appears on.
We need this method since not all nodes have :attr:`lineno` set.
:returns: The line number of this node,
or None if this could not be determined.
:rtype: int or None | Below is the the instruction that describes the task:
### Input:
Attempt to find the line that this node appears on.
We need this method since not all nodes have :attr:`lineno` set.
:returns: The line number of this node,
or None if this could not be determined.
:rtype: int or ... |
def read(self,filename,datatype=None,slaext=False,**kwargs):
'''
reader method.
:parameter filename: name of the file to load.
:keyword datatype: choose between DT/NRT/PISTACH/CTOH or other formats to call the corresponding reader. If datatype is :
* D... | reader method.
:parameter filename: name of the file to load.
:keyword datatype: choose between DT/NRT/PISTACH/CTOH or other formats to call the corresponding reader. If datatype is :
* DT or NRT or PISTACH : calls :func:`altimetry.data.alti_data.read_sla` or :func:`alt... | Below is the the instruction that describes the task:
### Input:
reader method.
:parameter filename: name of the file to load.
:keyword datatype: choose between DT/NRT/PISTACH/CTOH or other formats to call the corresponding reader. If datatype is :
* DT or NRT or PI... |
def listify(values, N=1, delim=None):
"""Return an N-length list, with elements values, extrapolating as necessary.
>>> listify("don't split into characters")
["don't split into characters"]
>>> listify("len = 3", 3)
['len = 3', 'len = 3', 'len = 3']
>>> listify("But split on a delimeter, if re... | Return an N-length list, with elements values, extrapolating as necessary.
>>> listify("don't split into characters")
["don't split into characters"]
>>> listify("len = 3", 3)
['len = 3', 'len = 3', 'len = 3']
>>> listify("But split on a delimeter, if requested.", delim=',')
['But split on a de... | Below is the the instruction that describes the task:
### Input:
Return an N-length list, with elements values, extrapolating as necessary.
>>> listify("don't split into characters")
["don't split into characters"]
>>> listify("len = 3", 3)
['len = 3', 'len = 3', 'len = 3']
>>> listify("But spl... |
def remote_getWorkerInfo(self):
"""This command retrieves data from the files in WORKERDIR/info/* and
sends the contents to the buildmaster. These are used to describe
the worker and its configuration, and should be created and
maintained by the worker administrator. They will be retriev... | This command retrieves data from the files in WORKERDIR/info/* and
sends the contents to the buildmaster. These are used to describe
the worker and its configuration, and should be created and
maintained by the worker administrator. They will be retrieved each
time the master-worker conn... | Below is the the instruction that describes the task:
### Input:
This command retrieves data from the files in WORKERDIR/info/* and
sends the contents to the buildmaster. These are used to describe
the worker and its configuration, and should be created and
maintained by the worker administr... |
def save_data(self, idx):
"""Save the internal data of all sequences with an activated flag.
Write to file if the corresponding disk flag is activated; store
in working memory if the corresponding ram flag is activated."""
for name in self:
actual = getattr(self, name)
... | Save the internal data of all sequences with an activated flag.
Write to file if the corresponding disk flag is activated; store
in working memory if the corresponding ram flag is activated. | Below is the the instruction that describes the task:
### Input:
Save the internal data of all sequences with an activated flag.
Write to file if the corresponding disk flag is activated; store
in working memory if the corresponding ram flag is activated.
### Response:
def save_data(self, idx):
... |
def output_hist(self, output_hist: Hist, input_observable: Any, **kwargs: Dict[str, Any]) -> Union[Hist, Any]:
""" Return an output object. It should store the ``output_hist``.
Note:
The output object could just be the raw histogram.
Note:
This function is just a basic ... | Return an output object. It should store the ``output_hist``.
Note:
The output object could just be the raw histogram.
Note:
This function is just a basic placeholder which returns the given output object (a histogram)
and likely should be overridden.
Args:... | Below is the the instruction that describes the task:
### Input:
Return an output object. It should store the ``output_hist``.
Note:
The output object could just be the raw histogram.
Note:
This function is just a basic placeholder which returns the given output object (a h... |
def cli(ctx, project_dir):
"""Verify the verilog code."""
exit_code = SCons(project_dir).verify()
ctx.exit(exit_code) | Verify the verilog code. | Below is the the instruction that describes the task:
### Input:
Verify the verilog code.
### Response:
def cli(ctx, project_dir):
"""Verify the verilog code."""
exit_code = SCons(project_dir).verify()
ctx.exit(exit_code) |
def override_config(self, path):
"""
Will take a yml located in home directory titled '.plugin_config.yml'.
It'll then override, using the yml, the plugin's config file
"""
status = (True, None)
config_override = False
try:
# parse the yml file
... | Will take a yml located in home directory titled '.plugin_config.yml'.
It'll then override, using the yml, the plugin's config file | Below is the the instruction that describes the task:
### Input:
Will take a yml located in home directory titled '.plugin_config.yml'.
It'll then override, using the yml, the plugin's config file
### Response:
def override_config(self, path):
"""
Will take a yml located in home directory t... |
def get_target_error(self,i):
"""Just get a single error characterization based on the index relative to the target
:param i: list index
:type i: int
:returns: base-wise error
:rtype: HPA group description
"""
x = self._target_hpas[i]
h = x['hpa']
pos = x['pos']
prob = 0
be... | Just get a single error characterization based on the index relative to the target
:param i: list index
:type i: int
:returns: base-wise error
:rtype: HPA group description | Below is the the instruction that describes the task:
### Input:
Just get a single error characterization based on the index relative to the target
:param i: list index
:type i: int
:returns: base-wise error
:rtype: HPA group description
### Response:
def get_target_error(self,i):
"""Just get ... |
def autopilot_version_send(self, capabilities, flight_sw_version, middleware_sw_version, os_sw_version, board_version, flight_custom_version, middleware_custom_version, os_custom_version, vendor_id, product_id, uid, force_mavlink1=False):
'''
Version and capability of autopilot software
... | Version and capability of autopilot software
capabilities : bitmask of capabilities (see MAV_PROTOCOL_CAPABILITY enum) (uint64_t)
flight_sw_version : Firmware version number (uint32_t)
middleware_sw_version : Middleware version number (uint32_... | Below is the the instruction that describes the task:
### Input:
Version and capability of autopilot software
capabilities : bitmask of capabilities (see MAV_PROTOCOL_CAPABILITY enum) (uint64_t)
flight_sw_version : Firmware version number (uint32_t)
... |
def get_array_size(self):
"""Attempts to parse array size out of the address"""
match = re.search(r"(?<=\[)\d+(?=\])", self.get_address())
return int(match.group(0)) | Attempts to parse array size out of the address | Below is the the instruction that describes the task:
### Input:
Attempts to parse array size out of the address
### Response:
def get_array_size(self):
"""Attempts to parse array size out of the address"""
match = re.search(r"(?<=\[)\d+(?=\])", self.get_address())
return int(match.group(0)... |
def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only process if stats exist, not empty (issue #871) and plugin not disabled
if not self.stats or (self.stats == {}) or self.is_disable():... | Return the dict to display in the curse interface. | Below is the the instruction that describes the task:
### Input:
Return the dict to display in the curse interface.
### Response:
def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only proce... |
def write_template_to_file(conf, template_body):
"""Writes the template to disk
"""
template_file_name = _get_stack_name(conf) + '-generated-cf-template.json'
with open(template_file_name, 'w') as opened_file:
opened_file.write(template_body)
print('wrote cf-template for %s to disk: %s' % (
... | Writes the template to disk | Below is the the instruction that describes the task:
### Input:
Writes the template to disk
### Response:
def write_template_to_file(conf, template_body):
"""Writes the template to disk
"""
template_file_name = _get_stack_name(conf) + '-generated-cf-template.json'
with open(template_file_name, 'w'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.