code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def match_any_char(self, chars, offset=0):
"""Match and return the current SourceString char if its in chars."""
if not self.has_space(offset=offset):
return ''
current = self.string[self.pos + offset]
return current if current in chars else '' | Match and return the current SourceString char if its in chars. | Below is the the instruction that describes the task:
### Input:
Match and return the current SourceString char if its in chars.
### Response:
def match_any_char(self, chars, offset=0):
"""Match and return the current SourceString char if its in chars."""
if not self.has_space(offset=offset):
... |
def get_state_batch(keys, namespace=None, consistent=True):
"""Get a batch of items from the state store."""
ukeys = set(keys)
if namespace:
ns_keys = ["{}:{}".format(namespace, key) for key in ukeys]
uvalues = {k: v for k, v
in zip(ukeys, get_item_batch(ns_keys, consistent=con... | Get a batch of items from the state store. | Below is the the instruction that describes the task:
### Input:
Get a batch of items from the state store.
### Response:
def get_state_batch(keys, namespace=None, consistent=True):
"""Get a batch of items from the state store."""
ukeys = set(keys)
if namespace:
ns_keys = ["{}:{}".format(name... |
def check(self, check_all=False):
"""Check whether some modules need to be reloaded."""
if not self.enabled and not check_all:
return
if check_all or self.check_all:
modules = sys.modules.keys()
else:
modules = self.modules.keys()
for modnam... | Check whether some modules need to be reloaded. | Below is the the instruction that describes the task:
### Input:
Check whether some modules need to be reloaded.
### Response:
def check(self, check_all=False):
"""Check whether some modules need to be reloaded."""
if not self.enabled and not check_all:
return
if check_all or ... |
def _list_remote(store, maildir, verbose=False):
"""List the a maildir.
store is an abstract representation of the source maildir.
maildir is the local maildir to which mail will be pulled.
This is a generator for a reason. Because of the way ssh
multi-mastering works a single open TCP connectio... | List the a maildir.
store is an abstract representation of the source maildir.
maildir is the local maildir to which mail will be pulled.
This is a generator for a reason. Because of the way ssh
multi-mastering works a single open TCP connection allows multiple
virtual ssh connections. So the en... | Below is the the instruction that describes the task:
### Input:
List the a maildir.
store is an abstract representation of the source maildir.
maildir is the local maildir to which mail will be pulled.
This is a generator for a reason. Because of the way ssh
multi-mastering works a single open ... |
def _try_cast_result(self, result, dtype=None):
""" try to cast the result to our original type, we may have
roundtripped thru object in the mean-time
"""
if dtype is None:
dtype = self.dtype
if self.is_integer or self.is_bool or self.is_datetime:
pass
... | try to cast the result to our original type, we may have
roundtripped thru object in the mean-time | Below is the the instruction that describes the task:
### Input:
try to cast the result to our original type, we may have
roundtripped thru object in the mean-time
### Response:
def _try_cast_result(self, result, dtype=None):
""" try to cast the result to our original type, we may have
roun... |
def close_shell(self, shell_id):
"""
Close the shell
@param string shell_id: The shell id on the remote machine.
See #open_shell
@returns This should have more error checking but it just returns true
for now.
@rtype bool
"""
message_id = uuid.uui... | Close the shell
@param string shell_id: The shell id on the remote machine.
See #open_shell
@returns This should have more error checking but it just returns true
for now.
@rtype bool | Below is the the instruction that describes the task:
### Input:
Close the shell
@param string shell_id: The shell id on the remote machine.
See #open_shell
@returns This should have more error checking but it just returns true
for now.
@rtype bool
### Response:
def close_... |
def ifinstalled(parser, token):
"""
Old-style ``if`` tag that renders contents if the given app is
installed. The main use case is:
{% ifinstalled app_name %}
{% include "app_name/template.html" %}
{% endifinstalled %}
so we need to manually pull out all tokens if the app isn't
install... | Old-style ``if`` tag that renders contents if the given app is
installed. The main use case is:
{% ifinstalled app_name %}
{% include "app_name/template.html" %}
{% endifinstalled %}
so we need to manually pull out all tokens if the app isn't
installed, since if we used a normal ``if`` tag wit... | Below is the the instruction that describes the task:
### Input:
Old-style ``if`` tag that renders contents if the given app is
installed. The main use case is:
{% ifinstalled app_name %}
{% include "app_name/template.html" %}
{% endifinstalled %}
so we need to manually pull out all tokens if ... |
def cv(data, units=False):
"""
Calculate coefficient of variation (cv) of data. Mean and standard deviation
are computed across time.
Parameters
----------
data : numpy.ndarray
1st axis unit, 2nd axis time.
units : bool
Average `cv`.
Returns
-------
numpy.ndar... | Calculate coefficient of variation (cv) of data. Mean and standard deviation
are computed across time.
Parameters
----------
data : numpy.ndarray
1st axis unit, 2nd axis time.
units : bool
Average `cv`.
Returns
-------
numpy.ndarray
If units=False, series of u... | Below is the the instruction that describes the task:
### Input:
Calculate coefficient of variation (cv) of data. Mean and standard deviation
are computed across time.
Parameters
----------
data : numpy.ndarray
1st axis unit, 2nd axis time.
units : bool
Average `cv`.
Retu... |
def _PrintAnalysisStatusUpdateLinear(self, processing_status):
"""Prints an analysis status update in linear mode.
Args:
processing_status (ProcessingStatus): processing status.
"""
for worker_status in processing_status.workers_status:
status_line = (
'{0:s} (PID: {1:d}) - events... | Prints an analysis status update in linear mode.
Args:
processing_status (ProcessingStatus): processing status. | Below is the the instruction that describes the task:
### Input:
Prints an analysis status update in linear mode.
Args:
processing_status (ProcessingStatus): processing status.
### Response:
def _PrintAnalysisStatusUpdateLinear(self, processing_status):
"""Prints an analysis status update in linear ... |
def draw_graph(G: nx.DiGraph, filename: str):
""" Draw a networkx graph with Pygraphviz. """
A = to_agraph(G)
A.graph_attr["rankdir"] = "LR"
A.draw(filename, prog="dot") | Draw a networkx graph with Pygraphviz. | Below is the the instruction that describes the task:
### Input:
Draw a networkx graph with Pygraphviz.
### Response:
def draw_graph(G: nx.DiGraph, filename: str):
""" Draw a networkx graph with Pygraphviz. """
A = to_agraph(G)
A.graph_attr["rankdir"] = "LR"
A.draw(filename, prog="dot") |
def shift_up(self, times=1):
"""
Finds Location shifted up by 1
:rtype: Location
"""
try:
return Location(self._rank + times, self._file)
except IndexError as e:
raise IndexError(e) | Finds Location shifted up by 1
:rtype: Location | Below is the the instruction that describes the task:
### Input:
Finds Location shifted up by 1
:rtype: Location
### Response:
def shift_up(self, times=1):
"""
Finds Location shifted up by 1
:rtype: Location
"""
try:
return Location(self._rank + times, ... |
def set_handler(self, handler):
""" Set transport handler
@param handler: Handler, should derive from the
C{sockjs.cyclone.transports.base.BaseTransportMixin}
"""
if self.handler is not None:
raise Exception('Attempted to overwrite BaseSession handler... | Set transport handler
@param handler: Handler, should derive from the
C{sockjs.cyclone.transports.base.BaseTransportMixin} | Below is the the instruction that describes the task:
### Input:
Set transport handler
@param handler: Handler, should derive from the
C{sockjs.cyclone.transports.base.BaseTransportMixin}
### Response:
def set_handler(self, handler):
""" Set transport handler
@para... |
def _submit_gauges_from_histogram(
self, name, metric, send_histograms_buckets=True, custom_tags=None, hostname=None
):
"""
Extracts metrics from a prometheus histogram and sends them as gauges
"""
if custom_tags is None:
custom_tags = []
# histograms do n... | Extracts metrics from a prometheus histogram and sends them as gauges | Below is the the instruction that describes the task:
### Input:
Extracts metrics from a prometheus histogram and sends them as gauges
### Response:
def _submit_gauges_from_histogram(
self, name, metric, send_histograms_buckets=True, custom_tags=None, hostname=None
):
"""
Extracts metri... |
def on_taskend(self, task):
""" Play sounds at task end.
"""
key = 'timer' if task.elapsed else 'end'
filename = self.files.get(key)
if filename:
self._play_sound(filename) | Play sounds at task end. | Below is the the instruction that describes the task:
### Input:
Play sounds at task end.
### Response:
def on_taskend(self, task):
""" Play sounds at task end.
"""
key = 'timer' if task.elapsed else 'end'
filename = self.files.get(key)
if filename:
self._pl... |
def _bind_args(sig, param_matchers, args, kwargs):
'''
Attempt to bind the args to the type signature. First try to just bind
to the signature, then ensure that all arguments match the parameter
types.
'''
#Bind to signature. May throw its own TypeError
bound = si... | Attempt to bind the args to the type signature. First try to just bind
to the signature, then ensure that all arguments match the parameter
types. | Below is the the instruction that describes the task:
### Input:
Attempt to bind the args to the type signature. First try to just bind
to the signature, then ensure that all arguments match the parameter
types.
### Response:
def _bind_args(sig, param_matchers, args, kwargs):
'''
At... |
def get_entity(
self, entity_type, entity_id, history_index=-1, connected=True):
"""Return an object instance for the given entity_type and id.
By default the object state matches the most recent state from
Juju. To get an instance of the object in an older state, pass
histo... | Return an object instance for the given entity_type and id.
By default the object state matches the most recent state from
Juju. To get an instance of the object in an older state, pass
history_index, an index into the history deque for the entity. | Below is the the instruction that describes the task:
### Input:
Return an object instance for the given entity_type and id.
By default the object state matches the most recent state from
Juju. To get an instance of the object in an older state, pass
history_index, an index into the history... |
def start_output (self):
"""
Write start of checking info as sql comment.
"""
super(SQLLogger, self).start_output()
if self.has_part("intro"):
self.write_intro()
self.writeln()
self.flush() | Write start of checking info as sql comment. | Below is the the instruction that describes the task:
### Input:
Write start of checking info as sql comment.
### Response:
def start_output (self):
"""
Write start of checking info as sql comment.
"""
super(SQLLogger, self).start_output()
if self.has_part("intro"):
... |
def create_lr_scheduler_with_warmup(lr_scheduler, warmup_start_value, warmup_end_value, warmup_duration,
save_history=False,
output_simulated_values=None):
"""
Helper method to create a LR scheduler with a linear warm-up.
Args:
... | Helper method to create a LR scheduler with a linear warm-up.
Args:
lr_scheduler (ParamScheduler or subclass of `torch.optim.lr_scheduler._LRScheduler`): LR scheduler after
the warm-up.
warmup_start_value (float): LR start value of the warm-up phase.
warmup_end_value (float): LR... | Below is the the instruction that describes the task:
### Input:
Helper method to create a LR scheduler with a linear warm-up.
Args:
lr_scheduler (ParamScheduler or subclass of `torch.optim.lr_scheduler._LRScheduler`): LR scheduler after
the warm-up.
warmup_start_value (float): LR s... |
def coords_on_grid(self, x, y):
""" Snap coordinates on the grid with integer coordinates """
if isinstance(x, float):
x = int(self._round(x))
if isinstance(y, float):
y = int(self._round(y))
if not self._y_coord_down:
y = self._extents - y
re... | Snap coordinates on the grid with integer coordinates | Below is the the instruction that describes the task:
### Input:
Snap coordinates on the grid with integer coordinates
### Response:
def coords_on_grid(self, x, y):
""" Snap coordinates on the grid with integer coordinates """
if isinstance(x, float):
x = int(self._round(x))
if... |
def from_seed(cls, seed, encoder=encoding.RawEncoder):
"""
Generate a PrivateKey using a deterministic construction
starting from a caller-provided seed
.. warning:: The seed **must** be high-entropy; therefore,
its generator **must** be a cryptographic quality
r... | Generate a PrivateKey using a deterministic construction
starting from a caller-provided seed
.. warning:: The seed **must** be high-entropy; therefore,
its generator **must** be a cryptographic quality
random function like, for example, :func:`~nacl.utils.random`.
.. w... | Below is the the instruction that describes the task:
### Input:
Generate a PrivateKey using a deterministic construction
starting from a caller-provided seed
.. warning:: The seed **must** be high-entropy; therefore,
its generator **must** be a cryptographic quality
random ... |
def split_coords_2d(seq):
"""
:param seq: a flat list with lons and lats
:returns: a validated list of pairs (lon, lat)
>>> split_coords_2d([1.1, 2.1, 2.2, 2.3])
[(1.1, 2.1), (2.2, 2.3)]
"""
lons, lats = [], []
for i, el in enumerate(seq):
if i % 2 == 0:
lons.append(... | :param seq: a flat list with lons and lats
:returns: a validated list of pairs (lon, lat)
>>> split_coords_2d([1.1, 2.1, 2.2, 2.3])
[(1.1, 2.1), (2.2, 2.3)] | Below is the the instruction that describes the task:
### Input:
:param seq: a flat list with lons and lats
:returns: a validated list of pairs (lon, lat)
>>> split_coords_2d([1.1, 2.1, 2.2, 2.3])
[(1.1, 2.1), (2.2, 2.3)]
### Response:
def split_coords_2d(seq):
"""
:param seq: a flat list with... |
def _render(self, contexts, partials):
"""render partials"""
try:
partial = partials[self.value]
except KeyError as e:
return self._escape(EMPTYSTRING)
partial = re_insert_indent.sub(r'\1' + ' '*self.indent, partial)
return inner_render(partial, contexts... | render partials | Below is the the instruction that describes the task:
### Input:
render partials
### Response:
def _render(self, contexts, partials):
"""render partials"""
try:
partial = partials[self.value]
except KeyError as e:
return self._escape(EMPTYSTRING)
partial = r... |
def create_args_parser(description):
""" Create a command-line arguments parser for OSPD. """
parser = argparse.ArgumentParser(description=description)
def network_port(string):
""" Check if provided string is a valid network port. """
value = int(string)
if not 0 < value <= 65535... | Create a command-line arguments parser for OSPD. | Below is the the instruction that describes the task:
### Input:
Create a command-line arguments parser for OSPD.
### Response:
def create_args_parser(description):
""" Create a command-line arguments parser for OSPD. """
parser = argparse.ArgumentParser(description=description)
def network_port(stri... |
def dropEdges(grph, minWeight = - float('inf'), maxWeight = float('inf'), parameterName = 'weight', ignoreUnweighted = False, dropSelfLoops = False):
"""Modifies _grph_ by dropping edges whose weight is not within the inclusive bounds of _minWeight_ and _maxWeight_, i.e after running _grph_ will only have edges who... | Modifies _grph_ by dropping edges whose weight is not within the inclusive bounds of _minWeight_ and _maxWeight_, i.e after running _grph_ will only have edges whose weights meet the following inequality: _minWeight_ <= edge's weight <= _maxWeight_. A `Keyerror` will be raised if the graph is unweighted unless _ignoreU... | Below is the the instruction that describes the task:
### Input:
Modifies _grph_ by dropping edges whose weight is not within the inclusive bounds of _minWeight_ and _maxWeight_, i.e after running _grph_ will only have edges whose weights meet the following inequality: _minWeight_ <= edge's weight <= _maxWeight_. A... |
def import_contacts(self, email, password, include_name=False):
"""
Fetch email contacts from a user's address book on one of the major email websites. Currently supports AOL, Gmail, Hotmail, and Yahoo! Mail.
"""
data = {'email': email,
'password': password}
if in... | Fetch email contacts from a user's address book on one of the major email websites. Currently supports AOL, Gmail, Hotmail, and Yahoo! Mail. | Below is the the instruction that describes the task:
### Input:
Fetch email contacts from a user's address book on one of the major email websites. Currently supports AOL, Gmail, Hotmail, and Yahoo! Mail.
### Response:
def import_contacts(self, email, password, include_name=False):
"""
Fetch email... |
def _Rforce(self,R,z,phi=0.,t=0.):
"""
NAME:
_Rforce
PURPOSE:T
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | NAME:
_Rforce
PURPOSE:T
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
the radial force | Below is the the instruction that describes the task:
### Input:
NAME:
_Rforce
PURPOSE:T
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTP... |
def cmd_arp_ping(ip, iface, verbose):
"""
Send ARP packets to check if a host it's alive in the local network.
Example:
\b
# habu.arp.ping 192.168.0.1
Ether / ARP is at a4:08:f5:19:17:a4 says 192.168.0.1 / Padding
"""
if verbose:
logging.basicConfig(level=logging.INFO, format=... | Send ARP packets to check if a host it's alive in the local network.
Example:
\b
# habu.arp.ping 192.168.0.1
Ether / ARP is at a4:08:f5:19:17:a4 says 192.168.0.1 / Padding | Below is the the instruction that describes the task:
### Input:
Send ARP packets to check if a host it's alive in the local network.
Example:
\b
# habu.arp.ping 192.168.0.1
Ether / ARP is at a4:08:f5:19:17:a4 says 192.168.0.1 / Padding
### Response:
def cmd_arp_ping(ip, iface, verbose):
"""
... |
def get_request_body(self):
"""
Fetch (and cache) the request body as a dictionary.
:raise web.HTTPError:
- if the content type cannot be matched, then the status code
is set to 415 Unsupported Media Type.
- if decoding the content body fails, then the stat... | Fetch (and cache) the request body as a dictionary.
:raise web.HTTPError:
- if the content type cannot be matched, then the status code
is set to 415 Unsupported Media Type.
- if decoding the content body fails, then the status code is
set to 400 Bad Syntax. | Below is the the instruction that describes the task:
### Input:
Fetch (and cache) the request body as a dictionary.
:raise web.HTTPError:
- if the content type cannot be matched, then the status code
is set to 415 Unsupported Media Type.
- if decoding the content body... |
def remove_token(self, *, payer_id, credit_card_token_id):
"""
This feature allows you to delete a tokenized credit card register.
Args:
payer_id:
credit_card_token_id:
Returns:
"""
payload = {
"language": self.client.language.value,... | This feature allows you to delete a tokenized credit card register.
Args:
payer_id:
credit_card_token_id:
Returns: | Below is the the instruction that describes the task:
### Input:
This feature allows you to delete a tokenized credit card register.
Args:
payer_id:
credit_card_token_id:
Returns:
### Response:
def remove_token(self, *, payer_id, credit_card_token_id):
"""
... |
def main():
"""Main method."""
args = parse_cmd_arguments()
html_file = args.file
try:
json.loads(args.add_tags or '{}')
json.loads(args.exc_tags or '{}')
except ValueError:
print('\033[91m' + 'Invalid json string: please provide a valid json '
'string e.g {}'.... | Main method. | Below is the the instruction that describes the task:
### Input:
Main method.
### Response:
def main():
"""Main method."""
args = parse_cmd_arguments()
html_file = args.file
try:
json.loads(args.add_tags or '{}')
json.loads(args.exc_tags or '{}')
except ValueError:
prin... |
def getData(self, pos):
"""
Returns dictionary with input and target given pos.
"""
retval = {}
if pos >= len(self.inputs):
raise IndexError('getData() pattern beyond range.', pos)
if self.verbosity >= 1: print("Getting input", pos, "...")
if len(self... | Returns dictionary with input and target given pos. | Below is the the instruction that describes the task:
### Input:
Returns dictionary with input and target given pos.
### Response:
def getData(self, pos):
"""
Returns dictionary with input and target given pos.
"""
retval = {}
if pos >= len(self.inputs):
raise I... |
def is_recording(self) -> Optional[bool]:
"""Indicate if this Monitor is currently recording."""
status_response = self._client.get_state(
'api/monitors/alarm/id:{}/command:status.json'.format(
self._monitor_id
)
)
if not status_response:
... | Indicate if this Monitor is currently recording. | Below is the the instruction that describes the task:
### Input:
Indicate if this Monitor is currently recording.
### Response:
def is_recording(self) -> Optional[bool]:
"""Indicate if this Monitor is currently recording."""
status_response = self._client.get_state(
'api/monitors/alarm/... |
def run(self, hosts, function, attempts=1):
"""
Add the given function to a queue, and call it once for each host
according to the threading options.
Use decorators.bind() if you also want to pass additional
arguments to the callback function.
Returns an object that repr... | Add the given function to a queue, and call it once for each host
according to the threading options.
Use decorators.bind() if you also want to pass additional
arguments to the callback function.
Returns an object that represents the queued task, and that may be
passed to is_com... | Below is the the instruction that describes the task:
### Input:
Add the given function to a queue, and call it once for each host
according to the threading options.
Use decorators.bind() if you also want to pass additional
arguments to the callback function.
Returns an object that... |
def get_color_theme(theme):
'''
Return the color theme to use
'''
# Keep the heavy lifting out of the module space
import salt.utils.data
import salt.utils.files
import salt.utils.yaml
if not os.path.isfile(theme):
log.warning('The named theme %s if not available', theme)
tr... | Return the color theme to use | Below is the the instruction that describes the task:
### Input:
Return the color theme to use
### Response:
def get_color_theme(theme):
'''
Return the color theme to use
'''
# Keep the heavy lifting out of the module space
import salt.utils.data
import salt.utils.files
import salt.util... |
def parseDEI(self,
xbrl,
ignore_errors=0):
"""
Parse DEI from our XBRL soup and return a DEI object.
"""
dei_obj = DEI()
if ignore_errors == 2:
logging.basicConfig(filename='/tmp/xbrl.log',
level=logging.ERROR,
... | Parse DEI from our XBRL soup and return a DEI object. | Below is the the instruction that describes the task:
### Input:
Parse DEI from our XBRL soup and return a DEI object.
### Response:
def parseDEI(self,
xbrl,
ignore_errors=0):
"""
Parse DEI from our XBRL soup and return a DEI object.
"""
dei_obj = D... |
def copy(self, props=None, value=None):
"""
Copy the Overlay possibly overriding props.
"""
return Overlay(self.text,
(self.start, self.end),
props=props or self.props,
value=value or self.value) | Copy the Overlay possibly overriding props. | Below is the the instruction that describes the task:
### Input:
Copy the Overlay possibly overriding props.
### Response:
def copy(self, props=None, value=None):
"""
Copy the Overlay possibly overriding props.
"""
return Overlay(self.text,
(self.start, self.... |
def kernel_restarted_message(self, msg):
"""Show kernel restarted/died messages."""
if not self.is_error_shown:
# If there are kernel creation errors, jupyter_client will
# try to restart the kernel and qtconsole prints a
# message about it.
# So we ... | Show kernel restarted/died messages. | Below is the the instruction that describes the task:
### Input:
Show kernel restarted/died messages.
### Response:
def kernel_restarted_message(self, msg):
"""Show kernel restarted/died messages."""
if not self.is_error_shown:
# If there are kernel creation errors, jupyter_client wi... |
def protein_header_split_generator(elements, headers, ns):
"""Loop through proteins of each PSM/peptide. If a protein does not
match any of headers, discard PSM/peptide immediately"""
for el in elements:
header_not_matching = False
for protein in el.findall('{%s}protein_id' % ns['xmlns']):
... | Loop through proteins of each PSM/peptide. If a protein does not
match any of headers, discard PSM/peptide immediately | Below is the the instruction that describes the task:
### Input:
Loop through proteins of each PSM/peptide. If a protein does not
match any of headers, discard PSM/peptide immediately
### Response:
def protein_header_split_generator(elements, headers, ns):
"""Loop through proteins of each PSM/peptide. If a... |
def get_constrained_fc2(supercell,
dataset_second_atoms,
atom1,
reduced_site_sym,
symprec):
"""
dataset_second_atoms: [{'number': 7,
'displacement': [],
'delta_... | dataset_second_atoms: [{'number': 7,
'displacement': [],
'delta_forces': []}, ...] | Below is the the instruction that describes the task:
### Input:
dataset_second_atoms: [{'number': 7,
'displacement': [],
'delta_forces': []}, ...]
### Response:
def get_constrained_fc2(supercell,
dataset_second_atoms,
... |
def ssh_sa_ssh_server_ssh_vrf_cont_use_vrf_use_vrf_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ssh_sa = ET.SubElement(config, "ssh-sa", xmlns="urn:brocade.com:mgmt:brocade-sec-services")
ssh = ET.SubElement(ssh_sa, "ssh")
server = ET.Sub... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def ssh_sa_ssh_server_ssh_vrf_cont_use_vrf_use_vrf_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ssh_sa = ET.SubElement(config, "ssh-sa", xmlns="urn:br... |
def _matrix_adjust(self, X):
"""Adjust all values in X to encode for NaNs and infinities in the data.
Parameters
----------
X : array-like, shape=(n_samples, n_feature)
Input array of type int.
Returns
-------
X : array-like, shape=(n_samples, n_feat... | Adjust all values in X to encode for NaNs and infinities in the data.
Parameters
----------
X : array-like, shape=(n_samples, n_feature)
Input array of type int.
Returns
-------
X : array-like, shape=(n_samples, n_feature)
Input array without any... | Below is the the instruction that describes the task:
### Input:
Adjust all values in X to encode for NaNs and infinities in the data.
Parameters
----------
X : array-like, shape=(n_samples, n_feature)
Input array of type int.
Returns
-------
X : array-l... |
def inverse(self):
"""
Return the inverse of the graph.
@rtype: graph
@return: Complement graph for the graph.
"""
inv = self.__class__()
inv.add_nodes(self.nodes())
inv.complete()
for each in self.edges():
if (inv.has_edge(ea... | Return the inverse of the graph.
@rtype: graph
@return: Complement graph for the graph. | Below is the the instruction that describes the task:
### Input:
Return the inverse of the graph.
@rtype: graph
@return: Complement graph for the graph.
### Response:
def inverse(self):
"""
Return the inverse of the graph.
@rtype: graph
@return: C... |
def replace_characters(self, text, characters, replacement=''):
"""Remove characters from text.
Removes custom characters from input text or replaces them
with a string if specified.
Args:
text: The text to be processed.
characters: Characters that will be repla... | Remove characters from text.
Removes custom characters from input text or replaces them
with a string if specified.
Args:
text: The text to be processed.
characters: Characters that will be replaced.
replacement: New text that will replace the custom charact... | Below is the the instruction that describes the task:
### Input:
Remove characters from text.
Removes custom characters from input text or replaces them
with a string if specified.
Args:
text: The text to be processed.
characters: Characters that will be replaced.
... |
def pop(stack, op_id):
"""Pop a value from the stack (i.e. read it from the tape).
Args:
stack: The stack to pop from.
op_id: A unique variable that is also passed into the matching push.
Allows optimization passes to track pairs of pushes and pops.
Returns:
The last value.
"""
if __debu... | Pop a value from the stack (i.e. read it from the tape).
Args:
stack: The stack to pop from.
op_id: A unique variable that is also passed into the matching push.
Allows optimization passes to track pairs of pushes and pops.
Returns:
The last value. | Below is the the instruction that describes the task:
### Input:
Pop a value from the stack (i.e. read it from the tape).
Args:
stack: The stack to pop from.
op_id: A unique variable that is also passed into the matching push.
Allows optimization passes to track pairs of pushes and pops.
Retur... |
def list_group_maintainers(self, name):
"""
Get the maintainers of a group.
Args:
name (string): Name of group to query.
Returns:
(list[string]): List of maintainer names.
Raises:
requests.HTTPError on failure.
"""
self.proje... | Get the maintainers of a group.
Args:
name (string): Name of group to query.
Returns:
(list[string]): List of maintainer names.
Raises:
requests.HTTPError on failure. | Below is the the instruction that describes the task:
### Input:
Get the maintainers of a group.
Args:
name (string): Name of group to query.
Returns:
(list[string]): List of maintainer names.
Raises:
requests.HTTPError on failure.
### Response:
def li... |
def click(self, force_no_call=False, milis=None):
"""
Call when the button is pressed. This start the callback function in a thread
If :milis is given, will release the button after :milis miliseconds
"""
if self.clicked:
return False
if not force_no_call an... | Call when the button is pressed. This start the callback function in a thread
If :milis is given, will release the button after :milis miliseconds | Below is the the instruction that describes the task:
### Input:
Call when the button is pressed. This start the callback function in a thread
If :milis is given, will release the button after :milis miliseconds
### Response:
def click(self, force_no_call=False, milis=None):
"""
Call when t... |
def find_one(cls, pattern, string, flags=0):
"""JS-like match object. Use index number to get groups, if not match or no group, will return ''.
Basic Usage::
>>> from torequests.utils import find_one
>>> string = "abcd"
>>> find_one("a.*", string)
<toreq... | JS-like match object. Use index number to get groups, if not match or no group, will return ''.
Basic Usage::
>>> from torequests.utils import find_one
>>> string = "abcd"
>>> find_one("a.*", string)
<torequests.utils.RegMatch object at 0x0705F1D0>
>... | Below is the the instruction that describes the task:
### Input:
JS-like match object. Use index number to get groups, if not match or no group, will return ''.
Basic Usage::
>>> from torequests.utils import find_one
>>> string = "abcd"
>>> find_one("a.*", string)
... |
def get_usage(self, start=None, end=None):
"""
Return the usage records for this load balancer. You may optionally
include a start datetime or an end datetime, or both, which will limit
the records to those on or after the start time, and those before or on
the end time. These ti... | Return the usage records for this load balancer. You may optionally
include a start datetime or an end datetime, or both, which will limit
the records to those on or after the start time, and those before or on
the end time. These times should be Python datetime.datetime objects,
Python ... | Below is the the instruction that describes the task:
### Input:
Return the usage records for this load balancer. You may optionally
include a start datetime or an end datetime, or both, which will limit
the records to those on or after the start time, and those before or on
the end time. Th... |
def _generateModel1(numCategories):
""" Generate the initial, first order, and second order transition
probabilities for 'model1'. For this model, we generate the following
set of sequences:
0-10-15 (1X)
0-11-16 (1X)
0-12-17 (1X)
0-13-18 (1X)
0-14-19 (1X)
1-10-20 (1X)
1-11-21 (1X)
1-12-22 (1X)... | Generate the initial, first order, and second order transition
probabilities for 'model1'. For this model, we generate the following
set of sequences:
0-10-15 (1X)
0-11-16 (1X)
0-12-17 (1X)
0-13-18 (1X)
0-14-19 (1X)
1-10-20 (1X)
1-11-21 (1X)
1-12-22 (1X)
1-13-23 (1X)
1-14-24 (1X)
Par... | Below is the the instruction that describes the task:
### Input:
Generate the initial, first order, and second order transition
probabilities for 'model1'. For this model, we generate the following
set of sequences:
0-10-15 (1X)
0-11-16 (1X)
0-12-17 (1X)
0-13-18 (1X)
0-14-19 (1X)
1-10-20 (1X)
... |
def read_bytes(self, length) -> bytes:
"""
Read the specified number of bytes from the stream.
Args:
length (int): number of bytes to read.
Returns:
bytes: `length` number of bytes.
"""
value = self.stream.read(length)
return value | Read the specified number of bytes from the stream.
Args:
length (int): number of bytes to read.
Returns:
bytes: `length` number of bytes. | Below is the the instruction that describes the task:
### Input:
Read the specified number of bytes from the stream.
Args:
length (int): number of bytes to read.
Returns:
bytes: `length` number of bytes.
### Response:
def read_bytes(self, length) -> bytes:
"""
... |
def best(self):
"""
Returns the element with the highest probability.
"""
b = (-1e999999, None)
for k, c in iteritems(self.counts):
b = max(b, (c, k))
return b[1] | Returns the element with the highest probability. | Below is the the instruction that describes the task:
### Input:
Returns the element with the highest probability.
### Response:
def best(self):
"""
Returns the element with the highest probability.
"""
b = (-1e999999, None)
for k, c in iteritems(self.counts):
b ... |
def as_text(self, is_proof=True, is_pretty=False):
"""Return the DDO as a JSON text.
:param if is_proof: if False then do not include the 'proof' element.
:param is_pretty: If True return dictionary in a prettier way, bool
:return: str
"""
data = self.as_dictionary(is_pr... | Return the DDO as a JSON text.
:param if is_proof: if False then do not include the 'proof' element.
:param is_pretty: If True return dictionary in a prettier way, bool
:return: str | Below is the the instruction that describes the task:
### Input:
Return the DDO as a JSON text.
:param if is_proof: if False then do not include the 'proof' element.
:param is_pretty: If True return dictionary in a prettier way, bool
:return: str
### Response:
def as_text(self, is_proof=Tr... |
def add(self, fn_process: Callable, *args: Any, **kwargs: Any) -> 'Process':
"""
Adds a process to the simulation. The process is embodied by a function, which will be called with the given
positional and keyword parameters when the simulation runs. As a process, this function runs on a special ... | Adds a process to the simulation. The process is embodied by a function, which will be called with the given
positional and keyword parameters when the simulation runs. As a process, this function runs on a special green
thread, and thus will be able to call functions `now()`, `advance()`, `pause()` and... | Below is the the instruction that describes the task:
### Input:
Adds a process to the simulation. The process is embodied by a function, which will be called with the given
positional and keyword parameters when the simulation runs. As a process, this function runs on a special green
thread, and th... |
def print_long(filename, stat, print_func):
"""Prints detailed information about the file passed in."""
size = stat_size(stat)
mtime = stat_mtime(stat)
file_mtime = time.localtime(mtime)
curr_time = time.time()
if mtime > (curr_time + SIX_MONTHS) or mtime < (curr_time - SIX_MONTHS):
prin... | Prints detailed information about the file passed in. | Below is the the instruction that describes the task:
### Input:
Prints detailed information about the file passed in.
### Response:
def print_long(filename, stat, print_func):
"""Prints detailed information about the file passed in."""
size = stat_size(stat)
mtime = stat_mtime(stat)
file_mtime = t... |
def table(
self,
dirPath=None):
"""*Render the results as an ascii table*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `tableSources` -- the top-level transient data
... | *Render the results as an ascii table*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `tableSources` -- the top-level transient data
- `tablePhot` -- all photometry associated with the tran... | Below is the the instruction that describes the task:
### Input:
*Render the results as an ascii table*
**Key Arguments:**
- ``dirPath`` -- the path to the directory to save the rendered results to. Default *None*
**Return:**
- `tableSources` -- the top-level transient data... |
def get_LR(self,in_data):
"""
Splits incoming packed stereo data into separate left and right channels
and returns an array of left samples and an array of right samples
Parameters
----------
in_data : input data from the streaming object in the callback f... | Splits incoming packed stereo data into separate left and right channels
and returns an array of left samples and an array of right samples
Parameters
----------
in_data : input data from the streaming object in the callback function.
Returns
--... | Below is the the instruction that describes the task:
### Input:
Splits incoming packed stereo data into separate left and right channels
and returns an array of left samples and an array of right samples
Parameters
----------
in_data : input data from the streaming obj... |
def configure_logging(debug=False):
"""Configure logging
The function configures log messages. By default, log messages
are sent to stderr. Set the parameter `debug` to activate the
debug mode.
:param debug: set the debug mode
"""
if not debug:
logging.basicConfig(level=logging.INFO,... | Configure logging
The function configures log messages. By default, log messages
are sent to stderr. Set the parameter `debug` to activate the
debug mode.
:param debug: set the debug mode | Below is the the instruction that describes the task:
### Input:
Configure logging
The function configures log messages. By default, log messages
are sent to stderr. Set the parameter `debug` to activate the
debug mode.
:param debug: set the debug mode
### Response:
def configure_logging(debug=Fals... |
def text(self, x, y, txt=''):
"Output a string"
txt = self.normalize_text(txt)
if (self.unifontsubset):
txt2 = self._escape(UTF8ToUTF16BE(txt, False))
for uni in UTF8StringToArray(txt):
self.current_font['subset'].append(uni)
else:
txt2... | Output a string | Below is the the instruction that describes the task:
### Input:
Output a string
### Response:
def text(self, x, y, txt=''):
"Output a string"
txt = self.normalize_text(txt)
if (self.unifontsubset):
txt2 = self._escape(UTF8ToUTF16BE(txt, False))
for uni in UTF8String... |
def parse_host(cls, host):
'''Parse the host and return hostname and port.'''
if host.endswith(']'):
return cls.parse_hostname(host), None
else:
hostname, sep, port = host.rpartition(':')
if sep:
port = int(port)
if port < 0 or port > 6553... | Parse the host and return hostname and port. | Below is the the instruction that describes the task:
### Input:
Parse the host and return hostname and port.
### Response:
def parse_host(cls, host):
'''Parse the host and return hostname and port.'''
if host.endswith(']'):
return cls.parse_hostname(host), None
else:
... |
def is_installed_extension(name,
user=None,
host=None,
port=None,
maintenance_db=None,
password=None,
runas=None):
'''
Test if a specific extension is... | Test if a specific extension is installed
CLI Example:
.. code-block:: bash
salt '*' postgres.is_installed_extension | Below is the the instruction that describes the task:
### Input:
Test if a specific extension is installed
CLI Example:
.. code-block:: bash
salt '*' postgres.is_installed_extension
### Response:
def is_installed_extension(name,
user=None,
ho... |
def convert_timeval(seconds_since_epoch):
"""Convert time into C style timeval."""
frac, whole = math.modf(seconds_since_epoch)
microseconds = math.floor(frac * 1000000)
seconds = math.floor(whole)
return seconds, microseconds | Convert time into C style timeval. | Below is the the instruction that describes the task:
### Input:
Convert time into C style timeval.
### Response:
def convert_timeval(seconds_since_epoch):
"""Convert time into C style timeval."""
frac, whole = math.modf(seconds_since_epoch)
microseconds = math.floor(frac * 1000000)
seconds = math.... |
def run():
"""CLI main entry point."""
# Use print() instead of logging when running in CLI mode:
set_pyftpsync_logger(None)
parser = argparse.ArgumentParser(
description="Synchronize folders over FTP.",
epilog="See also https://github.com/mar10/pyftpsync",
parents=[ve... | CLI main entry point. | Below is the the instruction that describes the task:
### Input:
CLI main entry point.
### Response:
def run():
"""CLI main entry point."""
# Use print() instead of logging when running in CLI mode:
set_pyftpsync_logger(None)
parser = argparse.ArgumentParser(
description="Synchroni... |
def _format_type(cls):
"""Format a type name for printing."""
if cls.__module__ == _BUILTIN_MODULE:
return cls.__name__
else:
return '%s.%s' % (cls.__module__, cls.__name__) | Format a type name for printing. | Below is the the instruction that describes the task:
### Input:
Format a type name for printing.
### Response:
def _format_type(cls):
"""Format a type name for printing."""
if cls.__module__ == _BUILTIN_MODULE:
return cls.__name__
else:
return '%s.%s' % (cls.__module__, cls.__name__) |
def datetime_from_ordinal_float(days):
"""Inverse of `ordinal_float()`, converts a float number of days back to a `datetime` object
>>> dt = datetime.datetime(1970, 1, 1)
>>> datetime_from_ordinal_float(ordinal_float(dt)) == dt
True
>>> dt = datetime.datetime(1, 2, 3, 4, 5, 6, 7)
>>> datetime_f... | Inverse of `ordinal_float()`, converts a float number of days back to a `datetime` object
>>> dt = datetime.datetime(1970, 1, 1)
>>> datetime_from_ordinal_float(ordinal_float(dt)) == dt
True
>>> dt = datetime.datetime(1, 2, 3, 4, 5, 6, 7)
>>> datetime_from_ordinal_float(ordinal_float(dt)) == dt
... | Below is the the instruction that describes the task:
### Input:
Inverse of `ordinal_float()`, converts a float number of days back to a `datetime` object
>>> dt = datetime.datetime(1970, 1, 1)
>>> datetime_from_ordinal_float(ordinal_float(dt)) == dt
True
>>> dt = datetime.datetime(1, 2, 3, 4, 5, 6... |
def version(self, flag=None, cmd=None, path=None):
"""
Generates and logs a hash to distinguish this particular installation
of the program (on a certain host, with a certain compiler, program
version, etc.)
Specify the optional 'binary' argument if the wrapper name is not
actually the program, e.g. if you... | Generates and logs a hash to distinguish this particular installation
of the program (on a certain host, with a certain compiler, program
version, etc.)
Specify the optional 'binary' argument if the wrapper name is not
actually the program, e.g. if your program has a Perl wrapper script.
Set 'binary' to the ... | Below is the the instruction that describes the task:
### Input:
Generates and logs a hash to distinguish this particular installation
of the program (on a certain host, with a certain compiler, program
version, etc.)
Specify the optional 'binary' argument if the wrapper name is not
actually the program, e... |
def K2OSiO2(self, Left=35, Right=79, X0=30, X1=90, X_Gap=7, Base=0,
Top=19, Y0=1, Y1=19, Y_Gap=19, FontSize=12, xlabel=r'$SiO_2 wt\%$', ylabel=r'$K_2O wt\%$', width=12,
height=12, dpi=300):
self.setWindowTitle('K2OSiO2 diagram ')
self.axes.clear()
#self.axes.axis('off')
... | self.axes.set_xticks([30,40,50,60,70,80,90])
self.axes.set_xticklabels([30,40,50,60,70,80,90])
self.axes.set_yticks([0, 5, 10, 15, 20])
self.axes.set_yticklabels([0, 5, 10, 15, 20])
self.axes.set_ylim(bottom=0) | Below is the the instruction that describes the task:
### Input:
self.axes.set_xticks([30,40,50,60,70,80,90])
self.axes.set_xticklabels([30,40,50,60,70,80,90])
self.axes.set_yticks([0, 5, 10, 15, 20])
self.axes.set_yticklabels([0, 5, 10, 15, 20])
self.axes.set_ylim(bottom=0)
### Re... |
def forward(self, sequence):
""" Forward propagate batch of sequences through the network, without accounting for the state """
data = self.input_block(sequence)
for idx in range(len(self.rnn_layers)):
data, _ = self.rnn_layers[idx](data)
if self.rnn_dropout_layers:
... | Forward propagate batch of sequences through the network, without accounting for the state | Below is the the instruction that describes the task:
### Input:
Forward propagate batch of sequences through the network, without accounting for the state
### Response:
def forward(self, sequence):
""" Forward propagate batch of sequences through the network, without accounting for the state """
d... |
def check_name_availability_local(
self, location, name, type, custom_headers=None, raw=False, **operation_config):
"""Check Name Availability for global uniqueness.
:param location: The location in which uniqueness will be verified.
:type location: str
:param name: Resource... | Check Name Availability for global uniqueness.
:param location: The location in which uniqueness will be verified.
:type location: str
:param name: Resource Name To Verify
:type name: str
:param type: Fully qualified resource type which includes provider
namespace
... | Below is the the instruction that describes the task:
### Input:
Check Name Availability for global uniqueness.
:param location: The location in which uniqueness will be verified.
:type location: str
:param name: Resource Name To Verify
:type name: str
:param type: Fully qua... |
async def get_match(self, m_id, force_update=False) -> Match:
""" get a single match by id
|methcoro|
Args:
m_id: match id
force_update (default=False): True to force an update to the Challonge API
Returns:
Match
Raises:
APIExce... | get a single match by id
|methcoro|
Args:
m_id: match id
force_update (default=False): True to force an update to the Challonge API
Returns:
Match
Raises:
APIException | Below is the the instruction that describes the task:
### Input:
get a single match by id
|methcoro|
Args:
m_id: match id
force_update (default=False): True to force an update to the Challonge API
Returns:
Match
Raises:
APIException... |
def _modem_sm(self):
"""Handle modem response state machine."""
import datetime
read_timeout = READ_IDLE_TIMEOUT
while self.ser:
try:
resp = self.read(read_timeout)
except (serial.SerialException, SystemExit, TypeError):
_LOGGER.de... | Handle modem response state machine. | Below is the the instruction that describes the task:
### Input:
Handle modem response state machine.
### Response:
def _modem_sm(self):
"""Handle modem response state machine."""
import datetime
read_timeout = READ_IDLE_TIMEOUT
while self.ser:
try:
resp... |
def do_requests_to_getall(self, uri, requested_count):
"""Helps to make http request for get_all method.
Note:
This method will be checking for the pagination URI in the response
and make request to pagination URI to get all the resources.
"""
items = []
... | Helps to make http request for get_all method.
Note:
This method will be checking for the pagination URI in the response
and make request to pagination URI to get all the resources. | Below is the the instruction that describes the task:
### Input:
Helps to make http request for get_all method.
Note:
This method will be checking for the pagination URI in the response
and make request to pagination URI to get all the resources.
### Response:
def do_requests_to_ge... |
def option_group_exists(name, tags=None, region=None, key=None, keyid=None,
profile=None):
'''
Check to see if an RDS option group exists.
CLI example::
salt myminion boto_rds.option_group_exists myoptiongr region=us-east-1
'''
conn = _get_conn(region=region, key=ke... | Check to see if an RDS option group exists.
CLI example::
salt myminion boto_rds.option_group_exists myoptiongr region=us-east-1 | Below is the the instruction that describes the task:
### Input:
Check to see if an RDS option group exists.
CLI example::
salt myminion boto_rds.option_group_exists myoptiongr region=us-east-1
### Response:
def option_group_exists(name, tags=None, region=None, key=None, keyid=None,
... |
def get_comment_init(request, obj):
"""
Возвращает словарь для инициализации начальных значений модели комментария
:param request: запрос
:param obj: объект к которому добавляется комментарий
:return:
"""
if request.user.is_authenticated():
init = {'obj': obj, 'username': request.use... | Возвращает словарь для инициализации начальных значений модели комментария
:param request: запрос
:param obj: объект к которому добавляется комментарий
:return: | Below is the the instruction that describes the task:
### Input:
Возвращает словарь для инициализации начальных значений модели комментария
:param request: запрос
:param obj: объект к которому добавляется комментарий
:return:
### Response:
def get_comment_init(request, obj):
"""
Возвращает слов... |
def pairwise_intersection(boxlist1, boxlist2):
"""Compute pairwise intersection areas between boxes.
Args:
boxlist1: Nx4 floatbox
boxlist2: Mx4
Returns:
a tensor with shape [N, M] representing pairwise intersections
"""
x_min1, y_min1, x_max1, y_max1 = tf.split(boxlist1, 4, axis=... | Compute pairwise intersection areas between boxes.
Args:
boxlist1: Nx4 floatbox
boxlist2: Mx4
Returns:
a tensor with shape [N, M] representing pairwise intersections | Below is the the instruction that describes the task:
### Input:
Compute pairwise intersection areas between boxes.
Args:
boxlist1: Nx4 floatbox
boxlist2: Mx4
Returns:
a tensor with shape [N, M] representing pairwise intersections
### Response:
def pairwise_intersection(boxlist1, boxlis... |
def get_buys(self, account_id, **params):
"""https://developers.coinbase.com/api/v2#list-buys"""
response = self._get('v2', 'accounts', account_id, 'buys', params=params)
return self._make_api_object(response, Buy) | https://developers.coinbase.com/api/v2#list-buys | Below is the the instruction that describes the task:
### Input:
https://developers.coinbase.com/api/v2#list-buys
### Response:
def get_buys(self, account_id, **params):
"""https://developers.coinbase.com/api/v2#list-buys"""
response = self._get('v2', 'accounts', account_id, 'buys', params=params)
... |
def validate(self, value, model_instance):
"""
Use custom validation for when using a multiple countries field.
"""
if not self.multiple:
return super(CountryField, self).validate(value, model_instance)
if not self.editable:
# Skip validation for non-edit... | Use custom validation for when using a multiple countries field. | Below is the the instruction that describes the task:
### Input:
Use custom validation for when using a multiple countries field.
### Response:
def validate(self, value, model_instance):
"""
Use custom validation for when using a multiple countries field.
"""
if not self.multiple:
... |
def encode_network(root):
"""Yield ref-containing obj table entries from object network"""
orig_objects = []
objects = []
def get_ref(value, objects=objects):
"""Returns the index of the given object in the object table,
adding it if needed.
"""
value = PythonicAdapter(... | Yield ref-containing obj table entries from object network | Below is the the instruction that describes the task:
### Input:
Yield ref-containing obj table entries from object network
### Response:
def encode_network(root):
"""Yield ref-containing obj table entries from object network"""
orig_objects = []
objects = []
def get_ref(value, objects=objects):
... |
def update_courses(self, event, account_id, course_ids):
"""
Update courses.
Update multiple courses in an account. Operates asynchronously; use the {api:ProgressController#show progress endpoint}
to query the status of an operation.
The action to take on each c... | Update courses.
Update multiple courses in an account. Operates asynchronously; use the {api:ProgressController#show progress endpoint}
to query the status of an operation.
The action to take on each course. Must be one of 'offer', 'conclude', 'delete', or 'undelete'.
... | Below is the the instruction that describes the task:
### Input:
Update courses.
Update multiple courses in an account. Operates asynchronously; use the {api:ProgressController#show progress endpoint}
to query the status of an operation.
The action to take on each course. Mu... |
def __getFormat(self, format):
"""
Defaults to JSON [ps: 'RDF' is the native rdflib representation]
"""
if format == "XML":
self.sparql.setReturnFormat(XML)
self.format = "XML"
elif format == "RDF":
self.sparql.setReturnFormat(RDF)
self.format = "RDF"
else:
self.sparql.setReturnFormat(JSON)
... | Defaults to JSON [ps: 'RDF' is the native rdflib representation] | Below is the the instruction that describes the task:
### Input:
Defaults to JSON [ps: 'RDF' is the native rdflib representation]
### Response:
def __getFormat(self, format):
"""
Defaults to JSON [ps: 'RDF' is the native rdflib representation]
"""
if format == "XML":
self.sparql.setReturnFormat(XML)
... |
def for_me(conditions, myself):
""" Am I among the intended audiences """
if not conditions.audience_restriction: # No audience restriction
return True
for restriction in conditions.audience_restriction:
if not restriction.audience:
continue
for audience in restriction... | Am I among the intended audiences | Below is the the instruction that describes the task:
### Input:
Am I among the intended audiences
### Response:
def for_me(conditions, myself):
""" Am I among the intended audiences """
if not conditions.audience_restriction: # No audience restriction
return True
for restriction in conditio... |
def centroids(self, instrument, min_abundance=1e-4, points_per_fwhm=25):
"""
Estimates centroided peaks for a given instrument model.
:param instrument: instrument model
:param min_abundance: minimum abundance for including a peak
:param points_per_fwhm: grid density used for en... | Estimates centroided peaks for a given instrument model.
:param instrument: instrument model
:param min_abundance: minimum abundance for including a peak
:param points_per_fwhm: grid density used for envelope calculation
:returns: peaks visible with the instrument used
:rtype: T... | Below is the the instruction that describes the task:
### Input:
Estimates centroided peaks for a given instrument model.
:param instrument: instrument model
:param min_abundance: minimum abundance for including a peak
:param points_per_fwhm: grid density used for envelope calculation
... |
def create_user(self, account_id, pseudonym_unique_id, communication_channel_address=None, communication_channel_confirmation_url=None, communication_channel_skip_confirmation=None, communication_channel_type=None, enable_sis_reactivation=None, force_validations=None, pseudonym_authentication_provider_id=None, pseudony... | Create a user.
Create and return a new user and pseudonym for an account.
If you don't have the "Modify login details for users" permission, but
self-registration is enabled on the account, you can still use this
endpoint to register new users. Certain fields will be requ... | Below is the the instruction that describes the task:
### Input:
Create a user.
Create and return a new user and pseudonym for an account.
If you don't have the "Modify login details for users" permission, but
self-registration is enabled on the account, you can still use this... |
def _set_blob_properties(self, ud):
# type: (Uploader, blobxfer.models.upload.Descriptor) -> None
"""Set blob properties (md5, cache control)
:param Uploader self: this
:param blobxfer.models.upload.Descriptor ud: upload descriptor
"""
if ud.requires_non_encrypted_md5_put... | Set blob properties (md5, cache control)
:param Uploader self: this
:param blobxfer.models.upload.Descriptor ud: upload descriptor | Below is the the instruction that describes the task:
### Input:
Set blob properties (md5, cache control)
:param Uploader self: this
:param blobxfer.models.upload.Descriptor ud: upload descriptor
### Response:
def _set_blob_properties(self, ud):
# type: (Uploader, blobxfer.models.upload.Des... |
def is_field_unique_by_group(df, field_col, group_col):
''' Determine if field is constant by group in df
'''
def num_unique(x):
return len(pd.unique(x))
num_distinct = df.groupby(group_col)[field_col].agg(num_unique)
return all(num_distinct == 1) | Determine if field is constant by group in df | Below is the the instruction that describes the task:
### Input:
Determine if field is constant by group in df
### Response:
def is_field_unique_by_group(df, field_col, group_col):
''' Determine if field is constant by group in df
'''
def num_unique(x):
return len(pd.unique(x))
num_distinct... |
def startLoop():
"""
Use nested asyncio event loop for Jupyter notebooks.
"""
def _ipython_loop_asyncio(kernel):
'''
Use asyncio event loop for the given IPython kernel.
'''
loop = asyncio.get_event_loop()
def kernel_handler():
kernel.do_one_iteration... | Use nested asyncio event loop for Jupyter notebooks. | Below is the the instruction that describes the task:
### Input:
Use nested asyncio event loop for Jupyter notebooks.
### Response:
def startLoop():
"""
Use nested asyncio event loop for Jupyter notebooks.
"""
def _ipython_loop_asyncio(kernel):
'''
Use asyncio event loop for the giv... |
def determine_packages_to_sync(self):
"""
Update the self.packages_to_sync to contain packages that need to be
synced.
"""
# In case we don't find any changes we will stay on the currently
# synced serial.
self.target_serial = self.synced_serial
self.packa... | Update the self.packages_to_sync to contain packages that need to be
synced. | Below is the the instruction that describes the task:
### Input:
Update the self.packages_to_sync to contain packages that need to be
synced.
### Response:
def determine_packages_to_sync(self):
"""
Update the self.packages_to_sync to contain packages that need to be
synced.
... |
def get(self, value):
"""
Get an enumeration item for an enumeration value.
:param unicode value: Enumeration value.
:raise InvalidEnumItem: If ``value`` does not match any known
enumeration value.
:rtype: EnumItem
"""
_nothing = object()
item = s... | Get an enumeration item for an enumeration value.
:param unicode value: Enumeration value.
:raise InvalidEnumItem: If ``value`` does not match any known
enumeration value.
:rtype: EnumItem | Below is the the instruction that describes the task:
### Input:
Get an enumeration item for an enumeration value.
:param unicode value: Enumeration value.
:raise InvalidEnumItem: If ``value`` does not match any known
enumeration value.
:rtype: EnumItem
### Response:
def get(self, ... |
def set_stop_chars(self, stop_chars):
"""
Set stop characters used when determining end of URL.
.. deprecated:: 0.7
Use :func:`set_stop_chars_left` or :func:`set_stop_chars_right`
instead.
:param list stop_chars: list of characters
"""
warnings.... | Set stop characters used when determining end of URL.
.. deprecated:: 0.7
Use :func:`set_stop_chars_left` or :func:`set_stop_chars_right`
instead.
:param list stop_chars: list of characters | Below is the the instruction that describes the task:
### Input:
Set stop characters used when determining end of URL.
.. deprecated:: 0.7
Use :func:`set_stop_chars_left` or :func:`set_stop_chars_right`
instead.
:param list stop_chars: list of characters
### Response:
def ... |
def newsnr_sgveto_psdvar(snr, bchisq, sgchisq, psd_var_val):
""" Combined SNR derived from NewSNR, Sine-Gaussian Chisq and PSD
variation statistic """
nsnr = numpy.array(newsnr_sgveto(snr, bchisq, sgchisq), ndmin=1)
psd_var_val = numpy.array(psd_var_val, ndmin=1)
lgc = psd_var_val >= 1.8
nsnr[lg... | Combined SNR derived from NewSNR, Sine-Gaussian Chisq and PSD
variation statistic | Below is the the instruction that describes the task:
### Input:
Combined SNR derived from NewSNR, Sine-Gaussian Chisq and PSD
variation statistic
### Response:
def newsnr_sgveto_psdvar(snr, bchisq, sgchisq, psd_var_val):
""" Combined SNR derived from NewSNR, Sine-Gaussian Chisq and PSD
variation stati... |
def process(cls, post, render=True):
"""
This method takes the post data and renders it
:param post:
:param render:
:return:
"""
post["slug"] = cls.create_slug(post["title"])
post["editable"] = cls.is_author(post, current_user)
post["url"] = cls.co... | This method takes the post data and renders it
:param post:
:param render:
:return: | Below is the the instruction that describes the task:
### Input:
This method takes the post data and renders it
:param post:
:param render:
:return:
### Response:
def process(cls, post, render=True):
"""
This method takes the post data and renders it
:param post:
... |
def get_sort_on(allowed_indexes=None):
""" returns the 'sort_on' from the request
"""
sort_on = get("sort_on")
if allowed_indexes and sort_on not in allowed_indexes:
logger.warn("Index '{}' is not in allowed_indexes".format(sort_on))
return None
return sort_on | returns the 'sort_on' from the request | Below is the the instruction that describes the task:
### Input:
returns the 'sort_on' from the request
### Response:
def get_sort_on(allowed_indexes=None):
""" returns the 'sort_on' from the request
"""
sort_on = get("sort_on")
if allowed_indexes and sort_on not in allowed_indexes:
logger.... |
def write(self, outfile=None, section=None):
"""Write the current config to a file (defaults to user config).
:param str outfile: The path to the file to write to.
:param None/str section: The config section to write, or :data:`None`
to write the entire config.
... | Write the current config to a file (defaults to user config).
:param str outfile: The path to the file to write to.
:param None/str section: The config section to write, or :data:`None`
to write the entire config. | Below is the the instruction that describes the task:
### Input:
Write the current config to a file (defaults to user config).
:param str outfile: The path to the file to write to.
:param None/str section: The config section to write, or :data:`None`
to write the en... |
def findDataItems(self, parentPath=None, ancestorPath=None,
type=None, id=None):
"""
You can use this operation to search through the various data
items registered in the server's data store.
Inputs:
parentPath - The path of the parent under w... | You can use this operation to search through the various data
items registered in the server's data store.
Inputs:
parentPath - The path of the parent under which to find items
ancestorPath - The path of the ancestor under which to find
item... | Below is the the instruction that describes the task:
### Input:
You can use this operation to search through the various data
items registered in the server's data store.
Inputs:
parentPath - The path of the parent under which to find items
ancestorPath - The path ... |
def add(self, f_ipaddr, f_macaddr, f_hostname, f_netbios_name, f_engineer, f_asset_group, f_confirmed):
"""
Add a t_hosts record
:param f_ipaddr: IP address
:param f_macaddr: MAC Address
:param f_hostname: Hostname
:param f_netbios_name: NetBIOS Name
:param f_eng... | Add a t_hosts record
:param f_ipaddr: IP address
:param f_macaddr: MAC Address
:param f_hostname: Hostname
:param f_netbios_name: NetBIOS Name
:param f_engineer: Engineer username
:param f_asset_group: Asset group
:param f_confirmed: Confirmed boolean
:re... | Below is the the instruction that describes the task:
### Input:
Add a t_hosts record
:param f_ipaddr: IP address
:param f_macaddr: MAC Address
:param f_hostname: Hostname
:param f_netbios_name: NetBIOS Name
:param f_engineer: Engineer username
:param f_asset_group: ... |
def domain(host, port, username, password, avail_timeout=240.):
"""
Endpoint domain.
:param str host:
Endpoint host.
:param int port:
Endpoint port.
:param str username:
Endpoint username.
:param str password:
Endpoint password.
:param float avail_timeout:
Availability check timeout in se... | Endpoint domain.
:param str host:
Endpoint host.
:param int port:
Endpoint port.
:param str username:
Endpoint username.
:param str password:
Endpoint password.
:param float avail_timeout:
Availability check timeout in seconds.
:rtype:
Domain
:return:
Domain for the given endpoint p... | Below is the the instruction that describes the task:
### Input:
Endpoint domain.
:param str host:
Endpoint host.
:param int port:
Endpoint port.
:param str username:
Endpoint username.
:param str password:
Endpoint password.
:param float avail_timeout:
Availability check timeout in secon... |
def _get_function_matches(attributes_a, attributes_b, filter_set_a=None, filter_set_b=None):
"""
:param attributes_a: A dict of functions to their attributes
:param attributes_b: A dict of functions to their attributes
The following parameters are optional.
:param filter_... | :param attributes_a: A dict of functions to their attributes
:param attributes_b: A dict of functions to their attributes
The following parameters are optional.
:param filter_set_a: A set to limit attributes_a to the functions in this set.
:param filter_set_b: A set to limi... | Below is the the instruction that describes the task:
### Input:
:param attributes_a: A dict of functions to their attributes
:param attributes_b: A dict of functions to their attributes
The following parameters are optional.
:param filter_set_a: A set to limit attributes_a to the... |
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
images = avail_images()
for key, value in six.iteritems(images):
if vm_image and vm_image in (images[key]['... | Return the image object to use | Below is the the instruction that describes the task:
### Input:
Return the image object to use
### Response:
def get_image(vm_):
'''
Return the image object to use
'''
vm_image = config.get_cloud_config_value('image', vm_, __opts__).encode(
'ascii', 'salt-cloud-force-ascii'
)
imag... |
def on_any_event(self, event):
"""On any event method"""
for delegate in self.delegates:
if hasattr(delegate, "on_any_event"):
delegate.on_any_event(event) | On any event method | Below is the the instruction that describes the task:
### Input:
On any event method
### Response:
def on_any_event(self, event):
"""On any event method"""
for delegate in self.delegates:
if hasattr(delegate, "on_any_event"):
delegate.on_any_event(event) |
def absolute_url_for(endpoint, **values):
"""Absolute url for endpoint."""
config = current_app.config
site_domain = config.get('SITE_DOMAIN')
relative_url = url_for(endpoint, **values)
return join_url(site_domain, relative_url) | Absolute url for endpoint. | Below is the the instruction that describes the task:
### Input:
Absolute url for endpoint.
### Response:
def absolute_url_for(endpoint, **values):
"""Absolute url for endpoint."""
config = current_app.config
site_domain = config.get('SITE_DOMAIN')
relative_url = url_for(endpoint, **values)
ret... |
def find_host_network_interfaces_of_type(self, type_p):
"""Searches through all host network interfaces and returns a list of interfaces of the specified type
in type_p of type :class:`HostNetworkInterfaceType`
type of the host network interfaces to search for.
return network_inter... | Searches through all host network interfaces and returns a list of interfaces of the specified type
in type_p of type :class:`HostNetworkInterfaceType`
type of the host network interfaces to search for.
return network_interfaces of type :class:`IHostNetworkInterface`
Found host... | Below is the the instruction that describes the task:
### Input:
Searches through all host network interfaces and returns a list of interfaces of the specified type
in type_p of type :class:`HostNetworkInterfaceType`
type of the host network interfaces to search for.
return network_int... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.