code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _parse_features(cls, feat_response):
# type: (Text) -> Dict[Text, Text]
"""Parse a dict of features from FTP feat response.
"""
features = {}
if feat_response.split("-")[0] == "211":
for line in feat_response.splitlines():
if line.startswith(" "):
... | Parse a dict of features from FTP feat response. | Below is the the instruction that describes the task:
### Input:
Parse a dict of features from FTP feat response.
### Response:
def _parse_features(cls, feat_response):
# type: (Text) -> Dict[Text, Text]
"""Parse a dict of features from FTP feat response.
"""
features = {}
i... |
def _kill_process(self, pid, cgroups=None, sig=signal.SIGKILL):
"""
Try to send signal to given process, either directly of with sudo.
Because we cannot send signals to the sudo process itself,
this method checks whether the target is the sudo process
and redirects the signal to ... | Try to send signal to given process, either directly of with sudo.
Because we cannot send signals to the sudo process itself,
this method checks whether the target is the sudo process
and redirects the signal to sudo's child in this case. | Below is the the instruction that describes the task:
### Input:
Try to send signal to given process, either directly of with sudo.
Because we cannot send signals to the sudo process itself,
this method checks whether the target is the sudo process
and redirects the signal to sudo's child in... |
def main():
""" Main
"""
args, otherthings = parse_known_args()
if args.version:
print_version()
return 0
verbosity = 0
if args.verbose:
verbosity = 1
far = Far(verbosity=verbosity)
if args.dry_run:
far.dry_run(old=args.old)
else:
far.find_... | Main | Below is the the instruction that describes the task:
### Input:
Main
### Response:
def main():
""" Main
"""
args, otherthings = parse_known_args()
if args.version:
print_version()
return 0
verbosity = 0
if args.verbose:
verbosity = 1
far = Far(verbosity=verbo... |
def skip_all(self):
"""Skip all readings in this walker."""
storage, streaming = self.engine.count()
if self.selector.output:
self.offset = streaming
else:
self.offset = storage
self._count = 0 | Skip all readings in this walker. | Below is the the instruction that describes the task:
### Input:
Skip all readings in this walker.
### Response:
def skip_all(self):
"""Skip all readings in this walker."""
storage, streaming = self.engine.count()
if self.selector.output:
self.offset = streaming
else:
... |
def get_most_relevant_words_for_topic(vocab, rel_mat, topic, n=None):
"""
Get words from `vocab` for `topic` ordered by most to least relevance (Sievert and Shirley 2014) using the relevance
matrix `rel_mat` obtained from `get_topic_word_relevance()`.
Optionally only return the `n` most relevant words.
... | Get words from `vocab` for `topic` ordered by most to least relevance (Sievert and Shirley 2014) using the relevance
matrix `rel_mat` obtained from `get_topic_word_relevance()`.
Optionally only return the `n` most relevant words. | Below is the the instruction that describes the task:
### Input:
Get words from `vocab` for `topic` ordered by most to least relevance (Sievert and Shirley 2014) using the relevance
matrix `rel_mat` obtained from `get_topic_word_relevance()`.
Optionally only return the `n` most relevant words.
### Response:... |
def _exposure_to_weights(self, y, exposure=None, weights=None):
"""simple tool to create a common API
Parameters
----------
y : array-like, shape (n_samples,)
Target values (integers in classification, real numbers in
regression)
For classification, l... | simple tool to create a common API
Parameters
----------
y : array-like, shape (n_samples,)
Target values (integers in classification, real numbers in
regression)
For classification, labels must correspond to classes.
exposure : array-like shape (n_sa... | Below is the the instruction that describes the task:
### Input:
simple tool to create a common API
Parameters
----------
y : array-like, shape (n_samples,)
Target values (integers in classification, real numbers in
regression)
For classification, labels ... |
def comparelist_view(self, request, object_id, extra_context=None):
"""Allow selecting versions to compare."""
opts = self.model._meta
object_id = unquote(object_id)
current = get_object_or_404(self.model, pk=object_id)
# As done by reversion's history_view
action_list = ... | Allow selecting versions to compare. | Below is the the instruction that describes the task:
### Input:
Allow selecting versions to compare.
### Response:
def comparelist_view(self, request, object_id, extra_context=None):
"""Allow selecting versions to compare."""
opts = self.model._meta
object_id = unquote(object_id)
c... |
def print_genl_hdr(ofd, start):
"""https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L821.
Positional arguments:
ofd -- function to call with arguments similar to `logging.debug`.
start -- bytearray() or bytearray_ptr() instance.
"""
ghdr = genlmsghdr(start)
ofd(' [GENERIC NETLIN... | https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L821.
Positional arguments:
ofd -- function to call with arguments similar to `logging.debug`.
start -- bytearray() or bytearray_ptr() instance. | Below is the the instruction that describes the task:
### Input:
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/msg.c#L821.
Positional arguments:
ofd -- function to call with arguments similar to `logging.debug`.
start -- bytearray() or bytearray_ptr() instance.
### Response:
def print_genl_hdr... |
def do_http_repo(self, repo):
'''
[Re]define REPO as http package repository.
http_repo REPO
'''
self.abort_on_missing_effective_repo_name(repo, 'http_repo')
repo_name = self.get_effective_repo_name(repo)
try:
self.network.set(repo_name, REPO.TYPE, RE... | [Re]define REPO as http package repository.
http_repo REPO | Below is the the instruction that describes the task:
### Input:
[Re]define REPO as http package repository.
http_repo REPO
### Response:
def do_http_repo(self, repo):
'''
[Re]define REPO as http package repository.
http_repo REPO
'''
self.abort_on_missing_effectiv... |
def point(self, t):
"""returns the coordinates of the Bezier curve evaluated at t."""
distance = self.end - self.start
return self.start + distance*t | returns the coordinates of the Bezier curve evaluated at t. | Below is the the instruction that describes the task:
### Input:
returns the coordinates of the Bezier curve evaluated at t.
### Response:
def point(self, t):
"""returns the coordinates of the Bezier curve evaluated at t."""
distance = self.end - self.start
return self.start + distance*t |
def from_string(cls, action_str):
"""
Creates a new Action instance from the given string.
The given string **must** match one of those patterns:
* module.function
* module.function()
* module.function(arg1=value1, arg2=value2)
Any other form will t... | Creates a new Action instance from the given string.
The given string **must** match one of those patterns:
* module.function
* module.function()
* module.function(arg1=value1, arg2=value2)
Any other form will trigger an Exception.
The function parses the ... | Below is the the instruction that describes the task:
### Input:
Creates a new Action instance from the given string.
The given string **must** match one of those patterns:
* module.function
* module.function()
* module.function(arg1=value1, arg2=value2)
Any ot... |
def get_service_marketplace(self, available=True, unavailable=False,
deprecated=False):
"""
Returns a list of service names. Can return all services, just
those supported by PredixPy, or just those not yet supported by
PredixPy.
:param available: Return the services... | Returns a list of service names. Can return all services, just
those supported by PredixPy, or just those not yet supported by
PredixPy.
:param available: Return the services that are
available in PredixPy. (Defaults to True)
:param unavailable: Return the services that a... | Below is the the instruction that describes the task:
### Input:
Returns a list of service names. Can return all services, just
those supported by PredixPy, or just those not yet supported by
PredixPy.
:param available: Return the services that are
available in PredixPy. (Defa... |
def do_reload(module: types.ModuleType, newer_than: int) -> bool:
"""
Executes the reload of the specified module if the source file that it was
loaded from was updated more recently than the specified time
:param module:
A module object to be reloaded
:param newer_than:
The time in... | Executes the reload of the specified module if the source file that it was
loaded from was updated more recently than the specified time
:param module:
A module object to be reloaded
:param newer_than:
The time in seconds since epoch that should be used to determine if
the module ne... | Below is the the instruction that describes the task:
### Input:
Executes the reload of the specified module if the source file that it was
loaded from was updated more recently than the specified time
:param module:
A module object to be reloaded
:param newer_than:
The time in seconds ... |
def get_model_home():
'''
Returns a root folder path for downloading models.
'''
d = os.path.join(get_data_home(), 'nnp_models')
if not os.path.isdir(d):
os.makedirs(d)
return d | Returns a root folder path for downloading models. | Below is the the instruction that describes the task:
### Input:
Returns a root folder path for downloading models.
### Response:
def get_model_home():
'''
Returns a root folder path for downloading models.
'''
d = os.path.join(get_data_home(), 'nnp_models')
if not os.path.isdir(d):
os.... |
def ntpl2array(ntpl):
"""
Convert a :func:`collections.namedtuple` object to a :class:`numpy.ndarray`
object that can be saved using :func:`numpy.savez`.
Parameters
----------
ntpl : collections.namedtuple object
Named tuple object to be converted to ndarray
Returns
-------
a... | Convert a :func:`collections.namedtuple` object to a :class:`numpy.ndarray`
object that can be saved using :func:`numpy.savez`.
Parameters
----------
ntpl : collections.namedtuple object
Named tuple object to be converted to ndarray
Returns
-------
arr : ndarray
Array represent... | Below is the the instruction that describes the task:
### Input:
Convert a :func:`collections.namedtuple` object to a :class:`numpy.ndarray`
object that can be saved using :func:`numpy.savez`.
Parameters
----------
ntpl : collections.namedtuple object
Named tuple object to be converted to nda... |
def feed(self, image):
"""
Feeds the network with an image
:param image: image (perhaps loaded with CV2)
:return: network result
"""
network_name = self.__class__.__name__.lower()
with tf.variable_scope(network_name):
return self._feed(image) | Feeds the network with an image
:param image: image (perhaps loaded with CV2)
:return: network result | Below is the the instruction that describes the task:
### Input:
Feeds the network with an image
:param image: image (perhaps loaded with CV2)
:return: network result
### Response:
def feed(self, image):
"""
Feeds the network with an image
:param image: image (perhaps loaded... |
def _find_template(self, template, tree, blocks, with_filename,
source, comment):
"""
If tree is true, then will display the track of template extend or include
"""
from uliweb import application
from uliweb.core.template import _format_code
de... | If tree is true, then will display the track of template extend or include | Below is the the instruction that describes the task:
### Input:
If tree is true, then will display the track of template extend or include
### Response:
def _find_template(self, template, tree, blocks, with_filename,
source, comment):
"""
If tree is true, then will display th... |
def filter(self, node, condition):
"""
This method accepts a node and the condition function; a
generator will be returned to yield the nodes that got matched
by the condition.
"""
if not isinstance(node, Node):
raise TypeError('not a node')
for chil... | This method accepts a node and the condition function; a
generator will be returned to yield the nodes that got matched
by the condition. | Below is the the instruction that describes the task:
### Input:
This method accepts a node and the condition function; a
generator will be returned to yield the nodes that got matched
by the condition.
### Response:
def filter(self, node, condition):
"""
This method accepts a node ... |
def decode_file(fname):
"""Given the name of a pcap file, open it, decode the contents and yield each packet."""
if _debug: decode_file._debug("decode_file %r", fname)
if not pcap:
raise RuntimeError("failed to import pcap")
# create a pcap object, reading from the file
p = pcap.pcap(fname... | Given the name of a pcap file, open it, decode the contents and yield each packet. | Below is the the instruction that describes the task:
### Input:
Given the name of a pcap file, open it, decode the contents and yield each packet.
### Response:
def decode_file(fname):
"""Given the name of a pcap file, open it, decode the contents and yield each packet."""
if _debug: decode_file._debug("d... |
def __calculate_always_decrease_rw_values(
table_name, read_units, provisioned_reads,
write_units, provisioned_writes):
""" Calculate values for always-decrease-rw-together
This will only return reads and writes decreases if both reads and writes
are lower than the current provisioning
... | Calculate values for always-decrease-rw-together
This will only return reads and writes decreases if both reads and writes
are lower than the current provisioning
:type table_name: str
:param table_name: Name of the DynamoDB table
:type read_units: int
:param read_units: New read unit provisi... | Below is the the instruction that describes the task:
### Input:
Calculate values for always-decrease-rw-together
This will only return reads and writes decreases if both reads and writes
are lower than the current provisioning
:type table_name: str
:param table_name: Name of the DynamoDB table
... |
def login(request):
'''
Logs in the user via given login and password.
'''
serializer_class = registration_settings.LOGIN_SERIALIZER_CLASS
serializer = serializer_class(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.get_authenticated_user()
if not user:
... | Logs in the user via given login and password. | Below is the the instruction that describes the task:
### Input:
Logs in the user via given login and password.
### Response:
def login(request):
'''
Logs in the user via given login and password.
'''
serializer_class = registration_settings.LOGIN_SERIALIZER_CLASS
serializer = serializer_class(... |
def static_arp_entry(self, ipaddress, macaddress, arp_type='static', netmask=32):
"""
Add an arp entry to this physical interface.
::
interface = engine.physical_interface.get(0)
interface.static_arp_entry(
ipaddress='23.23.23.23',
arp_typ... | Add an arp entry to this physical interface.
::
interface = engine.physical_interface.get(0)
interface.static_arp_entry(
ipaddress='23.23.23.23',
arp_type='static',
macaddress='02:02:02:02:04:04')
interface.save()
:par... | Below is the the instruction that describes the task:
### Input:
Add an arp entry to this physical interface.
::
interface = engine.physical_interface.get(0)
interface.static_arp_entry(
ipaddress='23.23.23.23',
arp_type='static',
macad... |
def CheckIfCanStartClientFlow(self, username, flow_name):
"""Checks whether a given user can start a given flow."""
del username # Unused.
flow_cls = flow.GRRFlow.GetPlugin(flow_name)
if not flow_cls.category:
raise access_control.UnauthorizedAccess(
"Flow %s can't be started via the ... | Checks whether a given user can start a given flow. | Below is the the instruction that describes the task:
### Input:
Checks whether a given user can start a given flow.
### Response:
def CheckIfCanStartClientFlow(self, username, flow_name):
"""Checks whether a given user can start a given flow."""
del username # Unused.
flow_cls = flow.GRRFlow.GetPlug... |
def attack(a, d, s):
"""
Linear ADS fading attack stream generator, useful to be multiplied with a
given stream.
Parameters
----------
a :
"Attack" time, in number of samples.
d :
"Decay" time, in number of samples.
s :
"Sustain" amplitude level (should be based on attack amplitude).
Th... | Linear ADS fading attack stream generator, useful to be multiplied with a
given stream.
Parameters
----------
a :
"Attack" time, in number of samples.
d :
"Decay" time, in number of samples.
s :
"Sustain" amplitude level (should be based on attack amplitude).
The sustain can be a Stream, if... | Below is the the instruction that describes the task:
### Input:
Linear ADS fading attack stream generator, useful to be multiplied with a
given stream.
Parameters
----------
a :
"Attack" time, in number of samples.
d :
"Decay" time, in number of samples.
s :
"Sustain" amplitude level (shou... |
def _check_start_timestamp(self):
"""Check that starting timestamp exists for cumulative metrics."""
if self.descriptor.type in (
metric_descriptor.MetricDescriptorType.CUMULATIVE_INT64,
metric_descriptor.MetricDescriptorType.CUMULATIVE_DOUBLE,
metric_desc... | Check that starting timestamp exists for cumulative metrics. | Below is the the instruction that describes the task:
### Input:
Check that starting timestamp exists for cumulative metrics.
### Response:
def _check_start_timestamp(self):
"""Check that starting timestamp exists for cumulative metrics."""
if self.descriptor.type in (
metric_descri... |
def _convert_to_from(self, to_mag, from_mag, fromVMag=None):
""" Converts from or to V mag using the conversion tables
:param to_mag: uppercase magnitude letter i.e. 'V' or 'K'
:param from_mag: uppercase magnitude letter i.e. 'V' or 'K'
:param fromVMag: MagV if from_mag is 'V'
... | Converts from or to V mag using the conversion tables
:param to_mag: uppercase magnitude letter i.e. 'V' or 'K'
:param from_mag: uppercase magnitude letter i.e. 'V' or 'K'
:param fromVMag: MagV if from_mag is 'V'
:return: estimated magnitude for to_mag from from_mag | Below is the the instruction that describes the task:
### Input:
Converts from or to V mag using the conversion tables
:param to_mag: uppercase magnitude letter i.e. 'V' or 'K'
:param from_mag: uppercase magnitude letter i.e. 'V' or 'K'
:param fromVMag: MagV if from_mag is 'V'
:ret... |
def _apply(self, ctx: ExtensionContext) -> AugmentedDict:
"""
Replaces any {{env::*}} directives with it's actual environment variable value or a default.
Args:
ctx: The processing context.
Returns:
Returns the altered node key and value.
"""
nod... | Replaces any {{env::*}} directives with it's actual environment variable value or a default.
Args:
ctx: The processing context.
Returns:
Returns the altered node key and value. | Below is the the instruction that describes the task:
### Input:
Replaces any {{env::*}} directives with it's actual environment variable value or a default.
Args:
ctx: The processing context.
Returns:
Returns the altered node key and value.
### Response:
def _apply(self, ... |
def ParseFileEntry(self, parser_mediator, file_entry):
"""Parses a file entry.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_entry (dfvfs.FileEntry): a file entry.
"""
stat_object = file_entry.Ge... | Parses a file entry.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_entry (dfvfs.FileEntry): a file entry. | Below is the the instruction that describes the task:
### Input:
Parses a file entry.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_entry (dfvfs.FileEntry): a file entry.
### Response:
def ParseFileEntr... |
def _load_neighbors_from_external_source(self) -> None:
"""
Loads the neighbors of the node from the igraph `Graph` instance that is
wrapped by the graph that has this node.
"""
graph: SpotifyArtistGraph = self._graph
items: List[NameExternalIDPair] = graph.client.similar... | Loads the neighbors of the node from the igraph `Graph` instance that is
wrapped by the graph that has this node. | Below is the the instruction that describes the task:
### Input:
Loads the neighbors of the node from the igraph `Graph` instance that is
wrapped by the graph that has this node.
### Response:
def _load_neighbors_from_external_source(self) -> None:
"""
Loads the neighbors of the node from t... |
def get_patient_mhc_haplotype(job, patient_dict):
"""
Convenience function to get the mhc haplotype from the patient dict
:param dict patient_dict: dict of patient info
:return: The MHCI and MHCII haplotypes
:rtype: toil.fileStore.FileID
"""
haplotype_archive = job.fileStore.readGlobalFile(... | Convenience function to get the mhc haplotype from the patient dict
:param dict patient_dict: dict of patient info
:return: The MHCI and MHCII haplotypes
:rtype: toil.fileStore.FileID | Below is the the instruction that describes the task:
### Input:
Convenience function to get the mhc haplotype from the patient dict
:param dict patient_dict: dict of patient info
:return: The MHCI and MHCII haplotypes
:rtype: toil.fileStore.FileID
### Response:
def get_patient_mhc_haplotype(job, pati... |
def generate_john_smith_chunk(path_to_original):
'''
This _looks_ like a Chunk only in that it generates StreamItem
instances when iterated upon.
'''
## Every StreamItem has a stream_time property. It usually comes
## from the document creation time. Here, we assume the JS corpus
## was cr... | This _looks_ like a Chunk only in that it generates StreamItem
instances when iterated upon. | Below is the the instruction that describes the task:
### Input:
This _looks_ like a Chunk only in that it generates StreamItem
instances when iterated upon.
### Response:
def generate_john_smith_chunk(path_to_original):
'''
This _looks_ like a Chunk only in that it generates StreamItem
instances w... |
def find(self, sub, in_current_line=False, include_current_position=False,
ignore_case=False, count=1):
"""
Find `text` after the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurance.
"""
... | Find `text` after the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurance. | Below is the the instruction that describes the task:
### Input:
Find `text` after the cursor, return position relative to the cursor
position. Return `None` if nothing was found.
:param count: Find the n-th occurance.
### Response:
def find(self, sub, in_current_line=False, include_current_positi... |
def referenced_tables(self):
"""Return referenced tables from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.referencedTables
:rtype: list of dict
:returns: mappings describing the query plan, or an empty list
... | Return referenced tables from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.referencedTables
:rtype: list of dict
:returns: mappings describing the query plan, or an empty list
if the query has not yet ... | Below is the the instruction that describes the task:
### Input:
Return referenced tables from job statistics, if present.
See:
https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#statistics.query.referencedTables
:rtype: list of dict
:returns: mappings describing the que... |
def _make_index(self, fasta, index):
""" Index a single, one-sequence fasta-file"""
out = open(index, "wb")
f = open(fasta)
# Skip first line of fasta-file
line = f.readline()
offset = f.tell()
line = f.readline()
while line:
out.write(pack(sel... | Index a single, one-sequence fasta-file | Below is the the instruction that describes the task:
### Input:
Index a single, one-sequence fasta-file
### Response:
def _make_index(self, fasta, index):
""" Index a single, one-sequence fasta-file"""
out = open(index, "wb")
f = open(fasta)
# Skip first line of fasta-file
... |
def handle_event(self, packet):
"""Handle incoming packet from rflink gateway."""
if packet.get('command'):
task = self.send_command_ack(packet['id'], packet['command'])
self.loop.create_task(task) | Handle incoming packet from rflink gateway. | Below is the the instruction that describes the task:
### Input:
Handle incoming packet from rflink gateway.
### Response:
def handle_event(self, packet):
"""Handle incoming packet from rflink gateway."""
if packet.get('command'):
task = self.send_command_ack(packet['id'], packet['comma... |
def _parse_the_ned_position_results(
self,
ra,
dec,
nedResults):
"""
*parse the ned results*
**Key Arguments:**
- ``ra`` -- the search ra
- ``dec`` -- the search dec
**Return:**
- ``results`` -- list of... | *parse the ned results*
**Key Arguments:**
- ``ra`` -- the search ra
- ``dec`` -- the search dec
**Return:**
- ``results`` -- list of result dictionaries | Below is the the instruction that describes the task:
### Input:
*parse the ned results*
**Key Arguments:**
- ``ra`` -- the search ra
- ``dec`` -- the search dec
**Return:**
- ``results`` -- list of result dictionaries
### Response:
def _parse_the_ned_position_... |
def _add_ctc_loss(pred, seq_len, num_label, loss_type):
""" Adds CTC loss on top of pred symbol and returns the resulting symbol """
label = mx.sym.Variable('label')
if loss_type == 'warpctc':
print("Using WarpCTC Loss")
sm = _add_warp_ctc_loss(pred, seq_len, num_label, label)
else:
... | Adds CTC loss on top of pred symbol and returns the resulting symbol | Below is the the instruction that describes the task:
### Input:
Adds CTC loss on top of pred symbol and returns the resulting symbol
### Response:
def _add_ctc_loss(pred, seq_len, num_label, loss_type):
""" Adds CTC loss on top of pred symbol and returns the resulting symbol """
label = mx.sym.Variable('l... |
def start_container(self, image, container_name: str, repo_path: Path):
""" Starts a container with the image and name ``container_name`` and copies the repository into the container.
:type image: docker.models.images.Image
:rtype: docker.models.container.Container
"""
command =... | Starts a container with the image and name ``container_name`` and copies the repository into the container.
:type image: docker.models.images.Image
:rtype: docker.models.container.Container | Below is the the instruction that describes the task:
### Input:
Starts a container with the image and name ``container_name`` and copies the repository into the container.
:type image: docker.models.images.Image
:rtype: docker.models.container.Container
### Response:
def start_container(self, ima... |
def template_engine(self, entry, startnode):
"""The format template interpetation engine. See the comment at the
beginning of this module for the how we interpret format
specifications such as %c, %C, and so on.
"""
# print("-----")
# print(startnode)
# print(en... | The format template interpetation engine. See the comment at the
beginning of this module for the how we interpret format
specifications such as %c, %C, and so on. | Below is the the instruction that describes the task:
### Input:
The format template interpetation engine. See the comment at the
beginning of this module for the how we interpret format
specifications such as %c, %C, and so on.
### Response:
def template_engine(self, entry, startnode):
""... |
def openList(self, char, mLastSection):
"""
These next three functions open, continue, and close the list
element appropriate to the prefix character passed into them.
"""
result = self.closeParagraph(mLastSection)
mDTopen = False
if char == u'*':
result += u'<ul><li>'
elif char == u'#':
result +... | These next three functions open, continue, and close the list
element appropriate to the prefix character passed into them. | Below is the the instruction that describes the task:
### Input:
These next three functions open, continue, and close the list
element appropriate to the prefix character passed into them.
### Response:
def openList(self, char, mLastSection):
"""
These next three functions open, continue, and close the list
... |
def _remove_extension_for_non_raw_file(self, name):
"""
Implemented as image and video files' Cloudinary public id
shouldn't contain file extensions, otherwise Cloudinary url
would contain doubled extension - Cloudinary adds extension to url
to allow file conversion to arbitrary ... | Implemented as image and video files' Cloudinary public id
shouldn't contain file extensions, otherwise Cloudinary url
would contain doubled extension - Cloudinary adds extension to url
to allow file conversion to arbitrary file, like png to jpg. | Below is the the instruction that describes the task:
### Input:
Implemented as image and video files' Cloudinary public id
shouldn't contain file extensions, otherwise Cloudinary url
would contain doubled extension - Cloudinary adds extension to url
to allow file conversion to arbitrary fil... |
def get_ref(obj):
"""
Get string reference to object. Stores a weak reference in a dictionary
using the object's id as the key. If the object cannot be weakly
referenced (e.g. dictionaries, frame objects), store a strong references
in a classic dictionary.
Returns the object's id as a string.
... | Get string reference to object. Stores a weak reference in a dictionary
using the object's id as the key. If the object cannot be weakly
referenced (e.g. dictionaries, frame objects), store a strong references
in a classic dictionary.
Returns the object's id as a string. | Below is the the instruction that describes the task:
### Input:
Get string reference to object. Stores a weak reference in a dictionary
using the object's id as the key. If the object cannot be weakly
referenced (e.g. dictionaries, frame objects), store a strong references
in a classic dictionary.
... |
def estimate_cpd(self, node, prior_type='BDeu', pseudo_counts=[], equivalent_sample_size=5):
"""
Method to estimate the CPD for a given variable.
Parameters
----------
node: int, string (any hashable python object)
The name of the variable for which the CPD is to be ... | Method to estimate the CPD for a given variable.
Parameters
----------
node: int, string (any hashable python object)
The name of the variable for which the CPD is to be estimated.
prior_type: 'dirichlet', 'BDeu', 'K2',
string indicting which type of prior to us... | Below is the the instruction that describes the task:
### Input:
Method to estimate the CPD for a given variable.
Parameters
----------
node: int, string (any hashable python object)
The name of the variable for which the CPD is to be estimated.
prior_type: 'dirichlet',... |
async def remove_tracks(self, *tracks):
"""Remove one or more tracks from the current user’s ‘Your Music’ library.
Parameters
----------
tracks : Sequence[Union[Track, str]]
A sequence of track objects or spotify IDs
"""
_tracks = [(obj if isinstance(obj, str... | Remove one or more tracks from the current user’s ‘Your Music’ library.
Parameters
----------
tracks : Sequence[Union[Track, str]]
A sequence of track objects or spotify IDs | Below is the the instruction that describes the task:
### Input:
Remove one or more tracks from the current user’s ‘Your Music’ library.
Parameters
----------
tracks : Sequence[Union[Track, str]]
A sequence of track objects or spotify IDs
### Response:
async def remove_tracks(s... |
def _value_and_gradients(fn, fn_arg_list, result=None, grads=None, name=None):
"""Helper to `maybe_call_fn_and_grads`."""
with tf.compat.v1.name_scope(name, 'value_and_gradients',
[fn_arg_list, result, grads]):
def _convert_to_tensor(x, name):
ctt = lambda x_: x_ if x_ is N... | Helper to `maybe_call_fn_and_grads`. | Below is the the instruction that describes the task:
### Input:
Helper to `maybe_call_fn_and_grads`.
### Response:
def _value_and_gradients(fn, fn_arg_list, result=None, grads=None, name=None):
"""Helper to `maybe_call_fn_and_grads`."""
with tf.compat.v1.name_scope(name, 'value_and_gradients',
... |
def main(argv=None):
'''
Main entry-point for calling layouts directly as a program.
'''
# Prep argparse
ap = argparse.ArgumentParser(
description='Basic query options for Python HID-IO Layouts repository',
)
ap.add_argument('--list', action='store_true', help='List available layout ... | Main entry-point for calling layouts directly as a program. | Below is the the instruction that describes the task:
### Input:
Main entry-point for calling layouts directly as a program.
### Response:
def main(argv=None):
'''
Main entry-point for calling layouts directly as a program.
'''
# Prep argparse
ap = argparse.ArgumentParser(
description='... |
def _get_validated_visibility_timeout(self, timeout=None):
"""
:raises ValueError: If specified visibility timeout exceeds MAXIMUM_VISIBILTY_TIMEOUT
:raises TypeError: If visibility timeout was not specified
"""
if timeout is not None:
visibility_timeout = int(timeout... | :raises ValueError: If specified visibility timeout exceeds MAXIMUM_VISIBILTY_TIMEOUT
:raises TypeError: If visibility timeout was not specified | Below is the the instruction that describes the task:
### Input:
:raises ValueError: If specified visibility timeout exceeds MAXIMUM_VISIBILTY_TIMEOUT
:raises TypeError: If visibility timeout was not specified
### Response:
def _get_validated_visibility_timeout(self, timeout=None):
"""
:rai... |
def part(self, channels, message=""):
"""Send a PART command."""
self.send_items('PART', ','.join(always_iterable(channels)), message) | Send a PART command. | Below is the the instruction that describes the task:
### Input:
Send a PART command.
### Response:
def part(self, channels, message=""):
"""Send a PART command."""
self.send_items('PART', ','.join(always_iterable(channels)), message) |
def active_link(context, viewnames, css_class=None, strict=None, *args, **kwargs):
"""
Renders the given CSS class if the request path matches the path of the view.
:param context: The context where the tag was called. Used to access the request object.
:param viewnames: The name of the view or views se... | Renders the given CSS class if the request path matches the path of the view.
:param context: The context where the tag was called. Used to access the request object.
:param viewnames: The name of the view or views separated by || (include namespaces if any).
:param css_class: The CSS class to render.
:... | Below is the the instruction that describes the task:
### Input:
Renders the given CSS class if the request path matches the path of the view.
:param context: The context where the tag was called. Used to access the request object.
:param viewnames: The name of the view or views separated by || (include nam... |
def check_valid_varname(varname,
custom_units,
custom_structs,
constants,
pos,
error_prefix="Variable name invalid.",
exc=None):
""" Handle invalid variable names """
e... | Handle invalid variable names | Below is the the instruction that describes the task:
### Input:
Handle invalid variable names
### Response:
def check_valid_varname(varname,
custom_units,
custom_structs,
constants,
pos,
error_p... |
def __import_pem(self, key_name, pem_file_path, password):
"""
Import PEM certificate with provider
:param key_name: name of the key to import
:param pem_file_path: path to the pem file
:param password: optional password for the pem file
"""
key_import = self.__ge... | Import PEM certificate with provider
:param key_name: name of the key to import
:param pem_file_path: path to the pem file
:param password: optional password for the pem file | Below is the the instruction that describes the task:
### Input:
Import PEM certificate with provider
:param key_name: name of the key to import
:param pem_file_path: path to the pem file
:param password: optional password for the pem file
### Response:
def __import_pem(self, key_name, pem_... |
def stop_all_periodic_tasks(self, remove_tasks=True):
"""Stop sending any messages that were started using bus.send_periodic
:param bool remove_tasks:
Stop tracking the stopped tasks.
"""
for task in self._periodic_tasks:
task.stop(remove_task=remove_tasks) | Stop sending any messages that were started using bus.send_periodic
:param bool remove_tasks:
Stop tracking the stopped tasks. | Below is the the instruction that describes the task:
### Input:
Stop sending any messages that were started using bus.send_periodic
:param bool remove_tasks:
Stop tracking the stopped tasks.
### Response:
def stop_all_periodic_tasks(self, remove_tasks=True):
"""Stop sending any messag... |
def check_vamp():
"Check Vamp host availability"
try:
from timeside.plugins.analyzer.externals import vamp_plugin
except VampImportError:
warnings.warn('Vamp host is not available', ImportWarning,
stacklevel=2)
_WITH_VAMP = False
else:
_WITH_VAMP = ... | Check Vamp host availability | Below is the the instruction that describes the task:
### Input:
Check Vamp host availability
### Response:
def check_vamp():
"Check Vamp host availability"
try:
from timeside.plugins.analyzer.externals import vamp_plugin
except VampImportError:
warnings.warn('Vamp host is not availabl... |
def execution_errors(self):
"""
Return a list of commands that encountered execution errors, with the error.
Each dictionary entry gives the command dictionary and the error dictionary
:return: list of commands that gave errors, with their error information
"""
if self.s... | Return a list of commands that encountered execution errors, with the error.
Each dictionary entry gives the command dictionary and the error dictionary
:return: list of commands that gave errors, with their error information | Below is the the instruction that describes the task:
### Input:
Return a list of commands that encountered execution errors, with the error.
Each dictionary entry gives the command dictionary and the error dictionary
:return: list of commands that gave errors, with their error information
### Resp... |
def create_zones(self, add_zones):
"""Create instances of additional zones for the receiver."""
for zone, zname in add_zones.items():
# Name either set explicitly or name of Main Zone with suffix
zonename = "{} {}".format(self._name, zone) if (
zname is None) else... | Create instances of additional zones for the receiver. | Below is the the instruction that describes the task:
### Input:
Create instances of additional zones for the receiver.
### Response:
def create_zones(self, add_zones):
"""Create instances of additional zones for the receiver."""
for zone, zname in add_zones.items():
# Name either set e... |
def find_all(self, collection):
"""
Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection.
"""
obj = getattr(self.db, collection)
result... | Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection. | Below is the the instruction that describes the task:
### Input:
Search a collection for all available items.
Args:
collection: The db collection. See main class documentation.
Returns:
List of all items in the collection.
### Response:
def find_all(self, collection):
... |
def resolve(self, year: int = YEAR_ANY) -> MDate:
"""Return the date object in the solar / lunar year.
:param year:
:return:
"""
year = year or self.year
if year:
return self._resolve(year)
raise ValueError('Unable resolve the date without a specified ... | Return the date object in the solar / lunar year.
:param year:
:return: | Below is the the instruction that describes the task:
### Input:
Return the date object in the solar / lunar year.
:param year:
:return:
### Response:
def resolve(self, year: int = YEAR_ANY) -> MDate:
"""Return the date object in the solar / lunar year.
:param year:
:return:... |
def clear_limit(self, identifier=None):
"""
Remove a single limit or all defined limits
:param identifier: The identifier to clear limits for, or if no identifier is supplied, clears ALL limits
:type identifier: int
:return: True if a limit was successfully found and removed, F... | Remove a single limit or all defined limits
:param identifier: The identifier to clear limits for, or if no identifier is supplied, clears ALL limits
:type identifier: int
:return: True if a limit was successfully found and removed, False if no limit could be matched for removal
:rtype... | Below is the the instruction that describes the task:
### Input:
Remove a single limit or all defined limits
:param identifier: The identifier to clear limits for, or if no identifier is supplied, clears ALL limits
:type identifier: int
:return: True if a limit was successfully found and r... |
def write_file(self, filename, content):
"""Write a file.
This is useful when writing a file that will fit within memory
:param filename: ``str``
:param content: ``str``
"""
with open(filename, 'wb') as f:
self.log.debug(content)
f.write(content) | Write a file.
This is useful when writing a file that will fit within memory
:param filename: ``str``
:param content: ``str`` | Below is the the instruction that describes the task:
### Input:
Write a file.
This is useful when writing a file that will fit within memory
:param filename: ``str``
:param content: ``str``
### Response:
def write_file(self, filename, content):
"""Write a file.
This is u... |
def write_short_at(self, n, pos, pack_into=Struct('>H').pack_into):
'''
Write an unsigned 16bit value at a specific position in the buffer.
Used for writing tables and frames.
'''
if 0 <= n <= 0xFFFF:
pack_into(self._output_buffer, pos, n)
else:
ra... | Write an unsigned 16bit value at a specific position in the buffer.
Used for writing tables and frames. | Below is the the instruction that describes the task:
### Input:
Write an unsigned 16bit value at a specific position in the buffer.
Used for writing tables and frames.
### Response:
def write_short_at(self, n, pos, pack_into=Struct('>H').pack_into):
'''
Write an unsigned 16bit value at a s... |
def MyDiplomacyEnum(ctx):
"""Player's Diplomacy Enumeration."""
return Enum(
ctx,
gaia=0,
self=1,
ally=2,
neutral=3,
enemy=4,
invalid_player=-1
) | Player's Diplomacy Enumeration. | Below is the the instruction that describes the task:
### Input:
Player's Diplomacy Enumeration.
### Response:
def MyDiplomacyEnum(ctx):
"""Player's Diplomacy Enumeration."""
return Enum(
ctx,
gaia=0,
self=1,
ally=2,
neutral=3,
enemy=4,
invalid_player... |
def read_numpy(fh, byteorder, dtype, count, offsetsize):
"""Read tag data from file and return as numpy array."""
dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]
return fh.read_array(dtype, count) | Read tag data from file and return as numpy array. | Below is the the instruction that describes the task:
### Input:
Read tag data from file and return as numpy array.
### Response:
def read_numpy(fh, byteorder, dtype, count, offsetsize):
"""Read tag data from file and return as numpy array."""
dtype = 'b' if dtype[-1] == 's' else byteorder+dtype[-1]
re... |
def check_include_exclude(path_str, include_pat=None, exclude_pat=None):
'''
Check for glob or regexp patterns for include_pat and exclude_pat in the
'path_str' string and return True/False conditions as follows.
- Default: return 'True' if no include_pat or exclude_pat patterns are
supplied
... | Check for glob or regexp patterns for include_pat and exclude_pat in the
'path_str' string and return True/False conditions as follows.
- Default: return 'True' if no include_pat or exclude_pat patterns are
supplied
- If only include_pat or exclude_pat is supplied: return 'True' if string
... | Below is the the instruction that describes the task:
### Input:
Check for glob or regexp patterns for include_pat and exclude_pat in the
'path_str' string and return True/False conditions as follows.
- Default: return 'True' if no include_pat or exclude_pat patterns are
supplied
- If only i... |
def insert(self, row):
"""
Add a row (type: dict) by inserting it into the table.
Columns must exist.
::
data = dict(title='I am a banana!')
table.insert(data)
Returns the inserted row's primary key.
"""
self._check_dropped()
res = ... | Add a row (type: dict) by inserting it into the table.
Columns must exist.
::
data = dict(title='I am a banana!')
table.insert(data)
Returns the inserted row's primary key. | Below is the the instruction that describes the task:
### Input:
Add a row (type: dict) by inserting it into the table.
Columns must exist.
::
data = dict(title='I am a banana!')
table.insert(data)
Returns the inserted row's primary key.
### Response:
def insert(self... |
def binary_shader_for_rules(self, output_jar, jar, rules, jvm_options=None):
"""Yields an `Executor.Runner` that will perform shading of the binary `jar` when `run()`.
No default rules are applied; only the rules passed in as a parameter will be used.
:param unicode output_jar: The path to dump the shaded... | Yields an `Executor.Runner` that will perform shading of the binary `jar` when `run()`.
No default rules are applied; only the rules passed in as a parameter will be used.
:param unicode output_jar: The path to dump the shaded jar to; will be over-written if it
exists.
:para... | Below is the the instruction that describes the task:
### Input:
Yields an `Executor.Runner` that will perform shading of the binary `jar` when `run()`.
No default rules are applied; only the rules passed in as a parameter will be used.
:param unicode output_jar: The path to dump the shaded jar to; will b... |
def _populate_type_attributes(self):
"""
Converts each struct, union, and route from a forward reference to a
full definition.
"""
for namespace in self.api.namespaces.values():
env = self._get_or_create_env(namespace.name)
# do annotations before everyth... | Converts each struct, union, and route from a forward reference to a
full definition. | Below is the the instruction that describes the task:
### Input:
Converts each struct, union, and route from a forward reference to a
full definition.
### Response:
def _populate_type_attributes(self):
"""
Converts each struct, union, and route from a forward reference to a
full def... |
def parse_numtuple(s,intype,length=2,scale=1):
'''parse a string into a list of numbers of a type'''
if intype == int:
numrx = intrx_s;
elif intype == float:
numrx = fltrx_s;
else:
raise NotImplementedError("Not implemented for type: {}".format(
intype));
if parse... | parse a string into a list of numbers of a type | Below is the the instruction that describes the task:
### Input:
parse a string into a list of numbers of a type
### Response:
def parse_numtuple(s,intype,length=2,scale=1):
'''parse a string into a list of numbers of a type'''
if intype == int:
numrx = intrx_s;
elif intype == float:
nu... |
def divide(n, iterable):
"""
split an iterable into n groups, per https://more-itertools.readthedocs.io/en/latest/api.html#grouping
:param int n: Number of unique groups
:param iter iterable: An iterable to split up
:return: a list of new iterables derived from the original iterable
:rtype: lis... | split an iterable into n groups, per https://more-itertools.readthedocs.io/en/latest/api.html#grouping
:param int n: Number of unique groups
:param iter iterable: An iterable to split up
:return: a list of new iterables derived from the original iterable
:rtype: list | Below is the the instruction that describes the task:
### Input:
split an iterable into n groups, per https://more-itertools.readthedocs.io/en/latest/api.html#grouping
:param int n: Number of unique groups
:param iter iterable: An iterable to split up
:return: a list of new iterables derived from the o... |
def _exc_to_net(param1, success):
""" translate http code to net code. if accertion failed, set net code to 314 """
if len(param1) <= 3:
# FIXME: we're unable to use better logic here, because we should support non-http codes
# but, we should look for core.util.HTTP or some other common logic
... | translate http code to net code. if accertion failed, set net code to 314 | Below is the the instruction that describes the task:
### Input:
translate http code to net code. if accertion failed, set net code to 314
### Response:
def _exc_to_net(param1, success):
""" translate http code to net code. if accertion failed, set net code to 314 """
if len(param1) <= 3:
# FIXME: ... |
def _debug(self):
"""This is just for debugging, so we can see what buttons would be drawn.
Not intended to be used in production."""
self.window.blit(self.surfaceUp, (self.loc[0], 10))
self.window.blit(self.surfaceOver, (self.loc[0], 60))
self.window.blit(self.surfaceDown... | This is just for debugging, so we can see what buttons would be drawn.
Not intended to be used in production. | Below is the the instruction that describes the task:
### Input:
This is just for debugging, so we can see what buttons would be drawn.
Not intended to be used in production.
### Response:
def _debug(self):
"""This is just for debugging, so we can see what buttons would be drawn.
Not... |
def into2dBlocks(arr, n0, n1):
"""
similar to blockshaped
but splits an array into n0*n1 blocks
"""
s0, s1 = arr.shape
b = blockshaped(arr, s0// n0, s1// n1)
return b.reshape(n0, n1, *b.shape[1:]) | similar to blockshaped
but splits an array into n0*n1 blocks | Below is the the instruction that describes the task:
### Input:
similar to blockshaped
but splits an array into n0*n1 blocks
### Response:
def into2dBlocks(arr, n0, n1):
"""
similar to blockshaped
but splits an array into n0*n1 blocks
"""
s0, s1 = arr.shape
b = blockshaped(arr, s0// n0... |
def _to_parent_frame(self, *args, **kwargs):
"""Conversion from Topocentric Frame to parent frame
"""
lat, lon, _ = self.latlonalt
m = rot3(-lon) @ rot2(lat - np.pi / 2.) @ rot3(self.heading)
offset = np.zeros(6)
offset[:3] = self.coordinates
return self._convert(... | Conversion from Topocentric Frame to parent frame | Below is the the instruction that describes the task:
### Input:
Conversion from Topocentric Frame to parent frame
### Response:
def _to_parent_frame(self, *args, **kwargs):
"""Conversion from Topocentric Frame to parent frame
"""
lat, lon, _ = self.latlonalt
m = rot3(-lon) @ rot2(l... |
def gross_lev(positions):
"""
Calculates the gross leverage of a strategy.
Parameters
----------
positions : pd.DataFrame
Daily net position values.
- See full explanation in tears.create_full_tear_sheet.
Returns
-------
pd.Series
Gross leverage.
"""
e... | Calculates the gross leverage of a strategy.
Parameters
----------
positions : pd.DataFrame
Daily net position values.
- See full explanation in tears.create_full_tear_sheet.
Returns
-------
pd.Series
Gross leverage. | Below is the the instruction that describes the task:
### Input:
Calculates the gross leverage of a strategy.
Parameters
----------
positions : pd.DataFrame
Daily net position values.
- See full explanation in tears.create_full_tear_sheet.
Returns
-------
pd.Series
... |
def best_value(Y,sign=1):
'''
Returns a vector whose components i are the minimum (default) or maximum of Y[:i]
'''
n = Y.shape[0]
Y_best = np.ones(n)
for i in range(n):
if sign == 1:
Y_best[i]=Y[:(i+1)].min()
else:
Y_best[i]=Y[:(i+1)].max()
return Y_b... | Returns a vector whose components i are the minimum (default) or maximum of Y[:i] | Below is the the instruction that describes the task:
### Input:
Returns a vector whose components i are the minimum (default) or maximum of Y[:i]
### Response:
def best_value(Y,sign=1):
'''
Returns a vector whose components i are the minimum (default) or maximum of Y[:i]
'''
n = Y.shape[0]
Y_b... |
def _scale_cores_to_memory(cores, mem_per_core, sysinfo, system_memory):
"""Scale multicore usage to avoid excessive memory usage based on system information.
"""
total_mem = "%.2f" % (cores * mem_per_core + system_memory)
if "cores" not in sysinfo:
return cores, total_mem, 1.0
total_mem = ... | Scale multicore usage to avoid excessive memory usage based on system information. | Below is the the instruction that describes the task:
### Input:
Scale multicore usage to avoid excessive memory usage based on system information.
### Response:
def _scale_cores_to_memory(cores, mem_per_core, sysinfo, system_memory):
"""Scale multicore usage to avoid excessive memory usage based on system inf... |
def next_event(self):
"""Simulates the queue forward one event.
Use :meth:`.simulate` instead.
Returns
-------
out : :class:`.Agent` (sometimes)
If the next event is a departure then the departing agent
is returned, otherwise nothing is returned.
... | Simulates the queue forward one event.
Use :meth:`.simulate` instead.
Returns
-------
out : :class:`.Agent` (sometimes)
If the next event is a departure then the departing agent
is returned, otherwise nothing is returned.
See Also
--------
... | Below is the the instruction that describes the task:
### Input:
Simulates the queue forward one event.
Use :meth:`.simulate` instead.
Returns
-------
out : :class:`.Agent` (sometimes)
If the next event is a departure then the departing agent
is returned, ot... |
def file_list(*packages, **kwargs):
'''
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.file_list httpd
salt... | List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.file_list httpd
salt '*' lowpkg.file_list httpd postfix
salt... | Below is the the instruction that describes the task:
### Input:
List the files that belong to a package. Not specifying any packages will
return a list of _every_ file on the system's package database (not
generally recommended).
CLI Examples:
.. code-block:: bash
salt '*' lowpkg.file_li... |
def _read_http_goaway(self, size, kind, flag):
"""Read HTTP/2 GOAWAY frames.
Structure of HTTP/2 GOAWAY frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+------------... | Read HTTP/2 GOAWAY frames.
Structure of HTTP/2 GOAWAY frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+---------------+
| Type (8) | Flags (8) |
... | Below is the the instruction that describes the task:
### Input:
Read HTTP/2 GOAWAY frames.
Structure of HTTP/2 GOAWAY frame [RFC 7540]:
+-----------------------------------------------+
| Length (24) |
+---------------+---------------+-... |
def get_latex_environment(s, pos, environmentname=None, **parse_flags):
"""
Reads a latex expression enclosed in a \\begin{environment}...\\end{environment}. The first
token in the stream must be the \\begin{environment}.
Returns a tuple (node, pos, len) with node being a :py:class:`LatexEnvironmentNod... | Reads a latex expression enclosed in a \\begin{environment}...\\end{environment}. The first
token in the stream must be the \\begin{environment}.
Returns a tuple (node, pos, len) with node being a :py:class:`LatexEnvironmentNode`.
.. deprecated:: 1.0
Please use :py:meth:`LatexWalker.get_latex_envir... | Below is the the instruction that describes the task:
### Input:
Reads a latex expression enclosed in a \\begin{environment}...\\end{environment}. The first
token in the stream must be the \\begin{environment}.
Returns a tuple (node, pos, len) with node being a :py:class:`LatexEnvironmentNode`.
.. dep... |
def _parameter_values(parameter_values_from_pillars, parameter_value_overrides):
'''
Return a dictionary of parameter values that configure the pipeline
parameter_values_from_pillars
The pillar key to use for lookup
parameter_value_overrides
Parameter values to use. Will override value... | Return a dictionary of parameter values that configure the pipeline
parameter_values_from_pillars
The pillar key to use for lookup
parameter_value_overrides
Parameter values to use. Will override values read from pillars. | Below is the the instruction that describes the task:
### Input:
Return a dictionary of parameter values that configure the pipeline
parameter_values_from_pillars
The pillar key to use for lookup
parameter_value_overrides
Parameter values to use. Will override values read from pillars.
###... |
def get_default(self):
"""Return the default VLAN from the set."""
length = len(self)
if length == 0:
return None
elif length == 1:
return self[0]
else:
return sorted(self, key=attrgetter('id'))[0] | Return the default VLAN from the set. | Below is the the instruction that describes the task:
### Input:
Return the default VLAN from the set.
### Response:
def get_default(self):
"""Return the default VLAN from the set."""
length = len(self)
if length == 0:
return None
elif length == 1:
return sel... |
def get_assets_by_search(self, asset_query, asset_search):
"""Gets the search results matching the given search query using the given search.
arg: asset_query (osid.repository.AssetQuery): the asset
query
arg: asset_search (osid.repository.AssetSearch): the asset
... | Gets the search results matching the given search query using the given search.
arg: asset_query (osid.repository.AssetQuery): the asset
query
arg: asset_search (osid.repository.AssetSearch): the asset
search
return: (osid.repository.AssetSearchResults) - t... | Below is the the instruction that describes the task:
### Input:
Gets the search results matching the given search query using the given search.
arg: asset_query (osid.repository.AssetQuery): the asset
query
arg: asset_search (osid.repository.AssetSearch): the asset
... |
def callgraph(func):
''' Makes a call graph
Note: be sure to install GraphViz prior to printing the dot graph!
'''
import pycallgraph
@functools.wraps(func)
def wrapper(*args, **kwargs):
pycallgraph.start_trace()
func(*args, **kwargs)
pycallgraph.save_dot('callgraph.log')... | Makes a call graph
Note: be sure to install GraphViz prior to printing the dot graph! | Below is the the instruction that describes the task:
### Input:
Makes a call graph
Note: be sure to install GraphViz prior to printing the dot graph!
### Response:
def callgraph(func):
''' Makes a call graph
Note: be sure to install GraphViz prior to printing the dot graph!
'''
import pycallgr... |
def _create_path(self, *args):
"""Create the URL path with the Fred endpoint and given arguments."""
args = filter(None, args)
path = self.endpoint + '/'.join(args)
return path | Create the URL path with the Fred endpoint and given arguments. | Below is the the instruction that describes the task:
### Input:
Create the URL path with the Fred endpoint and given arguments.
### Response:
def _create_path(self, *args):
"""Create the URL path with the Fred endpoint and given arguments."""
args = filter(None, args)
path = self.endpoint ... |
def step(self):
"""Run the environment for one time step. If the
actions and exogenous changes are independent, this method will
do. If there are interactions between them, you'll need to
override this method."""
if not self.is_done():
actions = [agent.program(self.p... | Run the environment for one time step. If the
actions and exogenous changes are independent, this method will
do. If there are interactions between them, you'll need to
override this method. | Below is the the instruction that describes the task:
### Input:
Run the environment for one time step. If the
actions and exogenous changes are independent, this method will
do. If there are interactions between them, you'll need to
override this method.
### Response:
def step(self):
... |
def download(url, proxies=None):
"""
Download a PDF or DJVU document from a url, eventually using proxies.
:params url: The URL to the PDF/DJVU document to fetch.
:params proxies: An optional list of proxies to use. Proxies will be \
used sequentially. Proxies should be a list of proxy stri... | Download a PDF or DJVU document from a url, eventually using proxies.
:params url: The URL to the PDF/DJVU document to fetch.
:params proxies: An optional list of proxies to use. Proxies will be \
used sequentially. Proxies should be a list of proxy strings. \
Do not forget to include `... | Below is the the instruction that describes the task:
### Input:
Download a PDF or DJVU document from a url, eventually using proxies.
:params url: The URL to the PDF/DJVU document to fetch.
:params proxies: An optional list of proxies to use. Proxies will be \
used sequentially. Proxies should... |
def serve_protected_file(request, path):
"""
Serve protected files to authenticated users with read permissions.
"""
path = path.rstrip('/')
try:
file_obj = File.objects.get(file=path)
except File.DoesNotExist:
raise Http404('File not found %s' % path)
if not file_obj.has_rea... | Serve protected files to authenticated users with read permissions. | Below is the the instruction that describes the task:
### Input:
Serve protected files to authenticated users with read permissions.
### Response:
def serve_protected_file(request, path):
"""
Serve protected files to authenticated users with read permissions.
"""
path = path.rstrip('/')
try:
... |
def close(self):
"""Closes the record and index files."""
if not self.is_open:
return
super(IndexCreator, self).close()
self.fidx.close() | Closes the record and index files. | Below is the the instruction that describes the task:
### Input:
Closes the record and index files.
### Response:
def close(self):
"""Closes the record and index files."""
if not self.is_open:
return
super(IndexCreator, self).close()
self.fidx.close() |
def start_meta(self, attrs):
"""Beautiful Soup can detect a charset included in a META tag,
try to convert the document to that charset, and re-parse the
document from the beginning."""
httpEquiv = None
contentType = None
contentTypeIndex = None
tagNeedsEncodingSu... | Beautiful Soup can detect a charset included in a META tag,
try to convert the document to that charset, and re-parse the
document from the beginning. | Below is the the instruction that describes the task:
### Input:
Beautiful Soup can detect a charset included in a META tag,
try to convert the document to that charset, and re-parse the
document from the beginning.
### Response:
def start_meta(self, attrs):
"""Beautiful Soup can detect a c... |
def wait(self, sensor_name, condition_or_value, timeout=5.0, quorum=None,
max_grace_period=1.0):
"""Wait for sensor present on all group clients to satisfy a condition.
Parameters
----------
sensor_name : string
The name of the sensor to check
condition_... | Wait for sensor present on all group clients to satisfy a condition.
Parameters
----------
sensor_name : string
The name of the sensor to check
condition_or_value : obj or callable, or seq of objs or callables
If obj, sensor.value is compared with obj. If callabl... | Below is the the instruction that describes the task:
### Input:
Wait for sensor present on all group clients to satisfy a condition.
Parameters
----------
sensor_name : string
The name of the sensor to check
condition_or_value : obj or callable, or seq of objs or callab... |
async def read_message(self) -> Optional[Data]:
"""
Read a single message from the connection.
Re-assemble data frames if the message is fragmented.
Return ``None`` when the closing handshake is started.
"""
frame = await self.read_data_frame(max_size=self.max_size)
... | Read a single message from the connection.
Re-assemble data frames if the message is fragmented.
Return ``None`` when the closing handshake is started. | Below is the the instruction that describes the task:
### Input:
Read a single message from the connection.
Re-assemble data frames if the message is fragmented.
Return ``None`` when the closing handshake is started.
### Response:
async def read_message(self) -> Optional[Data]:
"""
... |
def admin_required(function=None):
"""
Decorator for views that checks that the user is an administrator,
redirecting to the log-in page if necessary.
"""
def check_perms(user):
# if user not logged in, show login form
if not user.is_authenticated:
return False
# ... | Decorator for views that checks that the user is an administrator,
redirecting to the log-in page if necessary. | Below is the the instruction that describes the task:
### Input:
Decorator for views that checks that the user is an administrator,
redirecting to the log-in page if necessary.
### Response:
def admin_required(function=None):
"""
Decorator for views that checks that the user is an administrator,
re... |
def read_examples(input_file):
"""Read a list of `InputExample`s from an input file."""
examples = []
unique_id = 0
with open(input_file, "r", encoding='utf-8') as reader:
while True:
line = reader.readline()
if not line:
break
line = line.stri... | Read a list of `InputExample`s from an input file. | Below is the the instruction that describes the task:
### Input:
Read a list of `InputExample`s from an input file.
### Response:
def read_examples(input_file):
"""Read a list of `InputExample`s from an input file."""
examples = []
unique_id = 0
with open(input_file, "r", encoding='utf-8') as reade... |
def _get_path_from_parent(self, parent):
"""
Return a list of PathInfos containing the path from the parent
model to the current model, or an empty list if parent is not a
parent of the current model.
"""
if hasattr(self, 'get_path_from_parent'):
return self.get_path_from_parent(parent)
... | Return a list of PathInfos containing the path from the parent
model to the current model, or an empty list if parent is not a
parent of the current model. | Below is the the instruction that describes the task:
### Input:
Return a list of PathInfos containing the path from the parent
model to the current model, or an empty list if parent is not a
parent of the current model.
### Response:
def _get_path_from_parent(self, parent):
"""
Return a list of Pa... |
def _decodeRelativeValidityPeriod(tpVp):
""" Calculates the relative SMS validity period (based on the table in section 9.2.3.12 of GSM 03.40)
:rtype: datetime.timedelta
"""
if tpVp <= 143:
return timedelta(minutes=((tpVp + 1) * 5))
elif 144 <= tpVp <= 167:
return timedelta(hours=12,... | Calculates the relative SMS validity period (based on the table in section 9.2.3.12 of GSM 03.40)
:rtype: datetime.timedelta | Below is the the instruction that describes the task:
### Input:
Calculates the relative SMS validity period (based on the table in section 9.2.3.12 of GSM 03.40)
:rtype: datetime.timedelta
### Response:
def _decodeRelativeValidityPeriod(tpVp):
""" Calculates the relative SMS validity period (based on the ... |
def on_batch_begin(self, batch_info: BatchInfo):
""" Set proper learning rate """
cycle_length = self.cycle_lengths[batch_info.local_epoch_number - 1]
cycle_start = self.cycle_starts[batch_info.local_epoch_number - 1]
numerator = (batch_info.local_epoch_number - cycle_start - 1) * batch... | Set proper learning rate | Below is the the instruction that describes the task:
### Input:
Set proper learning rate
### Response:
def on_batch_begin(self, batch_info: BatchInfo):
""" Set proper learning rate """
cycle_length = self.cycle_lengths[batch_info.local_epoch_number - 1]
cycle_start = self.cycle_starts[batc... |
def create_key_index_object(key_index_name: str, iterables: Dict[str, Any]) -> Any:
""" Create a ``KeyIndex`` class based on the passed attributes.
This is wrapped into a helper function to allow for the ``__itter__`` to be specified for the object.
Further, this allows it to be called outside the package ... | Create a ``KeyIndex`` class based on the passed attributes.
This is wrapped into a helper function to allow for the ``__itter__`` to be specified for the object.
Further, this allows it to be called outside the package when it is needed in analysis tasks..
Args:
key_index_name: Name of the iterabl... | Below is the the instruction that describes the task:
### Input:
Create a ``KeyIndex`` class based on the passed attributes.
This is wrapped into a helper function to allow for the ``__itter__`` to be specified for the object.
Further, this allows it to be called outside the package when it is needed in an... |
def managedcloud(vm_):
'''
Determine if we should wait for the managed cloud automation before
running. Either 'False' (default) or 'True'.
'''
return config.get_cloud_config_value(
'managedcloud', vm_, __opts__, default=False,
search_global=False
) | Determine if we should wait for the managed cloud automation before
running. Either 'False' (default) or 'True'. | Below is the the instruction that describes the task:
### Input:
Determine if we should wait for the managed cloud automation before
running. Either 'False' (default) or 'True'.
### Response:
def managedcloud(vm_):
'''
Determine if we should wait for the managed cloud automation before
running. Eit... |
def alpha_(self,x):
""" Create a mappable function alpha to apply to each xmin in a list of xmins.
This is essentially the slow version of fplfit/cplfit, though I bet it could
be speeded up with a clever use of parellel_map. Not intended to be used by users."""
def alpha(xmin,x=x):
... | Create a mappable function alpha to apply to each xmin in a list of xmins.
This is essentially the slow version of fplfit/cplfit, though I bet it could
be speeded up with a clever use of parellel_map. Not intended to be used by users. | Below is the the instruction that describes the task:
### Input:
Create a mappable function alpha to apply to each xmin in a list of xmins.
This is essentially the slow version of fplfit/cplfit, though I bet it could
be speeded up with a clever use of parellel_map. Not intended to be used by users.... |
def from_dict(self, document):
"""Create experiment object from JSON document retrieved from database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
ExperimentHandle
Handle for experiment object
"... | Create experiment object from JSON document retrieved from database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
ExperimentHandle
Handle for experiment object | Below is the the instruction that describes the task:
### Input:
Create experiment object from JSON document retrieved from database.
Parameters
----------
document : JSON
Json document in database
Returns
-------
ExperimentHandle
Handle for ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.