code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def copy(self, object_version=None, key=None):
"""Copy a tag to a given object version.
:param object_version: The object version instance to copy the tag to.
Default: current object version.
:param key: Key of destination tag.
Default: current tag key.
:return: ... | Copy a tag to a given object version.
:param object_version: The object version instance to copy the tag to.
Default: current object version.
:param key: Key of destination tag.
Default: current tag key.
:return: The copied object version tag. | Below is the the instruction that describes the task:
### Input:
Copy a tag to a given object version.
:param object_version: The object version instance to copy the tag to.
Default: current object version.
:param key: Key of destination tag.
Default: current tag key.
... |
def snapshot(gta, plotter, key, do_weighted=True, make_plots=True):
"""Take a snapshot of the ROI
Parameters
----------
gta : `fermipy.GTAnalysis`
The analysis object
plotter : `fermipy.plotting.AnalysisPlotter`
The object that makes the plots
key : str
Key for this s... | Take a snapshot of the ROI
Parameters
----------
gta : `fermipy.GTAnalysis`
The analysis object
plotter : `fermipy.plotting.AnalysisPlotter`
The object that makes the plots
key : str
Key for this snapshot, used to create filenames
do_weighted : bool
If True, ... | Below is the the instruction that describes the task:
### Input:
Take a snapshot of the ROI
Parameters
----------
gta : `fermipy.GTAnalysis`
The analysis object
plotter : `fermipy.plotting.AnalysisPlotter`
The object that makes the plots
key : str
Key for this snapsho... |
def run(self):
"""Run command."""
onnx_script = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "tools/mypy-onnx.py"))
returncode = subprocess.call([sys.executable, onnx_script])
sys.exit(returncode) | Run command. | Below is the the instruction that describes the task:
### Input:
Run command.
### Response:
def run(self):
"""Run command."""
onnx_script = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "tools/mypy-onnx.py"))
returncode = subprocess.call([sys.executable, onnx_scr... |
def walk_interface(self, name, data, in_location):
interface = Interface()
location = "{}.{}".format(in_location, name)
if isinstance(data, dict):
interface.name = de_identifier(self.require_field(location, "name", data, "", str))
location = "{}.{}".format(in_location, cl... | self.require_field("url", "{}.url".format(location), data, str)
self.require_field("verb", "{}.verb".format(location), data, set(("get", "post", "delete", "put")))
self.recommend_field("format", "{}.format".format(location), data, set(("json", "xml", "html", "csv", "text")), not_found="Assuming ... | Below is the the instruction that describes the task:
### Input:
self.require_field("url", "{}.url".format(location), data, str)
self.require_field("verb", "{}.verb".format(location), data, set(("get", "post", "delete", "put")))
self.recommend_field("format", "{}.format".format(location), da... |
def is_token_from_emulator(auth_header: str) -> bool:
""" Determines if a given Auth header is from the Bot Framework Emulator
:param auth_header: Bearer Token, in the 'Bearer [Long String]' Format.
:type auth_header: str
:return: True, if the token was issued by the Emulator. Otherwis... | Determines if a given Auth header is from the Bot Framework Emulator
:param auth_header: Bearer Token, in the 'Bearer [Long String]' Format.
:type auth_header: str
:return: True, if the token was issued by the Emulator. Otherwise, false. | Below is the the instruction that describes the task:
### Input:
Determines if a given Auth header is from the Bot Framework Emulator
:param auth_header: Bearer Token, in the 'Bearer [Long String]' Format.
:type auth_header: str
:return: True, if the token was issued by the Emulator. Other... |
def _rewrite_ser_data(self, ser, series_data, date_1904):
"""
Rewrite the ``<c:tx>``, ``<c:xVal>`` and ``<c:yVal>`` child elements
of *ser* based on the values in *series_data*.
"""
ser._remove_tx()
ser._remove_xVal()
ser._remove_yVal()
xml_writer = _XySe... | Rewrite the ``<c:tx>``, ``<c:xVal>`` and ``<c:yVal>`` child elements
of *ser* based on the values in *series_data*. | Below is the the instruction that describes the task:
### Input:
Rewrite the ``<c:tx>``, ``<c:xVal>`` and ``<c:yVal>`` child elements
of *ser* based on the values in *series_data*.
### Response:
def _rewrite_ser_data(self, ser, series_data, date_1904):
"""
Rewrite the ``<c:tx>``, ``<c:xVal>... |
def from_hdf(cls, filename):
"""Load camera model params from a HDF5 file
The HDF5 file should contain the following datasets:
wc : (2,) float with distortion center
lgamma : float distortion parameter
readout : float readout value
size : (2,) int image s... | Load camera model params from a HDF5 file
The HDF5 file should contain the following datasets:
wc : (2,) float with distortion center
lgamma : float distortion parameter
readout : float readout value
size : (2,) int image size
fps : float frame rate
... | Below is the the instruction that describes the task:
### Input:
Load camera model params from a HDF5 file
The HDF5 file should contain the following datasets:
wc : (2,) float with distortion center
lgamma : float distortion parameter
readout : float readout value
... |
def connect(self, agent='Python'):
"""
Context manager for HTTP Connection state and ensures proper handling
of network sockets, sends a GET request.
Exception is raised at the yield statement.
:yield request: FileIO<Socket>
"""
headers = {'User-Agent': agent}
... | Context manager for HTTP Connection state and ensures proper handling
of network sockets, sends a GET request.
Exception is raised at the yield statement.
:yield request: FileIO<Socket> | Below is the the instruction that describes the task:
### Input:
Context manager for HTTP Connection state and ensures proper handling
of network sockets, sends a GET request.
Exception is raised at the yield statement.
:yield request: FileIO<Socket>
### Response:
def connect(self, agent=... |
def _create_pipeline_parser():
""" Create the parser for the %pipeline magics.
Note that because we use the func default handler dispatch mechanism of
argparse, our handlers can take only one argument which is the parsed args. So
we must create closures for the handlers that bind the cell contents and th... | Create the parser for the %pipeline magics.
Note that because we use the func default handler dispatch mechanism of
argparse, our handlers can take only one argument which is the parsed args. So
we must create closures for the handlers that bind the cell contents and thus
must recreate this parser for ... | Below is the the instruction that describes the task:
### Input:
Create the parser for the %pipeline magics.
Note that because we use the func default handler dispatch mechanism of
argparse, our handlers can take only one argument which is the parsed args. So
we must create closures for the handlers th... |
def done(message):
"""Create a Deleted response builder with specified message."""
def done(value, _context, **_params):
return Done(value, message)
return done | Create a Deleted response builder with specified message. | Below is the the instruction that describes the task:
### Input:
Create a Deleted response builder with specified message.
### Response:
def done(message):
"""Create a Deleted response builder with specified message."""
def done(value, _context, **_params):
return Done(value, message)
return ... |
def complete(self, text, state):
'''
Alternate entry point for using the argcomplete completer in a readline-based REPL. See also
`rlcompleter <https://docs.python.org/2/library/rlcompleter.html#completer-objects>`_.
Usage:
.. code-block:: python
import argcomplete... | Alternate entry point for using the argcomplete completer in a readline-based REPL. See also
`rlcompleter <https://docs.python.org/2/library/rlcompleter.html#completer-objects>`_.
Usage:
.. code-block:: python
import argcomplete, argparse, readline
parser = argparse.Ar... | Below is the the instruction that describes the task:
### Input:
Alternate entry point for using the argcomplete completer in a readline-based REPL. See also
`rlcompleter <https://docs.python.org/2/library/rlcompleter.html#completer-objects>`_.
Usage:
.. code-block:: python
im... |
def siteblock(parser, token):
"""Two notation types are acceptable:
1. Two arguments:
{% siteblock "myblock" %}
Used to render "myblock" site block.
2. Four arguments:
{% siteblock "myblock" as myvar %}
Used to put "myblock" site block into "m... | Two notation types are acceptable:
1. Two arguments:
{% siteblock "myblock" %}
Used to render "myblock" site block.
2. Four arguments:
{% siteblock "myblock" as myvar %}
Used to put "myblock" site block into "myvar" template variable. | Below is the the instruction that describes the task:
### Input:
Two notation types are acceptable:
1. Two arguments:
{% siteblock "myblock" %}
Used to render "myblock" site block.
2. Four arguments:
{% siteblock "myblock" as myvar %}
Used to ... |
def get(self, timeout=None):
"""Retrieve results from all the output tubes."""
valid = False
result = None
for tube in self._output_tubes:
if timeout:
valid, result = tube.get(timeout)
if valid:
result = result[0]
... | Retrieve results from all the output tubes. | Below is the the instruction that describes the task:
### Input:
Retrieve results from all the output tubes.
### Response:
def get(self, timeout=None):
"""Retrieve results from all the output tubes."""
valid = False
result = None
for tube in self._output_tubes:
if timeou... |
def stop(self):
"""Close serial port."""
self.logger.warning("Stop executed")
try:
self._reader.close()
except serial.serialutil.SerialException:
self.logger.error("Error while closing device")
raise VelbusException("Error while closing device")
... | Close serial port. | Below is the the instruction that describes the task:
### Input:
Close serial port.
### Response:
def stop(self):
"""Close serial port."""
self.logger.warning("Stop executed")
try:
self._reader.close()
except serial.serialutil.SerialException:
self.logger.err... |
def save_beat(
self,
output_file_name,
frequencys,
play_time,
sample_rate=44100,
volume=0.01
):
'''
引数で指定した条件でビートを鳴らす
Args:
frequencys: (左の周波数(Hz), 右の周波数(Hz))のtuple
play_time: 再生時間(秒)
... | 引数で指定した条件でビートを鳴らす
Args:
frequencys: (左の周波数(Hz), 右の周波数(Hz))のtuple
play_time: 再生時間(秒)
sample_rate: サンプルレート
volume: 音量
Returns:
void | Below is the the instruction that describes the task:
### Input:
引数で指定した条件でビートを鳴らす
Args:
frequencys: (左の周波数(Hz), 右の周波数(Hz))のtuple
play_time: 再生時間(秒)
sample_rate: サンプルレート
volume: 音量
Returns:
void
### Response: ... |
def writeExpression(self, rnaQuantificationId, quantfilename):
"""
Reads the quantification results file and adds entries to the
specified database.
"""
isNormalized = self._isNormalized
units = self._units
with open(quantfilename, "r") as quantFile:
q... | Reads the quantification results file and adds entries to the
specified database. | Below is the the instruction that describes the task:
### Input:
Reads the quantification results file and adds entries to the
specified database.
### Response:
def writeExpression(self, rnaQuantificationId, quantfilename):
"""
Reads the quantification results file and adds entries to the
... |
def choices(self):
"""Gets the experiment choices"""
if self._choices == None:
self._choices = [ExperimentChoice(self, choice_name) for choice_name in self.choice_names]
return self._choices | Gets the experiment choices | Below is the the instruction that describes the task:
### Input:
Gets the experiment choices
### Response:
def choices(self):
"""Gets the experiment choices"""
if self._choices == None:
self._choices = [ExperimentChoice(self, choice_name) for choice_name in self.choice_names]
... |
def discrete_binary_search(tab, lo, hi):
"""Binary search in a table
:param tab: boolean monotone table with tab[hi] = True
:param int lo:
:param int hi: with hi >= lo
:returns: first index i in [lo,hi] such that tab[i]
:complexity: `O(log(hi-lo))`
"""
while lo < hi:
mid = lo + ... | Binary search in a table
:param tab: boolean monotone table with tab[hi] = True
:param int lo:
:param int hi: with hi >= lo
:returns: first index i in [lo,hi] such that tab[i]
:complexity: `O(log(hi-lo))` | Below is the the instruction that describes the task:
### Input:
Binary search in a table
:param tab: boolean monotone table with tab[hi] = True
:param int lo:
:param int hi: with hi >= lo
:returns: first index i in [lo,hi] such that tab[i]
:complexity: `O(log(hi-lo))`
### Response:
def discre... |
def build_rectangle_dict(self,
north,
west,
south,
east,
stroke_color='#FF0000',
stroke_opacity=.8,
stroke_weight=2,
... | Set a dictionary with the javascript class Rectangle parameters
This function sets a default drawing configuration if the user just
pass the rectangle bounds, but also allows to set each parameter
individually if the user wish so.
Args:
north (float): The north latitude bou... | Below is the the instruction that describes the task:
### Input:
Set a dictionary with the javascript class Rectangle parameters
This function sets a default drawing configuration if the user just
pass the rectangle bounds, but also allows to set each parameter
individually if the user wish... |
def notify(self, subsystem, recipient, subject, body_html, body_text):
"""You can send messages either to channels and private groups by using the following formats
#channel-name
@username-direct-message
Args:
subsystem (`str`): Name of the subsystem originating the notific... | You can send messages either to channels and private groups by using the following formats
#channel-name
@username-direct-message
Args:
subsystem (`str`): Name of the subsystem originating the notification
recipient (`str`): Recipient
subject (`str`): Subjec... | Below is the the instruction that describes the task:
### Input:
You can send messages either to channels and private groups by using the following formats
#channel-name
@username-direct-message
Args:
subsystem (`str`): Name of the subsystem originating the notification
... |
def stop(self):
"""
Terminate any outstanding requests.
:returns: :class:``Deferred` which fires when fully stopped.
"""
self.stopping = True
# Cancel any outstanding request to our client
if self._batch_send_d:
self._batch_send_d.cancel()
# D... | Terminate any outstanding requests.
:returns: :class:``Deferred` which fires when fully stopped. | Below is the the instruction that describes the task:
### Input:
Terminate any outstanding requests.
:returns: :class:``Deferred` which fires when fully stopped.
### Response:
def stop(self):
"""
Terminate any outstanding requests.
:returns: :class:``Deferred` which fires when ful... |
def _set_nport_menu(self, v, load=False):
"""
Setter method for nport_menu, mapped from YANG variable /rbridge_id/ag/nport_menu (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_nport_menu is considered as a private
method. Backends looking to populate this... | Setter method for nport_menu, mapped from YANG variable /rbridge_id/ag/nport_menu (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_nport_menu is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_np... | Below is the the instruction that describes the task:
### Input:
Setter method for nport_menu, mapped from YANG variable /rbridge_id/ag/nport_menu (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_nport_menu is considered as a private
method. Backends looking t... |
def set_topological_dag_upstreams(dag, ops, op_runs, runs_by_ops):
"""Set the upstream runs for the operation runs in the dag following the topological sort."""
sorted_ops = dags.sort_topologically(dag=dag)
for op_id in sorted_ops:
op_run_id = runs_by_ops[op_id]
op_run = op_runs[op_run_id]
... | Set the upstream runs for the operation runs in the dag following the topological sort. | Below is the the instruction that describes the task:
### Input:
Set the upstream runs for the operation runs in the dag following the topological sort.
### Response:
def set_topological_dag_upstreams(dag, ops, op_runs, runs_by_ops):
"""Set the upstream runs for the operation runs in the dag following the topo... |
def epiweeks_in_year(year: int) -> int:
"""
Return number of epiweeks in a year
"""
if date_to_epiweek(epiweek_to_date(Epiweek(year, 53))).year == year:
return 53
else:
return 52 | Return number of epiweeks in a year | Below is the the instruction that describes the task:
### Input:
Return number of epiweeks in a year
### Response:
def epiweeks_in_year(year: int) -> int:
"""
Return number of epiweeks in a year
"""
if date_to_epiweek(epiweek_to_date(Epiweek(year, 53))).year == year:
return 53
else:
... |
def provider(self, value):
"""
Validate and set a WMI provider. Default to `ProviderArchitecture.DEFAULT`
"""
result = None
# `None` defaults to `ProviderArchitecture.DEFAULT`
defaulted_value = value or ProviderArchitecture.DEFAULT
try:
parsed_value ... | Validate and set a WMI provider. Default to `ProviderArchitecture.DEFAULT` | Below is the the instruction that describes the task:
### Input:
Validate and set a WMI provider. Default to `ProviderArchitecture.DEFAULT`
### Response:
def provider(self, value):
"""
Validate and set a WMI provider. Default to `ProviderArchitecture.DEFAULT`
"""
result = None
... |
def format_exception(cls, instance, trcback, context=1):
"""
| Formats given exception.
| The code produce a similar output to :func:`traceback.format_exception` except that it allows frames to be excluded
from the stack if the given stack trace frame tag is found in the frame locals and set **True*... | | Formats given exception.
| The code produce a similar output to :func:`traceback.format_exception` except that it allows frames to be excluded
from the stack if the given stack trace frame tag is found in the frame locals and set **True**.
:param cls: Exception class.
:type cls: object
:param... | Below is the the instruction that describes the task:
### Input:
| Formats given exception.
| The code produce a similar output to :func:`traceback.format_exception` except that it allows frames to be excluded
from the stack if the given stack trace frame tag is found in the frame locals and set **True*... |
def get_sheet_list(xl_path: str) -> List:
"""Return a list with the name of the sheets in
the Excel file in `xl_path`.
"""
wb = read_xl(xl_path)
if hasattr(wb, 'sheetnames'):
return wb.sheetnames
else:
return wb.sheet_names() | Return a list with the name of the sheets in
the Excel file in `xl_path`. | Below is the the instruction that describes the task:
### Input:
Return a list with the name of the sheets in
the Excel file in `xl_path`.
### Response:
def get_sheet_list(xl_path: str) -> List:
"""Return a list with the name of the sheets in
the Excel file in `xl_path`.
"""
wb = read_xl(xl_pat... |
def extract(self, dest_fldr, password=''):
"""
unzip the file contents to the dest_folder
(create if it doesn't exist)
and then return the list of files extracted
"""
#print('extracting to ' + dest_fldr)
if self.type == 'ZIP':
self._extract_zip(dest_fl... | unzip the file contents to the dest_folder
(create if it doesn't exist)
and then return the list of files extracted | Below is the the instruction that describes the task:
### Input:
unzip the file contents to the dest_folder
(create if it doesn't exist)
and then return the list of files extracted
### Response:
def extract(self, dest_fldr, password=''):
"""
unzip the file contents to the dest_folde... |
def insert(self, matcher, obj):
'''
Insert a new matcher
:param matcher: an EventMatcher
:param obj: object to return
'''
current = self.subtree(matcher, True)
#current.matchers[(obj, matcher)] = None
if current._use_dict:
cur... | Insert a new matcher
:param matcher: an EventMatcher
:param obj: object to return | Below is the the instruction that describes the task:
### Input:
Insert a new matcher
:param matcher: an EventMatcher
:param obj: object to return
### Response:
def insert(self, matcher, obj):
'''
Insert a new matcher
:param matcher: an EventMatche... |
def config(name='DATABASE_URL', default='sqlite://:memory:'):
"""Returns configured DATABASE dictionary from DATABASE_URL."""
config = {}
s = env(name, default)
if s:
config = parse_database_url(s)
return config | Returns configured DATABASE dictionary from DATABASE_URL. | Below is the the instruction that describes the task:
### Input:
Returns configured DATABASE dictionary from DATABASE_URL.
### Response:
def config(name='DATABASE_URL', default='sqlite://:memory:'):
"""Returns configured DATABASE dictionary from DATABASE_URL."""
config = {}
s = env(name, default)
i... |
def process_ssh(self, data, name):
"""
Processes SSH keys
:param data:
:param name:
:return:
"""
if data is None or len(data) == 0:
return
ret = []
try:
lines = [x.strip() for x in data.split(b'\n')]
for idx, li... | Processes SSH keys
:param data:
:param name:
:return: | Below is the the instruction that describes the task:
### Input:
Processes SSH keys
:param data:
:param name:
:return:
### Response:
def process_ssh(self, data, name):
"""
Processes SSH keys
:param data:
:param name:
:return:
"""
if da... |
def is_lower(self):
"""Asserts that val is non-empty string and all characters are lowercase."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if len(self.val) == 0:
raise ValueError('val is empty')
if self.val != self.val.lower():... | Asserts that val is non-empty string and all characters are lowercase. | Below is the the instruction that describes the task:
### Input:
Asserts that val is non-empty string and all characters are lowercase.
### Response:
def is_lower(self):
"""Asserts that val is non-empty string and all characters are lowercase."""
if not isinstance(self.val, str_types):
... |
def idle_send_acks_and_nacks(self):
'''Send packets to UAV in idle loop'''
max_blocks_to_send = 10
blocks_sent = 0
i=0
now = time.time()
while i < len(self.blocks_to_ack_and_nack) and blocks_sent < max_blocks_to_send:
# print("ACKLIST: %s" % ([x[1] for x in sel... | Send packets to UAV in idle loop | Below is the the instruction that describes the task:
### Input:
Send packets to UAV in idle loop
### Response:
def idle_send_acks_and_nacks(self):
'''Send packets to UAV in idle loop'''
max_blocks_to_send = 10
blocks_sent = 0
i=0
now = time.time()
while i < len(self... |
def list_all_option_values(cls, **kwargs):
"""List OptionValues
Return a list of OptionValues
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_option_values(async=True)
>>> res... | List OptionValues
Return a list of OptionValues
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_option_values(async=True)
>>> result = thread.get()
:param async bool
... | Below is the the instruction that describes the task:
### Input:
List OptionValues
Return a list of OptionValues
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_option_values(async=True)
... |
def _delta_t_supconj_perpass(period, ecc, per0):
"""
time shift between superior conjuction and periastron passage
"""
ups_sc = np.pi/2-per0
E_sc = 2*np.arctan( np.sqrt((1-ecc)/(1+ecc)) * np.tan(ups_sc/2) )
M_sc = E_sc - ecc*np.sin(E_sc)
return period*(M_sc/2./np.pi) | time shift between superior conjuction and periastron passage | Below is the the instruction that describes the task:
### Input:
time shift between superior conjuction and periastron passage
### Response:
def _delta_t_supconj_perpass(period, ecc, per0):
"""
time shift between superior conjuction and periastron passage
"""
ups_sc = np.pi/2-per0
E_sc = 2*np.a... |
def ToolMatches(tools=None, version='HEAD'):
""" Get the tools paths and versions that were specified """
matches = []
if tools:
for tool in tools:
match_version = version
if tool[1] != '':
match_version = tool[1]
match = ''
if tool[0].... | Get the tools paths and versions that were specified | Below is the the instruction that describes the task:
### Input:
Get the tools paths and versions that were specified
### Response:
def ToolMatches(tools=None, version='HEAD'):
""" Get the tools paths and versions that were specified """
matches = []
if tools:
for tool in tools:
mat... |
def switch_tab(self):
"""
takes care of the action that happen when switching between tabs
e.g. activates and deactives probes
"""
current_tab = str(self.tabWidget.tabText(self.tabWidget.currentIndex()))
if self.current_script is None:
if current_tab == 'Probe... | takes care of the action that happen when switching between tabs
e.g. activates and deactives probes | Below is the the instruction that describes the task:
### Input:
takes care of the action that happen when switching between tabs
e.g. activates and deactives probes
### Response:
def switch_tab(self):
"""
takes care of the action that happen when switching between tabs
e.g. activat... |
def distort(value):
"""
Distorts a string by randomly replacing characters in it.
:param value: a string to distort.
:return: a distored string.
"""
value = value.lower()
if (RandomBoolean.chance(1, 5)):
value = value[0:1].upper() + value[1:]
... | Distorts a string by randomly replacing characters in it.
:param value: a string to distort.
:return: a distored string. | Below is the the instruction that describes the task:
### Input:
Distorts a string by randomly replacing characters in it.
:param value: a string to distort.
:return: a distored string.
### Response:
def distort(value):
"""
Distorts a string by randomly replacing characters in it.... |
def _normalize_cwl_inputs(items):
"""Extract variation and validation data from CWL input list of batched samples.
"""
with_validate = {}
vrn_files = []
ready_items = []
batch_samples = []
for data in (cwlutils.normalize_missing(utils.to_single_data(d)) for d in items):
batch_samples... | Extract variation and validation data from CWL input list of batched samples. | Below is the the instruction that describes the task:
### Input:
Extract variation and validation data from CWL input list of batched samples.
### Response:
def _normalize_cwl_inputs(items):
"""Extract variation and validation data from CWL input list of batched samples.
"""
with_validate = {}
vrn_... |
def find_name(tagtype: str, name: str, language: {str, 'Language', None}=None):
"""
Find the subtag of a particular `tagtype` that has the given `name`.
The default language, "und", will allow matching names in any language,
so you can get the code 'fr' by looking up "French", "Français... | Find the subtag of a particular `tagtype` that has the given `name`.
The default language, "und", will allow matching names in any language,
so you can get the code 'fr' by looking up "French", "Français", or
"francés".
Occasionally, names are ambiguous in a way that can be resolved by... | Below is the the instruction that describes the task:
### Input:
Find the subtag of a particular `tagtype` that has the given `name`.
The default language, "und", will allow matching names in any language,
so you can get the code 'fr' by looking up "French", "Français", or
"francés".
... |
def query(cls, database, map_fun, reduce_fun,
language='javascript', **options):
"""Execute a CouchDB temporary view and map the result values back to
objects of this mapping.
Note that by default, any properties of the document that are not
included in the values of the v... | Execute a CouchDB temporary view and map the result values back to
objects of this mapping.
Note that by default, any properties of the document that are not
included in the values of the view will be treated as if they were
missing from the document. If you want to load the full docume... | Below is the the instruction that describes the task:
### Input:
Execute a CouchDB temporary view and map the result values back to
objects of this mapping.
Note that by default, any properties of the document that are not
included in the values of the view will be treated as if they were
... |
def get_key_signature_accidentals(key='C'):
"""Return the list of accidentals present into the key signature."""
accidentals = get_key_signature(key)
res = []
if accidentals < 0:
for i in range(-accidentals):
res.append('{0}{1}'.format(list(reversed(notes.fifths))[i], 'b'))
elif... | Return the list of accidentals present into the key signature. | Below is the the instruction that describes the task:
### Input:
Return the list of accidentals present into the key signature.
### Response:
def get_key_signature_accidentals(key='C'):
"""Return the list of accidentals present into the key signature."""
accidentals = get_key_signature(key)
res = []
... |
def Sphere(pos=(0, 0, 0), r=1, c="r", alpha=1, res=24):
"""Build a sphere at position `pos` of radius `r`.
|Sphere|
"""
ss = vtk.vtkSphereSource()
ss.SetRadius(r)
ss.SetThetaResolution(2 * res)
ss.SetPhiResolution(res)
ss.Update()
pd = ss.GetOutput()
actor = Actor(pd, c, alp... | Build a sphere at position `pos` of radius `r`.
|Sphere| | Below is the the instruction that describes the task:
### Input:
Build a sphere at position `pos` of radius `r`.
|Sphere|
### Response:
def Sphere(pos=(0, 0, 0), r=1, c="r", alpha=1, res=24):
"""Build a sphere at position `pos` of radius `r`.
|Sphere|
"""
ss = vtk.vtkSphereSource()
... |
def on_message(self, headers, message):
"""
Event method that gets called when this listener has received a JMS
message (representing an HMC notification).
Parameters:
headers (dict): JMS message headers, as described for `headers` tuple
item returned by the
... | Event method that gets called when this listener has received a JMS
message (representing an HMC notification).
Parameters:
headers (dict): JMS message headers, as described for `headers` tuple
item returned by the
:meth:`~zhmcclient.NotificationReceiver.notifications... | Below is the the instruction that describes the task:
### Input:
Event method that gets called when this listener has received a JMS
message (representing an HMC notification).
Parameters:
headers (dict): JMS message headers, as described for `headers` tuple
item returned by ... |
def constant_tuples_ordered_by_id(self):
"""
Returns
-------
constants: [(str, Constant)]
A list of tuples mapping strings to constants constants ordered by id
"""
return sorted(list(self.constant_tuple_dict), key=lambda constant_tuple: constant_tuple.constant... | Returns
-------
constants: [(str, Constant)]
A list of tuples mapping strings to constants constants ordered by id | Below is the the instruction that describes the task:
### Input:
Returns
-------
constants: [(str, Constant)]
A list of tuples mapping strings to constants constants ordered by id
### Response:
def constant_tuples_ordered_by_id(self):
"""
Returns
-------
... |
def rgb2term(r: int, g: int, b: int) -> str:
""" Convert an rgb value to a terminal code. """
return hex2term_map[rgb2termhex(r, g, b)] | Convert an rgb value to a terminal code. | Below is the the instruction that describes the task:
### Input:
Convert an rgb value to a terminal code.
### Response:
def rgb2term(r: int, g: int, b: int) -> str:
""" Convert an rgb value to a terminal code. """
return hex2term_map[rgb2termhex(r, g, b)] |
async def get_prefix(self, message):
"""|coro|
Retrieves the prefix the bot is listening to
with the message as a context.
Parameters
-----------
message: :class:`discord.Message`
The message context to get the prefix of.
Returns
--------
... | |coro|
Retrieves the prefix the bot is listening to
with the message as a context.
Parameters
-----------
message: :class:`discord.Message`
The message context to get the prefix of.
Returns
--------
Union[List[:class:`str`], :class:`str`]
... | Below is the the instruction that describes the task:
### Input:
|coro|
Retrieves the prefix the bot is listening to
with the message as a context.
Parameters
-----------
message: :class:`discord.Message`
The message context to get the prefix of.
Return... |
def get_token_stream(source: str) -> CommonTokenStream:
""" Get the antlr token stream.
"""
lexer = LuaLexer(InputStream(source))
stream = CommonTokenStream(lexer)
return stream | Get the antlr token stream. | Below is the the instruction that describes the task:
### Input:
Get the antlr token stream.
### Response:
def get_token_stream(source: str) -> CommonTokenStream:
""" Get the antlr token stream.
"""
lexer = LuaLexer(InputStream(source))
stream = CommonTokenStream(lexer)
return stream |
def _parse_alt_title(html_chunk):
"""
Parse title from alternative location if not found where it should be.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str: Book's title.
"""
title = html_chunk.find("img", fn=has_param("alt"))
i... | Parse title from alternative location if not found where it should be.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str: Book's title. | Below is the the instruction that describes the task:
### Input:
Parse title from alternative location if not found where it should be.
Args:
html_chunk (obj): HTMLElement containing slice of the page with details.
Returns:
str: Book's title.
### Response:
def _parse_alt_title(html_chunk)... |
def _create_more_application():
"""
Create an `Application` instance that displays the "--MORE--".
"""
from prompt_toolkit.shortcuts import create_prompt_application
registry = Registry()
@registry.add_binding(' ')
@registry.add_binding('y')
@registry.add_binding('Y')
@registry.add_... | Create an `Application` instance that displays the "--MORE--". | Below is the the instruction that describes the task:
### Input:
Create an `Application` instance that displays the "--MORE--".
### Response:
def _create_more_application():
"""
Create an `Application` instance that displays the "--MORE--".
"""
from prompt_toolkit.shortcuts import create_prompt_app... |
def join_states(*states: State) -> State:
"""Join two state vectors into a larger qubit state"""
vectors = [ket.vec for ket in states]
vec = reduce(outer_product, vectors)
return State(vec.tensor, vec.qubits) | Join two state vectors into a larger qubit state | Below is the the instruction that describes the task:
### Input:
Join two state vectors into a larger qubit state
### Response:
def join_states(*states: State) -> State:
"""Join two state vectors into a larger qubit state"""
vectors = [ket.vec for ket in states]
vec = reduce(outer_product, vectors)
... |
def expand_date_param(param, lower_upper):
"""
Expands a (possibly) incomplete date string to either the lowest
or highest possible contained date and returns
datetime.datetime for that string.
0753 (lower) => 0753-01-01
2012 (upper) => 2012-12-31
2012 (lower) => 2012-01-01
201208 (uppe... | Expands a (possibly) incomplete date string to either the lowest
or highest possible contained date and returns
datetime.datetime for that string.
0753 (lower) => 0753-01-01
2012 (upper) => 2012-12-31
2012 (lower) => 2012-01-01
201208 (upper) => 2012-08-31
etc. | Below is the the instruction that describes the task:
### Input:
Expands a (possibly) incomplete date string to either the lowest
or highest possible contained date and returns
datetime.datetime for that string.
0753 (lower) => 0753-01-01
2012 (upper) => 2012-12-31
2012 (lower) => 2012-01-01
... |
def get_nodes(self):
"""
Get the list of all nodes.
"""
return self.fold_up(lambda n, fl, fg: [n] + fl + fg, lambda leaf: [leaf]) | Get the list of all nodes. | Below is the the instruction that describes the task:
### Input:
Get the list of all nodes.
### Response:
def get_nodes(self):
"""
Get the list of all nodes.
"""
return self.fold_up(lambda n, fl, fg: [n] + fl + fg, lambda leaf: [leaf]) |
def create(**kwargs):
"""
Create and a return a specialized contract based on the given secType,
or a general Contract if secType is not given.
"""
secType = kwargs.get('secType', '')
cls = {
'': Contract,
'STK': Stock,
'OPT': Option,
... | Create and a return a specialized contract based on the given secType,
or a general Contract if secType is not given. | Below is the the instruction that describes the task:
### Input:
Create and a return a specialized contract based on the given secType,
or a general Contract if secType is not given.
### Response:
def create(**kwargs):
"""
Create and a return a specialized contract based on the given secTyp... |
def _cleanup(self, lr_decay_opt_states_reset: str, process_manager: Optional['DecoderProcessManager'] = None,
keep_training_state = False):
"""
Cleans parameter files, training state directory and waits for remaining decoding processes.
"""
utils.cleanup_params_files(sel... | Cleans parameter files, training state directory and waits for remaining decoding processes. | Below is the the instruction that describes the task:
### Input:
Cleans parameter files, training state directory and waits for remaining decoding processes.
### Response:
def _cleanup(self, lr_decay_opt_states_reset: str, process_manager: Optional['DecoderProcessManager'] = None,
keep_training_st... |
def do_help(self, arg):
"""Sets up the header for the help command that explains the background on how to use
the script generally. Help for each command then stands alone in the context of this
documentation. Although we could have documented this on the wiki, it is better served
when s... | Sets up the header for the help command that explains the background on how to use
the script generally. Help for each command then stands alone in the context of this
documentation. Although we could have documented this on the wiki, it is better served
when shipped with the shell. | Below is the the instruction that describes the task:
### Input:
Sets up the header for the help command that explains the background on how to use
the script generally. Help for each command then stands alone in the context of this
documentation. Although we could have documented this on the wiki, ... |
def execute(self,
command,
data=None,
returning=True,
mapper=dict,
writeAccess=False,
dryRun=False,
locale=None):
"""
Executes the inputted command into the current \
connection cursor... | Executes the inputted command into the current \
connection cursor.
:param command | <str>
data | <dict> || None
autoCommit | <bool> | commit database changes immediately
autoClose | <bool> | closes connections immediately
... | Below is the the instruction that describes the task:
### Input:
Executes the inputted command into the current \
connection cursor.
:param command | <str>
data | <dict> || None
autoCommit | <bool> | commit database changes immediately
... |
def get_line_data(self):
"""Return the line data collected.
Data is { filename: { lineno: None, ...}, ...}
"""
if self.branch:
# If we were measuring branches, then we have to re-build the dict
# to show line data.
line_data = {}
for f, a... | Return the line data collected.
Data is { filename: { lineno: None, ...}, ...} | Below is the the instruction that describes the task:
### Input:
Return the line data collected.
Data is { filename: { lineno: None, ...}, ...}
### Response:
def get_line_data(self):
"""Return the line data collected.
Data is { filename: { lineno: None, ...}, ...}
"""
if ... |
def create(self, **attributes):
"""
Creates a new record suject to the restructions in the query and with
the passed +attributes+. Operates using `build`.
"""
record = self.build(**attributes)
record.save()
return record | Creates a new record suject to the restructions in the query and with
the passed +attributes+. Operates using `build`. | Below is the the instruction that describes the task:
### Input:
Creates a new record suject to the restructions in the query and with
the passed +attributes+. Operates using `build`.
### Response:
def create(self, **attributes):
"""
Creates a new record suject to the restructions in the qu... |
def __init_keystone_session(self):
"""Create and return a Keystone session object."""
api = self._identity_api_version # for readability
tried = []
if api in ['3', None]:
sess = self.__init_keystone_session_v3(check=(api is None))
tried.append('v3')
i... | Create and return a Keystone session object. | Below is the the instruction that describes the task:
### Input:
Create and return a Keystone session object.
### Response:
def __init_keystone_session(self):
"""Create and return a Keystone session object."""
api = self._identity_api_version # for readability
tried = []
if api in ... |
def mrz():
"""
Command-line script for extracting MRZ from a given image
"""
parser = argparse.ArgumentParser(description='Run the MRZ OCR recognition algorithm on the given image.')
parser.add_argument('filename')
parser.add_argument('--json', action='store_true', help='Produce JSON (rather tha... | Command-line script for extracting MRZ from a given image | Below is the the instruction that describes the task:
### Input:
Command-line script for extracting MRZ from a given image
### Response:
def mrz():
"""
Command-line script for extracting MRZ from a given image
"""
parser = argparse.ArgumentParser(description='Run the MRZ OCR recognition algorithm o... |
def _cutadapt_trim(fastq_files, quality_format, adapters, out_files, log_file, data):
"""Trimming with cutadapt.
"""
if all([utils.file_exists(x) for x in out_files]):
return out_files
cmd = _cutadapt_trim_cmd(fastq_files, quality_format, adapters, out_files, data)
if len(fastq_files) == 1:
... | Trimming with cutadapt. | Below is the the instruction that describes the task:
### Input:
Trimming with cutadapt.
### Response:
def _cutadapt_trim(fastq_files, quality_format, adapters, out_files, log_file, data):
"""Trimming with cutadapt.
"""
if all([utils.file_exists(x) for x in out_files]):
return out_files
cmd... |
def load_archive(archive_file: str,
cuda_device: int = -1,
overrides: str = "",
weights_file: str = None) -> Archive:
"""
Instantiates an Archive from an archived `tar.gz` file.
Parameters
----------
archive_file: ``str``
The archive file t... | Instantiates an Archive from an archived `tar.gz` file.
Parameters
----------
archive_file: ``str``
The archive file to load the model from.
weights_file: ``str``, optional (default = None)
The weights file to use. If unspecified, weights.th in the archive_file will be used.
cuda_d... | Below is the the instruction that describes the task:
### Input:
Instantiates an Archive from an archived `tar.gz` file.
Parameters
----------
archive_file: ``str``
The archive file to load the model from.
weights_file: ``str``, optional (default = None)
The weights file to use. If... |
def VectorLen(self, off):
"""VectorLen retrieves the length of the vector whose offset is stored
at "off" in this object."""
N.enforce_number(off, N.UOffsetTFlags)
off += self.Pos
off += encode.Get(N.UOffsetTFlags.packer_type, self.Bytes, off)
ret = encode.Get(N.UOffs... | VectorLen retrieves the length of the vector whose offset is stored
at "off" in this object. | Below is the the instruction that describes the task:
### Input:
VectorLen retrieves the length of the vector whose offset is stored
at "off" in this object.
### Response:
def VectorLen(self, off):
"""VectorLen retrieves the length of the vector whose offset is stored
at "off" in this... |
def in_miso_and_inner(self):
"""
Test if a node is miso: multiple input and single output
"""
return len(self.successor) == 1 and self.successor[0] is not None and not self.successor[0].in_or_out and \
len(self.precedence) > 1 and self.precedence[0] is not None and not sel... | Test if a node is miso: multiple input and single output | Below is the the instruction that describes the task:
### Input:
Test if a node is miso: multiple input and single output
### Response:
def in_miso_and_inner(self):
"""
Test if a node is miso: multiple input and single output
"""
return len(self.successor) == 1 and self.successor[0]... |
def deprecated_name(name):
"""Allow old method names for backwards compatability. """
def decorator(func):
"""Decorator function."""
def func_wrapper(self):
"""Wrapper for original function."""
if hasattr(self, name):
# Return the old property
... | Allow old method names for backwards compatability. | Below is the the instruction that describes the task:
### Input:
Allow old method names for backwards compatability.
### Response:
def deprecated_name(name):
"""Allow old method names for backwards compatability. """
def decorator(func):
"""Decorator function."""
def func_wrapper(self):
... |
def argv_parse(schema, argv, init=None,
arg_names=None, arg_abbrevs=None, value_parser=True, defaults=None, filters=None):
'''
argv_parse(schema, argv) yields the tuple (unparsed_argv, params) where unparsed_argv is a list
subset of argv that contains only those command line arguments that ... | argv_parse(schema, argv) yields the tuple (unparsed_argv, params) where unparsed_argv is a list
subset of argv that contains only those command line arguments that were not understood by
the given argument schema and params is a dictionary of parameters as parsed by the given
schema. It is equivalent... | Below is the the instruction that describes the task:
### Input:
argv_parse(schema, argv) yields the tuple (unparsed_argv, params) where unparsed_argv is a list
subset of argv that contains only those command line arguments that were not understood by
the given argument schema and params is a dictionary... |
def send_message(adu, serial_port):
""" Send ADU over serial to to server and return parsed response.
:param adu: Request ADU.
:param sock: Serial port instance.
:return: Parsed response from server.
"""
serial_port.write(adu)
serial_port.flush()
# Check exception ADU (which is shorter... | Send ADU over serial to to server and return parsed response.
:param adu: Request ADU.
:param sock: Serial port instance.
:return: Parsed response from server. | Below is the the instruction that describes the task:
### Input:
Send ADU over serial to to server and return parsed response.
:param adu: Request ADU.
:param sock: Serial port instance.
:return: Parsed response from server.
### Response:
def send_message(adu, serial_port):
""" Send ADU over seria... |
def cluster_template_events_single_ifo(
self, tcolumn, column, window_size, ifo):
""" Cluster the internal events over the named column
"""
# Just call through to the standard function
self.template_events = self.template_event_dict[ifo]
self.cluster_template_events(t... | Cluster the internal events over the named column | Below is the the instruction that describes the task:
### Input:
Cluster the internal events over the named column
### Response:
def cluster_template_events_single_ifo(
self, tcolumn, column, window_size, ifo):
""" Cluster the internal events over the named column
"""
# Just cal... |
def get_task_subtasks(client, task_id, completed=False):
''' Gets subtasks for task with given ID '''
params = {
'task_id' : int(task_id),
'completed' : completed,
}
response = client.authenticated_request(client.api.Endpoints.SUBTASKS, params=params)
return response.... | Gets subtasks for task with given ID | Below is the the instruction that describes the task:
### Input:
Gets subtasks for task with given ID
### Response:
def get_task_subtasks(client, task_id, completed=False):
''' Gets subtasks for task with given ID '''
params = {
'task_id' : int(task_id),
'completed' : completed,
... |
def _log_future_exception(future, logger):
"""Log any exception raised by future."""
if not future.done():
return
try:
future.result()
except: #pylint:disable=bare-except;This is a background logging helper
logger.warning("Exception in ignored future: %s", future, exc_info=Tru... | Log any exception raised by future. | Below is the the instruction that describes the task:
### Input:
Log any exception raised by future.
### Response:
def _log_future_exception(future, logger):
"""Log any exception raised by future."""
if not future.done():
return
try:
future.result()
except: #pylint:disable=bare-e... |
def _clear(self):
"""
Clear all references (called by its bundle activator)
"""
self.__names.clear()
self.__queue.clear()
self.__context = None | Clear all references (called by its bundle activator) | Below is the the instruction that describes the task:
### Input:
Clear all references (called by its bundle activator)
### Response:
def _clear(self):
"""
Clear all references (called by its bundle activator)
"""
self.__names.clear()
self.__queue.clear()
self.__conte... |
def createEditor(self, delegate, parent, _option):
""" Creates a hidden widget so that only the reset button is visible during editing.
:type option: QStyleOptionViewItem
"""
return GroupCtiEditor(self, delegate, parent=parent) | Creates a hidden widget so that only the reset button is visible during editing.
:type option: QStyleOptionViewItem | Below is the the instruction that describes the task:
### Input:
Creates a hidden widget so that only the reset button is visible during editing.
:type option: QStyleOptionViewItem
### Response:
def createEditor(self, delegate, parent, _option):
""" Creates a hidden widget so that only the rese... |
def set_hash_value(self, key, field, value, pipeline=False):
"""Set the value of field in a hash stored at key.
Args:
key (str): key (name) of the hash
field (str): Field within the hash to set
value: Value to set
pipeline (bool): True, start a transactio... | Set the value of field in a hash stored at key.
Args:
key (str): key (name) of the hash
field (str): Field within the hash to set
value: Value to set
pipeline (bool): True, start a transaction block. Default false. | Below is the the instruction that describes the task:
### Input:
Set the value of field in a hash stored at key.
Args:
key (str): key (name) of the hash
field (str): Field within the hash to set
value: Value to set
pipeline (bool): True, start a transaction b... |
def _load_cell(args, schema):
"""Implements the BigQuery load magic used to load data from GCS to a table.
The supported syntax is:
%bigquery load -S|--source <source> -D|--destination <table> <other_args>
Args:
args: the arguments following '%bigquery load'.
schema: a JSON schema for the dest... | Implements the BigQuery load magic used to load data from GCS to a table.
The supported syntax is:
%bigquery load -S|--source <source> -D|--destination <table> <other_args>
Args:
args: the arguments following '%bigquery load'.
schema: a JSON schema for the destination table.
Returns:
A mes... | Below is the the instruction that describes the task:
### Input:
Implements the BigQuery load magic used to load data from GCS to a table.
The supported syntax is:
%bigquery load -S|--source <source> -D|--destination <table> <other_args>
Args:
args: the arguments following '%bigquery load'.
... |
def p_poke2(p):
""" statement : POKE numbertype expr COMMA expr
| POKE LP numbertype expr COMMA expr RP
"""
i = 2 if isinstance(p[2], Symbol) or p[2] is None else 3
if p[i + 1] is None or p[i + 3] is None:
p[0] = None
return
p[0] = make_sentence('POKE',
... | statement : POKE numbertype expr COMMA expr
| POKE LP numbertype expr COMMA expr RP | Below is the the instruction that describes the task:
### Input:
statement : POKE numbertype expr COMMA expr
| POKE LP numbertype expr COMMA expr RP
### Response:
def p_poke2(p):
""" statement : POKE numbertype expr COMMA expr
| POKE LP numbertype expr COMMA expr RP
""... |
def run(self):
"""Starts the uploading thread."""
root_path, folder_name = os.path.split(self.root_folder)
self.root_folder = os.path.join(root_path, folder_name)
for dirname, _, fnames in os.walk(self.root_folder):
self.upload_files_in_folder(dirname, fnames) | Starts the uploading thread. | Below is the the instruction that describes the task:
### Input:
Starts the uploading thread.
### Response:
def run(self):
"""Starts the uploading thread."""
root_path, folder_name = os.path.split(self.root_folder)
self.root_folder = os.path.join(root_path, folder_name)
for dirname,... |
def iri_to_uri(iri, charset='utf-8'):
r"""Converts any unicode based IRI to an acceptable ASCII URI. Werkzeug
always uses utf-8 URLs internally because this is what browsers and HTTP
do as well. In some places where it accepts an URL it also accepts a
unicode IRI and converts it into a URI.
Examp... | r"""Converts any unicode based IRI to an acceptable ASCII URI. Werkzeug
always uses utf-8 URLs internally because this is what browsers and HTTP
do as well. In some places where it accepts an URL it also accepts a
unicode IRI and converts it into a URI.
Examples for IRI versus URI:
>>> iri_to_ur... | Below is the the instruction that describes the task:
### Input:
r"""Converts any unicode based IRI to an acceptable ASCII URI. Werkzeug
always uses utf-8 URLs internally because this is what browsers and HTTP
do as well. In some places where it accepts an URL it also accepts a
unicode IRI and convert... |
def swapon(name, priority=None):
'''
Activate a swap disk
.. versionchanged:: 2016.3.2
CLI Example:
.. code-block:: bash
salt '*' mount.swapon /root/swapfile
'''
ret = {}
on_ = swaps()
if name in on_:
ret['stats'] = on_[name]
ret['new'] = False
ret... | Activate a swap disk
.. versionchanged:: 2016.3.2
CLI Example:
.. code-block:: bash
salt '*' mount.swapon /root/swapfile | Below is the the instruction that describes the task:
### Input:
Activate a swap disk
.. versionchanged:: 2016.3.2
CLI Example:
.. code-block:: bash
salt '*' mount.swapon /root/swapfile
### Response:
def swapon(name, priority=None):
'''
Activate a swap disk
.. versionchanged:: ... |
def requiredOneInGroup(col_name, group, dm, df, *args):
"""
If col_name is present in df, the group validation is satisfied.
If not, it still may be satisfied, but not by THIS col_name.
If col_name is missing, return col_name, else return None.
Later, we will validate to see if there is at least one... | If col_name is present in df, the group validation is satisfied.
If not, it still may be satisfied, but not by THIS col_name.
If col_name is missing, return col_name, else return None.
Later, we will validate to see if there is at least one None (non-missing)
value for this group. | Below is the the instruction that describes the task:
### Input:
If col_name is present in df, the group validation is satisfied.
If not, it still may be satisfied, but not by THIS col_name.
If col_name is missing, return col_name, else return None.
Later, we will validate to see if there is at least on... |
def unlink_version(self, source, target):
"""Unlink the current version of the target from the source
"""
if not hasattr(source, REFERENCE_VERSIONS):
return
target_uid = api.get_uid(target)
if target_uid in source.reference_versions[target_uid]:
# delete t... | Unlink the current version of the target from the source | Below is the the instruction that describes the task:
### Input:
Unlink the current version of the target from the source
### Response:
def unlink_version(self, source, target):
"""Unlink the current version of the target from the source
"""
if not hasattr(source, REFERENCE_VERSIONS):
... |
def update(self, iterable):
"""Update the list by adding all elements from *iterable*."""
_maxes, _lists, _keys = self._maxes, self._lists, self._keys
values = sorted(iterable, key=self._key)
if _maxes:
if len(values) * 4 >= self._len:
values.extend(chain.fro... | Update the list by adding all elements from *iterable*. | Below is the the instruction that describes the task:
### Input:
Update the list by adding all elements from *iterable*.
### Response:
def update(self, iterable):
"""Update the list by adding all elements from *iterable*."""
_maxes, _lists, _keys = self._maxes, self._lists, self._keys
value... |
def build(self, klass, name="default", amount=None):
"""
Makes a factory builder with a specified amount.
:param klass: The class
:type klass: class
:param name: The type
:type name: str
:param amount: The number of models to create
:type amount: int
... | Makes a factory builder with a specified amount.
:param klass: The class
:type klass: class
:param name: The type
:type name: str
:param amount: The number of models to create
:type amount: int
:return: mixed | Below is the the instruction that describes the task:
### Input:
Makes a factory builder with a specified amount.
:param klass: The class
:type klass: class
:param name: The type
:type name: str
:param amount: The number of models to create
:type amount: int
... |
def functions_to_table(mod, colwidth=[27, 48]):
r"""
Given a module of functions, returns a ReST formatted text string that
outputs a table when printed.
Parameters
----------
mod : module
The module containing the functions to be included in the table, such
as 'porespy.filters'... | r"""
Given a module of functions, returns a ReST formatted text string that
outputs a table when printed.
Parameters
----------
mod : module
The module containing the functions to be included in the table, such
as 'porespy.filters'.
colwidths : list of ints
The width of... | Below is the the instruction that describes the task:
### Input:
r"""
Given a module of functions, returns a ReST formatted text string that
outputs a table when printed.
Parameters
----------
mod : module
The module containing the functions to be included in the table, such
as ... |
def create_nv_link(self):
"""After a save(), write a link to the saved file using a non-versioned name"""
from os.path import abspath, islink
from os import unlink, symlink
nv_name = self.doc.as_version(None)
from_path = abspath(self._last_write_path or self.package_path.path)... | After a save(), write a link to the saved file using a non-versioned name | Below is the the instruction that describes the task:
### Input:
After a save(), write a link to the saved file using a non-versioned name
### Response:
def create_nv_link(self):
"""After a save(), write a link to the saved file using a non-versioned name"""
from os.path import abspath, islink
... |
def _bytes_from_json(value, field):
"""Base64-decode value"""
if _not_null(value, field):
return base64.standard_b64decode(_to_bytes(value)) | Base64-decode value | Below is the the instruction that describes the task:
### Input:
Base64-decode value
### Response:
def _bytes_from_json(value, field):
"""Base64-decode value"""
if _not_null(value, field):
return base64.standard_b64decode(_to_bytes(value)) |
def copy(self, **attributes):
"""Create a copy of this message.
"""
updated_options = attributes.pop("options", {})
options = self.options.copy()
options.update(updated_options)
return self._replace(**attributes, options=options) | Create a copy of this message. | Below is the the instruction that describes the task:
### Input:
Create a copy of this message.
### Response:
def copy(self, **attributes):
"""Create a copy of this message.
"""
updated_options = attributes.pop("options", {})
options = self.options.copy()
options.update(upda... |
def listPrimaryDatasets(self, primary_ds_name="", primary_ds_type=""):
"""
API to list primary datasets
:param primary_ds_type: List primary datasets with primary dataset type (Optional)
:type primary_ds_type: str
:param primary_ds_name: List that primary dataset (Optional)
... | API to list primary datasets
:param primary_ds_type: List primary datasets with primary dataset type (Optional)
:type primary_ds_type: str
:param primary_ds_name: List that primary dataset (Optional)
:type primary_ds_name: str
:returns: List of dictionaries containing the follow... | Below is the the instruction that describes the task:
### Input:
API to list primary datasets
:param primary_ds_type: List primary datasets with primary dataset type (Optional)
:type primary_ds_type: str
:param primary_ds_name: List that primary dataset (Optional)
:type primary_ds_n... |
def join_path_prefix(path, pre_path=None):
"""
If path set and not absolute, append it to pre path (if used)
:param path: path to append
:type path: str | None
:param pre_path: Base path to append to (default: None)
:type pre_path: None | str
:return: Path or appended path
:rtype: str |... | If path set and not absolute, append it to pre path (if used)
:param path: path to append
:type path: str | None
:param pre_path: Base path to append to (default: None)
:type pre_path: None | str
:return: Path or appended path
:rtype: str | None | Below is the the instruction that describes the task:
### Input:
If path set and not absolute, append it to pre path (if used)
:param path: path to append
:type path: str | None
:param pre_path: Base path to append to (default: None)
:type pre_path: None | str
:return: Path or appended path
... |
def cas(self, key, val, time=0, min_compress_len=0):
'''Sets a key to a given value in the memcache if it hasn't been
altered since last fetched. (See L{gets}).
The C{key} can optionally be an tuple, with the first element
being the server hash value and the second being the key.
... | Sets a key to a given value in the memcache if it hasn't been
altered since last fetched. (See L{gets}).
The C{key} can optionally be an tuple, with the first element
being the server hash value and the second being the key.
If you want to avoid making this module calculate a hash value... | Below is the the instruction that describes the task:
### Input:
Sets a key to a given value in the memcache if it hasn't been
altered since last fetched. (See L{gets}).
The C{key} can optionally be an tuple, with the first element
being the server hash value and the second being the key.
... |
def probe(self, params):
"""
Evaulates a single point x, to obtain the value y and then records them
as observations.
Notes
-----
If x has been previously seen returns a cached value of y.
Parameters
----------
x : ndarray
a single po... | Evaulates a single point x, to obtain the value y and then records them
as observations.
Notes
-----
If x has been previously seen returns a cached value of y.
Parameters
----------
x : ndarray
a single point, with len(x) == self.dim
Returns... | Below is the the instruction that describes the task:
### Input:
Evaulates a single point x, to obtain the value y and then records them
as observations.
Notes
-----
If x has been previously seen returns a cached value of y.
Parameters
----------
x : ndarray... |
def squash_xml_to_text(elm, remove_namespaces=False):
"""Squash the given XML element (as `elm`) to a text containing XML.
The outer most element/tag will be removed, but inner elements will
remain. If `remove_namespaces` is specified, XML namespace declarations
will be removed from the text.
:para... | Squash the given XML element (as `elm`) to a text containing XML.
The outer most element/tag will be removed, but inner elements will
remain. If `remove_namespaces` is specified, XML namespace declarations
will be removed from the text.
:param elm: XML element
:type elm: :class:`xml.etree.ElementTr... | Below is the the instruction that describes the task:
### Input:
Squash the given XML element (as `elm`) to a text containing XML.
The outer most element/tag will be removed, but inner elements will
remain. If `remove_namespaces` is specified, XML namespace declarations
will be removed from the text.
... |
def set_duration(self, duration):
"""Sets the assessment duration.
arg: duration (osid.calendaring.Duration): assessment
duration
raise: InvalidArgument - ``duration`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory ... | Sets the assessment duration.
arg: duration (osid.calendaring.Duration): assessment
duration
raise: InvalidArgument - ``duration`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.* | Below is the the instruction that describes the task:
### Input:
Sets the assessment duration.
arg: duration (osid.calendaring.Duration): assessment
duration
raise: InvalidArgument - ``duration`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
... |
def show_vcs_output_vcs_nodes_vcs_node_info_node_switch_mac(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_vcs = ET.Element("show_vcs")
config = show_vcs
output = ET.SubElement(show_vcs, "output")
vcs_nodes = ET.SubElement(output, "... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def show_vcs_output_vcs_nodes_vcs_node_info_node_switch_mac(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_vcs = ET.Element("show_vcs")
config =... |
def get_coin_snapshot(fsym, tsym):
"""
Get blockchain information, aggregated data as well as data for the
individual exchanges available for the specified currency pair.
Args:
fsym: FROM symbol.
tsym: TO symbol.
Returns:
The function returns a dictionairy containing blockain as well as
trading inform... | Get blockchain information, aggregated data as well as data for the
individual exchanges available for the specified currency pair.
Args:
fsym: FROM symbol.
tsym: TO symbol.
Returns:
The function returns a dictionairy containing blockain as well as
trading information from the different exchanges were t... | Below is the the instruction that describes the task:
### Input:
Get blockchain information, aggregated data as well as data for the
individual exchanges available for the specified currency pair.
Args:
fsym: FROM symbol.
tsym: TO symbol.
Returns:
The function returns a dictionairy containing blockain ... |
def work_dir(path):
'''
Context menager for executing commands in some working directory.
Returns to the previous wd when finished.
Usage:
>>> with work_dir(path):
... subprocess.call('git status')
'''
starting_directory = os.getcwd()
try:
os.chdir(path)
yield
... | Context menager for executing commands in some working directory.
Returns to the previous wd when finished.
Usage:
>>> with work_dir(path):
... subprocess.call('git status') | Below is the the instruction that describes the task:
### Input:
Context menager for executing commands in some working directory.
Returns to the previous wd when finished.
Usage:
>>> with work_dir(path):
... subprocess.call('git status')
### Response:
def work_dir(path):
'''
Context men... |
def _run_startup_files(self):
"""Run files from profile startup directory"""
startup_dir = self.profile_dir.startup_dir
startup_files = glob.glob(os.path.join(startup_dir, '*.py'))
startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
if not startup_files:
re... | Run files from profile startup directory | Below is the the instruction that describes the task:
### Input:
Run files from profile startup directory
### Response:
def _run_startup_files(self):
"""Run files from profile startup directory"""
startup_dir = self.profile_dir.startup_dir
startup_files = glob.glob(os.path.join(startup_dir,... |
def libvlc_audio_output_set(p_mi, psz_name):
'''Selects an audio output module.
@note: Any change will take be effect only after playback is stopped and
restarted. Audio output cannot be changed while playing.
@param p_mi: media player.
@param psz_name: name of audio output, use psz_name of See L{Au... | Selects an audio output module.
@note: Any change will take be effect only after playback is stopped and
restarted. Audio output cannot be changed while playing.
@param p_mi: media player.
@param psz_name: name of audio output, use psz_name of See L{AudioOutput}.
@return: 0 if function succeded, -1 ... | Below is the the instruction that describes the task:
### Input:
Selects an audio output module.
@note: Any change will take be effect only after playback is stopped and
restarted. Audio output cannot be changed while playing.
@param p_mi: media player.
@param psz_name: name of audio output, use psz... |
def notify(self, message):
"""Monitor output from heroku process.
This overrides the base class's `notify`
to make sure that we stop if the status-monitoring thread
has determined that the experiment is complete.
"""
if self.complete:
return HerokuLocalWrappe... | Monitor output from heroku process.
This overrides the base class's `notify`
to make sure that we stop if the status-monitoring thread
has determined that the experiment is complete. | Below is the the instruction that describes the task:
### Input:
Monitor output from heroku process.
This overrides the base class's `notify`
to make sure that we stop if the status-monitoring thread
has determined that the experiment is complete.
### Response:
def notify(self, message):
... |
def Random(self):
"""Chooses a random element from this PMF.
Returns:
float value from the Pmf
"""
if len(self.d) == 0:
raise ValueError('Pmf contains no values.')
target = random.random()
total = 0.0
for x, p in self.d.iteritems():
... | Chooses a random element from this PMF.
Returns:
float value from the Pmf | Below is the the instruction that describes the task:
### Input:
Chooses a random element from this PMF.
Returns:
float value from the Pmf
### Response:
def Random(self):
"""Chooses a random element from this PMF.
Returns:
float value from the Pmf
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.