code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def day_display(year, month, all_month_events, day):
"""
Returns the events that occur on the given day.
Works by getting all occurrences for the month, then drilling
down to only those occurring on the given day.
"""
# Get a dict with all of the events for the month
count = CountHandler(yea... | Returns the events that occur on the given day.
Works by getting all occurrences for the month, then drilling
down to only those occurring on the given day. | Below is the the instruction that describes the task:
### Input:
Returns the events that occur on the given day.
Works by getting all occurrences for the month, then drilling
down to only those occurring on the given day.
### Response:
def day_display(year, month, all_month_events, day):
"""
Return... |
def reindent(s, numspaces):
""" reinidents a string (s) by the given number of spaces (numspaces) """
leading_space = numspaces * ' '
lines = [leading_space + line.strip()for line in s.splitlines()]
return '\n'.join(lines) | reinidents a string (s) by the given number of spaces (numspaces) | Below is the the instruction that describes the task:
### Input:
reinidents a string (s) by the given number of spaces (numspaces)
### Response:
def reindent(s, numspaces):
""" reinidents a string (s) by the given number of spaces (numspaces) """
leading_space = numspaces * ' '
lines = [leading_space +... |
def update(self, email=None, username=None, first_name=None, last_name=None, country=None):
"""
Update values on an existing user. See the API docs for what kinds of update are possible.
:param email: new email for this user
:param username: new username for this user
:param fir... | Update values on an existing user. See the API docs for what kinds of update are possible.
:param email: new email for this user
:param username: new username for this user
:param first_name: new first name for this user
:param last_name: new last name for this user
:param count... | Below is the the instruction that describes the task:
### Input:
Update values on an existing user. See the API docs for what kinds of update are possible.
:param email: new email for this user
:param username: new username for this user
:param first_name: new first name for this user
... |
def set_url(self, url):
"""Sets the URL referring to a robots.txt file."""
self.url = url
self.host, self.path = urllib.parse.urlparse(url)[1:3] | Sets the URL referring to a robots.txt file. | Below is the the instruction that describes the task:
### Input:
Sets the URL referring to a robots.txt file.
### Response:
def set_url(self, url):
"""Sets the URL referring to a robots.txt file."""
self.url = url
self.host, self.path = urllib.parse.urlparse(url)[1:3] |
def create_assembly(self, did, wid, name='My Assembly'):
'''
Creates a new assembly element in the specified document / workspace.
Args:
- did (str): Document ID
- wid (str): Workspace ID
- name (str, default='My Assembly')
Returns:
- req... | Creates a new assembly element in the specified document / workspace.
Args:
- did (str): Document ID
- wid (str): Workspace ID
- name (str, default='My Assembly')
Returns:
- requests.Response: Onshape response data | Below is the the instruction that describes the task:
### Input:
Creates a new assembly element in the specified document / workspace.
Args:
- did (str): Document ID
- wid (str): Workspace ID
- name (str, default='My Assembly')
Returns:
- requests.Re... |
def execute(self, command, args):
""" Event firing and exception conversion around command execution.
Common exceptions are run through our exception handler for
pretty-printing or debugging and then converted to SystemExit so the
interpretor will exit without further ado (or be caught i... | Event firing and exception conversion around command execution.
Common exceptions are run through our exception handler for
pretty-printing or debugging and then converted to SystemExit so the
interpretor will exit without further ado (or be caught if
interactive). | Below is the the instruction that describes the task:
### Input:
Event firing and exception conversion around command execution.
Common exceptions are run through our exception handler for
pretty-printing or debugging and then converted to SystemExit so the
interpretor will exit without furt... |
def update(self, configuration=values.unset, unique_name=values.unset):
"""
Update the InstalledAddOnInstance
:param dict configuration: The JSON object representing the configuration
:param unicode unique_name: The string that uniquely identifies this Add-on installation
:retu... | Update the InstalledAddOnInstance
:param dict configuration: The JSON object representing the configuration
:param unicode unique_name: The string that uniquely identifies this Add-on installation
:returns: Updated InstalledAddOnInstance
:rtype: twilio.rest.preview.marketplace.installe... | Below is the the instruction that describes the task:
### Input:
Update the InstalledAddOnInstance
:param dict configuration: The JSON object representing the configuration
:param unicode unique_name: The string that uniquely identifies this Add-on installation
:returns: Updated InstalledA... |
def parse(self, channel_id, payload):
'''
Parse a header frame for a channel given a Reader payload.
'''
class_id = payload.read_short()
weight = payload.read_short()
size = payload.read_longlong()
properties = {}
# The AMQP spec is overly-complex when it... | Parse a header frame for a channel given a Reader payload. | Below is the the instruction that describes the task:
### Input:
Parse a header frame for a channel given a Reader payload.
### Response:
def parse(self, channel_id, payload):
'''
Parse a header frame for a channel given a Reader payload.
'''
class_id = payload.read_short()
... |
def _execute_task(task_id,
verbosity=None,
runmode='run',
sigmode=None,
monitor_interval=5,
resource_monitor_interval=60,
master_runtime={}):
'''A function that execute specified task within a local dictionar... | A function that execute specified task within a local dictionary
(from SoS env.sos_dict). This function should be self-contained in that
it can be handled by a task manager, be executed locally in a separate
process or remotely on a different machine. | Below is the the instruction that describes the task:
### Input:
A function that execute specified task within a local dictionary
(from SoS env.sos_dict). This function should be self-contained in that
it can be handled by a task manager, be executed locally in a separate
process or remotely on a differ... |
def histogram2d(x, y, bins, range, weights=None):
"""
Compute a 2D histogram assuming equally spaced bins.
Parameters
----------
x, y : `~numpy.ndarray`
The position of the points to bin in the 2D histogram
bins : int or iterable
The number of bins in each dimension. If given as... | Compute a 2D histogram assuming equally spaced bins.
Parameters
----------
x, y : `~numpy.ndarray`
The position of the points to bin in the 2D histogram
bins : int or iterable
The number of bins in each dimension. If given as an integer, the same
number of bins is used for each ... | Below is the the instruction that describes the task:
### Input:
Compute a 2D histogram assuming equally spaced bins.
Parameters
----------
x, y : `~numpy.ndarray`
The position of the points to bin in the 2D histogram
bins : int or iterable
The number of bins in each dimension. If g... |
def release_subnet(self, cidr, direc):
"""Routine to release a subnet from the DB. """
if direc == 'in':
self.service_in_ip.release_subnet(cidr)
else:
self.service_out_ip.release_subnet(cidr) | Routine to release a subnet from the DB. | Below is the the instruction that describes the task:
### Input:
Routine to release a subnet from the DB.
### Response:
def release_subnet(self, cidr, direc):
"""Routine to release a subnet from the DB. """
if direc == 'in':
self.service_in_ip.release_subnet(cidr)
else:
... |
def evaluate(self, s, value, insert=None):
"""Expression evaluator.
* For expressions, returns the value of the expression.
* For Blocks, returns a generator (or the empty list []).
"""
assert not isinstance(value, kurt.Script)
if insert and insert.unevaluated:
... | Expression evaluator.
* For expressions, returns the value of the expression.
* For Blocks, returns a generator (or the empty list []). | Below is the the instruction that describes the task:
### Input:
Expression evaluator.
* For expressions, returns the value of the expression.
* For Blocks, returns a generator (or the empty list []).
### Response:
def evaluate(self, s, value, insert=None):
"""Expression evaluator.
... |
def replace_grid(self, updated_grid):
"""
replace all cells in current grid with updated grid
"""
for col in range(self.get_grid_width()):
for row in range(self.get_grid_height()):
if updated_grid[row][col] == EMPTY:
self.set_empty(row, col... | replace all cells in current grid with updated grid | Below is the the instruction that describes the task:
### Input:
replace all cells in current grid with updated grid
### Response:
def replace_grid(self, updated_grid):
"""
replace all cells in current grid with updated grid
"""
for col in range(self.get_grid_width()):
f... |
def _DoubleDecoder():
"""Returns a decoder for a double field.
This code works around a bug in struct.unpack for not-a-number.
"""
local_unpack = struct.unpack
def InnerDecode(buffer, pos):
# We expect a 64-bit value in little-endian byte order. Bit 1 is the sign
# bit, bits 2-12 represent the exp... | Returns a decoder for a double field.
This code works around a bug in struct.unpack for not-a-number. | Below is the the instruction that describes the task:
### Input:
Returns a decoder for a double field.
This code works around a bug in struct.unpack for not-a-number.
### Response:
def _DoubleDecoder():
"""Returns a decoder for a double field.
This code works around a bug in struct.unpack for not-a-number.... |
def mean_return_by_quantile(factor_data,
by_date=False,
by_group=False,
demeaned=True,
group_adjust=False):
"""
Computes mean returns for factor quantiles across
provided forward returns columns.
... | Computes mean returns for factor quantiles across
provided forward returns columns.
Parameters
----------
factor_data : pd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1),
containing the values for a single alpha factor, forward returns for
... | Below is the the instruction that describes the task:
### Input:
Computes mean returns for factor quantiles across
provided forward returns columns.
Parameters
----------
factor_data : pd.DataFrame - MultiIndex
A MultiIndex DataFrame indexed by date (level 0) and asset (level 1),
co... |
def metadata(sceneid, pmin=2, pmax=98, **kwargs):
"""
Retrieve image bounds and band statistics.
Attributes
----------
sceneid : str
Landsat sceneid. For scenes after May 2017,
sceneid have to be LANDSAT_PRODUCT_ID.
pmin : int, optional, (default: 2)
Histogram minimum cu... | Retrieve image bounds and band statistics.
Attributes
----------
sceneid : str
Landsat sceneid. For scenes after May 2017,
sceneid have to be LANDSAT_PRODUCT_ID.
pmin : int, optional, (default: 2)
Histogram minimum cut.
pmax : int, optional, (default: 98)
Histogram m... | Below is the the instruction that describes the task:
### Input:
Retrieve image bounds and band statistics.
Attributes
----------
sceneid : str
Landsat sceneid. For scenes after May 2017,
sceneid have to be LANDSAT_PRODUCT_ID.
pmin : int, optional, (default: 2)
Histogram min... |
def remove_phenotype(self, ind_obj, phenotypes=None):
"""Remove multiple phenotypes from an individual."""
if phenotypes is None:
logger.info("delete all phenotypes related to %s", ind_obj.ind_id)
self.query(PhenotypeTerm).filter_by(ind_id=ind_obj.id).delete()
else:
... | Remove multiple phenotypes from an individual. | Below is the the instruction that describes the task:
### Input:
Remove multiple phenotypes from an individual.
### Response:
def remove_phenotype(self, ind_obj, phenotypes=None):
"""Remove multiple phenotypes from an individual."""
if phenotypes is None:
logger.info("delete all phenoty... |
def get_jwt_data_from_app_context():
"""
Fetches a dict of jwt token data from the top of the flask app's context
"""
ctx = flask._app_ctx_stack.top
jwt_data = getattr(ctx, 'jwt_data', None)
PraetorianError.require_condition(
jwt_data is not None,
"""
No jwt_data found in... | Fetches a dict of jwt token data from the top of the flask app's context | Below is the the instruction that describes the task:
### Input:
Fetches a dict of jwt token data from the top of the flask app's context
### Response:
def get_jwt_data_from_app_context():
"""
Fetches a dict of jwt token data from the top of the flask app's context
"""
ctx = flask._app_ctx_stack.to... |
def enqueue_mod(self, dn, mod):
"""Enqueue a LDAP modification.
Arguments:
dn -- the distinguished name of the object to modify
mod -- an ldap modfication entry to enqueue
"""
# mark for update
if dn not in self.__pending_mod_dn__:
self.__pending_mod_... | Enqueue a LDAP modification.
Arguments:
dn -- the distinguished name of the object to modify
mod -- an ldap modfication entry to enqueue | Below is the the instruction that describes the task:
### Input:
Enqueue a LDAP modification.
Arguments:
dn -- the distinguished name of the object to modify
mod -- an ldap modfication entry to enqueue
### Response:
def enqueue_mod(self, dn, mod):
"""Enqueue a LDAP modification.
... |
def add_output(self, out_name, type_or_serialize=None, **kwargs):
""" Declare an output
"""
if out_name not in self.engine.all_outputs():
raise ValueError("'%s' is not generated by the engine %s" % (out_name, self.engine.all_outputs()))
if type_or_serialize is None:
... | Declare an output | Below is the the instruction that describes the task:
### Input:
Declare an output
### Response:
def add_output(self, out_name, type_or_serialize=None, **kwargs):
""" Declare an output
"""
if out_name not in self.engine.all_outputs():
raise ValueError("'%s' is not generated by t... |
def open_args(subparsers):
"""
The `mp open` command will open a resource with the system application, such as Excel or OpenOffice
"""
parser = subparsers.add_parser(
'open',
help='open a CSV resoruce with a system application',
description=open_args.__doc__,
formatter_c... | The `mp open` command will open a resource with the system application, such as Excel or OpenOffice | Below is the the instruction that describes the task:
### Input:
The `mp open` command will open a resource with the system application, such as Excel or OpenOffice
### Response:
def open_args(subparsers):
"""
The `mp open` command will open a resource with the system application, such as Excel or OpenOffi... |
def height(self, value):
"""
Set the height of the vowel.
:param str value: the value to be set
"""
if (value is not None) and (not value in DG_V_HEIGHT):
raise ValueError("Unrecognized value for height: '%s'" % value)
self.__height = value | Set the height of the vowel.
:param str value: the value to be set | Below is the the instruction that describes the task:
### Input:
Set the height of the vowel.
:param str value: the value to be set
### Response:
def height(self, value):
"""
Set the height of the vowel.
:param str value: the value to be set
"""
if (value is not No... |
def regenerate(location='http://www.iana.org/assignments/language-subtag-registry',
filename=None, default_encoding='utf-8'):
"""
Generate the languages Python module.
"""
paren = re.compile('\([^)]*\)')
# Get the language list.
data = urllib2.urlopen(location)
if ('content-t... | Generate the languages Python module. | Below is the the instruction that describes the task:
### Input:
Generate the languages Python module.
### Response:
def regenerate(location='http://www.iana.org/assignments/language-subtag-registry',
filename=None, default_encoding='utf-8'):
"""
Generate the languages Python module.
"""... |
def find(self, node_label):
"""Finds the set containing the node_label.
Returns the set label.
"""
queue = []
current_node = node_label
while self.__forest[current_node] >= 0:
queue.append(current_node)
current_node = self.__forest[current_node]
... | Finds the set containing the node_label.
Returns the set label. | Below is the the instruction that describes the task:
### Input:
Finds the set containing the node_label.
Returns the set label.
### Response:
def find(self, node_label):
"""Finds the set containing the node_label.
Returns the set label.
"""
queue = []
current_node =... |
def wait_until_element_value_is(self, locator, expected, strip=False, timeout=None):
"""Waits until the element identified by `locator` value is exactly the
expected value. You might want to use `Element Value Should Be` instead.
| *Argument* | *Description* | *Example* |
| locator | Selenium 2 element locator... | Waits until the element identified by `locator` value is exactly the
expected value. You might want to use `Element Value Should Be` instead.
| *Argument* | *Description* | *Example* |
| locator | Selenium 2 element locator | id=my_id |
| expected | expected value | My Name Is Slim Shady |
| strip | boolean,... | Below is the the instruction that describes the task:
### Input:
Waits until the element identified by `locator` value is exactly the
expected value. You might want to use `Element Value Should Be` instead.
| *Argument* | *Description* | *Example* |
| locator | Selenium 2 element locator | id=my_id |
| exp... |
def determine_file_type(self, z):
"""Determine file type."""
mimetype = z.read('mimetype').decode('utf-8').strip()
self.type = MIMEMAP[mimetype] | Determine file type. | Below is the the instruction that describes the task:
### Input:
Determine file type.
### Response:
def determine_file_type(self, z):
"""Determine file type."""
mimetype = z.read('mimetype').decode('utf-8').strip()
self.type = MIMEMAP[mimetype] |
def joint(letters, marks):
""" joint the letters with the marks
the length ot letters and marks must be equal
return word
@param letters: the word letters
@type letters: unicode
@param marks: the word marks
@type marks: unicode
@return: word
@rtype: unicode
"""
# The length o... | joint the letters with the marks
the length ot letters and marks must be equal
return word
@param letters: the word letters
@type letters: unicode
@param marks: the word marks
@type marks: unicode
@return: word
@rtype: unicode | Below is the the instruction that describes the task:
### Input:
joint the letters with the marks
the length ot letters and marks must be equal
return word
@param letters: the word letters
@type letters: unicode
@param marks: the word marks
@type marks: unicode
@return: word
@rtype: ... |
def with_prefix(self, prefix, strict=False):
"""
decorator to handle commands with prefixes
Parameters
----------
prefix : str
the prefix of the command
strict : bool, optional
If set to True the command must be at the beginning
of... | decorator to handle commands with prefixes
Parameters
----------
prefix : str
the prefix of the command
strict : bool, optional
If set to True the command must be at the beginning
of the message. Defaults to False.
Returns
-------
... | Below is the the instruction that describes the task:
### Input:
decorator to handle commands with prefixes
Parameters
----------
prefix : str
the prefix of the command
strict : bool, optional
If set to True the command must be at the beginning
of... |
def get_instance(self, payload):
"""
Build an instance of TaskQueueCumulativeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsInstance
:rt... | Build an instance of TaskQueueCumulativeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsInstance
:rtype: twilio.rest.taskrouter.v1.workspace.task_queue.t... | Below is the the instruction that describes the task:
### Input:
Build an instance of TaskQueueCumulativeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics.TaskQueueCumulativeStatisticsInst... |
def is_standalone(text, start, end):
"""check if the string text[start:end] is standalone by checking forwards
and backwards for blankspaces
:text: TODO
:(start, end): TODO
:returns: the start of next index after text[start:end]
"""
left = False
start -= 1
while start >= 0 and text[... | check if the string text[start:end] is standalone by checking forwards
and backwards for blankspaces
:text: TODO
:(start, end): TODO
:returns: the start of next index after text[start:end] | Below is the the instruction that describes the task:
### Input:
check if the string text[start:end] is standalone by checking forwards
and backwards for blankspaces
:text: TODO
:(start, end): TODO
:returns: the start of next index after text[start:end]
### Response:
def is_standalone(text, start, ... |
def assembly(self, value):
"""The assembly property.
Args:
value (string). the property value.
"""
if value == self._defaults['assembly'] and 'assembly' in self._values:
del self._values['assembly']
else:
self._values['assembly'] = val... | The assembly property.
Args:
value (string). the property value. | Below is the the instruction that describes the task:
### Input:
The assembly property.
Args:
value (string). the property value.
### Response:
def assembly(self, value):
"""The assembly property.
Args:
value (string). the property value.
""... |
def _get_responses(cls, requests, dispatcher):
""" Response to each single JSON-RPC Request.
:return iterator(JSONRPC20Response):
.. versionadded: 1.9.0
TypeError inside the function is distinguished from Invalid Params.
"""
for request in requests:
def r... | Response to each single JSON-RPC Request.
:return iterator(JSONRPC20Response):
.. versionadded: 1.9.0
TypeError inside the function is distinguished from Invalid Params. | Below is the the instruction that describes the task:
### Input:
Response to each single JSON-RPC Request.
:return iterator(JSONRPC20Response):
.. versionadded: 1.9.0
TypeError inside the function is distinguished from Invalid Params.
### Response:
def _get_responses(cls, requests, disp... |
def calcEL(self,**kwargs):
"""
NAME:
calcEL
PURPOSE:
calculate the energy and angular momentum
INPUT:
scipy.integrate.quadrature keywords
OUTPUT:
(E,L)
HISTORY:
2012-11-27 - Written - Bovy (IAS)
""" ... | NAME:
calcEL
PURPOSE:
calculate the energy and angular momentum
INPUT:
scipy.integrate.quadrature keywords
OUTPUT:
(E,L)
HISTORY:
2012-11-27 - Written - Bovy (IAS) | Below is the the instruction that describes the task:
### Input:
NAME:
calcEL
PURPOSE:
calculate the energy and angular momentum
INPUT:
scipy.integrate.quadrature keywords
OUTPUT:
(E,L)
HISTORY:
2012-11-27 - Written - Bovy (IAS)
... |
def reset_logformat(logger: logging.Logger,
fmt: str,
datefmt: str = '%Y-%m-%d %H:%M:%S') -> None:
"""
Create a new formatter and apply it to the logger.
:func:`logging.basicConfig` won't reset the formatter if another module
has called it, so always set the form... | Create a new formatter and apply it to the logger.
:func:`logging.basicConfig` won't reset the formatter if another module
has called it, so always set the formatter like this.
Args:
logger: logger to modify
fmt: passed to the ``fmt=`` argument of :class:`logging.Formatter`
datefmt... | Below is the the instruction that describes the task:
### Input:
Create a new formatter and apply it to the logger.
:func:`logging.basicConfig` won't reset the formatter if another module
has called it, so always set the formatter like this.
Args:
logger: logger to modify
fmt: passed t... |
def concat_padded(base, *args):
"""
Concatenate string and zero-padded 4 digit number
"""
ret = base
for n in args:
if is_string(n):
ret = "%s_%s" % (ret, n)
else:
ret = "%s_%04i" % (ret, n + 1)
return ret | Concatenate string and zero-padded 4 digit number | Below is the the instruction that describes the task:
### Input:
Concatenate string and zero-padded 4 digit number
### Response:
def concat_padded(base, *args):
"""
Concatenate string and zero-padded 4 digit number
"""
ret = base
for n in args:
if is_string(n):
ret = "%s_%s"... |
def parse_vmnet_range(start, end):
"""
Parse the vmnet range on the command line.
"""
class Range(argparse.Action):
def __call__(self, parser, args, values, option_string=None):
if len(values) != 2:
raise argparse.ArgumentTypeError("vmnet range must consist of 2 num... | Parse the vmnet range on the command line. | Below is the the instruction that describes the task:
### Input:
Parse the vmnet range on the command line.
### Response:
def parse_vmnet_range(start, end):
"""
Parse the vmnet range on the command line.
"""
class Range(argparse.Action):
def __call__(self, parser, args, values, option_str... |
def log_create(self, instance, **kwargs):
"""
Helper method to create a new log entry. This method automatically populates some fields when no explicit value
is given.
:param instance: The model instance to log a change for.
:type instance: Model
:param kwargs: Field ove... | Helper method to create a new log entry. This method automatically populates some fields when no explicit value
is given.
:param instance: The model instance to log a change for.
:type instance: Model
:param kwargs: Field overrides for the :py:class:`LogEntry` object.
:return: T... | Below is the the instruction that describes the task:
### Input:
Helper method to create a new log entry. This method automatically populates some fields when no explicit value
is given.
:param instance: The model instance to log a change for.
:type instance: Model
:param kwargs: Fi... |
def _tidy_repr(self, max_vals=10, footer=True):
""" a short repr displaying only max_vals and an optional (but default
footer)
"""
num = max_vals // 2
head = self[:num]._get_repr(length=False, footer=False)
tail = self[-(max_vals - num):]._get_repr(length=False, footer=Fa... | a short repr displaying only max_vals and an optional (but default
footer) | Below is the the instruction that describes the task:
### Input:
a short repr displaying only max_vals and an optional (but default
footer)
### Response:
def _tidy_repr(self, max_vals=10, footer=True):
""" a short repr displaying only max_vals and an optional (but default
footer)
""... |
def _init_model(self):
"""
Composes all layers of 2D CNN.
"""
model = Sequential()
model.add(Conv2D(input_shape=list(self.image_size) + [self.channels], filters=self.filters,
kernel_size=self.kernel_size, activation='relu', data_format='channels_last'))
... | Composes all layers of 2D CNN. | Below is the the instruction that describes the task:
### Input:
Composes all layers of 2D CNN.
### Response:
def _init_model(self):
"""
Composes all layers of 2D CNN.
"""
model = Sequential()
model.add(Conv2D(input_shape=list(self.image_size) + [self.channels], filters=self... |
def _mean_prediction(self, lmda, Y, scores, h, t_params, X_oos):
""" Creates a h-step ahead mean prediction
Parameters
----------
lmda : np.array
The past predicted values
Y : np.array
The past data
scores : np.array
The past scores
... | Creates a h-step ahead mean prediction
Parameters
----------
lmda : np.array
The past predicted values
Y : np.array
The past data
scores : np.array
The past scores
h : int
How many steps ahead for the prediction
... | Below is the the instruction that describes the task:
### Input:
Creates a h-step ahead mean prediction
Parameters
----------
lmda : np.array
The past predicted values
Y : np.array
The past data
scores : np.array
The past scores
... |
def ReadRaster(self, *args, **kwargs):
"""Returns raster data bytes for partial or full extent.
Overrides gdal.Dataset.ReadRaster() with the full raster size by
default.
"""
args = args or (0, 0, self.ds.RasterXSize, self.ds.RasterYSize)
return self.ds.ReadRaster(*args, ... | Returns raster data bytes for partial or full extent.
Overrides gdal.Dataset.ReadRaster() with the full raster size by
default. | Below is the the instruction that describes the task:
### Input:
Returns raster data bytes for partial or full extent.
Overrides gdal.Dataset.ReadRaster() with the full raster size by
default.
### Response:
def ReadRaster(self, *args, **kwargs):
"""Returns raster data bytes for partial or ... |
def read_tsv(self):
"""
Read in the .tsv contig report file with pandas, and create a dictionary of all the headers: values
"""
logging.info('Parsing MOB-recon outputs')
for sample in self.metadata:
if os.path.isfile(sample[self.analysistype].contig_report):
... | Read in the .tsv contig report file with pandas, and create a dictionary of all the headers: values | Below is the the instruction that describes the task:
### Input:
Read in the .tsv contig report file with pandas, and create a dictionary of all the headers: values
### Response:
def read_tsv(self):
"""
Read in the .tsv contig report file with pandas, and create a dictionary of all the headers: val... |
def runtime_values(self):
"""
All of the concrete values used by this function at runtime (i.e., including passed-in arguments and global
values).
"""
constants = set()
for b in self.block_addrs:
for sirsb in self._function_manager._cfg.get_all_irsbs(b):
... | All of the concrete values used by this function at runtime (i.e., including passed-in arguments and global
values). | Below is the the instruction that describes the task:
### Input:
All of the concrete values used by this function at runtime (i.e., including passed-in arguments and global
values).
### Response:
def runtime_values(self):
"""
All of the concrete values used by this function at runtime (i.e.... |
def process_request(self, request, response):
"""Get session ID from cookie, load corresponding session data from coupled store and inject session data into
the request context.
"""
sid = request.cookies.get(self.cookie_name, None)
data = {}
if sid is not None:
... | Get session ID from cookie, load corresponding session data from coupled store and inject session data into
the request context. | Below is the the instruction that describes the task:
### Input:
Get session ID from cookie, load corresponding session data from coupled store and inject session data into
the request context.
### Response:
def process_request(self, request, response):
"""Get session ID from cookie, load corre... |
def multi_session(self):
''' convert the multi_session param a number '''
_val = 0
if "multi_session" in self._dict:
_val = self._dict["multi_session"]
if str(_val).lower() == 'all':
_val = -1
return int(_val) | convert the multi_session param a number | Below is the the instruction that describes the task:
### Input:
convert the multi_session param a number
### Response:
def multi_session(self):
''' convert the multi_session param a number '''
_val = 0
if "multi_session" in self._dict:
_val = self._dict["multi_session"]
... |
def items(self, section=_UNSET, raw=False, vars=None):
"""Return a list of (name, value) tuples for each option in a section.
All % interpolations are expanded in the return values, based on the
defaults passed into the constructor, unless the optional argument
`raw' is true. Additiona... | Return a list of (name, value) tuples for each option in a section.
All % interpolations are expanded in the return values, based on the
defaults passed into the constructor, unless the optional argument
`raw' is true. Additional substitutions may be provided using the
`vars' argument,... | Below is the the instruction that describes the task:
### Input:
Return a list of (name, value) tuples for each option in a section.
All % interpolations are expanded in the return values, based on the
defaults passed into the constructor, unless the optional argument
`raw' is true. Additi... |
def generate_legacy_webfinger(template=None, *args, **kwargs):
"""Generate a legacy webfinger XRD document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: Rendered XRD document... | Generate a legacy webfinger XRD document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: Rendered XRD document (str) | Below is the the instruction that describes the task:
### Input:
Generate a legacy webfinger XRD document.
Template specific key-value pairs need to be passed as ``kwargs``, see classes.
:arg template: Ready template to fill with args, for example "diaspora" (optional)
:returns: Rendered XRD document ... |
def process_request(self, request):
"""
Store memory data to log later.
"""
if self._is_enabled():
self._cache.set(self.guid_key, six.text_type(uuid4()))
log_prefix = self._log_prefix(u"Before", request)
self._cache.set(self.memory_data_key, self._memo... | Store memory data to log later. | Below is the the instruction that describes the task:
### Input:
Store memory data to log later.
### Response:
def process_request(self, request):
"""
Store memory data to log later.
"""
if self._is_enabled():
self._cache.set(self.guid_key, six.text_type(uuid4()))
... |
def is_valid(cls, arg):
"""Return True if arg is valid value for the class."""
return isinstance(arg, (int, long)) and (not isinstance(arg, bool)) | Return True if arg is valid value for the class. | Below is the the instruction that describes the task:
### Input:
Return True if arg is valid value for the class.
### Response:
def is_valid(cls, arg):
"""Return True if arg is valid value for the class."""
return isinstance(arg, (int, long)) and (not isinstance(arg, bool)) |
def reset(self):
"""
Reset the videostream by restarting ffmpeg
"""
if self.ffmpeg_process is not None:
# Close the previous stream
try:
self.ffmpeg_process.send_signal(signal.SIGINT)
except OSError:
pass
comma... | Reset the videostream by restarting ffmpeg | Below is the the instruction that describes the task:
### Input:
Reset the videostream by restarting ffmpeg
### Response:
def reset(self):
"""
Reset the videostream by restarting ffmpeg
"""
if self.ffmpeg_process is not None:
# Close the previous stream
try:... |
def tile(imgs, cmap='gray', bar=False, nans=True, clim=None, grid=None, size=9, axis=0, fig=None):
"""
Display a collection of images as a grid of tiles
Parameters
----------
img : list or ndarray (2D or 3D)
The images to display. Can be a list of either 2D, 3D,
or a mix of 2D and 3... | Display a collection of images as a grid of tiles
Parameters
----------
img : list or ndarray (2D or 3D)
The images to display. Can be a list of either 2D, 3D,
or a mix of 2D and 3D numpy arrays. Can also be a single
numpy array, in which case the axis parameter will be assumed
... | Below is the the instruction that describes the task:
### Input:
Display a collection of images as a grid of tiles
Parameters
----------
img : list or ndarray (2D or 3D)
The images to display. Can be a list of either 2D, 3D,
or a mix of 2D and 3D numpy arrays. Can also be a single
... |
def get_query(self, query):
"""Make a GET request, including a query, to the endpoint.
The path of the request is to the base URL assigned to the endpoint.
Parameters
----------
query : DataQuery
The query to pass when making the request
Returns
---... | Make a GET request, including a query, to the endpoint.
The path of the request is to the base URL assigned to the endpoint.
Parameters
----------
query : DataQuery
The query to pass when making the request
Returns
-------
resp : requests.Response
... | Below is the the instruction that describes the task:
### Input:
Make a GET request, including a query, to the endpoint.
The path of the request is to the base URL assigned to the endpoint.
Parameters
----------
query : DataQuery
The query to pass when making the reques... |
def get_parent(self):
""" the parent of this DriveItem
:return: Parent of this item
:rtype: Drive or drive.Folder
"""
if self._parent and self._parent.object_id == self.parent_id:
return self._parent
else:
if self.parent_id:
return... | the parent of this DriveItem
:return: Parent of this item
:rtype: Drive or drive.Folder | Below is the the instruction that describes the task:
### Input:
the parent of this DriveItem
:return: Parent of this item
:rtype: Drive or drive.Folder
### Response:
def get_parent(self):
""" the parent of this DriveItem
:return: Parent of this item
:rtype: Drive or drive... |
def add_assembly_names(opts):
"""add assembly names as aliases to existing sequences
Specifically, associate aliases like GRCh37.p9:1 with existing
refseq accessions
```
[{'aliases': ['chr19'],
'assembly_unit': 'Primary Assembly',
'genbank_ac': 'CM000681.2',
'length': 58617616,
... | add assembly names as aliases to existing sequences
Specifically, associate aliases like GRCh37.p9:1 with existing
refseq accessions
```
[{'aliases': ['chr19'],
'assembly_unit': 'Primary Assembly',
'genbank_ac': 'CM000681.2',
'length': 58617616,
'name': '19',
'refseq_ac':... | Below is the the instruction that describes the task:
### Input:
add assembly names as aliases to existing sequences
Specifically, associate aliases like GRCh37.p9:1 with existing
refseq accessions
```
[{'aliases': ['chr19'],
'assembly_unit': 'Primary Assembly',
'genbank_ac': 'CM000681... |
def get_brain_by_uid(self, uid):
"""Lookup brain from the right catalog
"""
if uid == "0":
return api.get_portal()
# ensure we have the primary catalog
if self._catalog is None:
uid_catalog = api.get_tool("uid_catalog")
results = uid_catalog({... | Lookup brain from the right catalog | Below is the the instruction that describes the task:
### Input:
Lookup brain from the right catalog
### Response:
def get_brain_by_uid(self, uid):
"""Lookup brain from the right catalog
"""
if uid == "0":
return api.get_portal()
# ensure we have the primary catalog
... |
def convert_to_ascii(statement):
"""
Converts unicode characters to ASCII character equivalents.
For example: "på fédéral" becomes "pa federal".
"""
import unicodedata
text = unicodedata.normalize('NFKD', statement.text)
text = text.encode('ascii', 'ignore').decode('utf-8')
statement.t... | Converts unicode characters to ASCII character equivalents.
For example: "på fédéral" becomes "pa federal". | Below is the the instruction that describes the task:
### Input:
Converts unicode characters to ASCII character equivalents.
For example: "på fédéral" becomes "pa federal".
### Response:
def convert_to_ascii(statement):
"""
Converts unicode characters to ASCII character equivalents.
For example: "p... |
def _extract_features(self):
"""
Extracts and sets the feature data from the log file necessary for a reduction
"""
for parsed_line in self.parsed_lines:
# If it's ssh, we can handle it
if parsed_line.get('program') == 'sshd':
result = self._parse... | Extracts and sets the feature data from the log file necessary for a reduction | Below is the the instruction that describes the task:
### Input:
Extracts and sets the feature data from the log file necessary for a reduction
### Response:
def _extract_features(self):
"""
Extracts and sets the feature data from the log file necessary for a reduction
"""
for parse... |
def enforce_types(key, val):
'''
Force params to be strings unless they should remain a different type
'''
non_string_params = {
'ssl_verify': bool,
'insecure_auth': bool,
'disable_saltenv_mapping': bool,
'env_whitelist': 'stringlist',
'env_blacklist': 'stringlist... | Force params to be strings unless they should remain a different type | Below is the the instruction that describes the task:
### Input:
Force params to be strings unless they should remain a different type
### Response:
def enforce_types(key, val):
'''
Force params to be strings unless they should remain a different type
'''
non_string_params = {
'ssl_verify':... |
def stop_tracking(self, end_time = None):
"""Stop tracking current activity. end_time can be passed in if the
activity should have other end time than the current moment"""
end_time = timegm((end_time or dt.datetime.now()).timetuple())
return self.conn.StopTracking(end_time) | Stop tracking current activity. end_time can be passed in if the
activity should have other end time than the current moment | Below is the the instruction that describes the task:
### Input:
Stop tracking current activity. end_time can be passed in if the
activity should have other end time than the current moment
### Response:
def stop_tracking(self, end_time = None):
"""Stop tracking current activity. end_time can be pa... |
def get_routertypes(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None,
page_reverse=False):
"""Lists defined router types."""
pass | Lists defined router types. | Below is the the instruction that describes the task:
### Input:
Lists defined router types.
### Response:
def get_routertypes(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None,
page_reverse=False):
"""Lists defined router types.""... |
def _add_slice(seq, slc):
""" Our textwrap routine deals in slices. This function will concat
contiguous slices as an optimization so lookup performance is faster.
It expects a sequence (probably a list) to add slice to or will extend
the last slice of the sequence if it ends where the new slice begins... | Our textwrap routine deals in slices. This function will concat
contiguous slices as an optimization so lookup performance is faster.
It expects a sequence (probably a list) to add slice to or will extend
the last slice of the sequence if it ends where the new slice begins. | Below is the the instruction that describes the task:
### Input:
Our textwrap routine deals in slices. This function will concat
contiguous slices as an optimization so lookup performance is faster.
It expects a sequence (probably a list) to add slice to or will extend
the last slice of the sequence if... |
def decode_qp_numpy(msg, return_matrix=True):
"""Decode SAPI response, results in a `qp` format, explicitly using numpy.
If numpy is not installed, the method will fail.
To use numpy for decoding, but return the results a lists (instead of
numpy matrices), set `return_matrix=False`.
"""
import ... | Decode SAPI response, results in a `qp` format, explicitly using numpy.
If numpy is not installed, the method will fail.
To use numpy for decoding, but return the results a lists (instead of
numpy matrices), set `return_matrix=False`. | Below is the the instruction that describes the task:
### Input:
Decode SAPI response, results in a `qp` format, explicitly using numpy.
If numpy is not installed, the method will fail.
To use numpy for decoding, but return the results a lists (instead of
numpy matrices), set `return_matrix=False`.
###... |
def to_json(df, state_index, color_index, fills):
"""Transforms dataframe to json response"""
records = {}
for i, row in df.iterrows():
records[row[state_index]] = {
"fillKey": row[color_index]
}
return {
"data": records,
... | Transforms dataframe to json response | Below is the the instruction that describes the task:
### Input:
Transforms dataframe to json response
### Response:
def to_json(df, state_index, color_index, fills):
"""Transforms dataframe to json response"""
records = {}
for i, row in df.iterrows():
records[row[state_index]]... |
def spherical_to_cartesian(lons, lats, depths=None):
"""
Return the position vectors (in Cartesian coordinates) of list of spherical
coordinates.
For equations see: http://mathworld.wolfram.com/SphericalCoordinates.html.
Parameters are components of spherical coordinates in a form of scalars,
... | Return the position vectors (in Cartesian coordinates) of list of spherical
coordinates.
For equations see: http://mathworld.wolfram.com/SphericalCoordinates.html.
Parameters are components of spherical coordinates in a form of scalars,
lists or numpy arrays. ``depths`` can be ``None`` in which case i... | Below is the the instruction that describes the task:
### Input:
Return the position vectors (in Cartesian coordinates) of list of spherical
coordinates.
For equations see: http://mathworld.wolfram.com/SphericalCoordinates.html.
Parameters are components of spherical coordinates in a form of scalars,
... |
def energy(self, sample_like, dtype=np.float):
"""The energy of the given sample.
Args:
sample_like (samples_like):
A raw sample. `sample_like` is an extension of
NumPy's array_like structure. See :func:`.as_samples`.
dtype (:class:`numpy.dtype`,... | The energy of the given sample.
Args:
sample_like (samples_like):
A raw sample. `sample_like` is an extension of
NumPy's array_like structure. See :func:`.as_samples`.
dtype (:class:`numpy.dtype`, optional):
The data type of the returned ... | Below is the the instruction that describes the task:
### Input:
The energy of the given sample.
Args:
sample_like (samples_like):
A raw sample. `sample_like` is an extension of
NumPy's array_like structure. See :func:`.as_samples`.
dtype (:class:`nu... |
def r_cts(self):
""" Actual main route of CTS APIs. Transfer typical requests through the ?request=REQUESTNAME route
:return: Response
"""
_request = request.args.get("request", None)
if _request is not None:
try:
if _request.lower() == "getcapabiliti... | Actual main route of CTS APIs. Transfer typical requests through the ?request=REQUESTNAME route
:return: Response | Below is the the instruction that describes the task:
### Input:
Actual main route of CTS APIs. Transfer typical requests through the ?request=REQUESTNAME route
:return: Response
### Response:
def r_cts(self):
""" Actual main route of CTS APIs. Transfer typical requests through the ?request=REQUES... |
def ordinal_float(dt):
"""Like datetime.ordinal, but rather than integer allows fractional days (so float not ordinal at all)
Similar to the Microsoft Excel numerical representation of a datetime object
>>> ordinal_float(datetime.datetime(1970, 1, 1))
719163.0
>>> ordinal_float(datetime.datetime(1... | Like datetime.ordinal, but rather than integer allows fractional days (so float not ordinal at all)
Similar to the Microsoft Excel numerical representation of a datetime object
>>> ordinal_float(datetime.datetime(1970, 1, 1))
719163.0
>>> ordinal_float(datetime.datetime(1, 2, 3, 4, 5, 6, 7)) # doctes... | Below is the the instruction that describes the task:
### Input:
Like datetime.ordinal, but rather than integer allows fractional days (so float not ordinal at all)
Similar to the Microsoft Excel numerical representation of a datetime object
>>> ordinal_float(datetime.datetime(1970, 1, 1))
719163.0
... |
def help(context, command):
'''Get command help'''
if command:
cmd = cli.commands.get(command, None)
if cmd:
context.info_name = command
click.echo(cmd.get_help(context))
else:
raise click.ClickException('no command: %s' % command)
else:
cl... | Get command help | Below is the the instruction that describes the task:
### Input:
Get command help
### Response:
def help(context, command):
'''Get command help'''
if command:
cmd = cli.commands.get(command, None)
if cmd:
context.info_name = command
click.echo(cmd.get_help(context))
... |
def sign(user_id, user_type=None, today=None, session=None):
"""Check user id for validity, then sign user in if they are signed
out, or out if they are signed in.
:param user_id: The ID of the user to sign in or out.
:param user_type: (optional) Specify whether user is signing in as a `'student'` or `... | Check user id for validity, then sign user in if they are signed
out, or out if they are signed in.
:param user_id: The ID of the user to sign in or out.
:param user_type: (optional) Specify whether user is signing in as a `'student'` or `'tutor'`.
:param today: (optional) The current date as a `dateti... | Below is the the instruction that describes the task:
### Input:
Check user id for validity, then sign user in if they are signed
out, or out if they are signed in.
:param user_id: The ID of the user to sign in or out.
:param user_type: (optional) Specify whether user is signing in as a `'student'` or ... |
def update_bounds(self, bounds):
'''Update cylinders start and end positions
'''
starts = bounds[:,0,:]
ends = bounds[:,1,:]
self.bounds = bounds
self.lengths = np.sqrt(((ends - starts)**2).sum(axis=1))
vertices, normals, colors = self._process_refere... | Update cylinders start and end positions | Below is the the instruction that describes the task:
### Input:
Update cylinders start and end positions
### Response:
def update_bounds(self, bounds):
'''Update cylinders start and end positions
'''
starts = bounds[:,0,:]
ends = bounds[:,1,:]
self.bounds = bounds
... |
def split_leading_indent(line, max_indents=None):
"""Split line into leading indent and main."""
indent = ""
while (
(max_indents is None or max_indents > 0)
and line.startswith((openindent, closeindent))
) or line.lstrip() != line:
if max_indents is not None and line.startswith(... | Split line into leading indent and main. | Below is the the instruction that describes the task:
### Input:
Split line into leading indent and main.
### Response:
def split_leading_indent(line, max_indents=None):
"""Split line into leading indent and main."""
indent = ""
while (
(max_indents is None or max_indents > 0)
and line.... |
def set_until(self, frame, lineno=None):
"""Stop when the current line number in frame is greater than lineno or
when returning from frame."""
if lineno is None:
lineno = frame.f_lineno + 1
self._set_stopinfo(frame, lineno) | Stop when the current line number in frame is greater than lineno or
when returning from frame. | Below is the the instruction that describes the task:
### Input:
Stop when the current line number in frame is greater than lineno or
when returning from frame.
### Response:
def set_until(self, frame, lineno=None):
"""Stop when the current line number in frame is greater than lineno or
whe... |
def _parse_sequences(ilines, expect_qlen):
"""Parse the sequences in the current block.
Sequence looks like:
$3=227(209):
>gi|15606894|ref|NP_214275.1| {|2(244)|<Aquificae(B)>}DNA polymerase III gamma subunit [Aquifex aeolicus VF5] >gi|2984127|gb|AAC07663.1| DNA polymerase III gamma subunit [Aquifex ... | Parse the sequences in the current block.
Sequence looks like:
$3=227(209):
>gi|15606894|ref|NP_214275.1| {|2(244)|<Aquificae(B)>}DNA polymerase III gamma subunit [Aquifex aeolicus VF5] >gi|2984127|gb|AAC07663.1| DNA polymerase III gamma subunit [Aquifex aeolicus VF5] >gi|75
{()YVPFARKYRPKFFREVIGQEAP... | Below is the the instruction that describes the task:
### Input:
Parse the sequences in the current block.
Sequence looks like:
$3=227(209):
>gi|15606894|ref|NP_214275.1| {|2(244)|<Aquificae(B)>}DNA polymerase III gamma subunit [Aquifex aeolicus VF5] >gi|2984127|gb|AAC07663.1| DNA polymerase III gamm... |
def metric(self, name, count, elapsed):
"""A metric function that writes a single CSV file
:arg str name: name of the metric
:arg int count: number of items
:arg float elapsed: time in seconds
"""
if name is None:
warnings.warn("Ignoring unnamed metric", sta... | A metric function that writes a single CSV file
:arg str name: name of the metric
:arg int count: number of items
:arg float elapsed: time in seconds | Below is the the instruction that describes the task:
### Input:
A metric function that writes a single CSV file
:arg str name: name of the metric
:arg int count: number of items
:arg float elapsed: time in seconds
### Response:
def metric(self, name, count, elapsed):
"""A metric f... |
def increment(version, major=False, minor=False, patch=True):
"""
Increment a semantic version
:param version: str of the version to increment
:param major: bool specifying major level version increment
:param minor: bool specifying minor level version increment
:param patch: bool specifying pa... | Increment a semantic version
:param version: str of the version to increment
:param major: bool specifying major level version increment
:param minor: bool specifying minor level version increment
:param patch: bool specifying patch level version increment
:return: str of the incremented version | Below is the the instruction that describes the task:
### Input:
Increment a semantic version
:param version: str of the version to increment
:param major: bool specifying major level version increment
:param minor: bool specifying minor level version increment
:param patch: bool specifying patch l... |
def set_keep_alive(self, sock, after_idle_sec=5, interval_sec=60,
max_fails=5):
"""
This function instructs the TCP socket to send a heart beat every n
seconds to detect dead connections. It's the TCP equivalent of the
IRC ping-pong protocol and allows for better c... | This function instructs the TCP socket to send a heart beat every n
seconds to detect dead connections. It's the TCP equivalent of the
IRC ping-pong protocol and allows for better cleanup / detection
of dead TCP connections.
It activates after 1 second (after_idle_sec) of idleness, then... | Below is the the instruction that describes the task:
### Input:
This function instructs the TCP socket to send a heart beat every n
seconds to detect dead connections. It's the TCP equivalent of the
IRC ping-pong protocol and allows for better cleanup / detection
of dead TCP connections.
... |
def setup_ipython(self):
"""Monkey patch shell's error handler.
This method is to monkey-patch the showtraceback method of
IPython's InteractiveShell to
__IPYTHON__ is not detected when starting an IPython kernel,
so this method is called from start_kernel in spyder-modelx.
... | Monkey patch shell's error handler.
This method is to monkey-patch the showtraceback method of
IPython's InteractiveShell to
__IPYTHON__ is not detected when starting an IPython kernel,
so this method is called from start_kernel in spyder-modelx. | Below is the the instruction that describes the task:
### Input:
Monkey patch shell's error handler.
This method is to monkey-patch the showtraceback method of
IPython's InteractiveShell to
__IPYTHON__ is not detected when starting an IPython kernel,
so this method is called from s... |
def save(self, *args, **kwargs):
"""
Create formatted version of body text.
"""
self.body_formatted = sanetize_text(self.body)
super(Contact, self).save() | Create formatted version of body text. | Below is the the instruction that describes the task:
### Input:
Create formatted version of body text.
### Response:
def save(self, *args, **kwargs):
"""
Create formatted version of body text.
"""
self.body_formatted = sanetize_text(self.body)
super(Contact, self).save() |
def handle_wiki(msg):
""" Given a wiki message, return the FAS username. """
if 'wiki.article.edit' in msg.topic:
username = msg.msg['user']
elif 'wiki.upload.complete' in msg.topic:
username = msg.msg['user_text']
else:
raise ValueError("Unhandled topic.")
return username | Given a wiki message, return the FAS username. | Below is the the instruction that describes the task:
### Input:
Given a wiki message, return the FAS username.
### Response:
def handle_wiki(msg):
""" Given a wiki message, return the FAS username. """
if 'wiki.article.edit' in msg.topic:
username = msg.msg['user']
elif 'wiki.upload.complete'... |
def transform_frame(frame, transform, columns=None, direction='forward',
return_all=True, args=(), **kwargs):
"""
Apply transform to specified columns.
direction: 'forward' | 'inverse'
return_all: bool
True - return all columns, with specified ones transformed.
Fals... | Apply transform to specified columns.
direction: 'forward' | 'inverse'
return_all: bool
True - return all columns, with specified ones transformed.
False - return only specified columns.
.. warning:: deprecated | Below is the the instruction that describes the task:
### Input:
Apply transform to specified columns.
direction: 'forward' | 'inverse'
return_all: bool
True - return all columns, with specified ones transformed.
False - return only specified columns.
.. warning:: deprecated
### Respo... |
def generate_data_key(self, name, key_type, context="", nonce="", bits=256, mount_point=DEFAULT_MOUNT_POINT):
"""Generates a new high-entropy key and the value encrypted with the named key.
Optionally return the plaintext of the key as well. Whether plaintext is returned depends on the path; as a
... | Generates a new high-entropy key and the value encrypted with the named key.
Optionally return the plaintext of the key as well. Whether plaintext is returned depends on the path; as a
result, you can use Vault ACL policies to control whether a user is allowed to retrieve the plaintext value of a
... | Below is the the instruction that describes the task:
### Input:
Generates a new high-entropy key and the value encrypted with the named key.
Optionally return the plaintext of the key as well. Whether plaintext is returned depends on the path; as a
result, you can use Vault ACL policies to control... |
def all(self):
" execute query, get all list of lists"
query,inputs = self._toedn()
return self.db.q(query,
inputs = inputs,
limit = self._limit,
offset = self._offset,
history = self._history) | execute query, get all list of lists | Below is the the instruction that describes the task:
### Input:
execute query, get all list of lists
### Response:
def all(self):
" execute query, get all list of lists"
query,inputs = self._toedn()
return self.db.q(query,
inputs = inputs,
limit = self._limit,
offset = self._offs... |
def _create_bundle(self, data):
"""Return a bundle initialised by the given dict."""
kwargs = {}
filters = None
if isinstance(data, dict):
kwargs.update(
filters=data.get('filters', None),
output=data.get('output', None),
debug=... | Return a bundle initialised by the given dict. | Below is the the instruction that describes the task:
### Input:
Return a bundle initialised by the given dict.
### Response:
def _create_bundle(self, data):
"""Return a bundle initialised by the given dict."""
kwargs = {}
filters = None
if isinstance(data, dict):
kwargs... |
def create_vm(self, userid, cpu, memory, disk_list,
user_profile, max_cpu, max_mem, ipl_from,
ipl_param, ipl_loadparam):
"""Create z/VM userid into user directory for a z/VM instance."""
LOG.info("Creating the user directory for vm %s", userid)
info = self._s... | Create z/VM userid into user directory for a z/VM instance. | Below is the the instruction that describes the task:
### Input:
Create z/VM userid into user directory for a z/VM instance.
### Response:
def create_vm(self, userid, cpu, memory, disk_list,
user_profile, max_cpu, max_mem, ipl_from,
ipl_param, ipl_loadparam):
"""Create z... |
def interrupt_guard(msg='', reraise=True):
"""
context for guard keyboardinterrupt
ex)
with interrupt_guard('need long time'):
critical_work_to_prevent()
:param str msg: message to print when interrupted
:param reraise: re-raise or not when exit
:return: context
"""
def echo... | context for guard keyboardinterrupt
ex)
with interrupt_guard('need long time'):
critical_work_to_prevent()
:param str msg: message to print when interrupted
:param reraise: re-raise or not when exit
:return: context | Below is the the instruction that describes the task:
### Input:
context for guard keyboardinterrupt
ex)
with interrupt_guard('need long time'):
critical_work_to_prevent()
:param str msg: message to print when interrupted
:param reraise: re-raise or not when exit
:return: context
### Re... |
def download_image(self, image_type, image):
"""
Read file of a project and download it
:param image_type: Image type
:param image: The path of the image
:returns: A file stream
"""
url = self._getUrl("/{}/images/{}".format(image_type, image))
response =... | Read file of a project and download it
:param image_type: Image type
:param image: The path of the image
:returns: A file stream | Below is the the instruction that describes the task:
### Input:
Read file of a project and download it
:param image_type: Image type
:param image: The path of the image
:returns: A file stream
### Response:
def download_image(self, image_type, image):
"""
Read file of a pr... |
def position_half_h(pslit, cpix, backw=4):
"""Find the position where the value is half of the peak"""
# Find the first peak to the right of cpix
next_peak = simple_prot(pslit, cpix)
if next_peak is None:
raise ValueError
dis_peak = next_peak - cpix
wpos2 = cpix - dis_peak
wpos1 ... | Find the position where the value is half of the peak | Below is the the instruction that describes the task:
### Input:
Find the position where the value is half of the peak
### Response:
def position_half_h(pslit, cpix, backw=4):
"""Find the position where the value is half of the peak"""
# Find the first peak to the right of cpix
next_peak = simple_prot... |
def parse_diaspora_webfinger(document):
"""
Parse Diaspora webfinger which is either in JSON format (new) or XRD (old).
https://diaspora.github.io/diaspora_federation/discovery/webfinger.html
"""
webfinger = {
"hcard_url": None,
}
try:
doc = json.loads(document)
for ... | Parse Diaspora webfinger which is either in JSON format (new) or XRD (old).
https://diaspora.github.io/diaspora_federation/discovery/webfinger.html | Below is the the instruction that describes the task:
### Input:
Parse Diaspora webfinger which is either in JSON format (new) or XRD (old).
https://diaspora.github.io/diaspora_federation/discovery/webfinger.html
### Response:
def parse_diaspora_webfinger(document):
"""
Parse Diaspora webfinger which ... |
def calculate_border_width(self):
"""
Calculate the width of the menu border. This will be the width of the maximum allowable
dimensions (usually the screen size), minus the left and right margins and the newline character.
For example, given a maximum width of 80 characters, with left a... | Calculate the width of the menu border. This will be the width of the maximum allowable
dimensions (usually the screen size), minus the left and right margins and the newline character.
For example, given a maximum width of 80 characters, with left and right margins both
set to 1, the border wid... | Below is the the instruction that describes the task:
### Input:
Calculate the width of the menu border. This will be the width of the maximum allowable
dimensions (usually the screen size), minus the left and right margins and the newline character.
For example, given a maximum width of 80 characte... |
def get_attrs(obj):
"""Helper for dir2 implementation."""
if not hasattr(obj, '__dict__'):
return [] # slots only
proxy_type = types.MappingProxyType if six.PY3 else types.DictProxyType
if not isinstance(obj.__dict__, (dict, proxy_type)):
print(type(obj.__dict__), obj)
raise Typ... | Helper for dir2 implementation. | Below is the the instruction that describes the task:
### Input:
Helper for dir2 implementation.
### Response:
def get_attrs(obj):
"""Helper for dir2 implementation."""
if not hasattr(obj, '__dict__'):
return [] # slots only
proxy_type = types.MappingProxyType if six.PY3 else types.DictProxyTy... |
def get_image_name(self):
"""
@rtype: int
@return: Filename of the process main module.
This method does it's best to retrieve the filename.
However sometimes this is not possible, so C{None} may
be returned instead.
"""
# Method 1: Module.f... | @rtype: int
@return: Filename of the process main module.
This method does it's best to retrieve the filename.
However sometimes this is not possible, so C{None} may
be returned instead. | Below is the the instruction that describes the task:
### Input:
@rtype: int
@return: Filename of the process main module.
This method does it's best to retrieve the filename.
However sometimes this is not possible, so C{None} may
be returned instead.
### Response:
def... |
def bookmark_create(endpoint_plus_path, bookmark_name):
"""
Executor for `globus bookmark create`
"""
endpoint_id, path = endpoint_plus_path
client = get_client()
submit_data = {"endpoint_id": str(endpoint_id), "path": path, "name": bookmark_name}
res = client.create_bookmark(submit_data)
... | Executor for `globus bookmark create` | Below is the the instruction that describes the task:
### Input:
Executor for `globus bookmark create`
### Response:
def bookmark_create(endpoint_plus_path, bookmark_name):
"""
Executor for `globus bookmark create`
"""
endpoint_id, path = endpoint_plus_path
client = get_client()
submit_dat... |
def get_sun_times(dates, lon, lat, time_zone):
"""Computes the times of sunrise, solar noon, and sunset for each day.
Parameters
----
dates: datetime
lat : latitude in DecDeg
lon : longitude in DecDeg
time_zone : timezone
Returns
----
DataFrame: [sunrise,... | Computes the times of sunrise, solar noon, and sunset for each day.
Parameters
----
dates: datetime
lat : latitude in DecDeg
lon : longitude in DecDeg
time_zone : timezone
Returns
----
DataFrame: [sunrise, sunnoon, sunset, day length] in dec hours | Below is the the instruction that describes the task:
### Input:
Computes the times of sunrise, solar noon, and sunset for each day.
Parameters
----
dates: datetime
lat : latitude in DecDeg
lon : longitude in DecDeg
time_zone : timezone
Returns
----
DataFr... |
def from_irafpath(irafpath):
"""Resolve IRAF path like ``jref$`` into actual file path.
Parameters
----------
irafpath : str
Path containing IRAF syntax.
Returns
-------
realpath : str
Actual file path. If input does not follow ``path$filename``
format, then this is... | Resolve IRAF path like ``jref$`` into actual file path.
Parameters
----------
irafpath : str
Path containing IRAF syntax.
Returns
-------
realpath : str
Actual file path. If input does not follow ``path$filename``
format, then this is the same as input.
Raises
... | Below is the the instruction that describes the task:
### Input:
Resolve IRAF path like ``jref$`` into actual file path.
Parameters
----------
irafpath : str
Path containing IRAF syntax.
Returns
-------
realpath : str
Actual file path. If input does not follow ``path$filena... |
def extract(pcmiter, samplerate, channels, duration = -1):
"""Given a PCM data stream, extract fingerprint data from the
audio. Returns a byte string of fingerprint data. Raises an
ExtractionError if fingerprinting fails.
"""
extractor = _fplib.Extractor(samplerate, channels, duration)
# Get fi... | Given a PCM data stream, extract fingerprint data from the
audio. Returns a byte string of fingerprint data. Raises an
ExtractionError if fingerprinting fails. | Below is the the instruction that describes the task:
### Input:
Given a PCM data stream, extract fingerprint data from the
audio. Returns a byte string of fingerprint data. Raises an
ExtractionError if fingerprinting fails.
### Response:
def extract(pcmiter, samplerate, channels, duration = -1):
"""Gi... |
def whitelist_method_generator(base, klass, whitelist):
"""
Yields all GroupBy member defs for DataFrame/Series names in whitelist.
Parameters
----------
base : class
base class
klass : class
class where members are defined.
Should be Series or DataFrame
whitelist : ... | Yields all GroupBy member defs for DataFrame/Series names in whitelist.
Parameters
----------
base : class
base class
klass : class
class where members are defined.
Should be Series or DataFrame
whitelist : list
list of names of klass methods to be constructed
R... | Below is the the instruction that describes the task:
### Input:
Yields all GroupBy member defs for DataFrame/Series names in whitelist.
Parameters
----------
base : class
base class
klass : class
class where members are defined.
Should be Series or DataFrame
whitelist :... |
def get_placeholder_formats_list(self, format_string):
"""
Parses the format_string and returns a list of tuples
(placeholder, format).
"""
placeholders = []
# Tokenize the format string and process them
for token in self.tokens(format_string):
if toke... | Parses the format_string and returns a list of tuples
(placeholder, format). | Below is the the instruction that describes the task:
### Input:
Parses the format_string and returns a list of tuples
(placeholder, format).
### Response:
def get_placeholder_formats_list(self, format_string):
"""
Parses the format_string and returns a list of tuples
(placeholder, ... |
def on_resize(self, event):
"""Resize handler
Parameters
----------
event : instance of Event
The resize event.
"""
self._update_transforms()
if self._central_widget is not None:
self._central_widget.size = self.size
... | Resize handler
Parameters
----------
event : instance of Event
The resize event. | Below is the the instruction that describes the task:
### Input:
Resize handler
Parameters
----------
event : instance of Event
The resize event.
### Response:
def on_resize(self, event):
"""Resize handler
Parameters
----------
event : instance ... |
def get_asset_notification_session(self, asset_receiver):
"""Gets the notification session for notifications pertaining to asset changes.
arg: asset_receiver (osid.repository.AssetReceiver): the
notification callback
return: (osid.repository.AssetNotificationSession) - an
... | Gets the notification session for notifications pertaining to asset changes.
arg: asset_receiver (osid.repository.AssetReceiver): the
notification callback
return: (osid.repository.AssetNotificationSession) - an
``AssetNotificationSession``
raise: NullArgumen... | Below is the the instruction that describes the task:
### Input:
Gets the notification session for notifications pertaining to asset changes.
arg: asset_receiver (osid.repository.AssetReceiver): the
notification callback
return: (osid.repository.AssetNotificationSession) - an
... |
def _chk_docopt_kws(self, docdict, exp):
"""Check for common user errors when running from the command-line."""
for key, val in docdict.items():
if isinstance(val, str):
assert '=' not in val, self._err("'=' FOUND IN VALUE", key, val, exp)
elif key != 'help' and k... | Check for common user errors when running from the command-line. | Below is the the instruction that describes the task:
### Input:
Check for common user errors when running from the command-line.
### Response:
def _chk_docopt_kws(self, docdict, exp):
"""Check for common user errors when running from the command-line."""
for key, val in docdict.items():
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.