Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
Font.size
(self)
The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|float|numpy.ndarray
The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] - A tuple, list, or one-dimensional numpy array of the above
def size(self): """ The 'size' property is a number and may be specified as: - An int or float in the interval [1, inf] - A tuple, list, or one-dimensional numpy array of the above Returns ------- int|float|numpy.ndarray """ return self["size"...
[ "def", "size", "(", "self", ")", ":", "return", "self", "[", "\"size\"", "]" ]
[ 145, 4 ]
[ 155, 27 ]
python
en
['en', 'error', 'th']
False
Font.sizesrc
(self)
Sets the source reference on Chart Studio Cloud for size . The 'sizesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str
Sets the source reference on Chart Studio Cloud for size . The 'sizesrc' property must be specified as a string or as a plotly.grid_objs.Column object
def sizesrc(self): """ Sets the source reference on Chart Studio Cloud for size . The 'sizesrc' property must be specified as a string or as a plotly.grid_objs.Column object Returns ------- str """ return self["sizesrc"]
[ "def", "sizesrc", "(", "self", ")", ":", "return", "self", "[", "\"sizesrc\"", "]" ]
[ 164, 4 ]
[ 175, 30 ]
python
en
['en', 'error', 'th']
False
Font.__init__
( self, arg=None, color=None, colorsrc=None, family=None, familysrc=None, size=None, sizesrc=None, **kwargs )
Construct a new Font object Sets the font used for `title`. Note that the title's font used to be set by the now deprecated `titlefont` attribute. Parameters ---------- arg dict of properties compatible with this constructor or an instan...
Construct a new Font object Sets the font used for `title`. Note that the title's font used to be set by the now deprecated `titlefont` attribute.
def __init__( self, arg=None, color=None, colorsrc=None, family=None, familysrc=None, size=None, sizesrc=None, **kwargs ): """ Construct a new Font object Sets the font used for `title`. Note that the title's fo...
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "color", "=", "None", ",", "colorsrc", "=", "None", ",", "family", "=", "None", ",", "familysrc", "=", "None", ",", "size", "=", "None", ",", "sizesrc", "=", "None", ",", "*", "*", "kw...
[ 215, 4 ]
[ 330, 34 ]
python
en
['en', 'error', 'th']
False
VerifyFileExists
(directory, relative_path)
Verifies that the given file exists; aborts on failure. relative_path is the file path relative to the given directory.
Verifies that the given file exists; aborts on failure.
def VerifyFileExists(directory, relative_path): """Verifies that the given file exists; aborts on failure. relative_path is the file path relative to the given directory. """ if not os.path.isfile(os.path.join(directory, relative_path)): print('ERROR: Cannot find %s in directory %s.' % (relative_path, ...
[ "def", "VerifyFileExists", "(", "directory", ",", "relative_path", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "directory", ",", "relative_path", ")", ")", ":", "print", "(", "'ERROR: Cannot find %s in...
[ 88, 0 ]
[ 99, 15 ]
python
en
['en', 'en', 'en']
True
ValidateGTestRootDir
(gtest_root)
Makes sure gtest_root points to a valid gtest root directory. The function aborts the program on failure.
Makes sure gtest_root points to a valid gtest root directory.
def ValidateGTestRootDir(gtest_root): """Makes sure gtest_root points to a valid gtest root directory. The function aborts the program on failure. """ VerifyFileExists(gtest_root, GTEST_H_SEED) VerifyFileExists(gtest_root, GTEST_ALL_CC_SEED)
[ "def", "ValidateGTestRootDir", "(", "gtest_root", ")", ":", "VerifyFileExists", "(", "gtest_root", ",", "GTEST_H_SEED", ")", "VerifyFileExists", "(", "gtest_root", ",", "GTEST_ALL_CC_SEED", ")" ]
[ 102, 0 ]
[ 109, 49 ]
python
en
['en', 'en', 'en']
True
VerifyOutputFile
(output_dir, relative_path)
Verifies that the given output file path is valid. relative_path is relative to the output_dir directory.
Verifies that the given output file path is valid.
def VerifyOutputFile(output_dir, relative_path): """Verifies that the given output file path is valid. relative_path is relative to the output_dir directory. """ # Makes sure the output file either doesn't exist or can be overwritten. output_file = os.path.join(output_dir, relative_path) if os.path.exists...
[ "def", "VerifyOutputFile", "(", "output_dir", ",", "relative_path", ")", ":", "# Makes sure the output file either doesn't exist or can be overwritten.", "output_file", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "relative_path", ")", "if", "os", ".", ...
[ 112, 0 ]
[ 135, 33 ]
python
en
['en', 'en', 'en']
True
ValidateOutputDir
(output_dir)
Makes sure output_dir points to a valid output directory. The function aborts the program on failure.
Makes sure output_dir points to a valid output directory.
def ValidateOutputDir(output_dir): """Makes sure output_dir points to a valid output directory. The function aborts the program on failure. """ VerifyOutputFile(output_dir, GTEST_H_OUTPUT) VerifyOutputFile(output_dir, GTEST_ALL_CC_OUTPUT)
[ "def", "ValidateOutputDir", "(", "output_dir", ")", ":", "VerifyOutputFile", "(", "output_dir", ",", "GTEST_H_OUTPUT", ")", "VerifyOutputFile", "(", "output_dir", ",", "GTEST_ALL_CC_OUTPUT", ")" ]
[ 138, 0 ]
[ 145, 51 ]
python
en
['en', 'en', 'en']
True
FuseGTestH
(gtest_root, output_dir)
Scans folder gtest_root to generate gtest/gtest.h in output_dir.
Scans folder gtest_root to generate gtest/gtest.h in output_dir.
def FuseGTestH(gtest_root, output_dir): """Scans folder gtest_root to generate gtest/gtest.h in output_dir.""" output_file = open(os.path.join(output_dir, GTEST_H_OUTPUT), 'w') processed_files = set() # Holds all gtest headers we've processed. def ProcessFile(gtest_header_path): """Processes the given gt...
[ "def", "FuseGTestH", "(", "gtest_root", ",", "output_dir", ")", ":", "output_file", "=", "open", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "GTEST_H_OUTPUT", ")", ",", "'w'", ")", "processed_files", "=", "set", "(", ")", "# Holds all gtes...
[ 148, 0 ]
[ 174, 21 ]
python
en
['af', 'en', 'en']
True
FuseGTestAllCcToFile
(gtest_root, output_file)
Scans folder gtest_root to generate gtest/gtest-all.cc in output_file.
Scans folder gtest_root to generate gtest/gtest-all.cc in output_file.
def FuseGTestAllCcToFile(gtest_root, output_file): """Scans folder gtest_root to generate gtest/gtest-all.cc in output_file.""" processed_files = set() def ProcessFile(gtest_source_file): """Processes the given gtest source file.""" # We don't process the same #included file twice. if gtest_source_...
[ "def", "FuseGTestAllCcToFile", "(", "gtest_root", ",", "output_file", ")", ":", "processed_files", "=", "set", "(", ")", "def", "ProcessFile", "(", "gtest_source_file", ")", ":", "\"\"\"Processes the given gtest source file.\"\"\"", "# We don't process the same #included file...
[ 177, 0 ]
[ 217, 32 ]
python
en
['af', 'en', 'en']
True
FuseGTestAllCc
(gtest_root, output_dir)
Scans folder gtest_root to generate gtest/gtest-all.cc in output_dir.
Scans folder gtest_root to generate gtest/gtest-all.cc in output_dir.
def FuseGTestAllCc(gtest_root, output_dir): """Scans folder gtest_root to generate gtest/gtest-all.cc in output_dir.""" output_file = open(os.path.join(output_dir, GTEST_ALL_CC_OUTPUT), 'w') FuseGTestAllCcToFile(gtest_root, output_file) output_file.close()
[ "def", "FuseGTestAllCc", "(", "gtest_root", ",", "output_dir", ")", ":", "output_file", "=", "open", "(", "os", ".", "path", ".", "join", "(", "output_dir", ",", "GTEST_ALL_CC_OUTPUT", ")", ",", "'w'", ")", "FuseGTestAllCcToFile", "(", "gtest_root", ",", "ou...
[ 220, 0 ]
[ 225, 21 ]
python
en
['af', 'en', 'en']
True
FuseGTest
(gtest_root, output_dir)
Fuses gtest.h and gtest-all.cc.
Fuses gtest.h and gtest-all.cc.
def FuseGTest(gtest_root, output_dir): """Fuses gtest.h and gtest-all.cc.""" ValidateGTestRootDir(gtest_root) ValidateOutputDir(output_dir) FuseGTestH(gtest_root, output_dir) FuseGTestAllCc(gtest_root, output_dir)
[ "def", "FuseGTest", "(", "gtest_root", ",", "output_dir", ")", ":", "ValidateGTestRootDir", "(", "gtest_root", ")", "ValidateOutputDir", "(", "output_dir", ")", "FuseGTestH", "(", "gtest_root", ",", "output_dir", ")", "FuseGTestAllCc", "(", "gtest_root", ",", "out...
[ 228, 0 ]
[ 235, 40 ]
python
en
['en', 'en', 'en']
True
maintain_dialog_history
( history, observation, reply='', historyLength=1, useReplies='label_else_model', dict=None, useStartEndIndices=True, splitSentences=False, )
Keep track of dialog history, up to a truncation length. Either includes replies from the labels, model, or not all using param 'replies'. DEPRECATED. USE PARLAI.CORE.TORCH_AGENT INSTEAD.
Keep track of dialog history, up to a truncation length.
def maintain_dialog_history( history, observation, reply='', historyLength=1, useReplies='label_else_model', dict=None, useStartEndIndices=True, splitSentences=False, ): """ Keep track of dialog history, up to a truncation length. Either includes replies from the labels, mod...
[ "def", "maintain_dialog_history", "(", "history", ",", "observation", ",", "reply", "=", "''", ",", "historyLength", "=", "1", ",", "useReplies", "=", "'label_else_model'", ",", "dict", "=", "None", ",", "useStartEndIndices", "=", "True", ",", "splitSentences", ...
[ 51, 0 ]
[ 118, 28 ]
python
en
['en', 'error', 'th']
False
load_cands
(path, lines_have_ids=False, cands_are_replies=False)
Load global fixed set of candidate labels that the teacher provides. Every example will include these as candidates. The true labels for a specific example are also added to this set, so that it's possible to get the right answer.
Load global fixed set of candidate labels that the teacher provides.
def load_cands(path, lines_have_ids=False, cands_are_replies=False): """ Load global fixed set of candidate labels that the teacher provides. Every example will include these as candidates. The true labels for a specific example are also added to this set, so that it's possible to get the right answer....
[ "def", "load_cands", "(", "path", ",", "lines_have_ids", "=", "False", ",", "cands_are_replies", "=", "False", ")", ":", "if", "path", "is", "None", ":", "return", "None", "cands", "=", "[", "]", "cnt", "=", "0", "with", "PathManager", ".", "open", "("...
[ 121, 0 ]
[ 155, 16 ]
python
en
['en', 'error', 'th']
False
_report_sort_key
(report_key: str)
Sorting name for reports. Sorts by main metric alphabetically, then by task.
Sorting name for reports.
def _report_sort_key(report_key: str) -> Tuple[str, str]: """ Sorting name for reports. Sorts by main metric alphabetically, then by task. """ # if metric is on its own, like "f1", we will return ('', 'f1') # if metric is from multitask, we denote it. # e.g. "convai2/f1" -> ('convai2', 'f1'...
[ "def", "_report_sort_key", "(", "report_key", ":", "str", ")", "->", "Tuple", "[", "str", ",", "str", "]", ":", "# if metric is on its own, like \"f1\", we will return ('', 'f1')", "# if metric is from multitask, we denote it.", "# e.g. \"convai2/f1\" -> ('convai2', 'f1')", "# we...
[ 329, 0 ]
[ 343, 39 ]
python
en
['en', 'error', 'th']
False
float_formatter
(f: Union[float, int])
Format a float as a pretty string.
Format a float as a pretty string.
def float_formatter(f: Union[float, int]) -> str: """ Format a float as a pretty string. """ if f != f: # instead of returning nan, return "" so it shows blank in table return "" if isinstance(f, int): # don't do any rounding of integers, leave them alone return str(f...
[ "def", "float_formatter", "(", "f", ":", "Union", "[", "float", ",", "int", "]", ")", "->", "str", ":", "if", "f", "!=", "f", ":", "# instead of returning nan, return \"\" so it shows blank in table", "return", "\"\"", "if", "isinstance", "(", "f", ",", "int",...
[ 346, 0 ]
[ 371, 12 ]
python
en
['en', 'error', 'th']
False
nice_report
(report)
Render an agent Report as a beautiful string. If pandas is installed, we will use it to render as a table. Multitask metrics will be shown per row, e.g. .. code-block: f1 ppl all .410 27.0 task1 .400 32.0 task2 .420 22.0 If pandas is not availa...
Render an agent Report as a beautiful string.
def nice_report(report) -> str: """ Render an agent Report as a beautiful string. If pandas is installed, we will use it to render as a table. Multitask metrics will be shown per row, e.g. .. code-block: f1 ppl all .410 27.0 task1 .400 32.0 task2 ...
[ "def", "nice_report", "(", "report", ")", "->", "str", ":", "if", "not", "report", ":", "return", "\"\"", "from", "parlai", ".", "core", ".", "metrics", "import", "Metric", "try", ":", "import", "pandas", "as", "pd", "use_pandas", "=", "True", "except", ...
[ 388, 0 ]
[ 447, 9 ]
python
en
['en', 'error', 'th']
False
round_sigfigs
(x: Union[float, 'torch.Tensor'], sigfigs=4)
Round value to specified significant figures. :param x: input number :param sigfigs: number of significant figures to return :returns: float number rounded to specified sigfigs
Round value to specified significant figures.
def round_sigfigs(x: Union[float, 'torch.Tensor'], sigfigs=4) -> float: """ Round value to specified significant figures. :param x: input number :param sigfigs: number of significant figures to return :returns: float number rounded to specified sigfigs """ x_: float if __TORCH_AVAILABL...
[ "def", "round_sigfigs", "(", "x", ":", "Union", "[", "float", ",", "'torch.Tensor'", "]", ",", "sigfigs", "=", "4", ")", "->", "float", ":", "x_", ":", "float", "if", "__TORCH_AVAILABLE", "and", "isinstance", "(", "x", ",", "torch", ".", "Tensor", ")",...
[ 450, 0 ]
[ 473, 20 ]
python
en
['en', 'error', 'th']
False
no_lock
()
Build a nolock for other classes to use for no-op locking.
Build a nolock for other classes to use for no-op locking.
def no_lock(): """ Build a nolock for other classes to use for no-op locking. """ return single_nolock
[ "def", "no_lock", "(", ")", ":", "return", "single_nolock" ]
[ 479, 0 ]
[ 483, 24 ]
python
en
['en', 'error', 'th']
False
clip_text
(text, max_len)
Clip text to max length, adding ellipses.
Clip text to max length, adding ellipses.
def clip_text(text, max_len): """ Clip text to max length, adding ellipses. """ if len(text) > max_len: begin_text = ' '.join(text[: math.floor(0.8 * max_len)].split(' ')[:-1]) end_text = ' '.join( text[(len(text) - math.floor(0.2 * max_len)) :].split(' ')[1:] ) ...
[ "def", "clip_text", "(", "text", ",", "max_len", ")", ":", "if", "len", "(", "text", ")", ">", "max_len", ":", "begin_text", "=", "' '", ".", "join", "(", "text", "[", ":", "math", ".", "floor", "(", "0.8", "*", "max_len", ")", "]", ".", "split",...
[ 486, 0 ]
[ 499, 15 ]
python
en
['en', 'error', 'th']
False
_ellipse
(lst: List[str], max_display: int = 5, sep: str = '|')
Like join, but possibly inserts an ellipsis. :param lst: The list to join on :param int max_display: the number of items to display for ellipsing. If -1, shows all items :param string sep: the delimiter to join on
Like join, but possibly inserts an ellipsis.
def _ellipse(lst: List[str], max_display: int = 5, sep: str = '|') -> str: """ Like join, but possibly inserts an ellipsis. :param lst: The list to join on :param int max_display: the number of items to display for ellipsing. If -1, shows all items :param string sep: the delimiter to join o...
[ "def", "_ellipse", "(", "lst", ":", "List", "[", "str", "]", ",", "max_display", ":", "int", "=", "5", ",", "sep", ":", "str", "=", "'|'", ")", "->", "str", ":", "# copy the list (or force it to a list if it's a set)", "choices", "=", "list", "(", "lst", ...
[ 502, 0 ]
[ 517, 44 ]
python
en
['en', 'error', 'th']
False
display_messages
( msgs: List[Dict[str, Any]], prettify: bool = False, ignore_agent_reply: bool = False, add_fields: str = '', max_len: int = 1000, verbose: bool = False, )
Return a string describing the set of messages provided. If prettify is true, candidates are displayed using prettytable. add_fields provides a list of fields in the msgs which should be displayed if verbose is off.
Return a string describing the set of messages provided.
def display_messages( msgs: List[Dict[str, Any]], prettify: bool = False, ignore_agent_reply: bool = False, add_fields: str = '', max_len: int = 1000, verbose: bool = False, ) -> Optional[str]: """ Return a string describing the set of messages provided. If prettify is true, candida...
[ "def", "display_messages", "(", "msgs", ":", "List", "[", "Dict", "[", "str", ",", "Any", "]", "]", ",", "prettify", ":", "bool", "=", "False", ",", "ignore_agent_reply", ":", "bool", "=", "False", ",", "add_fields", ":", "str", "=", "''", ",", "max_...
[ 520, 0 ]
[ 653, 27 ]
python
en
['en', 'error', 'th']
False
str_to_msg
(txt, ignore_fields='')
Convert formatted string to ParlAI message dict. :param txt: formatted string to convert. String format is tab-separated fields, with colon separating field name and contents. :param ignore_fields: (default '') comma-separated field names to not include in the msg dict even...
Convert formatted string to ParlAI message dict.
def str_to_msg(txt, ignore_fields=''): """ Convert formatted string to ParlAI message dict. :param txt: formatted string to convert. String format is tab-separated fields, with colon separating field name and contents. :param ignore_fields: (default '') comma-separated field nam...
[ "def", "str_to_msg", "(", "txt", ",", "ignore_fields", "=", "''", ")", ":", "def", "tostr", "(", "txt", ")", ":", "txt", "=", "str", "(", "txt", ")", "txt", "=", "txt", ".", "replace", "(", "'\\\\t'", ",", "'\\t'", ")", "txt", "=", "txt", ".", ...
[ 656, 0 ]
[ 707, 23 ]
python
en
['en', 'error', 'th']
False
msg_to_str
(msg, ignore_fields='')
Convert ParlAI message dict to string. :param msg: dict to convert into a string. :param ignore_fields: (default '') comma-separated field names to not include in the string even if they're in the msg dict.
Convert ParlAI message dict to string.
def msg_to_str(msg, ignore_fields=''): """ Convert ParlAI message dict to string. :param msg: dict to convert into a string. :param ignore_fields: (default '') comma-separated field names to not include in the string even if they're in the msg dict. """ def filter(txt):...
[ "def", "msg_to_str", "(", "msg", ",", "ignore_fields", "=", "''", ")", ":", "def", "filter", "(", "txt", ")", ":", "txt", "=", "str", "(", "txt", ")", "txt", "=", "txt", ".", "replace", "(", "'\\t'", ",", "'\\\\t'", ")", "txt", "=", "txt", ".", ...
[ 710, 0 ]
[ 760, 27 ]
python
en
['en', 'error', 'th']
False
set_namedtuple_defaults
(namedtuple, default=None)
Set *all* of the fields for a given nametuple to a singular value. Additionally removes the default docstring for each field. Modifies the tuple in place, but returns it anyway. More info: https://stackoverflow.com/a/18348004 :param namedtuple: A constructed collections.namedtuple :param...
Set *all* of the fields for a given nametuple to a singular value.
def set_namedtuple_defaults(namedtuple, default=None): """ Set *all* of the fields for a given nametuple to a singular value. Additionally removes the default docstring for each field. Modifies the tuple in place, but returns it anyway. More info: https://stackoverflow.com/a/18348004 :par...
[ "def", "set_namedtuple_defaults", "(", "namedtuple", ",", "default", "=", "None", ")", ":", "namedtuple", ".", "__new__", ".", "__defaults__", "=", "(", "default", ",", ")", "*", "len", "(", "namedtuple", ".", "_fields", ")", "for", "f", "in", "namedtuple"...
[ 764, 0 ]
[ 782, 21 ]
python
en
['en', 'error', 'th']
False
warn_once
(msg: str)
Log a warning, but only once. :param str msg: Message to display
Log a warning, but only once.
def warn_once(msg: str) -> None: """ Log a warning, but only once. :param str msg: Message to display """ global _seen_logs if msg not in _seen_logs: _seen_logs.add(msg) logging.warn(msg)
[ "def", "warn_once", "(", "msg", ":", "str", ")", "->", "None", ":", "global", "_seen_logs", "if", "msg", "not", "in", "_seen_logs", ":", "_seen_logs", ".", "add", "(", "msg", ")", "logging", ".", "warn", "(", "msg", ")" ]
[ 788, 0 ]
[ 797, 25 ]
python
en
['en', 'error', 'th']
False
error_once
(msg: str)
Log an error, but only once. :param str msg: Message to display
Log an error, but only once.
def error_once(msg: str) -> None: """ Log an error, but only once. :param str msg: Message to display """ global _seen_logs if msg not in _seen_logs: _seen_logs.add(msg) logging.error(msg)
[ "def", "error_once", "(", "msg", ":", "str", ")", "->", "None", ":", "global", "_seen_logs", "if", "msg", "not", "in", "_seen_logs", ":", "_seen_logs", ".", "add", "(", "msg", ")", "logging", ".", "error", "(", "msg", ")" ]
[ 800, 0 ]
[ 809, 26 ]
python
en
['en', 'error', 'th']
False
recursive_getattr
(obj, attr, *args)
Recursive call to getattr for nested attributes.
Recursive call to getattr for nested attributes.
def recursive_getattr(obj, attr, *args): """ Recursive call to getattr for nested attributes. """ def _getattr(obj, attr): return getattr(obj, attr, *args) return functools.reduce(_getattr, [obj] + attr.split('.'))
[ "def", "recursive_getattr", "(", "obj", ",", "attr", ",", "*", "args", ")", ":", "def", "_getattr", "(", "obj", ",", "attr", ")", ":", "return", "getattr", "(", "obj", ",", "attr", ",", "*", "args", ")", "return", "functools", ".", "reduce", "(", "...
[ 812, 0 ]
[ 820, 62 ]
python
en
['en', 'error', 'th']
False
Timer.__init__
(self)
Initialize timer.
Initialize timer.
def __init__(self): """ Initialize timer. """ self.running = True self.total = 0 self.start = time.time()
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "running", "=", "True", "self", ".", "total", "=", "0", "self", ".", "start", "=", "time", ".", "time", "(", ")" ]
[ 163, 4 ]
[ 169, 32 ]
python
en
['en', 'error', 'th']
False
Timer.reset
(self)
Reset timer to zero.
Reset timer to zero.
def reset(self): """ Reset timer to zero. """ self.running = True self.total = 0 self.start = time.time() return self
[ "def", "reset", "(", "self", ")", ":", "self", ".", "running", "=", "True", "self", ".", "total", "=", "0", "self", ".", "start", "=", "time", ".", "time", "(", ")", "return", "self" ]
[ 171, 4 ]
[ 178, 19 ]
python
en
['en', 'error', 'th']
False
Timer.resume
(self)
Resume timer.
Resume timer.
def resume(self): """ Resume timer. """ if not self.running: self.running = True self.start = time.time() return self
[ "def", "resume", "(", "self", ")", ":", "if", "not", "self", ".", "running", ":", "self", ".", "running", "=", "True", "self", ".", "start", "=", "time", ".", "time", "(", ")", "return", "self" ]
[ 180, 4 ]
[ 187, 19 ]
python
en
['en', 'error', 'th']
False
Timer.stop
(self)
Pause timer.
Pause timer.
def stop(self): """ Pause timer. """ if self.running: self.running = False self.total += time.time() - self.start return self
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "running", ":", "self", ".", "running", "=", "False", "self", ".", "total", "+=", "time", ".", "time", "(", ")", "-", "self", ".", "start", "return", "self" ]
[ 189, 4 ]
[ 196, 19 ]
python
en
['en', 'error', 'th']
False
Timer.time
(self)
Get current timer time.
Get current timer time.
def time(self): """ Get current timer time. """ if self.running: return self.total + time.time() - self.start return self.total
[ "def", "time", "(", "self", ")", ":", "if", "self", ".", "running", ":", "return", "self", ".", "total", "+", "time", ".", "time", "(", ")", "-", "self", ".", "start", "return", "self", ".", "total" ]
[ 198, 4 ]
[ 204, 25 ]
python
en
['en', 'error', 'th']
False
TimeLogger.__init__
(self)
Set up timer.
Set up timer.
def __init__(self): """ Set up timer. """ self.timer = Timer() self.tot_time = 0
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "timer", "=", "Timer", "(", ")", "self", ".", "tot_time", "=", "0" ]
[ 212, 4 ]
[ 217, 25 ]
python
en
['en', 'error', 'th']
False
TimeLogger.total_time
(self)
Return time elapsed at last log call.
Return time elapsed at last log call.
def total_time(self): """ Return time elapsed at last log call. """ return self.tot_time
[ "def", "total_time", "(", "self", ")", ":", "return", "self", ".", "tot_time" ]
[ 219, 4 ]
[ 223, 28 ]
python
en
['en', 'error', 'th']
False
TimeLogger.time
(self)
Return current timer time.
Return current timer time.
def time(self): """ Return current timer time. """ return self.timer.time()
[ "def", "time", "(", "self", ")", ":", "return", "self", ".", "timer", ".", "time", "(", ")" ]
[ 225, 4 ]
[ 229, 32 ]
python
en
['en', 'error', 'th']
False
TimeLogger.log
(self, done, total, report=None)
Log report, time elapsed, and percentage progress towards goal. :param done: number of examples completed so far :param total: total number of elements to be completed. if total > 0, calculates the time remaining and percentage complete. :param report: dict of pai...
Log report, time elapsed, and percentage progress towards goal.
def log(self, done, total, report=None): """ Log report, time elapsed, and percentage progress towards goal. :param done: number of examples completed so far :param total: total number of elements to be completed. if total > 0, calculates the time remaining and per...
[ "def", "log", "(", "self", ",", "done", ",", "total", ",", "report", "=", "None", ")", ":", "from", "parlai", ".", "core", ".", "metrics", "import", "Metric", "# delay import to prevent circular dep", "if", "isinstance", "(", "done", ",", "Metric", ")", ":...
[ 231, 4 ]
[ 270, 27 ]
python
en
['en', 'error', 'th']
False
AttrDict.__init__
(self, *args, **kwargs)
Initialize AttrDict using input dict.
Initialize AttrDict using input dict.
def __init__(self, *args, **kwargs): """ Initialize AttrDict using input dict. """ super().__init__(*args, **kwargs) self.__dict__ = self
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "__dict__", "=", "self" ]
[ 286, 4 ]
[ 291, 28 ]
python
en
['en', 'error', 'th']
False
NoLock.__enter__
(self)
No-op.
No-op.
def __enter__(self): """ No-op. """ return self
[ "def", "__enter__", "(", "self", ")", ":", "return", "self" ]
[ 301, 4 ]
[ 305, 19 ]
python
en
['en', 'error', 'th']
False
NoLock.__exit__
(self, exc_type, exc_value, exc_traceback)
No-op.
No-op.
def __exit__(self, exc_type, exc_value, exc_traceback): """ No-op. """ pass
[ "def", "__exit__", "(", "self", ",", "exc_type", ",", "exc_value", ",", "exc_traceback", ")", ":", "pass" ]
[ 307, 4 ]
[ 311, 12 ]
python
en
['en', 'error', 'th']
False
preprocess_schema
(plotly_schema)
Central location to make changes to schema before it's seen by the PlotlyNode classes
Central location to make changes to schema before it's seen by the PlotlyNode classes
def preprocess_schema(plotly_schema): """ Central location to make changes to schema before it's seen by the PlotlyNode classes """ # Update template # --------------- layout = plotly_schema["layout"]["layoutAttributes"] # Create codegen-friendly template scheme template = { ...
[ "def", "preprocess_schema", "(", "plotly_schema", ")", ":", "# Update template", "# ---------------", "layout", "=", "plotly_schema", "[", "\"layout\"", "]", "[", "\"layoutAttributes\"", "]", "# Create codegen-friendly template scheme", "template", "=", "{", "\"data\"", "...
[ 38, 0 ]
[ 84, 62 ]
python
en
['en', 'error', 'th']
False
opt_to_kwargs
(opt)
Get kwargs for seq2seq from opt.
Get kwargs for seq2seq from opt.
def opt_to_kwargs(opt): """ Get kwargs for seq2seq from opt. """ kwargs = {} for k in [ 'numlayers', 'dropout', 'bidirectional', 'rnn_class', 'lookuptable', 'decoder', 'numsoftmax', 'attention', 'attention_length', 'atte...
[ "def", "opt_to_kwargs", "(", "opt", ")", ":", "kwargs", "=", "{", "}", "for", "k", "in", "[", "'numlayers'", ",", "'dropout'", ",", "'bidirectional'", ",", "'rnn_class'", ",", "'lookuptable'", ",", "'decoder'", ",", "'numsoftmax'", ",", "'attention'", ",", ...
[ 20, 0 ]
[ 41, 17 ]
python
en
['en', 'error', 'th']
False
pad
(tensor, length, dim=0, pad=0)
Pad tensor to a specific length. :param tensor: vector to pad :param length: new length :param dim: (default 0) dimension to pad :returns: padded tensor if the tensor is shorter than length
Pad tensor to a specific length.
def pad(tensor, length, dim=0, pad=0): """ Pad tensor to a specific length. :param tensor: vector to pad :param length: new length :param dim: (default 0) dimension to pad :returns: padded tensor if the tensor is shorter than length """ if tensor.size(dim) < length: return torc...
[ "def", "pad", "(", "tensor", ",", "length", ",", "dim", "=", "0", ",", "pad", "=", "0", ")", ":", "if", "tensor", ".", "size", "(", "dim", ")", "<", "length", ":", "return", "torch", ".", "cat", "(", "[", "tensor", ",", "tensor", ".", "new", ...
[ 44, 0 ]
[ 67, 21 ]
python
en
['en', 'error', 'th']
False
Seq2seq.__init__
( self, num_features, embeddingsize, hiddensize, numlayers=2, dropout=0, bidirectional=False, rnn_class='lstm', lookuptable='unique', decoder='same', numsoftmax=1, attention='none', attention_length=48, atten...
Initialize seq2seq model. See cmdline args in Seq2seqAgent for description of arguments.
Initialize seq2seq model.
def __init__( self, num_features, embeddingsize, hiddensize, numlayers=2, dropout=0, bidirectional=False, rnn_class='lstm', lookuptable='unique', decoder='same', numsoftmax=1, attention='none', attention_length=48, ...
[ "def", "__init__", "(", "self", ",", "num_features", ",", "embeddingsize", ",", "hiddensize", ",", "numlayers", "=", "2", ",", "dropout", "=", "0", ",", "bidirectional", "=", "False", ",", "rnn_class", "=", "'lstm'", ",", "lookuptable", "=", "'unique'", ",...
[ 77, 4 ]
[ 164, 9 ]
python
en
['en', 'error', 'th']
False
Seq2seq._encode
(self, xs, prev_enc=None)
Encode the input or return cached encoder state.
Encode the input or return cached encoder state.
def _encode(self, xs, prev_enc=None): """ Encode the input or return cached encoder state. """ if prev_enc is not None: return prev_enc else: return self.encoder(xs)
[ "def", "_encode", "(", "self", ",", "xs", ",", "prev_enc", "=", "None", ")", ":", "if", "prev_enc", "is", "not", "None", ":", "return", "prev_enc", "else", ":", "return", "self", ".", "encoder", "(", "xs", ")" ]
[ 166, 4 ]
[ 173, 35 ]
python
en
['en', 'error', 'th']
False
Seq2seq._starts
(self, bsz)
Return bsz start tokens.
Return bsz start tokens.
def _starts(self, bsz): """ Return bsz start tokens. """ return self.START.detach().expand(bsz, 1)
[ "def", "_starts", "(", "self", ",", "bsz", ")", ":", "return", "self", ".", "START", ".", "detach", "(", ")", ".", "expand", "(", "bsz", ",", "1", ")" ]
[ 175, 4 ]
[ 179, 49 ]
python
en
['en', 'error', 'th']
False
Seq2seq._decode_forced
(self, ys, ctrl_inputs, encoder_states)
Decode with teacher forcing.
Decode with teacher forcing.
def _decode_forced(self, ys, ctrl_inputs, encoder_states): """ Decode with teacher forcing. """ bsz = ys.size(0) seqlen = ys.size(1) hidden = encoder_states[1] attn_params = (encoder_states[0], encoder_states[2]) # input to model is START + each target e...
[ "def", "_decode_forced", "(", "self", ",", "ys", ",", "ctrl_inputs", ",", "encoder_states", ")", ":", "bsz", "=", "ys", ".", "size", "(", "0", ")", "seqlen", "=", "ys", ".", "size", "(", "1", ")", "hidden", "=", "encoder_states", "[", "1", "]", "at...
[ 181, 4 ]
[ 210, 21 ]
python
en
['en', 'error', 'th']
False
Seq2seq._decode
(self, ctrl_inputs, encoder_states, maxlen)
Decode maxlen tokens.
Decode maxlen tokens.
def _decode(self, ctrl_inputs, encoder_states, maxlen): """ Decode maxlen tokens. """ hidden = encoder_states[1] attn_params = (encoder_states[0], encoder_states[2]) bsz = encoder_states[0].size(0) xs = self._starts(bsz) # input start token scores = [] ...
[ "def", "_decode", "(", "self", ",", "ctrl_inputs", ",", "encoder_states", ",", "maxlen", ")", ":", "hidden", "=", "encoder_states", "[", "1", "]", "attn_params", "=", "(", "encoder_states", "[", "0", "]", ",", "encoder_states", "[", "2", "]", ")", "bsz",...
[ 212, 4 ]
[ 231, 21 ]
python
en
['en', 'error', 'th']
False
Seq2seq._align_inds
(self, encoder_states, cand_inds)
Select the encoder states relevant to valid candidates.
Select the encoder states relevant to valid candidates.
def _align_inds(self, encoder_states, cand_inds): """ Select the encoder states relevant to valid candidates. """ enc_out, hidden, attn_mask = encoder_states # LSTM or GRU/RNN hidden state? if isinstance(hidden, torch.Tensor): hid, cell = hidden, None ...
[ "def", "_align_inds", "(", "self", ",", "encoder_states", ",", "cand_inds", ")", ":", "enc_out", ",", "hidden", ",", "attn_mask", "=", "encoder_states", "# LSTM or GRU/RNN hidden state?", "if", "isinstance", "(", "hidden", ",", "torch", ".", "Tensor", ")", ":", ...
[ 233, 4 ]
[ 260, 41 ]
python
en
['en', 'error', 'th']
False
Seq2seq._extract_cur
(self, encoder_states, index, num_cands)
Extract encoder states at current index and expand them.
Extract encoder states at current index and expand them.
def _extract_cur(self, encoder_states, index, num_cands): """ Extract encoder states at current index and expand them. """ enc_out, hidden, attn_mask = encoder_states if isinstance(hidden, torch.Tensor): cur_hid = hidden.select(1, index).unsqueeze(1).expand(-1, num_ca...
[ "def", "_extract_cur", "(", "self", ",", "encoder_states", ",", "index", ",", "num_cands", ")", ":", "enc_out", ",", "hidden", ",", "attn_mask", "=", "encoder_states", "if", "isinstance", "(", "hidden", ",", "torch", ".", "Tensor", ")", ":", "cur_hid", "="...
[ 262, 4 ]
[ 287, 41 ]
python
en
['en', 'error', 'th']
False
Seq2seq._rank
(self, cands, cand_inds, encoder_states)
Rank each cand by the average log-probability of the sequence.
Rank each cand by the average log-probability of the sequence.
def _rank(self, cands, cand_inds, encoder_states): """ Rank each cand by the average log-probability of the sequence. """ if cands is None: return None encoder_states = self._align_inds(encoder_states, cand_inds) cand_scores = [] for batch_idx in rang...
[ "def", "_rank", "(", "self", ",", "cands", ",", "cand_inds", ",", "encoder_states", ")", ":", "if", "cands", "is", "None", ":", "return", "None", "encoder_states", "=", "self", ".", "_align_inds", "(", "encoder_states", ",", "cand_inds", ")", "cand_scores", ...
[ 289, 4 ]
[ 318, 26 ]
python
en
['en', 'error', 'th']
False
Seq2seq.forward
( self, xs, ctrl_inputs=None, ys=None, cands=None, prev_enc=None, maxlen=None, seq_len=None, )
Get output predictions from the model. :param xs: (bsz x seqlen) LongTensor input to the encoder :param ys: expected output from the decoder. used for teacher forcing to calculate loss. :param cands: set of candidates to rank :par...
Get output predictions from the model.
def forward( self, xs, ctrl_inputs=None, ys=None, cands=None, prev_enc=None, maxlen=None, seq_len=None, ): """ Get output predictions from the model. :param xs: (bsz x seqlen) LongTensor input to the encoder ...
[ "def", "forward", "(", "self", ",", "xs", ",", "ctrl_inputs", "=", "None", ",", "ys", "=", "None", ",", "cands", "=", "None", ",", "prev_enc", "=", "None", ",", "maxlen", "=", "None", ",", "seq_len", "=", "None", ",", ")", ":", "if", "ys", "is", ...
[ 320, 4 ]
[ 398, 50 ]
python
en
['en', 'error', 'th']
False
ControlEncoder.forward
(self, control_inputs)
Forward pass. :param control_inputs: (bsz x num_control_vars) LongTensor of control variable values (i.e. bucket ids) :returns: control_embs, (bsz x sum of control emb sizes) FloatTensor of control variable embeddings, concatenated
Forward pass.
def forward(self, control_inputs): """ Forward pass. :param control_inputs: (bsz x num_control_vars) LongTensor of control variable values (i.e. bucket ids) :returns: control_embs, (bsz x sum of control emb sizes) FloatTensor of control variable embeddings, conc...
[ "def", "forward", "(", "self", ",", "control_inputs", ")", ":", "# list length num_control_vars of tensors shape (bsz, 1)", "control_inputs", "=", "torch", ".", "split", "(", "control_inputs", ",", "1", ",", "dim", "=", "1", ")", "# list length num_control_vars of tenso...
[ 423, 4 ]
[ 448, 27 ]
python
en
['en', 'error', 'th']
False
UnknownDropout.__init__
(self, unknown_idx, probability)
Initialize layer. :param unknown_idx: index of unknown token, replace tokens with this :param probability: during training, replaces tokens with unknown token at this rate.
Initialize layer.
def __init__(self, unknown_idx, probability): """ Initialize layer. :param unknown_idx: index of unknown token, replace tokens with this :param probability: during training, replaces tokens with unknown token at this rate. """ super().__init__...
[ "def", "__init__", "(", "self", ",", "unknown_idx", ",", "probability", ")", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "unknown_idx", "=", "unknown_idx", "self", ".", "prob", "=", "probability" ]
[ 459, 4 ]
[ 469, 31 ]
python
en
['en', 'error', 'th']
False
UnknownDropout.forward
(self, input)
If training and dropout rate > 0, masks input with unknown token.
If training and dropout rate > 0, masks input with unknown token.
def forward(self, input): """ If training and dropout rate > 0, masks input with unknown token. """ if self.training and self.prob > 0: mask = input.new(input.size()).float().uniform_(0, 1) < self.prob input.masked_fill_(mask, self.unknown_idx) return inpu...
[ "def", "forward", "(", "self", ",", "input", ")", ":", "if", "self", ".", "training", "and", "self", ".", "prob", ">", "0", ":", "mask", "=", "input", ".", "new", "(", "input", ".", "size", "(", ")", ")", ".", "float", "(", ")", ".", "uniform_"...
[ 471, 4 ]
[ 478, 20 ]
python
en
['en', 'error', 'th']
False
RNNEncoder.__init__
( self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidirectional=False, shared_lt=None, shared_rnn=None, input_dropout=0, unknown_idx=None, sparse=Fals...
Initialize recurrent encoder.
Initialize recurrent encoder.
def __init__( self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidirectional=False, shared_lt=None, shared_rnn=None, input_dropout=0, unknown_idx=None, ...
[ "def", "__init__", "(", "self", ",", "num_features", ",", "embeddingsize", ",", "hiddensize", ",", "padding_idx", "=", "0", ",", "rnn_class", "=", "'lstm'", ",", "numlayers", "=", "2", ",", "dropout", "=", "0.1", ",", "bidirectional", "=", "False", ",", ...
[ 486, 4 ]
[ 535, 33 ]
python
en
['en', 'error', 'th']
False
RNNEncoder.forward
(self, xs)
Encode sequence. :param xs: (bsz x seqlen) LongTensor of input token indices :returns: encoder outputs, hidden state, attention mask encoder outputs are the output state at each step of the encoding. the hidden state is the final hidden state of the encoder. ...
Encode sequence.
def forward(self, xs): """ Encode sequence. :param xs: (bsz x seqlen) LongTensor of input token indices :returns: encoder outputs, hidden state, attention mask encoder outputs are the output state at each step of the encoding. the hidden state is the final hidde...
[ "def", "forward", "(", "self", ",", "xs", ")", ":", "bsz", "=", "len", "(", "xs", ")", "# embed input tokens", "xs", "=", "self", ".", "input_dropout", "(", "xs", ")", "xes", "=", "self", ".", "dropout", "(", "self", ".", "lt", "(", "xs", ")", ")...
[ 537, 4 ]
[ 575, 48 ]
python
en
['en', 'error', 'th']
False
RNNDecoder.__init__
( self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidir_input=False, attn_type='none', attn_time='pre', attn_length=-1, sparse=False, control_settings...
Initialize recurrent decoder.
Initialize recurrent decoder.
def __init__( self, num_features, embeddingsize, hiddensize, padding_idx=0, rnn_class='lstm', numlayers=2, dropout=0.1, bidir_input=False, attn_type='none', attn_time='pre', attn_length=-1, sparse=False, cont...
[ "def", "__init__", "(", "self", ",", "num_features", ",", "embeddingsize", ",", "hiddensize", ",", "padding_idx", "=", "0", ",", "rnn_class", "=", "'lstm'", ",", "numlayers", "=", "2", ",", "dropout", "=", "0.1", ",", "bidir_input", "=", "False", ",", "a...
[ 585, 4 ]
[ 639, 80 ]
python
en
['en', 'error', 'th']
False
RNNDecoder.forward
(self, xs, ctrl_inputs=None, hidden=None, attn_params=None)
Decode from input tokens. :param xs: (bsz x seqlen) LongTensor of input token indices :param ctrl_inputs: (bsz, num_controls) LongTensor :param hidden: hidden state to feed into decoder. default (None) initializes tensors using the RNN's defaul...
Decode from input tokens.
def forward(self, xs, ctrl_inputs=None, hidden=None, attn_params=None): """ Decode from input tokens. :param xs: (bsz x seqlen) LongTensor of input token indices :param ctrl_inputs: (bsz, num_controls) LongTensor :param hidden: hidden state to feed into decoder. de...
[ "def", "forward", "(", "self", ",", "xs", ",", "ctrl_inputs", "=", "None", ",", "hidden", "=", "None", ",", "attn_params", "=", "None", ")", ":", "# sequence indices => sequence embeddings", "xes", "=", "self", ".", "dropout", "(", "self", ".", "lt", "(", ...
[ 641, 4 ]
[ 686, 33 ]
python
en
['en', 'error', 'th']
False
OutputLayer.__init__
( self, num_features, embeddingsize, hiddensize, dropout=0, numsoftmax=1, shared_weight=None, padding_idx=-1, )
Initialize output layer. :param num_features: number of candidates to rank :param hiddensize: (last) dimension of the input vectors :param embeddingsize: (last) dimension of the candidate vectors :param numsoftmax: (default 1) number of softmaxes to calculate. ...
Initialize output layer.
def __init__( self, num_features, embeddingsize, hiddensize, dropout=0, numsoftmax=1, shared_weight=None, padding_idx=-1, ): """ Initialize output layer. :param num_features: number of candidates to rank :param hiddens...
[ "def", "__init__", "(", "self", ",", "num_features", ",", "embeddingsize", ",", "hiddensize", ",", "dropout", "=", "0", ",", "numsoftmax", "=", "1", ",", "shared_weight", "=", "None", ",", "padding_idx", "=", "-", "1", ",", ")", ":", "super", "(", ")",...
[ 694, 4 ]
[ 760, 38 ]
python
en
['en', 'error', 'th']
False
OutputLayer.reset_parameters
(self)
Reset bias param.
Reset bias param.
def reset_parameters(self): """ Reset bias param. """ if hasattr(self, 'bias'): stdv = 1.0 / math.sqrt(self.bias.size(0)) self.bias.data.uniform_(-stdv, stdv)
[ "def", "reset_parameters", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'bias'", ")", ":", "stdv", "=", "1.0", "/", "math", ".", "sqrt", "(", "self", ".", "bias", ".", "size", "(", "0", ")", ")", "self", ".", "bias", ".", "data", ...
[ 762, 4 ]
[ 768, 48 ]
python
en
['en', 'error', 'th']
False
OutputLayer.forward
(self, input)
Compute scores from inputs. :param input: (bsz x seq_len x num_directions * hiddensize) tensor of states, e.g. the output states of an RNN :returns: (bsz x seqlen x num_cands) scores for each candidate
Compute scores from inputs.
def forward(self, input): """ Compute scores from inputs. :param input: (bsz x seq_len x num_directions * hiddensize) tensor of states, e.g. the output states of an RNN :returns: (bsz x seqlen x num_cands) scores for each candidate """ # next comp...
[ "def", "forward", "(", "self", ",", "input", ")", ":", "# next compute scores over dictionary", "if", "self", ".", "numsoftmax", ">", "1", ":", "bsz", "=", "input", ".", "size", "(", "0", ")", "seqlen", "=", "input", ".", "size", "(", "1", ")", "if", ...
[ 770, 4 ]
[ 811, 21 ]
python
en
['en', 'error', 'th']
False
AttentionLayer.__init__
( self, attn_type, hiddensize, embeddingsize, bidirectional=False, attn_length=-1, attn_time='pre', )
Initialize attention layer.
Initialize attention layer.
def __init__( self, attn_type, hiddensize, embeddingsize, bidirectional=False, attn_length=-1, attn_time='pre', ): """ Initialize attention layer. """ super().__init__() self.attention = attn_type if self.attent...
[ "def", "__init__", "(", "self", ",", "attn_type", ",", "hiddensize", ",", "embeddingsize", ",", "bidirectional", "=", "False", ",", "attn_length", "=", "-", "1", ",", "attn_time", "=", "'pre'", ",", ")", ":", "super", "(", ")", ".", "__init__", "(", ")...
[ 821, 4 ]
[ 864, 64 ]
python
en
['en', 'error', 'th']
False
AttentionLayer.forward
(self, xes, hidden, attn_params)
Compute attention over attn_params given input and hidden states. :param xes: input state. will be combined with applied attention. :param hidden: hidden state from model. will be used to select states to attend to in from th...
Compute attention over attn_params given input and hidden states.
def forward(self, xes, hidden, attn_params): """ Compute attention over attn_params given input and hidden states. :param xes: input state. will be combined with applied attention. :param hidden: hidden state from model. will be used to select ...
[ "def", "forward", "(", "self", ",", "xes", ",", "hidden", ",", "attn_params", ")", ":", "if", "self", ".", "attention", "==", "'none'", ":", "# do nothing, no attention", "return", "xes", ",", "None", "if", "type", "(", "hidden", ")", "==", "tuple", ":",...
[ 866, 4 ]
[ 943, 35 ]
python
en
['en', 'error', 'th']
False
setTTL
(qstate, ttl)
Sets return_msg TTL and all the RRs TTL
Sets return_msg TTL and all the RRs TTL
def setTTL(qstate, ttl): """Sets return_msg TTL and all the RRs TTL""" if qstate.return_msg: qstate.return_msg.rep.ttl = ttl if (qstate.return_msg.rep): for i in range(0,qstate.return_msg.rep.rrset_count): d = qstate.return_msg.rep.rrsets[i].entry.data ...
[ "def", "setTTL", "(", "qstate", ",", "ttl", ")", ":", "if", "qstate", ".", "return_msg", ":", "qstate", ".", "return_msg", ".", "rep", ".", "ttl", "=", "ttl", "if", "(", "qstate", ".", "return_msg", ".", "rep", ")", ":", "for", "i", "in", "range", ...
[ 49, 0 ]
[ 57, 37 ]
python
en
['en', 'en', 'en']
True
SimpleDictionaryAgent.add_to_dict
(self, tokens)
Builds dictionary from the list of provided tokens. Only adds words contained in self.embedding_words, if not None.
Builds dictionary from the list of provided tokens.
def add_to_dict(self, tokens): """ Builds dictionary from the list of provided tokens. Only adds words contained in self.embedding_words, if not None. """ for token in tokens: if self.embedding_words is not None and token not in self.embedding_words: ...
[ "def", "add_to_dict", "(", "self", ",", "tokens", ")", ":", "for", "token", "in", "tokens", ":", "if", "self", ".", "embedding_words", "is", "not", "None", "and", "token", "not", "in", "self", ".", "embedding_words", ":", "continue", "self", ".", "freq",...
[ 84, 4 ]
[ 97, 43 ]
python
en
['en', 'error', 'th']
False
DrqaAgent.act
(self)
Update or predict on a single example (batchsize = 1).
Update or predict on a single example (batchsize = 1).
def act(self): """Update or predict on a single example (batchsize = 1).""" reply = {'id': self.getID()} ex = self._build_ex(self.observation) if ex is None: return reply batch = batchify( [ex], null=self.word_dict[self.word_dict.null_token], cuda=self.op...
[ "def", "act", "(", "self", ")", ":", "reply", "=", "{", "'id'", ":", "self", ".", "getID", "(", ")", "}", "ex", "=", "self", ".", "_build_ex", "(", "self", ".", "observation", ")", "if", "ex", "is", "None", ":", "return", "reply", "batch", "=", ...
[ 344, 4 ]
[ 366, 20 ]
python
en
['en', 'en', 'en']
True
DrqaAgent.batch_act
(self, observations)
Update or predict on a batch of examples. More efficient than act().
Update or predict on a batch of examples.
def batch_act(self, observations): """ Update or predict on a batch of examples. More efficient than act(). """ batchsize = len(observations) batch_reply = [{'id': self.getID()} for _ in range(batchsize)] # Some examples will be None (no answer found). Filter th...
[ "def", "batch_act", "(", "self", ",", "observations", ")", ":", "batchsize", "=", "len", "(", "observations", ")", "batch_reply", "=", "[", "{", "'id'", ":", "self", ".", "getID", "(", ")", "}", "for", "_", "in", "range", "(", "batchsize", ")", "]", ...
[ 368, 4 ]
[ 421, 26 ]
python
en
['en', 'error', 'th']
False
DrqaAgent.save
(self, fname=None)
Save the parameters of the agent to a file.
Save the parameters of the agent to a file.
def save(self, fname=None): """ Save the parameters of the agent to a file. """ fname = self.opt.get('model_file', None) if fname is None else fname if fname: print("[ saving model: " + fname + " ]") self.opt['trained'] = True self.model.save(f...
[ "def", "save", "(", "self", ",", "fname", "=", "None", ")", ":", "fname", "=", "self", ".", "opt", ".", "get", "(", "'model_file'", ",", "None", ")", "if", "fname", "is", "None", "else", "fname", "if", "fname", ":", "print", "(", "\"[ saving model: \...
[ 423, 4 ]
[ 434, 43 ]
python
en
['en', 'error', 'th']
False
DrqaAgent._build_ex
(self, ex)
Find the token span of the answer in the context for this example. If a token span cannot be found, return None. Otherwise, torchify.
Find the token span of the answer in the context for this example.
def _build_ex(self, ex): """ Find the token span of the answer in the context for this example. If a token span cannot be found, return None. Otherwise, torchify. """ # Check if empty input (end of epoch) if 'text' not in ex: return # Split out docum...
[ "def", "_build_ex", "(", "self", ",", "ex", ")", ":", "# Check if empty input (end of epoch)", "if", "'text'", "not", "in", "ex", ":", "return", "# Split out document + question", "inputs", "=", "{", "}", "fields", "=", "ex", "[", "'text'", "]", ".", "strip", ...
[ 440, 4 ]
[ 495, 45 ]
python
en
['en', 'error', 'th']
False
DrqaAgent._find_target
(self, document, labels)
Find the start/end token span for all labels in document. Return a random one for training.
Find the start/end token span for all labels in document.
def _find_target(self, document, labels): """ Find the start/end token span for all labels in document. Return a random one for training. """ def _positions(d, l): for i in range(len(d)): for j in range(i, min(len(d) - 1, i + len(l))): ...
[ "def", "_find_target", "(", "self", ",", "document", ",", "labels", ")", ":", "def", "_positions", "(", "d", ",", "l", ")", ":", "for", "i", "in", "range", "(", "len", "(", "d", ")", ")", ":", "for", "j", "in", "range", "(", "i", ",", "min", ...
[ 497, 4 ]
[ 515, 54 ]
python
en
['en', 'error', 'th']
False
DrqaAgent._subsample_doc
(self, paras, labels, subsample)
Subsample paragraphs from the document (mostly for training speed).
Subsample paragraphs from the document (mostly for training speed).
def _subsample_doc(self, paras, labels, subsample): """ Subsample paragraphs from the document (mostly for training speed). """ # first find a valid paragraph (with a label) pi = -1 for ind, p in enumerate(paras): for l in labels: if p.find(l):...
[ "def", "_subsample_doc", "(", "self", ",", "paras", ",", "labels", ",", "subsample", ")", ":", "# first find a valid paragraph (with a label)", "pi", "=", "-", "1", "for", "ind", ",", "p", "in", "enumerate", "(", "paras", ")", ":", "for", "l", "in", "label...
[ 517, 4 ]
[ 541, 24 ]
python
en
['en', 'error', 'th']
False
Marker.color
(self)
Sets the marker color of unselected points, applied only when a selection exists. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') ...
Sets the marker color of unselected points, applied only when a selection exists. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') ...
def color(self): """ Sets the marker color of unselected points, applied only when a selection exists. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla stri...
[ "def", "color", "(", "self", ")", ":", "return", "self", "[", "\"color\"", "]" ]
[ 15, 4 ]
[ 66, 28 ]
python
en
['en', 'error', 'th']
False
Marker.opacity
(self)
Sets the marker opacity of unselected points, applied only when a selection exists. The 'opacity' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float
Sets the marker opacity of unselected points, applied only when a selection exists. The 'opacity' property is a number and may be specified as: - An int or float in the interval [0, 1]
def opacity(self): """ Sets the marker opacity of unselected points, applied only when a selection exists. The 'opacity' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float """ ...
[ "def", "opacity", "(", "self", ")", ":", "return", "self", "[", "\"opacity\"", "]" ]
[ 75, 4 ]
[ 87, 30 ]
python
en
['en', 'error', 'th']
False
Marker.size
(self)
Sets the marker size of unselected points, applied only when a selection exists. The 'size' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float
Sets the marker size of unselected points, applied only when a selection exists. The 'size' property is a number and may be specified as: - An int or float in the interval [0, inf]
def size(self): """ Sets the marker size of unselected points, applied only when a selection exists. The 'size' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ r...
[ "def", "size", "(", "self", ")", ":", "return", "self", "[", "\"size\"", "]" ]
[ 96, 4 ]
[ 108, 27 ]
python
en
['en', 'error', 'th']
False
Marker.__init__
(self, arg=None, color=None, opacity=None, size=None, **kwargs)
Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.box.unselected.Marker` color Sets the marker color of unselected point...
Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.box.unselected.Marker` color Sets the marker color of unselected point...
def __init__(self, arg=None, color=None, opacity=None, size=None, **kwargs): """ Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.bo...
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "color", "=", "None", ",", "opacity", "=", "None", ",", "size", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Marker", ",", "self", ")", ".", "__init__", "(", "\"marke...
[ 130, 4 ]
[ 202, 34 ]
python
en
['en', 'error', 'th']
False
PresentationManager.__init__
(self, context: InjectionContext)
Initialize a PresentationManager. Args: context: The context for this presentation
Initialize a PresentationManager.
def __init__(self, context: InjectionContext): """ Initialize a PresentationManager. Args: context: The context for this presentation """ self._context = context self._logger = logging.getLogger(__name__)
[ "def", "__init__", "(", "self", ",", "context", ":", "InjectionContext", ")", ":", "self", ".", "_context", "=", "context", "self", ".", "_logger", "=", "logging", ".", "getLogger", "(", "__name__", ")" ]
[ 28, 4 ]
[ 37, 50 ]
python
en
['en', 'error', 'th']
False
PresentationManager.context
(self)
Accessor for the current request context. Returns: The injection context for this presentation manager
Accessor for the current request context.
def context(self) -> InjectionContext: """ Accessor for the current request context. Returns: The injection context for this presentation manager """ return self._context
[ "def", "context", "(", "self", ")", "->", "InjectionContext", ":", "return", "self", ".", "_context" ]
[ 40, 4 ]
[ 48, 28 ]
python
en
['en', 'error', 'th']
False
PresentationManager.create_exchange_for_proposal
( self, connection_id: str, presentation_proposal_message: PresentationProposal, auto_present: bool = None, )
Create a presentation exchange record for input presentation proposal. Args: connection_id: connection identifier presentation_proposal_message: presentation proposal to serialize to exchange record auto_present: whether to present proof upon receivi...
Create a presentation exchange record for input presentation proposal.
async def create_exchange_for_proposal( self, connection_id: str, presentation_proposal_message: PresentationProposal, auto_present: bool = None, ): """ Create a presentation exchange record for input presentation proposal. Args: connection_id: co...
[ "async", "def", "create_exchange_for_proposal", "(", "self", ",", "connection_id", ":", "str", ",", "presentation_proposal_message", ":", "PresentationProposal", ",", "auto_present", ":", "bool", "=", "None", ",", ")", ":", "presentation_exchange_record", "=", "V10Pre...
[ 50, 4 ]
[ 83, 43 ]
python
en
['en', 'error', 'th']
False
PresentationManager.receive_proposal
(self)
Receive a presentation proposal from message in context on manager creation. Returns: Presentation exchange record, created
Receive a presentation proposal from message in context on manager creation.
async def receive_proposal(self): """ Receive a presentation proposal from message in context on manager creation. Returns: Presentation exchange record, created """ presentation_proposal_message = self.context.message presentation_exchange_record = V10Prese...
[ "async", "def", "receive_proposal", "(", "self", ")", ":", "presentation_proposal_message", "=", "self", ".", "context", ".", "message", "presentation_exchange_record", "=", "V10PresentationExchange", "(", "connection_id", "=", "self", ".", "context", ".", "connection...
[ 85, 4 ]
[ 106, 43 ]
python
en
['en', 'error', 'th']
False
PresentationManager.create_bound_request
( self, presentation_exchange_record: V10PresentationExchange, name: str = None, version: str = None, nonce: str = None, comment: str = None, )
Create a presentation request bound to a proposal. Args: presentation_exchange_record: Presentation exchange record for which to create presentation request name: name to use in presentation request (None for default) version: version to use in prese...
Create a presentation request bound to a proposal.
async def create_bound_request( self, presentation_exchange_record: V10PresentationExchange, name: str = None, version: str = None, nonce: str = None, comment: str = None, ): """ Create a presentation request bound to a proposal. Args: ...
[ "async", "def", "create_bound_request", "(", "self", ",", "presentation_exchange_record", ":", "V10PresentationExchange", ",", "name", ":", "str", "=", "None", ",", "version", ":", "str", "=", "None", ",", "nonce", ":", "str", "=", "None", ",", "comment", ":...
[ 108, 4 ]
[ 159, 73 ]
python
en
['en', 'error', 'th']
False
PresentationManager.create_exchange_for_request
( self, connection_id: str, presentation_request_message: PresentationRequest )
Create a presentation exchange record for input presentation request. Args: connection_id: connection identifier presentation_request_message: presentation request to use in creating exchange record, extracting indy proof request and thread id Returns: ...
Create a presentation exchange record for input presentation request.
async def create_exchange_for_request( self, connection_id: str, presentation_request_message: PresentationRequest ): """ Create a presentation exchange record for input presentation request. Args: connection_id: connection identifier presentation_request_mes...
[ "async", "def", "create_exchange_for_request", "(", "self", ",", "connection_id", ":", "str", ",", "presentation_request_message", ":", "PresentationRequest", ")", ":", "presentation_exchange_record", "=", "V10PresentationExchange", "(", "connection_id", "=", "connection_id...
[ 161, 4 ]
[ 188, 43 ]
python
en
['en', 'error', 'th']
False
PresentationManager.receive_request
( self, presentation_exchange_record: V10PresentationExchange )
Receive a presentation request. Args: presentation_exchange_record: presentation exchange record with request to receive Returns: The presentation_exchange_record, updated
Receive a presentation request.
async def receive_request( self, presentation_exchange_record: V10PresentationExchange ): """ Receive a presentation request. Args: presentation_exchange_record: presentation exchange record with request to receive Returns: The presen...
[ "async", "def", "receive_request", "(", "self", ",", "presentation_exchange_record", ":", "V10PresentationExchange", ")", ":", "presentation_exchange_record", ".", "state", "=", "(", "V10PresentationExchange", ".", "STATE_REQUEST_RECEIVED", ")", "await", "presentation_excha...
[ 190, 4 ]
[ 211, 43 ]
python
en
['en', 'error', 'th']
False
PresentationManager.create_presentation
( self, presentation_exchange_record: V10PresentationExchange, requested_credentials: dict, comment: str = None, )
Create a presentation. Args: presentation_exchange_record: Record to update requested_credentials: Indy formatted requested_credentials e.g., :: { "self_attested_attributes": { "j233ffbc-bd35...
Create a presentation.
async def create_presentation( self, presentation_exchange_record: V10PresentationExchange, requested_credentials: dict, comment: str = None, ): """ Create a presentation. Args: presentation_exchange_record: Record to update requested_...
[ "async", "def", "create_presentation", "(", "self", ",", "presentation_exchange_record", ":", "V10PresentationExchange", ",", "requested_credentials", ":", "dict", ",", "comment", ":", "str", "=", "None", ",", ")", ":", "# Get all credential ids for this presentation", ...
[ 213, 4 ]
[ 324, 65 ]
python
en
['en', 'error', 'th']
False
PresentationManager.receive_presentation
(self)
Receive a presentation, from message in context on manager creation. Returns: presentation exchange record, retrieved and updated
Receive a presentation, from message in context on manager creation.
async def receive_presentation(self): """ Receive a presentation, from message in context on manager creation. Returns: presentation exchange record, retrieved and updated """ presentation = self.context.message.indy_proof() thread_id = self.context.message....
[ "async", "def", "receive_presentation", "(", "self", ")", ":", "presentation", "=", "self", ".", "context", ".", "message", ".", "indy_proof", "(", ")", "thread_id", "=", "self", ".", "context", ".", "message", ".", "_thread_id", "(", "presentation_exchange_re...
[ 326, 4 ]
[ 353, 43 ]
python
en
['en', 'error', 'th']
False
PresentationManager.verify_presentation
( self, presentation_exchange_record: V10PresentationExchange )
Verify a presentation. Args: presentation_exchange_record: presentation exchange record with presentation request and presentation to verify Returns: presentation record, updated
Verify a presentation.
async def verify_presentation( self, presentation_exchange_record: V10PresentationExchange ): """ Verify a presentation. Args: presentation_exchange_record: presentation exchange record with presentation request and presentation to verify Returns...
[ "async", "def", "verify_presentation", "(", "self", ",", "presentation_exchange_record", ":", "V10PresentationExchange", ")", ":", "indy_proof_request", "=", "presentation_exchange_record", ".", "presentation_request", "indy_proof", "=", "presentation_exchange_record", ".", "...
[ 355, 4 ]
[ 411, 43 ]
python
en
['en', 'error', 'th']
False
PresentationManager.send_presentation_ack
( self, presentation_exchange_record: V10PresentationExchange )
Send acknowledgement of presentation receipt. Args: presentation_exchange_record: presentation exchange record with thread id
Send acknowledgement of presentation receipt.
async def send_presentation_ack( self, presentation_exchange_record: V10PresentationExchange ): """ Send acknowledgement of presentation receipt. Args: presentation_exchange_record: presentation exchange record with thread id """ responder = await self.c...
[ "async", "def", "send_presentation_ack", "(", "self", ",", "presentation_exchange_record", ":", "V10PresentationExchange", ")", ":", "responder", "=", "await", "self", ".", "context", ".", "inject", "(", "BaseResponder", ",", "required", "=", "False", ")", "if", ...
[ 413, 4 ]
[ 436, 13 ]
python
en
['en', 'error', 'th']
False
PresentationManager.receive_presentation_ack
(self)
Receive a presentation ack, from message in context on manager creation. Returns: presentation exchange record, retrieved and updated
Receive a presentation ack, from message in context on manager creation.
async def receive_presentation_ack(self): """ Receive a presentation ack, from message in context on manager creation. Returns: presentation exchange record, retrieved and updated """ ( presentation_exchange_record ) = await V10PresentationExchan...
[ "async", "def", "receive_presentation_ack", "(", "self", ")", ":", "(", "presentation_exchange_record", ")", "=", "await", "V10PresentationExchange", ".", "retrieve_by_tag_filter", "(", "self", ".", "context", ",", "tag_filter", "=", "{", "\"thread_id\"", ":", "self...
[ 438, 4 ]
[ 465, 43 ]
python
en
['en', 'error', 'th']
False
Marker.color
(self)
Sets the marker color of unselected points, applied only when a selection exists. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') ...
Sets the marker color of unselected points, applied only when a selection exists. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla string (e.g. 'hsl(0,100%,50%)') ...
def color(self): """ Sets the marker color of unselected points, applied only when a selection exists. The 'color' property is a color and may be specified as: - A hex string (e.g. '#ff0000') - An rgb/rgba string (e.g. 'rgb(255,0,0)') - An hsl/hsla stri...
[ "def", "color", "(", "self", ")", ":", "return", "self", "[", "\"color\"", "]" ]
[ 15, 4 ]
[ 66, 28 ]
python
en
['en', 'error', 'th']
False
Marker.opacity
(self)
Sets the marker opacity of unselected points, applied only when a selection exists. The 'opacity' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float
Sets the marker opacity of unselected points, applied only when a selection exists. The 'opacity' property is a number and may be specified as: - An int or float in the interval [0, 1]
def opacity(self): """ Sets the marker opacity of unselected points, applied only when a selection exists. The 'opacity' property is a number and may be specified as: - An int or float in the interval [0, 1] Returns ------- int|float """ ...
[ "def", "opacity", "(", "self", ")", ":", "return", "self", "[", "\"opacity\"", "]" ]
[ 75, 4 ]
[ 87, 30 ]
python
en
['en', 'error', 'th']
False
Marker.size
(self)
Sets the marker size of unselected points, applied only when a selection exists. The 'size' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float
Sets the marker size of unselected points, applied only when a selection exists. The 'size' property is a number and may be specified as: - An int or float in the interval [0, inf]
def size(self): """ Sets the marker size of unselected points, applied only when a selection exists. The 'size' property is a number and may be specified as: - An int or float in the interval [0, inf] Returns ------- int|float """ r...
[ "def", "size", "(", "self", ")", ":", "return", "self", "[", "\"size\"", "]" ]
[ 96, 4 ]
[ 108, 27 ]
python
en
['en', 'error', 'th']
False
Marker.__init__
(self, arg=None, color=None, opacity=None, size=None, **kwargs)
Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.violin.unselected.Marker` color Sets the marker color of unselected po...
Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.violin.unselected.Marker` color Sets the marker color of unselected po...
def __init__(self, arg=None, color=None, opacity=None, size=None, **kwargs): """ Construct a new Marker object Parameters ---------- arg dict of properties compatible with this constructor or an instance of :class:`plotly.graph_objs.vi...
[ "def", "__init__", "(", "self", ",", "arg", "=", "None", ",", "color", "=", "None", ",", "opacity", "=", "None", ",", "size", "=", "None", ",", "*", "*", "kwargs", ")", ":", "super", "(", "Marker", ",", "self", ")", ".", "__init__", "(", "\"marke...
[ 130, 4 ]
[ 202, 34 ]
python
en
['en', 'error', 'th']
False
is_this_circleci
()
Return if we are currently running in CircleCI.
Return if we are currently running in CircleCI.
def is_this_circleci(): """ Return if we are currently running in CircleCI. """ return bool(os.environ.get('CIRCLECI'))
[ "def", "is_this_circleci", "(", ")", ":", "return", "bool", "(", "os", ".", "environ", ".", "get", "(", "'CIRCLECI'", ")", ")" ]
[ 65, 0 ]
[ 69, 43 ]
python
en
['en', 'error', 'th']
False
skipUnlessTorch
(testfn, reason='pytorch is not installed')
Decorate a test to skip if torch is not installed.
Decorate a test to skip if torch is not installed.
def skipUnlessTorch(testfn, reason='pytorch is not installed'): """ Decorate a test to skip if torch is not installed. """ return unittest.skipUnless(TORCH_AVAILABLE, reason)(testfn)
[ "def", "skipUnlessTorch", "(", "testfn", ",", "reason", "=", "'pytorch is not installed'", ")", ":", "return", "unittest", ".", "skipUnless", "(", "TORCH_AVAILABLE", ",", "reason", ")", "(", "testfn", ")" ]
[ 72, 0 ]
[ 76, 63 ]
python
en
['en', 'error', 'th']
False
skipIfGPU
(testfn, reason='Test is CPU-only')
Decorate a test to skip if a GPU is available. Useful for disabling hogwild tests.
Decorate a test to skip if a GPU is available.
def skipIfGPU(testfn, reason='Test is CPU-only'): """ Decorate a test to skip if a GPU is available. Useful for disabling hogwild tests. """ return unittest.skipIf(GPU_AVAILABLE, reason)(testfn)
[ "def", "skipIfGPU", "(", "testfn", ",", "reason", "=", "'Test is CPU-only'", ")", ":", "return", "unittest", ".", "skipIf", "(", "GPU_AVAILABLE", ",", "reason", ")", "(", "testfn", ")" ]
[ 79, 0 ]
[ 85, 57 ]
python
en
['en', 'error', 'th']
False
skipUnlessGPU
(testfn, reason='Test requires a GPU')
Decorate a test to skip if no GPU is available.
Decorate a test to skip if no GPU is available.
def skipUnlessGPU(testfn, reason='Test requires a GPU'): """ Decorate a test to skip if no GPU is available. """ return unittest.skipUnless(GPU_AVAILABLE, reason)(testfn)
[ "def", "skipUnlessGPU", "(", "testfn", ",", "reason", "=", "'Test requires a GPU'", ")", ":", "return", "unittest", ".", "skipUnless", "(", "GPU_AVAILABLE", ",", "reason", ")", "(", "testfn", ")" ]
[ 88, 0 ]
[ 92, 61 ]
python
en
['en', 'error', 'th']
False
skipUnlessBPE
(testfn, reason='Test requires subword NMT')
Decorate a test to skip if BPE is not installed.
Decorate a test to skip if BPE is not installed.
def skipUnlessBPE(testfn, reason='Test requires subword NMT'): """ Decorate a test to skip if BPE is not installed. """ return unittest.skipUnless(BPE_INSTALLED, reason)(testfn)
[ "def", "skipUnlessBPE", "(", "testfn", ",", "reason", "=", "'Test requires subword NMT'", ")", ":", "return", "unittest", ".", "skipUnless", "(", "BPE_INSTALLED", ",", "reason", ")", "(", "testfn", ")" ]
[ 95, 0 ]
[ 99, 61 ]
python
en
['en', 'error', 'th']
False
skipIfCircleCI
(testfn, reason='Test disabled in CircleCI')
Decorate a test to skip if running on CircleCI.
Decorate a test to skip if running on CircleCI.
def skipIfCircleCI(testfn, reason='Test disabled in CircleCI'): """ Decorate a test to skip if running on CircleCI. """ return unittest.skipIf(is_this_circleci(), reason)(testfn)
[ "def", "skipIfCircleCI", "(", "testfn", ",", "reason", "=", "'Test disabled in CircleCI'", ")", ":", "return", "unittest", ".", "skipIf", "(", "is_this_circleci", "(", ")", ",", "reason", ")", "(", "testfn", ")" ]
[ 102, 0 ]
[ 106, 62 ]
python
en
['en', 'error', 'th']
False
skipUnlessVision
(testfn, reason='torchvision not installed')
Decorate a test to skip unless torchvision is installed.
Decorate a test to skip unless torchvision is installed.
def skipUnlessVision(testfn, reason='torchvision not installed'): """ Decorate a test to skip unless torchvision is installed. """ return unittest.skipUnless(VISION_AVAILABLE, reason)(testfn)
[ "def", "skipUnlessVision", "(", "testfn", ",", "reason", "=", "'torchvision not installed'", ")", ":", "return", "unittest", ".", "skipUnless", "(", "VISION_AVAILABLE", ",", "reason", ")", "(", "testfn", ")" ]
[ 109, 0 ]
[ 113, 64 ]
python
en
['en', 'error', 'th']
False
skipUnlessDetectron
( testfn, reason='maskrcnn_benchmark and/or opencv not installed' )
Decorate a test to skip unless maskrcnn_benchmark and opencv are installed.
Decorate a test to skip unless maskrcnn_benchmark and opencv are installed.
def skipUnlessDetectron( testfn, reason='maskrcnn_benchmark and/or opencv not installed' ): """ Decorate a test to skip unless maskrcnn_benchmark and opencv are installed. """ return unittest.skipUnless(DETECTRON_AVAILABLE, reason)(testfn)
[ "def", "skipUnlessDetectron", "(", "testfn", ",", "reason", "=", "'maskrcnn_benchmark and/or opencv not installed'", ")", ":", "return", "unittest", ".", "skipUnless", "(", "DETECTRON_AVAILABLE", ",", "reason", ")", "(", "testfn", ")" ]
[ 116, 0 ]
[ 122, 67 ]
python
en
['en', 'error', 'th']
False
git_ls_files
(root=None, skip_nonexisting=True)
List all files tracked by git.
List all files tracked by git.
def git_ls_files(root=None, skip_nonexisting=True): """ List all files tracked by git. """ filenames = git_.ls_files(root).split('\n') if skip_nonexisting: filenames = [fn for fn in filenames if PathManager.exists(fn)] return filenames
[ "def", "git_ls_files", "(", "root", "=", "None", ",", "skip_nonexisting", "=", "True", ")", ":", "filenames", "=", "git_", ".", "ls_files", "(", "root", ")", ".", "split", "(", "'\\n'", ")", "if", "skip_nonexisting", ":", "filenames", "=", "[", "fn", "...
[ 166, 0 ]
[ 173, 20 ]
python
en
['en', 'error', 'th']
False