INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Adds handlers from a different Hug API to this one - to create a single API | def extend(self, http_api, route="", base_url="", **kwargs):
"""Adds handlers from a different Hug API to this one - to create a single API"""
self.versions.update(http_api.versions)
base_url = base_url or self.base_url
for router_base_url, routes in http_api.routes.items():
... |
Sets the not_found handler for the specified version of the api | def set_not_found_handler(self, handler, version=None):
"""Sets the not_found handler for the specified version of the api"""
if not self.not_found_handlers:
self._not_found_handlers = {}
self.not_found_handlers[version] = handler |
Generates and returns documentation for this API endpoint | def documentation(self, base_url=None, api_version=None, prefix=""):
"""Generates and returns documentation for this API endpoint"""
documentation = OrderedDict()
base_url = self.base_url if base_url is None else base_url
overview = self.api.doc
if overview:
documenta... |
Runs the basic hug development server against this API | def serve(self, host='', port=8000, no_documentation=False, display_intro=True):
"""Runs the basic hug development server against this API"""
if no_documentation:
api = self.server(None)
else:
api = self.server()
if display_intro:
print(INTRO)
... |
Determines the appropriate version given the set api_version, the request header, and URL query params | def determine_version(self, request, api_version=None):
"""Determines the appropriate version given the set api_version, the request header, and URL query params"""
if api_version is False:
api_version = None
for version in self.versions:
if version and "v{0}".for... |
Returns a smart 404 page that contains documentation for the written API | def documentation_404(self, base_url=None):
"""Returns a smart 404 page that contains documentation for the written API"""
base_url = self.base_url if base_url is None else base_url
def handle_404(request, response, *args, **kwargs):
url_prefix = request.forwarded_uri[:-1]
... |
Intelligently routes a request to the correct handler based on the version being requested | def version_router(self, request, response, api_version=None, versions={}, not_found=None, **kwargs):
"""Intelligently routes a request to the correct handler based on the version being requested"""
request_version = self.determine_version(request, api_version)
if request_version:
re... |
Extends this CLI api with the commands present in the provided cli_api object | def extend(self, cli_api, command_prefix="", sub_command="", **kwargs):
"""Extends this CLI api with the commands present in the provided cli_api object"""
if sub_command and command_prefix:
raise ValueError('It is not currently supported to provide both a command_prefix and sub_command')
... |
Returns all directives applicable to this Hug API | def directives(self):
"""Returns all directives applicable to this Hug API"""
directive_sources = chain(hug.defaults.directives.items(), getattr(self, '_directives', {}).items())
return {'hug_' + directive_name: directive for directive_name, directive in directive_sources} |
Returns the loaded directive with the specified name, or default if passed name is not present | def directive(self, name, default=None):
"""Returns the loaded directive with the specified name, or default if passed name is not present"""
return getattr(self, '_directives', {}).get(name, hug.defaults.directives.get(name, default)) |
Returns all registered handlers attached to this API | def handlers(self):
"""Returns all registered handlers attached to this API"""
if getattr(self, '_http'):
yield from self.http.handlers()
if getattr(self, '_cli'):
yield from self.cli.handlers() |
Adds handlers from a different Hug API to this one - to create a single API | def extend(self, api, route="", base_url="", http=True, cli=True, **kwargs):
"""Adds handlers from a different Hug API to this one - to create a single API"""
api = API(api)
if http and hasattr(api, '_http'):
self.http.extend(api.http, route, base_url, **kwargs)
if cli and ... |
Adds a startup handler to the hug api | def add_startup_handler(self, handler):
"""Adds a startup handler to the hug api"""
if not self.startup_handlers:
self._startup_handlers = []
self.startup_handlers.append(handler) |
Marks the API as started and runs all startup handlers | def _ensure_started(self):
"""Marks the API as started and runs all startup handlers"""
if not self.started:
async_handlers = [startup_handler for startup_handler in self.startup_handlers if
introspect.is_coroutine(startup_handler)]
if async_handlers... |
Helper for `WeightDrop`. | def _weight_drop(module, weights, dropout):
"""
Helper for `WeightDrop`.
"""
for name_w in weights:
w = getattr(module, name_w)
del module._parameters[name_w]
module.register_parameter(name_w + '_raw', Parameter(w))
original_module_forward = module.forward
def forward(... |
Load the IMDB dataset (Large Movie Review Dataset v1.0).
This is a dataset for binary sentiment classification containing substantially more data than
previous benchmark datasets. Provided a set of 25,000 highly polar movie reviews for
training, and 25,000 for testing. There is additional unlabeled data fo... | def imdb_dataset(directory='data/',
train=False,
test=False,
train_directory='train',
test_directory='test',
extracted_name='aclImdb',
check_files=['aclImdb/README'],
url='http://ai.stanford.edu/~amaas... |
Load the Text REtrieval Conference (TREC) Question Classification dataset.
TREC dataset contains 5500 labeled questions in training set and another 500 for test set. The
dataset has 6 labels, 50 level-2 labels. Average length of each sentence is 10, vocabulary size
of 8700.
References:
* https... | def trec_dataset(directory='data/trec/',
train=False,
test=False,
train_filename='train_5500.label',
test_filename='TREC_10.label',
check_files=['train_5500.label'],
urls=[
'http://cogcomp.org/Data... |
Args:
query (:class:`torch.FloatTensor` [batch size, output length, dimensions]): Sequence of
queries to query the context.
context (:class:`torch.FloatTensor` [batch size, query length, dimensions]): Data
overwhich to apply the attention mechanism.
Retur... | def forward(self, query, context):
"""
Args:
query (:class:`torch.FloatTensor` [batch size, output length, dimensions]): Sequence of
queries to query the context.
context (:class:`torch.FloatTensor` [batch size, query length, dimensions]): Data
ove... |
Encodes an object.
Args:
object_ (object): Object to encode.
Returns:
object: Encoding of the object. | def encode(self, object_):
""" Encodes an object.
Args:
object_ (object): Object to encode.
Returns:
object: Encoding of the object.
"""
if self.enforce_reversible:
self.enforce_reversible = False
if self.decode(self.encode(object... |
Args:
batch (list): Batch of objects to encode.
*args: Arguments passed to ``encode``.
**kwargs: Keyword arguments passed to ``encode``.
Returns:
list: Batch of encoded objects. | def batch_encode(self, iterator, *args, **kwargs):
"""
Args:
batch (list): Batch of objects to encode.
*args: Arguments passed to ``encode``.
**kwargs: Keyword arguments passed to ``encode``.
Returns:
list: Batch of encoded objects.
"""
... |
Decodes an object.
Args:
object_ (object): Encoded object.
Returns:
object: Object decoded. | def decode(self, encoded):
""" Decodes an object.
Args:
object_ (object): Encoded object.
Returns:
object: Object decoded.
"""
if self.enforce_reversible:
self.enforce_reversible = False
if self.encode(self.decode(encoded)) != enc... |
Args:
iterator (list): Batch of encoded objects.
*args: Arguments passed to ``decode``.
**kwargs: Keyword arguments passed to ``decode``.
Returns:
list: Batch of decoded objects. | def batch_decode(self, iterator, *args, **kwargs):
"""
Args:
iterator (list): Batch of encoded objects.
*args: Arguments passed to ``decode``.
**kwargs: Keyword arguments passed to ``decode``.
Returns:
list: Batch of decoded objects.
"""
... |
Args:
tokens (:class:`torch.FloatTensor` [batch_size, num_tokens, input_dim]): Sequence
matrix to encode.
mask (:class:`torch.FloatTensor`): Broadcastable matrix to `tokens` used as a mask.
Returns:
(:class:`torch.FloatTensor` [batch_size, output_dim]): Encodi... | def forward(self, tokens, mask=None):
"""
Args:
tokens (:class:`torch.FloatTensor` [batch_size, num_tokens, input_dim]): Sequence
matrix to encode.
mask (:class:`torch.FloatTensor`): Broadcastable matrix to `tokens` used as a mask.
Returns:
(:c... |
Inverse of _escape_token().
Args:
escaped_token: a unicode string
Returns:
token: a unicode string | def _unescape_token(escaped_token):
"""
Inverse of _escape_token().
Args:
escaped_token: a unicode string
Returns:
token: a unicode string
"""
def match(m):
if m.group(1) is None:
return u"_" if m.group(0) == u"\\u" else u"\\"
try:
return six... |
Converts a list of tokens to a list of subtoken.
Args:
tokens: a list of strings.
Returns:
a list of integers in the range [0, vocab_size) | def _tokens_to_subtoken(self, tokens):
""" Converts a list of tokens to a list of subtoken.
Args:
tokens: a list of strings.
Returns:
a list of integers in the range [0, vocab_size)
"""
ret = []
for token in tokens:
ret.extend(
... |
Converts a list of subtoken to a list of tokens.
Args:
subtokens: a list of integers in the range [0, vocab_size)
Returns:
a list of strings. | def _subtoken_to_tokens(self, subtokens):
""" Converts a list of subtoken to a list of tokens.
Args:
subtokens: a list of integers in the range [0, vocab_size)
Returns:
a list of strings.
"""
concatenated = "".join(subtokens)
split = concatenated.spl... |
Converts an escaped token string to a list of subtoken strings.
Args:
escaped_token: An escaped token as a unicode string.
Returns:
A list of subtokens as unicode strings. | def _escaped_token_to_subtoken_strings(self, escaped_token):
""" Converts an escaped token string to a list of subtoken strings.
Args:
escaped_token: An escaped token as a unicode string.
Returns:
A list of subtokens as unicode strings.
"""
# NOTE: This algor... |
Builds a SubwordTextTokenizer that has `vocab_size` near `target_size`.
Uses simple recursive binary search to find a minimum token count that most
closely matches the `target_size`.
Args:
target_size: Desired vocab_size to approximate.
token_counts: A dictionary of token c... | def build_to_target_size_from_token_counts(cls,
target_size,
token_counts,
min_val,
max_val,
... |
Train a SubwordTextTokenizer based on a dictionary of word counts.
Args:
token_counts: a dictionary of Unicode strings to int.
min_count: an integer - discard subtokens with lower counts.
num_iterations: an integer; how many iterations of refinement. | def build_from_token_counts(self, token_counts, min_count, num_iterations=4):
"""Train a SubwordTextTokenizer based on a dictionary of word counts.
Args:
token_counts: a dictionary of Unicode strings to int.
min_count: an integer - discard subtokens with lower counts.
num_... |
Initialize token information from a list of subtoken strings. | def _init_subtokens_from_list(self, subtoken_strings):
"""Initialize token information from a list of subtoken strings."""
# we remember the maximum length of any subtoken to avoid having to
# check arbitrarily long strings.
self._all_subtoken_strings = set([s for s in subtoken_strings i... |
Initialize alphabet from an iterable of token or subtoken strings. | def _init_alphabet_from_tokens(self, tokens):
"""Initialize alphabet from an iterable of token or subtoken strings."""
# Include all characters from all tokens in the alphabet to guarantee that
# any token can be encoded. Additionally, include all escaping
# characters.
self._alp... |
Get the BLEU score using the moses `multi-bleu.perl` script.
**Script:**
https://raw.githubusercontent.com/moses-smt/mosesdecoder/master/scripts/generic/multi-bleu.perl
Args:
hypotheses (list of str): List of predicted values
references (list of str): List of target values
lowercase (boo... | def get_moses_multi_bleu(hypotheses, references, lowercase=False):
"""Get the BLEU score using the moses `multi-bleu.perl` script.
**Script:**
https://raw.githubusercontent.com/moses-smt/mosesdecoder/master/scripts/generic/multi-bleu.perl
Args:
hypotheses (list of str): List of predicted values
... |
Load the Universal Dependencies - English Dependency Treebank dataset.
Corpus of sentences annotated using Universal Dependencies annotation. The corpus comprises
254,830 words and 16,622 sentences, taken from various web media including weblogs, newsgroups,
emails, reviews, and Yahoo! answers.
Refere... | def ud_pos_dataset(directory='data/',
train=False,
dev=False,
test=False,
train_filename='en-ud-tag.v2.train.txt',
dev_filename='en-ud-tag.v2.dev.txt',
test_filename='en-ud-tag.v2.test.txt',
... |
helper function for python 2 and 3 to call os.makedirs()
avoiding an error if the directory to be created already exists | def makedirs(name):
"""helper function for python 2 and 3 to call os.makedirs()
avoiding an error if the directory to be created already exists"""
import os, errno
try:
os.makedirs(name)
except OSError as ex:
if ex.errno == errno.EEXIST and os.path.isdir(name):
# ign... |
list of tensors to a batch tensors | def collate_fn(batch, train=True):
""" list of tensors to a batch tensors """
premise_batch, _ = pad_batch([row['premise'] for row in batch])
hypothesis_batch, _ = pad_batch([row['hypothesis'] for row in batch])
label_batch = torch.stack([row['label'] for row in batch])
# PyTorch RNN requires batch... |
Load the Stanford Sentiment Treebank dataset.
Semantic word spaces have been very useful but cannot express the meaning of longer phrases in
a principled way. Further progress towards understanding compositionality in tasks such as
sentiment detection requires richer supervised training and evaluation reso... | def smt_dataset(directory='data/',
train=False,
dev=False,
test=False,
train_filename='train.txt',
dev_filename='dev.txt',
test_filename='test.txt',
extracted_name='trees',
check_files=['trees... |
Load the SimpleQuestions dataset.
Single-relation factoid questions (simple questions) are common in many settings
(e.g. Microsoft’s search query logs and WikiAnswers questions). The SimpleQuestions dataset is
one of the most commonly used benchmarks for studying single-relation factoid questions.
**R... | def simple_qa_dataset(
directory='data/',
train=False,
dev=False,
test=False,
extracted_name='SimpleQuestions_v2',
train_filename='annotated_fb_data_train.txt',
dev_filename='annotated_fb_data_valid.txt',
test_filename='annotated_fb_data_test.txt',
... |
Args:
x (:class:`torch.FloatTensor` [batch size, sequence length, rnn hidden size]): Input to
apply dropout too. | def forward(self, x):
"""
Args:
x (:class:`torch.FloatTensor` [batch size, sequence length, rnn hidden size]): Input to
apply dropout too.
"""
if not self.training or not self.p:
return x
x = x.clone()
mask = x.new_empty(1, x.size(1... |
Pad a ``tensor`` to ``length`` with ``padding_index``.
Args:
tensor (torch.Tensor [n, ...]): Tensor to pad.
length (int): Pad the ``tensor`` up to ``length``.
padding_index (int, optional): Index to pad tensor with.
Returns
(torch.Tensor [length, ...]) Padded Tensor. | def pad_tensor(tensor, length, padding_index=DEFAULT_PADDING_INDEX):
""" Pad a ``tensor`` to ``length`` with ``padding_index``.
Args:
tensor (torch.Tensor [n, ...]): Tensor to pad.
length (int): Pad the ``tensor`` up to ``length``.
padding_index (int, optional): Index to pad tensor with... |
Pad a :class:`list` of ``tensors`` (``batch``) with ``padding_index``.
Args:
batch (:class:`list` of :class:`torch.Tensor`): Batch of tensors to pad.
padding_index (int, optional): Index to pad tensors with.
dim (int, optional): Dimension on to which to concatenate the batch of tensors.
... | def stack_and_pad_tensors(batch, padding_index=DEFAULT_PADDING_INDEX, dim=0):
""" Pad a :class:`list` of ``tensors`` (``batch``) with ``padding_index``.
Args:
batch (:class:`list` of :class:`torch.Tensor`): Batch of tensors to pad.
padding_index (int, optional): Index to pad tensors with.
... |
Args:
iterator (iterator): Batch of text to encode.
*args: Arguments passed onto ``Encoder.__init__``.
dim (int, optional): Dimension along which to concatenate tensors.
**kwargs: Keyword arguments passed onto ``Encoder.__init__``.
Returns
torch.Tenso... | def batch_encode(self, iterator, *args, dim=0, **kwargs):
"""
Args:
iterator (iterator): Batch of text to encode.
*args: Arguments passed onto ``Encoder.__init__``.
dim (int, optional): Dimension along which to concatenate tensors.
**kwargs: Keyword argume... |
Args:
batch (list of :class:`torch.Tensor`): Batch of encoded sequences.
lengths (list of int): Original lengths of sequences.
dim (int, optional): Dimension along which to split tensors.
*args: Arguments passed to ``decode``.
**kwargs: Key word arguments pass... | def batch_decode(self, tensor, lengths, dim=0, *args, **kwargs):
"""
Args:
batch (list of :class:`torch.Tensor`): Batch of encoded sequences.
lengths (list of int): Original lengths of sequences.
dim (int, optional): Dimension along which to split tensors.
... |
Encodes a ``sequence``.
Args:
sequence (str): String ``sequence`` to encode.
Returns:
torch.Tensor: Encoding of the ``sequence``. | def encode(self, sequence):
""" Encodes a ``sequence``.
Args:
sequence (str): String ``sequence`` to encode.
Returns:
torch.Tensor: Encoding of the ``sequence``.
"""
sequence = super().encode(sequence)
sequence = self.tokenize(sequence)
v... |
Decodes a tensor into a sequence.
Args:
encoded (torch.Tensor): Encoded sequence.
Returns:
str: Sequence decoded from ``encoded``. | def decode(self, encoded):
""" Decodes a tensor into a sequence.
Args:
encoded (torch.Tensor): Encoded sequence.
Returns:
str: Sequence decoded from ``encoded``.
"""
encoded = super().decode(encoded)
tokens = [self.itos[index] for index in encode... |
``reporthook`` to use with ``urllib.request`` that prints the process of the download.
Uses ``tqdm`` for progress bar.
**Reference:**
https://github.com/tqdm/tqdm
Args:
t (tqdm.tqdm) Progress bar.
Example:
>>> with tqdm(unit='B', unit_scale=True, miniters=1, desc=filename) as t: ... | def _reporthook(t):
""" ``reporthook`` to use with ``urllib.request`` that prints the process of the download.
Uses ``tqdm`` for progress bar.
**Reference:**
https://github.com/tqdm/tqdm
Args:
t (tqdm.tqdm) Progress bar.
Example:
>>> with tqdm(unit='B', unit_scale=True, minit... |
Download filename from google drive unless it's already in directory.
Args:
filename (str): Name of the file to download to (do nothing if it already exists).
url (str): URL to download from. | def _download_file_from_drive(filename, url): # pragma: no cover
""" Download filename from google drive unless it's already in directory.
Args:
filename (str): Name of the file to download to (do nothing if it already exists).
url (str): URL to download from.
"""
confirm_token = None
... |
Extract a compressed file to ``directory``.
Args:
compressed_filename (str): Compressed file.
directory (str): Extract to directory.
extension (str, optional): Extension of the file; Otherwise, attempts to extract extension
from the filename. | def _maybe_extract(compressed_filename, directory, extension=None):
""" Extract a compressed file to ``directory``.
Args:
compressed_filename (str): Compressed file.
directory (str): Extract to directory.
extension (str, optional): Extension of the file; Otherwise, attempts to extract e... |
Return a filename from a URL
Args:
url (str): URL to extract filename from
Returns:
(str): Filename in URL | def _get_filename_from_url(url):
""" Return a filename from a URL
Args:
url (str): URL to extract filename from
Returns:
(str): Filename in URL
"""
parse = urlparse(url)
return os.path.basename(parse.path) |
Download the files at ``urls`` to ``directory``. Extract to ``directory`` if tar or zip.
Args:
urls (str): Url of files.
directory (str): Directory to download to.
check_files (list of str): Check if these files exist, ensuring the download succeeded.
If these files exist before... | def download_files_maybe_extract(urls, directory, check_files=[]):
""" Download the files at ``urls`` to ``directory``. Extract to ``directory`` if tar or zip.
Args:
urls (str): Url of files.
directory (str): Directory to download to.
check_files (list of str): Check if these files exis... |
Download the file at ``url`` to ``directory``. Extract to ``directory`` if tar or zip.
Args:
url (str): Url of file.
directory (str): Directory to download to.
filename (str, optional): Name of the file to download; Otherwise, a filename is extracted
from the url.
extens... | def download_file_maybe_extract(url, directory, filename=None, extension=None, check_files=[]):
""" Download the file at ``url`` to ``directory``. Extract to ``directory`` if tar or zip.
Args:
url (str): Url of file.
directory (str): Directory to download to.
filename (str, optional): N... |
Get the accuracy top-k accuracy between two tensors.
Args:
targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure
saccuracy
outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector
ignore_index (int, optional): Specifies a target index that is ... | def get_accuracy(targets, outputs, k=1, ignore_index=None):
""" Get the accuracy top-k accuracy between two tensors.
Args:
targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure
saccuracy
outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector
... |
Get the accuracy token accuracy between two tensors.
Args:
targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure
saccuracy
outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector
ignore_index (int, optional): Specifies a target index that is ... | def get_token_accuracy(targets, outputs, ignore_index=None):
""" Get the accuracy token accuracy between two tensors.
Args:
targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure
saccuracy
outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector
... |
Given a batch sampler or sampler returns examples instead of indices
Args:
dataset (torch.utils.data.Dataset): Dataset to sample from.
sampler (torch.utils.data.sampler.Sampler): Sampler over the dataset.
Returns:
generator over dataset examples | def sampler_to_iterator(dataset, sampler):
""" Given a batch sampler or sampler returns examples instead of indices
Args:
dataset (torch.utils.data.Dataset): Dataset to sample from.
sampler (torch.utils.data.sampler.Sampler): Sampler over the dataset.
Returns:
generator over datase... |
Get all tensors associated with ``object_``
Args:
object_ (any): Any object to look for tensors.
Returns:
(list of torch.tensor): List of tensors that are associated with ``object_``. | def get_tensors(object_):
""" Get all tensors associated with ``object_``
Args:
object_ (any): Any object to look for tensors.
Returns:
(list of torch.tensor): List of tensors that are associated with ``object_``.
"""
if torch.is_tensor(object_):
return [object_]
elif i... |
Deterministic shuffle and split algorithm.
Given the same two datasets and the same ``random_seed``, the split happens the same exact way
every call.
Args:
dataset (lib.datasets.Dataset): First dataset.
other_dataset (lib.datasets.Dataset): Another dataset.
random_seed (int, option... | def resplit_datasets(dataset, other_dataset, random_seed=None, split=None):
"""Deterministic shuffle and split algorithm.
Given the same two datasets and the same ``random_seed``, the split happens the same exact way
every call.
Args:
dataset (lib.datasets.Dataset): First dataset.
othe... |
Compute ``torch.equal`` with the optional mask parameter.
Args:
ignore_index (int, optional): Specifies a ``tensor`` index that is ignored.
Returns:
(bool) Returns ``True`` if target and prediction are equal. | def torch_equals_ignore_index(tensor, tensor_other, ignore_index=None):
"""
Compute ``torch.equal`` with the optional mask parameter.
Args:
ignore_index (int, optional): Specifies a ``tensor`` index that is ignored.
Returns:
(bool) Returns ``True`` if target and prediction are equal.
... |
Given a list of lengths, create a batch mask.
Example:
>>> lengths_to_mask([1, 2, 3])
tensor([[1, 0, 0],
[1, 1, 0],
[1, 1, 1]], dtype=torch.uint8)
>>> lengths_to_mask([1, 2, 2], [1, 2, 2])
tensor([[[1, 0],
[0, 0]],
<BLANKLINE>... | def lengths_to_mask(*lengths, **kwargs):
""" Given a list of lengths, create a batch mask.
Example:
>>> lengths_to_mask([1, 2, 3])
tensor([[1, 0, 0],
[1, 1, 0],
[1, 1, 1]], dtype=torch.uint8)
>>> lengths_to_mask([1, 2, 2], [1, 2, 2])
tensor([[[1, ... |
Collate a list of type ``k`` (dict, namedtuple, list, etc.) with tensors.
Inspired by:
https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31
Args:
batch (list of k): List of rows of type ``k``.
stack_tensors (callable): Function to stack tensors into a batch... | def collate_tensors(batch, stack_tensors=torch.stack):
""" Collate a list of type ``k`` (dict, namedtuple, list, etc.) with tensors.
Inspired by:
https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31
Args:
batch (list of k): List of rows of type ``k``.
s... |
Apply ``torch.Tensor.to`` to tensors in a generic data structure.
Inspired by:
https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31
Args:
tensors (tensor, dict, list, namedtuple or tuple): Data structure with tensor values to
move.
*args: Argume... | def tensors_to(tensors, *args, **kwargs):
""" Apply ``torch.Tensor.to`` to tensors in a generic data structure.
Inspired by:
https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31
Args:
tensors (tensor, dict, list, namedtuple or tuple): Data structure with tensor... |
Load the Zero dataset.
The Zero dataset is a simple task of predicting zero from zero. This dataset is useful for
integration testing. The extreme simplicity of the dataset allows for models to learn the task
quickly allowing for quick end-to-end testing.
Args:
train (bool, optional): If to lo... | def zero_dataset(train=False, dev=False, test=False, train_rows=256, dev_rows=64, test_rows=64):
"""
Load the Zero dataset.
The Zero dataset is a simple task of predicting zero from zero. This dataset is useful for
integration testing. The extreme simplicity of the dataset allows for models to learn th... |
Decodes a tensor into a sequence.
Args:
encoded (torch.Tensor): Encoded sequence.
Returns:
str: Sequence decoded from ``encoded``. | def decode(self, encoded):
""" Decodes a tensor into a sequence.
Args:
encoded (torch.Tensor): Encoded sequence.
Returns:
str: Sequence decoded from ``encoded``.
"""
encoded = super().decode(encoded)
return self.tokenizer.decode([self.itos[index]... |
Encodes a ``label``.
Args:
label (object): Label to encode.
Returns:
torch.Tensor: Encoding of the label. | def encode(self, label):
""" Encodes a ``label``.
Args:
label (object): Label to encode.
Returns:
torch.Tensor: Encoding of the label.
"""
label = super().encode(label)
return torch.tensor(self.stoi.get(label, self.unknown_index)) |
Args:
iterator (iterator): Batch of labels to encode.
*args: Arguments passed to ``Encoder.batch_encode``.
dim (int, optional): Dimension along which to concatenate tensors.
**kwargs: Keyword arguments passed to ``Encoder.batch_encode``.
Returns:
torc... | def batch_encode(self, iterator, *args, dim=0, **kwargs):
"""
Args:
iterator (iterator): Batch of labels to encode.
*args: Arguments passed to ``Encoder.batch_encode``.
dim (int, optional): Dimension along which to concatenate tensors.
**kwargs: Keyword ar... |
Decodes ``encoded`` label.
Args:
encoded (torch.Tensor): Encoded label.
Returns:
object: Label decoded from ``encoded``. | def decode(self, encoded):
""" Decodes ``encoded`` label.
Args:
encoded (torch.Tensor): Encoded label.
Returns:
object: Label decoded from ``encoded``.
"""
encoded = super().decode(encoded)
if encoded.numel() > 1:
raise ValueError(
... |
Args:
tensor (torch.Tensor): Batch of tensors.
*args: Arguments passed to ``Encoder.batch_decode``.
dim (int, optional): Dimension along which to split tensors.
**kwargs: Keyword arguments passed to ``Encoder.batch_decode``.
Returns:
list: Batch of de... | def batch_decode(self, tensor, *args, dim=0, **kwargs):
"""
Args:
tensor (torch.Tensor): Batch of tensors.
*args: Arguments passed to ``Encoder.batch_decode``.
dim (int, optional): Dimension along which to split tensors.
**kwargs: Keyword arguments passed ... |
Load the Count dataset.
The Count dataset is a simple task of counting the number of integers in a sequence. This
dataset is useful for testing implementations of sequence to label models.
Args:
train (bool, optional): If to load the training split of the dataset.
dev (bool, optional): If ... | def count_dataset(train=False,
dev=False,
test=False,
train_rows=10000,
dev_rows=1000,
test_rows=1000,
seq_max_length=10):
"""
Load the Count dataset.
The Count dataset is a simple task of counting t... |
Load the WMT 2016 machine translation dataset.
As a translation task, this task consists in translating English sentences that describe an
image into German, given the English sentence itself. As training and development data, we
provide 29,000 and 1,014 triples respectively, each containing an English sou... | def multi30k_dataset(directory='data/multi30k/',
train=False,
dev=False,
test=False,
train_filename='train',
dev_filename='val',
test_filename='test',
check_files=['train.de... |
Wraps hidden states in new Tensors, to detach them from their history. | def repackage_hidden(h):
"""Wraps hidden states in new Tensors, to detach them from their history."""
if isinstance(h, torch.Tensor):
return h.detach()
else:
return tuple(repackage_hidden(v) for v in h) |
Parses the given vyper source code and returns a list of python AST objects
for all statements in the source. Performs pre-processing of source code
before parsing as well as post-processing of the resulting AST.
:param source_code: The vyper source code to be parsed.
:return: The post-processed list ... | def parse_to_ast(source_code: str) -> List[ast.stmt]:
"""
Parses the given vyper source code and returns a list of python AST objects
for all statements in the source. Performs pre-processing of source code
before parsing as well as post-processing of the resulting AST.
:param source_code: The vyp... |
Copy necessary variables to pre-allocated memory section.
:param holder: Complete holder for all args
:param maxlen: Total length in bytes of the full arg section (static + dynamic).
:param arg: Current arg to pack
:param context: Context of arg
:param placeholder: Static placeholder for static arg... | def pack_args_by_32(holder, maxlen, arg, typ, context, placeholder,
dynamic_offset_counter=None, datamem_start=None, zero_pad_i=None, pos=None):
"""
Copy necessary variables to pre-allocated memory section.
:param holder: Complete holder for all args
:param maxlen: Total length in b... |
Validates a version pragma directive against the current compiler version. | def validate_version_pragma(version_str: str, start: ParserPosition) -> None:
"""
Validates a version pragma directive against the current compiler version.
"""
from vyper import (
__version__,
)
version_arr = version_str.split('@version')
file_version = version_arr[1].strip()
... |
Valid variable name, checked against global context. | def is_valid_varname(self, name, item):
""" Valid variable name, checked against global context. """
check_valid_varname(name, self._custom_units, self._structs, self._constants, item)
if name in self._globals:
raise VariableDeclarationException(
'Invalid name "%s", p... |
Re-formats a vyper source string into a python source string and performs
some validation. More specifically,
* Translates "contract" and "struct" keyword into python "class" keyword
* Validates "@version" pragma against current compiler version
* Prevents direct use of python "class" keyword
* Pr... | def pre_parse(code: str) -> Tuple[ClassTypes, str]:
"""
Re-formats a vyper source string into a python source string and performs
some validation. More specifically,
* Translates "contract" and "struct" keyword into python "class" keyword
* Validates "@version" pragma against current compiler vers... |
Nonrentrant locks use a prefix with a counter to minimise deployment cost of a contract. | def get_nonrentrant_counter(self, key):
"""
Nonrentrant locks use a prefix with a counter to minimise deployment cost of a contract.
"""
prefix = NONRENTRANT_STORAGE_OFFSET
if key in self._nonrentrant_keys:
return self._nonrentrant_keys[key]
else:
... |
Test if the current statement is a type of list, used in for loops. | def _is_list_iter(self):
"""
Test if the current statement is a type of list, used in for loops.
"""
# Check for literal or memory list.
iter_var_type = (
self.context.vars.get(self.stmt.iter.id).typ
if isinstance(self.stmt.iter, ast.Name)
els... |
Return unrolled const | def get_constant(self, const_name, context):
""" Return unrolled const """
# check if value is compatible with
const = self._constants[const_name]
if isinstance(const, ast.AnnAssign): # Handle ByteArrays.
if context:
expr = Expr(const.value, context).lll_no... |
Using a list of args, determine the most accurate signature to use from
the given context | def lookup_sig(cls, sigs, method_name, expr_args, stmt_or_expr, context):
"""
Using a list of args, determine the most accurate signature to use from
the given context
"""
def synonymise(s):
return s.replace('int128', 'num').replace('uint256', 'num')
# for s... |
Performs annotation and optimization on a parsed python AST by doing the
following:
* Annotating all AST nodes with the originating source code of the AST
* Annotating class definition nodes with their original class type
("contract" or "struct")
* Substituting negative values for unary subtracti... | def annotate_and_optimize_ast(
parsed_ast: ast.Module,
source_code: str,
class_types: Optional[ClassTypes] = None,
) -> None:
"""
Performs annotation and optimization on a parsed python AST by doing the
following:
* Annotating all AST nodes with the originating source code of the AST
* ... |
Handle invalid variable names | def check_valid_varname(varname,
custom_units,
custom_structs,
constants,
pos,
error_prefix="Variable name invalid.",
exc=None):
""" Handle invalid variable names """
e... |
Allocate a MID which has not been used yet. | def allocate_mid(mids):
"""
Allocate a MID which has not been used yet.
"""
i = 0
while True:
mid = str(i)
if mid not in mids:
mids.add(mid)
return mid
i += 1 |
Add a new :class:`RTCIceCandidate` received from the remote peer.
The specified candidate must have a value for either `sdpMid` or `sdpMLineIndex`. | def addIceCandidate(self, candidate):
"""
Add a new :class:`RTCIceCandidate` received from the remote peer.
The specified candidate must have a value for either `sdpMid` or `sdpMLineIndex`.
"""
if candidate.sdpMid is None and candidate.sdpMLineIndex is None:
raise Va... |
Add a :class:`MediaStreamTrack` to the set of media tracks which
will be transmitted to the remote peer. | def addTrack(self, track):
"""
Add a :class:`MediaStreamTrack` to the set of media tracks which
will be transmitted to the remote peer.
"""
# check state is valid
self.__assertNotClosed()
if track.kind not in ['audio', 'video']:
raise InternalError('In... |
Add a new :class:`RTCRtpTransceiver`. | def addTransceiver(self, trackOrKind, direction='sendrecv'):
"""
Add a new :class:`RTCRtpTransceiver`.
"""
self.__assertNotClosed()
# determine track or kind
if hasattr(trackOrKind, 'kind'):
kind = trackOrKind.kind
track = trackOrKind
else... |
Terminate the ICE agent, ending ICE processing and streams. | async def close(self):
"""
Terminate the ICE agent, ending ICE processing and streams.
"""
if self.__isClosed:
return
self.__isClosed = True
self.__setSignalingState('closed')
# stop senders / receivers
for transceiver in self.__transceivers:
... |
Create an SDP answer to an offer received from a remote peer during
the offer/answer negotiation of a WebRTC connection.
:rtype: :class:`RTCSessionDescription` | async def createAnswer(self):
"""
Create an SDP answer to an offer received from a remote peer during
the offer/answer negotiation of a WebRTC connection.
:rtype: :class:`RTCSessionDescription`
"""
# check state is valid
self.__assertNotClosed()
if self.s... |
Create a data channel with the given label.
:rtype: :class:`RTCDataChannel` | def createDataChannel(self, label, maxPacketLifeTime=None, maxRetransmits=None,
ordered=True, protocol='', negotiated=False, id=None):
"""
Create a data channel with the given label.
:rtype: :class:`RTCDataChannel`
"""
if maxPacketLifeTime is not None a... |
Create an SDP offer for the purpose of starting a new WebRTC
connection to a remote peer.
:rtype: :class:`RTCSessionDescription` | async def createOffer(self):
"""
Create an SDP offer for the purpose of starting a new WebRTC
connection to a remote peer.
:rtype: :class:`RTCSessionDescription`
"""
# check state is valid
self.__assertNotClosed()
if not self.__sctp and not self.__transc... |
Returns statistics for the connection.
:rtype: :class:`RTCStatsReport` | async def getStats(self):
"""
Returns statistics for the connection.
:rtype: :class:`RTCStatsReport`
"""
merged = RTCStatsReport()
coros = [x.getStats() for x in (self.getSenders() + self.getReceivers())]
for report in await asyncio.gather(*coros):
me... |
Change the local description associated with the connection.
:param: sessionDescription: An :class:`RTCSessionDescription` generated
by :meth:`createOffer` or :meth:`createAnswer()`. | async def setLocalDescription(self, sessionDescription):
"""
Change the local description associated with the connection.
:param: sessionDescription: An :class:`RTCSessionDescription` generated
by :meth:`createOffer` or :meth:`createAnswer()`.
"""
... |
Changes the remote description associated with the connection.
:param: sessionDescription: An :class:`RTCSessionDescription` created from
information received over the signaling channel. | async def setRemoteDescription(self, sessionDescription):
"""
Changes the remote description associated with the connection.
:param: sessionDescription: An :class:`RTCSessionDescription` created from
information received over the signaling channel.
""... |
Pack the FCI for a Receiver Estimated Maximum Bitrate report.
https://tools.ietf.org/html/draft-alvestrand-rmcat-remb-03 | def pack_remb_fci(bitrate, ssrcs):
"""
Pack the FCI for a Receiver Estimated Maximum Bitrate report.
https://tools.ietf.org/html/draft-alvestrand-rmcat-remb-03
"""
data = b'REMB'
exponent = 0
mantissa = bitrate
while mantissa > 0x3ffff:
mantissa >>= 1
exponent += 1
d... |
Unpack the FCI for a Receiver Estimated Maximum Bitrate report.
https://tools.ietf.org/html/draft-alvestrand-rmcat-remb-03 | def unpack_remb_fci(data):
"""
Unpack the FCI for a Receiver Estimated Maximum Bitrate report.
https://tools.ietf.org/html/draft-alvestrand-rmcat-remb-03
"""
if len(data) < 8 or data[0:4] != b'REMB':
raise ValueError('Invalid REMB prefix')
exponent = (data[5] & 0xfc) >> 2
mantissa ... |
Parse header extensions according to RFC 5285. | def unpack_header_extensions(extension_profile: int,
extension_value: bytes) -> List[Tuple[int, bytes]]:
"""
Parse header extensions according to RFC 5285.
"""
extensions = []
pos = 0
if extension_profile == 0xBEDE:
# One-Byte Header
while pos < len(... |
Serialize header extensions according to RFC 5285. | def pack_header_extensions(extensions: List[Tuple[int, bytes]]) -> Tuple[int, bytes]:
"""
Serialize header extensions according to RFC 5285.
"""
extension_profile = 0
extension_value = b''
if not extensions:
return extension_profile, extension_value
one_byte = True
for x_id, x_... |
Recover initial packet from a retransmission packet. | def unwrap_rtx(rtx, payload_type, ssrc):
"""
Recover initial packet from a retransmission packet.
"""
packet = RtpPacket(
payload_type=payload_type,
marker=rtx.marker,
sequence_number=unpack('!H', rtx.payload[0:2])[0],
timestamp=rtx.timestamp,
ssrc=ssrc,
p... |
Create a retransmission packet from a lost packet. | def wrap_rtx(packet, payload_type, sequence_number, ssrc):
"""
Create a retransmission packet from a lost packet.
"""
rtx = RtpPacket(
payload_type=payload_type,
marker=packet.marker,
sequence_number=sequence_number,
timestamp=packet.timestamp,
ssrc=ssrc,
... |
Returns statistics about the RTP sender.
:rtype: :class:`RTCStatsReport` | async def getStats(self):
"""
Returns statistics about the RTP sender.
:rtype: :class:`RTCStatsReport`
"""
self.__stats.add(RTCOutboundRtpStreamStats(
# RTCStats
timestamp=clock.current_datetime(),
type='outbound-rtp',
id='outbound... |
Attempt to set the parameters controlling the sending of media.
:param: parameters: The :class:`RTCRtpParameters` for the sender. | async def send(self, parameters: RTCRtpSendParameters):
"""
Attempt to set the parameters controlling the sending of media.
:param: parameters: The :class:`RTCRtpParameters` for the sender.
"""
if not self.__started:
self.__cname = parameters.rtcp.cname
s... |
Irreversibly stop the sender. | async def stop(self):
"""
Irreversibly stop the sender.
"""
if self.__started:
self.__transport._unregister_rtp_sender(self)
self.__rtp_task.cancel()
self.__rtcp_task.cancel()
await asyncio.gather(
self.__rtp_exited.wait(),
... |
Retransmit an RTP packet which was reported as lost. | async def _retransmit(self, sequence_number):
"""
Retransmit an RTP packet which was reported as lost.
"""
packet = self.__rtp_history.get(sequence_number % RTP_HISTORY_SIZE)
if packet and packet.sequence_number == sequence_number:
if self.__rtx_payload_type is not No... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.