nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
makepanda/makepanda.py
python
CompileRes
(target, src, opts)
Compiles a Windows .rc file into a .res file.
Compiles a Windows .rc file into a .res file.
[ "Compiles", "a", "Windows", ".", "rc", "file", "into", "a", ".", "res", "file", "." ]
def CompileRes(target, src, opts): """Compiles a Windows .rc file into a .res file.""" ipath = GetListOption(opts, "DIR:") if (COMPILER == "MSVC"): cmd = "rc" cmd += " /Fo" + BracketNameWithQuotes(target) for x in ipath: cmd += " /I" + x for (opt,dir) in INCDIRECTORIES: if (opt=="ALWAYS") or (opt in opts): cmd += " /I" + BracketNameWithQuotes(dir) for (opt,var,val) in DEFSYMBOLS: if (opt=="ALWAYS") or (opt in opts): cmd += " /D" + var + "=" + val cmd += " " + BracketNameWithQuotes(src) else: cmd = "windres" for x in ipath: cmd += " -I" + x for (opt,dir) in INCDIRECTORIES: if (opt=="ALWAYS") or (opt in opts): cmd += " -I" + BracketNameWithQuotes(dir) for (opt,var,val) in DEFSYMBOLS: if (opt=="ALWAYS") or (opt in opts): cmd += " -D" + var + "=" + val cmd += " -i " + BracketNameWithQuotes(src) cmd += " -o " + BracketNameWithQuotes(target) oscmd(cmd)
[ "def", "CompileRes", "(", "target", ",", "src", ",", "opts", ")", ":", "ipath", "=", "GetListOption", "(", "opts", ",", "\"DIR:\"", ")", "if", "(", "COMPILER", "==", "\"MSVC\"", ")", ":", "cmd", "=", "\"rc\"", "cmd", "+=", "\" /Fo\"", "+", "BracketNameWithQuotes", "(", "target", ")", "for", "x", "in", "ipath", ":", "cmd", "+=", "\" /I\"", "+", "x", "for", "(", "opt", ",", "dir", ")", "in", "INCDIRECTORIES", ":", "if", "(", "opt", "==", "\"ALWAYS\"", ")", "or", "(", "opt", "in", "opts", ")", ":", "cmd", "+=", "\" /I\"", "+", "BracketNameWithQuotes", "(", "dir", ")", "for", "(", "opt", ",", "var", ",", "val", ")", "in", "DEFSYMBOLS", ":", "if", "(", "opt", "==", "\"ALWAYS\"", ")", "or", "(", "opt", "in", "opts", ")", ":", "cmd", "+=", "\" /D\"", "+", "var", "+", "\"=\"", "+", "val", "cmd", "+=", "\" \"", "+", "BracketNameWithQuotes", "(", "src", ")", "else", ":", "cmd", "=", "\"windres\"", "for", "x", "in", "ipath", ":", "cmd", "+=", "\" -I\"", "+", "x", "for", "(", "opt", ",", "dir", ")", "in", "INCDIRECTORIES", ":", "if", "(", "opt", "==", "\"ALWAYS\"", ")", "or", "(", "opt", "in", "opts", ")", ":", "cmd", "+=", "\" -I\"", "+", "BracketNameWithQuotes", "(", "dir", ")", "for", "(", "opt", ",", "var", ",", "val", ")", "in", "DEFSYMBOLS", ":", "if", "(", "opt", "==", "\"ALWAYS\"", ")", "or", "(", "opt", "in", "opts", ")", ":", "cmd", "+=", "\" -D\"", "+", "var", "+", "\"=\"", "+", "val", "cmd", "+=", "\" -i \"", "+", "BracketNameWithQuotes", "(", "src", ")", "cmd", "+=", "\" -o \"", "+", "BracketNameWithQuotes", "(", "target", ")", "oscmd", "(", "cmd", ")" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/makepanda/makepanda.py#L1983-L2009
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/ipython/py3/IPython/core/interactiveshell.py
python
InteractiveShell.init_readline
(self)
DEPRECATED Moved to terminal subclass, here only to simplify the init logic.
DEPRECATED
[ "DEPRECATED" ]
def init_readline(self): """DEPRECATED Moved to terminal subclass, here only to simplify the init logic.""" # Set a number of methods that depend on readline to be no-op warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated', DeprecationWarning, stacklevel=2) self.set_custom_completer = no_op
[ "def", "init_readline", "(", "self", ")", ":", "# Set a number of methods that depend on readline to be no-op", "warnings", ".", "warn", "(", "'`init_readline` is no-op since IPython 5.0 and is Deprecated'", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "self", ".", "set_custom_completer", "=", "no_op" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/ipython/py3/IPython/core/interactiveshell.py#L2146-L2153
fatih/subvim
241b6d170597857105da219c9b7d36059e9f11fb
vim/base/ultisnips/plugin/UltiSnips/text_objects/_python_code.py
python
SnippetUtil.__rshift__
(self, other)
Same as shift.
Same as shift.
[ "Same", "as", "shift", "." ]
def __rshift__(self, other): """ Same as shift. """ self.shift(other)
[ "def", "__rshift__", "(", "self", ",", "other", ")", ":", "self", ".", "shift", "(", "other", ")" ]
https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/ultisnips/plugin/UltiSnips/text_objects/_python_code.py#L167-L169
kungfu-origin/kungfu
90c84b2b590855654cb9a6395ed050e0f7763512
core/deps/SQLiteCpp-2.3.0/cpplint.py
python
ReplaceAll
(pattern, rep, s)
return _regexp_compile_cache[pattern].sub(rep, s)
Replaces instances of pattern in a string with a replacement. The compiled regex is kept in a cache shared by Match and Search. Args: pattern: regex pattern rep: replacement text s: search string Returns: string with replacements made (or original string if no replacements)
Replaces instances of pattern in a string with a replacement.
[ "Replaces", "instances", "of", "pattern", "in", "a", "string", "with", "a", "replacement", "." ]
def ReplaceAll(pattern, rep, s): """Replaces instances of pattern in a string with a replacement. The compiled regex is kept in a cache shared by Match and Search. Args: pattern: regex pattern rep: replacement text s: search string Returns: string with replacements made (or original string if no replacements) """ if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].sub(rep, s)
[ "def", "ReplaceAll", "(", "pattern", ",", "rep", ",", "s", ")", ":", "if", "pattern", "not", "in", "_regexp_compile_cache", ":", "_regexp_compile_cache", "[", "pattern", "]", "=", "sre_compile", ".", "compile", "(", "pattern", ")", "return", "_regexp_compile_cache", "[", "pattern", "]", ".", "sub", "(", "rep", ",", "s", ")" ]
https://github.com/kungfu-origin/kungfu/blob/90c84b2b590855654cb9a6395ed050e0f7763512/core/deps/SQLiteCpp-2.3.0/cpplint.py#L513-L528
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
uCSIsMongolian
(code)
return ret
Check whether the character is part of Mongolian UCS Block
Check whether the character is part of Mongolian UCS Block
[ "Check", "whether", "the", "character", "is", "part", "of", "Mongolian", "UCS", "Block" ]
def uCSIsMongolian(code): """Check whether the character is part of Mongolian UCS Block """ ret = libxml2mod.xmlUCSIsMongolian(code) return ret
[ "def", "uCSIsMongolian", "(", "code", ")", ":", "ret", "=", "libxml2mod", ".", "xmlUCSIsMongolian", "(", "code", ")", "return", "ret" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L1982-L1985
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/Blast/3rdParty/assimp/port/PyAssimp/scripts/transformations.py
python
quaternion_multiply
(quaternion1, quaternion0)
return numpy.array(( x1*w0 + y1*z0 - z1*y0 + w1*x0, -x1*z0 + y1*w0 + z1*x0 + w1*y0, x1*y0 - y1*x0 + z1*w0 + w1*z0, -x1*x0 - y1*y0 - z1*z0 + w1*w0), dtype=numpy.float64)
Return multiplication of two quaternions. >>> q = quaternion_multiply([1, -2, 3, 4], [-5, 6, 7, 8]) >>> numpy.allclose(q, [-44, -14, 48, 28]) True
Return multiplication of two quaternions.
[ "Return", "multiplication", "of", "two", "quaternions", "." ]
def quaternion_multiply(quaternion1, quaternion0): """Return multiplication of two quaternions. >>> q = quaternion_multiply([1, -2, 3, 4], [-5, 6, 7, 8]) >>> numpy.allclose(q, [-44, -14, 48, 28]) True """ x0, y0, z0, w0 = quaternion0 x1, y1, z1, w1 = quaternion1 return numpy.array(( x1*w0 + y1*z0 - z1*y0 + w1*x0, -x1*z0 + y1*w0 + z1*x0 + w1*y0, x1*y0 - y1*x0 + z1*w0 + w1*z0, -x1*x0 - y1*y0 - z1*z0 + w1*w0), dtype=numpy.float64)
[ "def", "quaternion_multiply", "(", "quaternion1", ",", "quaternion0", ")", ":", "x0", ",", "y0", ",", "z0", ",", "w0", "=", "quaternion0", "x1", ",", "y1", ",", "z1", ",", "w1", "=", "quaternion1", "return", "numpy", ".", "array", "(", "(", "x1", "*", "w0", "+", "y1", "*", "z0", "-", "z1", "*", "y0", "+", "w1", "*", "x0", ",", "-", "x1", "*", "z0", "+", "y1", "*", "w0", "+", "z1", "*", "x0", "+", "w1", "*", "y0", ",", "x1", "*", "y0", "-", "y1", "*", "x0", "+", "z1", "*", "w0", "+", "w1", "*", "z0", ",", "-", "x1", "*", "x0", "-", "y1", "*", "y0", "-", "z1", "*", "z0", "+", "w1", "*", "w0", ")", ",", "dtype", "=", "numpy", ".", "float64", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/Blast/3rdParty/assimp/port/PyAssimp/scripts/transformations.py#L1228-L1242
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/backend.py
python
manual_variable_initialization
(value)
Sets the manual variable initialization flag. This boolean flag determines whether variables should be initialized as they are instantiated (default), or if the user should handle the initialization (e.g. via `tf.compat.v1.initialize_all_variables()`). Args: value: Python boolean.
Sets the manual variable initialization flag.
[ "Sets", "the", "manual", "variable", "initialization", "flag", "." ]
def manual_variable_initialization(value): """Sets the manual variable initialization flag. This boolean flag determines whether variables should be initialized as they are instantiated (default), or if the user should handle the initialization (e.g. via `tf.compat.v1.initialize_all_variables()`). Args: value: Python boolean. """ global _MANUAL_VAR_INIT _MANUAL_VAR_INIT = value
[ "def", "manual_variable_initialization", "(", "value", ")", ":", "global", "_MANUAL_VAR_INIT", "_MANUAL_VAR_INIT", "=", "value" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/backend.py#L326-L339
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py3/jinja2/bccache.py
python
Bucket.bytecode_to_string
(self)
return out.getvalue()
Return the bytecode as bytes.
Return the bytecode as bytes.
[ "Return", "the", "bytecode", "as", "bytes", "." ]
def bytecode_to_string(self) -> bytes: """Return the bytecode as bytes.""" out = BytesIO() self.write_bytecode(out) return out.getvalue()
[ "def", "bytecode_to_string", "(", "self", ")", "->", "bytes", ":", "out", "=", "BytesIO", "(", ")", "self", ".", "write_bytecode", "(", "out", ")", "return", "out", ".", "getvalue", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/bccache.py#L94-L98
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ftplib.py
python
FTP.rmd
(self, dirname)
return self.voidcmd('RMD ' + dirname)
Remove a directory.
Remove a directory.
[ "Remove", "a", "directory", "." ]
def rmd(self, dirname): '''Remove a directory.''' return self.voidcmd('RMD ' + dirname)
[ "def", "rmd", "(", "self", ",", "dirname", ")", ":", "return", "self", ".", "voidcmd", "(", "'RMD '", "+", "dirname", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/ftplib.py#L571-L573
citizenfx/fivem
88276d40cc7baf8285d02754cc5ae42ec7a8563f
code/tools/idl/xpidl/xpidl.py
python
IDLParser.t_singlelinecomment
(self, t)
r'(?m)//.*?$
r'(?m)//.*?$
[ "r", "(", "?m", ")", "//", ".", "*", "?$" ]
def t_singlelinecomment(self, t): r'(?m)//.*?$'
[ "def", "t_singlelinecomment", "(", "self", ",", "t", ")", ":" ]
https://github.com/citizenfx/fivem/blob/88276d40cc7baf8285d02754cc5ae42ec7a8563f/code/tools/idl/xpidl/xpidl.py#L1081-L1082
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/turtle.py
python
_Screen.setup
(self, width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"])
Set the size and position of the main window. Arguments: width: as integer a size in pixels, as float a fraction of the screen. Default is 50% of screen. height: as integer the height in pixels, as float a fraction of the screen. Default is 75% of screen. startx: if positive, starting position in pixels from the left edge of the screen, if negative from the right edge Default, startx=None is to center window horizontally. starty: if positive, starting position in pixels from the top edge of the screen, if negative from the bottom edge Default, starty=None is to center window vertically. Examples (for a Screen instance named screen): >>> screen.setup (width=200, height=200, startx=0, starty=0) sets window to 200x200 pixels, in upper left of screen >>> screen.setup(width=.75, height=0.5, startx=None, starty=None) sets window to 75% of screen by 50% of screen and centers
Set the size and position of the main window.
[ "Set", "the", "size", "and", "position", "of", "the", "main", "window", "." ]
def setup(self, width=_CFG["width"], height=_CFG["height"], startx=_CFG["leftright"], starty=_CFG["topbottom"]): """ Set the size and position of the main window. Arguments: width: as integer a size in pixels, as float a fraction of the screen. Default is 50% of screen. height: as integer the height in pixels, as float a fraction of the screen. Default is 75% of screen. startx: if positive, starting position in pixels from the left edge of the screen, if negative from the right edge Default, startx=None is to center window horizontally. starty: if positive, starting position in pixels from the top edge of the screen, if negative from the bottom edge Default, starty=None is to center window vertically. Examples (for a Screen instance named screen): >>> screen.setup (width=200, height=200, startx=0, starty=0) sets window to 200x200 pixels, in upper left of screen >>> screen.setup(width=.75, height=0.5, startx=None, starty=None) sets window to 75% of screen by 50% of screen and centers """ if not hasattr(self._root, "set_geometry"): return sw = self._root.win_width() sh = self._root.win_height() if isinstance(width, float) and 0 <= width <= 1: width = sw*width if startx is None: startx = (sw - width) / 2 if isinstance(height, float) and 0 <= height <= 1: height = sh*height if starty is None: starty = (sh - height) / 2 self._root.set_geometry(width, height, startx, starty) self.update()
[ "def", "setup", "(", "self", ",", "width", "=", "_CFG", "[", "\"width\"", "]", ",", "height", "=", "_CFG", "[", "\"height\"", "]", ",", "startx", "=", "_CFG", "[", "\"leftright\"", "]", ",", "starty", "=", "_CFG", "[", "\"topbottom\"", "]", ")", ":", "if", "not", "hasattr", "(", "self", ".", "_root", ",", "\"set_geometry\"", ")", ":", "return", "sw", "=", "self", ".", "_root", ".", "win_width", "(", ")", "sh", "=", "self", ".", "_root", ".", "win_height", "(", ")", "if", "isinstance", "(", "width", ",", "float", ")", "and", "0", "<=", "width", "<=", "1", ":", "width", "=", "sw", "*", "width", "if", "startx", "is", "None", ":", "startx", "=", "(", "sw", "-", "width", ")", "/", "2", "if", "isinstance", "(", "height", ",", "float", ")", "and", "0", "<=", "height", "<=", "1", ":", "height", "=", "sh", "*", "height", "if", "starty", "is", "None", ":", "starty", "=", "(", "sh", "-", "height", ")", "/", "2", "self", ".", "_root", ".", "set_geometry", "(", "width", ",", "height", ",", "startx", ",", "starty", ")", "self", ".", "update", "(", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/turtle.py#L3693-L3731
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
RichTextCtrl.ApplyTextEffectToSelection
(*args, **kwargs)
return _richtext.RichTextCtrl_ApplyTextEffectToSelection(*args, **kwargs)
ApplyTextEffectToSelection(self, int flags) -> bool
ApplyTextEffectToSelection(self, int flags) -> bool
[ "ApplyTextEffectToSelection", "(", "self", "int", "flags", ")", "-", ">", "bool" ]
def ApplyTextEffectToSelection(*args, **kwargs): """ApplyTextEffectToSelection(self, int flags) -> bool""" return _richtext.RichTextCtrl_ApplyTextEffectToSelection(*args, **kwargs)
[ "def", "ApplyTextEffectToSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_ApplyTextEffectToSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L3975-L3977
AirtestProject/Poco-SDK
e7bd6c21236051092e67ae44178d45890f70d803
sdk/python/sdk/Selector.py
python
Selector.select
(self, cond, multiple=False)
return self.selectImpl(cond, multiple, self.getRoot(), 9999, True, True)
See Also: :py:meth:`select <poco.sdk.Selector.ISelector.select>` method in ``ISelector``.
See Also: :py:meth:`select <poco.sdk.Selector.ISelector.select>` method in ``ISelector``.
[ "See", "Also", ":", ":", "py", ":", "meth", ":", "select", "<poco", ".", "sdk", ".", "Selector", ".", "ISelector", ".", "select", ">", "method", "in", "ISelector", "." ]
def select(self, cond, multiple=False): """ See Also: :py:meth:`select <poco.sdk.Selector.ISelector.select>` method in ``ISelector``. """ return self.selectImpl(cond, multiple, self.getRoot(), 9999, True, True)
[ "def", "select", "(", "self", ",", "cond", ",", "multiple", "=", "False", ")", ":", "return", "self", ".", "selectImpl", "(", "cond", ",", "multiple", ",", "self", ".", "getRoot", "(", ")", ",", "9999", ",", "True", ",", "True", ")" ]
https://github.com/AirtestProject/Poco-SDK/blob/e7bd6c21236051092e67ae44178d45890f70d803/sdk/python/sdk/Selector.py#L72-L77
psnonis/FinBERT
c0c555d833a14e2316a3701e59c0b5156f804b4e
bert-gpu/run_squad.py
python
get_final_text
(pred_text, orig_text, do_lower_case)
return output_text
Project the tokenized prediction back to the original text.
Project the tokenized prediction back to the original text.
[ "Project", "the", "tokenized", "prediction", "back", "to", "the", "original", "text", "." ]
def get_final_text(pred_text, orig_text, do_lower_case): """Project the tokenized prediction back to the original text.""" # When we created the data, we kept track of the alignment between original # (whitespace tokenized) tokens and our WordPiece tokenized tokens. So # now `orig_text` contains the span of our original text corresponding to the # span that we predicted. # # However, `orig_text` may contain extra characters that we don't want in # our prediction. # # For example, let's say: # pred_text = steve smith # orig_text = Steve Smith's # # We don't want to return `orig_text` because it contains the extra "'s". # # We don't want to return `pred_text` because it's already been normalized # (the SQuAD eval script also does punctuation stripping/lower casing but # our tokenizer does additional normalization like stripping accent # characters). # # What we really want to return is "Steve Smith". # # Therefore, we have to apply a semi-complicated alignment heruistic between # `pred_text` and `orig_text` to get a character-to-charcter alignment. This # can fail in certain cases in which case we just return `orig_text`. def _strip_spaces(text): ns_chars = [] ns_to_s_map = collections.OrderedDict() for (i, c) in enumerate(text): if c == " ": continue ns_to_s_map[len(ns_chars)] = i ns_chars.append(c) ns_text = "".join(ns_chars) return (ns_text, ns_to_s_map) # We first tokenize `orig_text`, strip whitespace from the result # and `pred_text`, and check if they are the same length. If they are # NOT the same length, the heuristic has failed. If they are the same # length, we assume the characters are one-to-one aligned. tokenizer = tokenization.BasicTokenizer(do_lower_case=do_lower_case) tok_text = " ".join(tokenizer.tokenize(orig_text)) start_position = tok_text.find(pred_text) if start_position == -1: if FLAGS.verbose_logging: tf.logging.info( "Unable to find text: '%s' in '%s'" % (pred_text, orig_text)) return orig_text end_position = start_position + len(pred_text) - 1 (orig_ns_text, orig_ns_to_s_map) = _strip_spaces(orig_text) (tok_ns_text, tok_ns_to_s_map) = _strip_spaces(tok_text) if len(orig_ns_text) != len(tok_ns_text): if FLAGS.verbose_logging: tf.logging.info("Length not equal after stripping spaces: '%s' vs '%s'", orig_ns_text, tok_ns_text) return orig_text # We then project the characters in `pred_text` back to `orig_text` using # the character-to-character alignment. tok_s_to_ns_map = {} for (i, tok_index) in six.iteritems(tok_ns_to_s_map): tok_s_to_ns_map[tok_index] = i orig_start_position = None if start_position in tok_s_to_ns_map: ns_start_position = tok_s_to_ns_map[start_position] if ns_start_position in orig_ns_to_s_map: orig_start_position = orig_ns_to_s_map[ns_start_position] if orig_start_position is None: if FLAGS.verbose_logging: tf.logging.info("Couldn't map start position") return orig_text orig_end_position = None if end_position in tok_s_to_ns_map: ns_end_position = tok_s_to_ns_map[end_position] if ns_end_position in orig_ns_to_s_map: orig_end_position = orig_ns_to_s_map[ns_end_position] if orig_end_position is None: if FLAGS.verbose_logging: tf.logging.info("Couldn't map end position") return orig_text output_text = orig_text[orig_start_position:(orig_end_position + 1)] return output_text
[ "def", "get_final_text", "(", "pred_text", ",", "orig_text", ",", "do_lower_case", ")", ":", "# When we created the data, we kept track of the alignment between original", "# (whitespace tokenized) tokens and our WordPiece tokenized tokens. So", "# now `orig_text` contains the span of our original text corresponding to the", "# span that we predicted.", "#", "# However, `orig_text` may contain extra characters that we don't want in", "# our prediction.", "#", "# For example, let's say:", "# pred_text = steve smith", "# orig_text = Steve Smith's", "#", "# We don't want to return `orig_text` because it contains the extra \"'s\".", "#", "# We don't want to return `pred_text` because it's already been normalized", "# (the SQuAD eval script also does punctuation stripping/lower casing but", "# our tokenizer does additional normalization like stripping accent", "# characters).", "#", "# What we really want to return is \"Steve Smith\".", "#", "# Therefore, we have to apply a semi-complicated alignment heruistic between", "# `pred_text` and `orig_text` to get a character-to-charcter alignment. This", "# can fail in certain cases in which case we just return `orig_text`.", "def", "_strip_spaces", "(", "text", ")", ":", "ns_chars", "=", "[", "]", "ns_to_s_map", "=", "collections", ".", "OrderedDict", "(", ")", "for", "(", "i", ",", "c", ")", "in", "enumerate", "(", "text", ")", ":", "if", "c", "==", "\" \"", ":", "continue", "ns_to_s_map", "[", "len", "(", "ns_chars", ")", "]", "=", "i", "ns_chars", ".", "append", "(", "c", ")", "ns_text", "=", "\"\"", ".", "join", "(", "ns_chars", ")", "return", "(", "ns_text", ",", "ns_to_s_map", ")", "# We first tokenize `orig_text`, strip whitespace from the result", "# and `pred_text`, and check if they are the same length. If they are", "# NOT the same length, the heuristic has failed. If they are the same", "# length, we assume the characters are one-to-one aligned.", "tokenizer", "=", "tokenization", ".", "BasicTokenizer", "(", "do_lower_case", "=", "do_lower_case", ")", "tok_text", "=", "\" \"", ".", "join", "(", "tokenizer", ".", "tokenize", "(", "orig_text", ")", ")", "start_position", "=", "tok_text", ".", "find", "(", "pred_text", ")", "if", "start_position", "==", "-", "1", ":", "if", "FLAGS", ".", "verbose_logging", ":", "tf", ".", "logging", ".", "info", "(", "\"Unable to find text: '%s' in '%s'\"", "%", "(", "pred_text", ",", "orig_text", ")", ")", "return", "orig_text", "end_position", "=", "start_position", "+", "len", "(", "pred_text", ")", "-", "1", "(", "orig_ns_text", ",", "orig_ns_to_s_map", ")", "=", "_strip_spaces", "(", "orig_text", ")", "(", "tok_ns_text", ",", "tok_ns_to_s_map", ")", "=", "_strip_spaces", "(", "tok_text", ")", "if", "len", "(", "orig_ns_text", ")", "!=", "len", "(", "tok_ns_text", ")", ":", "if", "FLAGS", ".", "verbose_logging", ":", "tf", ".", "logging", ".", "info", "(", "\"Length not equal after stripping spaces: '%s' vs '%s'\"", ",", "orig_ns_text", ",", "tok_ns_text", ")", "return", "orig_text", "# We then project the characters in `pred_text` back to `orig_text` using", "# the character-to-character alignment.", "tok_s_to_ns_map", "=", "{", "}", "for", "(", "i", ",", "tok_index", ")", "in", "six", ".", "iteritems", "(", "tok_ns_to_s_map", ")", ":", "tok_s_to_ns_map", "[", "tok_index", "]", "=", "i", "orig_start_position", "=", "None", "if", "start_position", "in", "tok_s_to_ns_map", ":", "ns_start_position", "=", "tok_s_to_ns_map", "[", "start_position", "]", "if", "ns_start_position", "in", "orig_ns_to_s_map", ":", "orig_start_position", "=", "orig_ns_to_s_map", "[", "ns_start_position", "]", "if", "orig_start_position", "is", "None", ":", "if", "FLAGS", ".", "verbose_logging", ":", "tf", ".", "logging", ".", "info", "(", "\"Couldn't map start position\"", ")", "return", "orig_text", "orig_end_position", "=", "None", "if", "end_position", "in", "tok_s_to_ns_map", ":", "ns_end_position", "=", "tok_s_to_ns_map", "[", "end_position", "]", "if", "ns_end_position", "in", "orig_ns_to_s_map", ":", "orig_end_position", "=", "orig_ns_to_s_map", "[", "ns_end_position", "]", "if", "orig_end_position", "is", "None", ":", "if", "FLAGS", ".", "verbose_logging", ":", "tf", ".", "logging", ".", "info", "(", "\"Couldn't map end position\"", ")", "return", "orig_text", "output_text", "=", "orig_text", "[", "orig_start_position", ":", "(", "orig_end_position", "+", "1", ")", "]", "return", "output_text" ]
https://github.com/psnonis/FinBERT/blob/c0c555d833a14e2316a3701e59c0b5156f804b4e/bert-gpu/run_squad.py#L607-L700
rodeofx/OpenWalter
6116fbe3f04f1146c854afbfbdbe944feaee647e
walter/common/walterWidgets/walterLayersView.py
python
LayersItem.getActions
(self)
return [ (self.OPEN_ICON, 1.0, self.ACTION_OPEN), (self.VIS_ICON, visibleOpacity, self.ACTION_VISIBLE), (self.RND_ICON, renderableOpacity, self.ACTION_RENDERABLE)]
The list of actions to draw on the right side of the item in the tree view. It should return the data in the following format: [(icon1, opacity1, action1), (icon2, opacity2, action2), ...]
The list of actions to draw on the right side of the item in the tree view. It should return the data in the following format: [(icon1, opacity1, action1), (icon2, opacity2, action2), ...]
[ "The", "list", "of", "actions", "to", "draw", "on", "the", "right", "side", "of", "the", "item", "in", "the", "tree", "view", ".", "It", "should", "return", "the", "data", "in", "the", "following", "format", ":", "[", "(", "icon1", "opacity1", "action1", ")", "(", "icon2", "opacity2", "action2", ")", "...", "]" ]
def getActions(self): """ The list of actions to draw on the right side of the item in the tree view. It should return the data in the following format: [(icon1, opacity1, action1), (icon2, opacity2, action2), ...] """ visibleOpacity = 1.0 if self.visible else 0.2 renderableOpacity = 1.0 if self.renderable else 0.2 return [ (self.OPEN_ICON, 1.0, self.ACTION_OPEN), (self.VIS_ICON, visibleOpacity, self.ACTION_VISIBLE), (self.RND_ICON, renderableOpacity, self.ACTION_RENDERABLE)]
[ "def", "getActions", "(", "self", ")", ":", "visibleOpacity", "=", "1.0", "if", "self", ".", "visible", "else", "0.2", "renderableOpacity", "=", "1.0", "if", "self", ".", "renderable", "else", "0.2", "return", "[", "(", "self", ".", "OPEN_ICON", ",", "1.0", ",", "self", ".", "ACTION_OPEN", ")", ",", "(", "self", ".", "VIS_ICON", ",", "visibleOpacity", ",", "self", ".", "ACTION_VISIBLE", ")", ",", "(", "self", ".", "RND_ICON", ",", "renderableOpacity", ",", "self", ".", "ACTION_RENDERABLE", ")", "]" ]
https://github.com/rodeofx/OpenWalter/blob/6116fbe3f04f1146c854afbfbdbe944feaee647e/walter/common/walterWidgets/walterLayersView.py#L286-L297
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/src/robotsim.py
python
Geometry3D.setCollisionMargin
(self, margin: "double")
return _robotsim.Geometry3D_setCollisionMargin(self, margin)
r""" setCollisionMargin(Geometry3D self, double margin) Sets a padding around the base geometry which affects the results of proximity queries.
r""" setCollisionMargin(Geometry3D self, double margin)
[ "r", "setCollisionMargin", "(", "Geometry3D", "self", "double", "margin", ")" ]
def setCollisionMargin(self, margin: "double") -> "void": r""" setCollisionMargin(Geometry3D self, double margin) Sets a padding around the base geometry which affects the results of proximity queries. """ return _robotsim.Geometry3D_setCollisionMargin(self, margin)
[ "def", "setCollisionMargin", "(", "self", ",", "margin", ":", "\"double\"", ")", "->", "\"void\"", ":", "return", "_robotsim", ".", "Geometry3D_setCollisionMargin", "(", "self", ",", "margin", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/src/robotsim.py#L2373-L2382
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_gdi.py
python
Region.IntersectRect
(*args, **kwargs)
return _gdi_.Region_IntersectRect(*args, **kwargs)
IntersectRect(self, Rect rect) -> bool
IntersectRect(self, Rect rect) -> bool
[ "IntersectRect", "(", "self", "Rect", "rect", ")", "-", ">", "bool" ]
def IntersectRect(*args, **kwargs): """IntersectRect(self, Rect rect) -> bool""" return _gdi_.Region_IntersectRect(*args, **kwargs)
[ "def", "IntersectRect", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Region_IntersectRect", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_gdi.py#L1587-L1589
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/robotsim.py
python
TerrainModel.setName
(self, name: str)
return _robotsim.TerrainModel_setName(self, name)
r""" Args: name (str)
r""" Args: name (str)
[ "r", "Args", ":", "name", "(", "str", ")" ]
def setName(self, name: str) ->None: r""" Args: name (str) """ return _robotsim.TerrainModel_setName(self, name)
[ "def", "setName", "(", "self", ",", "name", ":", "str", ")", "->", "None", ":", "return", "_robotsim", ".", "TerrainModel_setName", "(", "self", ",", "name", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/robotsim.py#L5533-L5538
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
ItemContainer.SetStringSelection
(*args, **kwargs)
return _core_.ItemContainer_SetStringSelection(*args, **kwargs)
SetStringSelection(self, String s) -> bool
SetStringSelection(self, String s) -> bool
[ "SetStringSelection", "(", "self", "String", "s", ")", "-", ">", "bool" ]
def SetStringSelection(*args, **kwargs): """SetStringSelection(self, String s) -> bool""" return _core_.ItemContainer_SetStringSelection(*args, **kwargs)
[ "def", "SetStringSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "ItemContainer_SetStringSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L13008-L13010
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/docs/bcdoc/restdoc.py
python
DocumentStructure.delete_section
(self, name)
Delete a section
Delete a section
[ "Delete", "a", "section" ]
def delete_section(self, name): """Delete a section""" del self._structure[name]
[ "def", "delete_section", "(", "self", ",", "name", ")", ":", "del", "self", ".", "_structure", "[", "name", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/botocore/docs/bcdoc/restdoc.py#L189-L191
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/make.py
python
MakefileWriter.WriteSources
(self, configs, deps, sources, extra_outputs, extra_link_deps, part_of_all, precompiled_header)
Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target. configs, deps, sources: input from gyp. extra_outputs: a list of extra outputs this action should be dependent on; used to serialize action/rules before compilation extra_link_deps: a list that will be filled in with any outputs of compilation (to be used in link lines) part_of_all: flag indicating this target is part of 'all'
Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target.
[ "Write", "Makefile", "code", "for", "any", "sources", "from", "the", "gyp", "input", ".", "These", "are", "source", "files", "necessary", "to", "build", "the", "current", "target", "." ]
def WriteSources(self, configs, deps, sources, extra_outputs, extra_link_deps, part_of_all, precompiled_header): """Write Makefile code for any 'sources' from the gyp input. These are source files necessary to build the current target. configs, deps, sources: input from gyp. extra_outputs: a list of extra outputs this action should be dependent on; used to serialize action/rules before compilation extra_link_deps: a list that will be filled in with any outputs of compilation (to be used in link lines) part_of_all: flag indicating this target is part of 'all' """ # Write configuration-specific variables for CFLAGS, etc. for configname in sorted(configs.keys()): config = configs[configname] self.WriteList(config.get('defines'), 'DEFS_%s' % configname, prefix='-D', quoter=EscapeCppDefine) if self.flavor == 'mac': cflags = self.xcode_settings.GetCflags(configname) cflags_c = self.xcode_settings.GetCflagsC(configname) cflags_cc = self.xcode_settings.GetCflagsCC(configname) cflags_objc = self.xcode_settings.GetCflagsObjC(configname) cflags_objcc = self.xcode_settings.GetCflagsObjCC(configname) else: cflags = config.get('cflags') cflags_c = config.get('cflags_c') cflags_cc = config.get('cflags_cc') self.WriteLn("# Flags passed to all source files."); self.WriteList(cflags, 'CFLAGS_%s' % configname) self.WriteLn("# Flags passed to only C files."); self.WriteList(cflags_c, 'CFLAGS_C_%s' % configname) self.WriteLn("# Flags passed to only C++ files."); self.WriteList(cflags_cc, 'CFLAGS_CC_%s' % configname) if self.flavor == 'mac': self.WriteLn("# Flags passed to only ObjC files."); self.WriteList(cflags_objc, 'CFLAGS_OBJC_%s' % configname) self.WriteLn("# Flags passed to only ObjC++ files."); self.WriteList(cflags_objcc, 'CFLAGS_OBJCC_%s' % configname) includes = config.get('include_dirs') if includes: includes = map(Sourceify, map(self.Absolutify, includes)) self.WriteList(includes, 'INCS_%s' % configname, prefix='-I') compilable = filter(Compilable, sources) objs = map(self.Objectify, map(self.Absolutify, map(Target, compilable))) self.WriteList(objs, 'OBJS') for obj in objs: assert ' ' not in obj, ( "Spaces in object filenames not supported (%s)" % obj) self.WriteLn('# Add to the list of files we specially track ' 'dependencies for.') self.WriteLn('all_deps += $(OBJS)') self.WriteLn() # Make sure our dependencies are built first. if deps: self.WriteMakeRule(['$(OBJS)'], deps, comment = 'Make sure our dependencies are built ' 'before any of us.', order_only = True) # Make sure the actions and rules run first. # If they generate any extra headers etc., the per-.o file dep tracking # will catch the proper rebuilds, so order only is still ok here. if extra_outputs: self.WriteMakeRule(['$(OBJS)'], extra_outputs, comment = 'Make sure our actions/rules run ' 'before any of us.', order_only = True) pchdeps = precompiled_header.GetObjDependencies(compilable, objs ) if pchdeps: self.WriteLn('# Dependencies from obj files to their precompiled headers') for source, obj, gch in pchdeps: self.WriteLn('%s: %s' % (obj, gch)) self.WriteLn('# End precompiled header dependencies') if objs: extra_link_deps.append('$(OBJS)') self.WriteLn("""\ # CFLAGS et al overrides must be target-local. # See "Target-specific Variable Values" in the GNU Make manual.""") self.WriteLn("$(OBJS): TOOLSET := $(TOOLSET)") self.WriteLn("$(OBJS): GYP_CFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('c') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_C_$(BUILDTYPE))") self.WriteLn("$(OBJS): GYP_CXXFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('cc') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_CC_$(BUILDTYPE))") if self.flavor == 'mac': self.WriteLn("$(OBJS): GYP_OBJCFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('m') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_C_$(BUILDTYPE)) " "$(CFLAGS_OBJC_$(BUILDTYPE))") self.WriteLn("$(OBJS): GYP_OBJCXXFLAGS := " "$(DEFS_$(BUILDTYPE)) " "$(INCS_$(BUILDTYPE)) " "%s " % precompiled_header.GetInclude('mm') + "$(CFLAGS_$(BUILDTYPE)) " "$(CFLAGS_CC_$(BUILDTYPE)) " "$(CFLAGS_OBJCC_$(BUILDTYPE))") self.WritePchTargets(precompiled_header.GetPchBuildCommands()) # If there are any object files in our input file list, link them into our # output. extra_link_deps += filter(Linkable, sources) self.WriteLn()
[ "def", "WriteSources", "(", "self", ",", "configs", ",", "deps", ",", "sources", ",", "extra_outputs", ",", "extra_link_deps", ",", "part_of_all", ",", "precompiled_header", ")", ":", "# Write configuration-specific variables for CFLAGS, etc.", "for", "configname", "in", "sorted", "(", "configs", ".", "keys", "(", ")", ")", ":", "config", "=", "configs", "[", "configname", "]", "self", ".", "WriteList", "(", "config", ".", "get", "(", "'defines'", ")", ",", "'DEFS_%s'", "%", "configname", ",", "prefix", "=", "'-D'", ",", "quoter", "=", "EscapeCppDefine", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "cflags", "=", "self", ".", "xcode_settings", ".", "GetCflags", "(", "configname", ")", "cflags_c", "=", "self", ".", "xcode_settings", ".", "GetCflagsC", "(", "configname", ")", "cflags_cc", "=", "self", ".", "xcode_settings", ".", "GetCflagsCC", "(", "configname", ")", "cflags_objc", "=", "self", ".", "xcode_settings", ".", "GetCflagsObjC", "(", "configname", ")", "cflags_objcc", "=", "self", ".", "xcode_settings", ".", "GetCflagsObjCC", "(", "configname", ")", "else", ":", "cflags", "=", "config", ".", "get", "(", "'cflags'", ")", "cflags_c", "=", "config", ".", "get", "(", "'cflags_c'", ")", "cflags_cc", "=", "config", ".", "get", "(", "'cflags_cc'", ")", "self", ".", "WriteLn", "(", "\"# Flags passed to all source files.\"", ")", "self", ".", "WriteList", "(", "cflags", ",", "'CFLAGS_%s'", "%", "configname", ")", "self", ".", "WriteLn", "(", "\"# Flags passed to only C files.\"", ")", "self", ".", "WriteList", "(", "cflags_c", ",", "'CFLAGS_C_%s'", "%", "configname", ")", "self", ".", "WriteLn", "(", "\"# Flags passed to only C++ files.\"", ")", "self", ".", "WriteList", "(", "cflags_cc", ",", "'CFLAGS_CC_%s'", "%", "configname", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "self", ".", "WriteLn", "(", "\"# Flags passed to only ObjC files.\"", ")", "self", ".", "WriteList", "(", "cflags_objc", ",", "'CFLAGS_OBJC_%s'", "%", "configname", ")", "self", ".", "WriteLn", "(", "\"# Flags passed to only ObjC++ files.\"", ")", "self", ".", "WriteList", "(", "cflags_objcc", ",", "'CFLAGS_OBJCC_%s'", "%", "configname", ")", "includes", "=", "config", ".", "get", "(", "'include_dirs'", ")", "if", "includes", ":", "includes", "=", "map", "(", "Sourceify", ",", "map", "(", "self", ".", "Absolutify", ",", "includes", ")", ")", "self", ".", "WriteList", "(", "includes", ",", "'INCS_%s'", "%", "configname", ",", "prefix", "=", "'-I'", ")", "compilable", "=", "filter", "(", "Compilable", ",", "sources", ")", "objs", "=", "map", "(", "self", ".", "Objectify", ",", "map", "(", "self", ".", "Absolutify", ",", "map", "(", "Target", ",", "compilable", ")", ")", ")", "self", ".", "WriteList", "(", "objs", ",", "'OBJS'", ")", "for", "obj", "in", "objs", ":", "assert", "' '", "not", "in", "obj", ",", "(", "\"Spaces in object filenames not supported (%s)\"", "%", "obj", ")", "self", ".", "WriteLn", "(", "'# Add to the list of files we specially track '", "'dependencies for.'", ")", "self", ".", "WriteLn", "(", "'all_deps += $(OBJS)'", ")", "self", ".", "WriteLn", "(", ")", "# Make sure our dependencies are built first.", "if", "deps", ":", "self", ".", "WriteMakeRule", "(", "[", "'$(OBJS)'", "]", ",", "deps", ",", "comment", "=", "'Make sure our dependencies are built '", "'before any of us.'", ",", "order_only", "=", "True", ")", "# Make sure the actions and rules run first.", "# If they generate any extra headers etc., the per-.o file dep tracking", "# will catch the proper rebuilds, so order only is still ok here.", "if", "extra_outputs", ":", "self", ".", "WriteMakeRule", "(", "[", "'$(OBJS)'", "]", ",", "extra_outputs", ",", "comment", "=", "'Make sure our actions/rules run '", "'before any of us.'", ",", "order_only", "=", "True", ")", "pchdeps", "=", "precompiled_header", ".", "GetObjDependencies", "(", "compilable", ",", "objs", ")", "if", "pchdeps", ":", "self", ".", "WriteLn", "(", "'# Dependencies from obj files to their precompiled headers'", ")", "for", "source", ",", "obj", ",", "gch", "in", "pchdeps", ":", "self", ".", "WriteLn", "(", "'%s: %s'", "%", "(", "obj", ",", "gch", ")", ")", "self", ".", "WriteLn", "(", "'# End precompiled header dependencies'", ")", "if", "objs", ":", "extra_link_deps", ".", "append", "(", "'$(OBJS)'", ")", "self", ".", "WriteLn", "(", "\"\"\"\\\n# CFLAGS et al overrides must be target-local.\n# See \"Target-specific Variable Values\" in the GNU Make manual.\"\"\"", ")", "self", ".", "WriteLn", "(", "\"$(OBJS): TOOLSET := $(TOOLSET)\"", ")", "self", ".", "WriteLn", "(", "\"$(OBJS): GYP_CFLAGS := \"", "\"$(DEFS_$(BUILDTYPE)) \"", "\"$(INCS_$(BUILDTYPE)) \"", "\"%s \"", "%", "precompiled_header", ".", "GetInclude", "(", "'c'", ")", "+", "\"$(CFLAGS_$(BUILDTYPE)) \"", "\"$(CFLAGS_C_$(BUILDTYPE))\"", ")", "self", ".", "WriteLn", "(", "\"$(OBJS): GYP_CXXFLAGS := \"", "\"$(DEFS_$(BUILDTYPE)) \"", "\"$(INCS_$(BUILDTYPE)) \"", "\"%s \"", "%", "precompiled_header", ".", "GetInclude", "(", "'cc'", ")", "+", "\"$(CFLAGS_$(BUILDTYPE)) \"", "\"$(CFLAGS_CC_$(BUILDTYPE))\"", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "self", ".", "WriteLn", "(", "\"$(OBJS): GYP_OBJCFLAGS := \"", "\"$(DEFS_$(BUILDTYPE)) \"", "\"$(INCS_$(BUILDTYPE)) \"", "\"%s \"", "%", "precompiled_header", ".", "GetInclude", "(", "'m'", ")", "+", "\"$(CFLAGS_$(BUILDTYPE)) \"", "\"$(CFLAGS_C_$(BUILDTYPE)) \"", "\"$(CFLAGS_OBJC_$(BUILDTYPE))\"", ")", "self", ".", "WriteLn", "(", "\"$(OBJS): GYP_OBJCXXFLAGS := \"", "\"$(DEFS_$(BUILDTYPE)) \"", "\"$(INCS_$(BUILDTYPE)) \"", "\"%s \"", "%", "precompiled_header", ".", "GetInclude", "(", "'mm'", ")", "+", "\"$(CFLAGS_$(BUILDTYPE)) \"", "\"$(CFLAGS_CC_$(BUILDTYPE)) \"", "\"$(CFLAGS_OBJCC_$(BUILDTYPE))\"", ")", "self", ".", "WritePchTargets", "(", "precompiled_header", ".", "GetPchBuildCommands", "(", ")", ")", "# If there are any object files in our input file list, link them into our", "# output.", "extra_link_deps", "+=", "filter", "(", "Linkable", ",", "sources", ")", "self", ".", "WriteLn", "(", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/tools/gyp/pylib/gyp/generator/make.py#L1219-L1341
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/Tpm.py
python
Tpm.ECC_Parameters
(self, curveID)
return res.parameters if res else None
This command returns the parameters of an ECC curve identified by its TCG-assigned curveID. Args: curveID (TPM_ECC_CURVE): Parameter set selector Returns: parameters - ECC parameters for the selected curve
This command returns the parameters of an ECC curve identified by its TCG-assigned curveID.
[ "This", "command", "returns", "the", "parameters", "of", "an", "ECC", "curve", "identified", "by", "its", "TCG", "-", "assigned", "curveID", "." ]
def ECC_Parameters(self, curveID): """ This command returns the parameters of an ECC curve identified by its TCG-assigned curveID. Args: curveID (TPM_ECC_CURVE): Parameter set selector Returns: parameters - ECC parameters for the selected curve """ req = TPM2_ECC_Parameters_REQUEST(curveID) respBuf = self.dispatchCommand(TPM_CC.ECC_Parameters, req) res = self.processResponse(respBuf, ECC_ParametersResponse) return res.parameters if res else None
[ "def", "ECC_Parameters", "(", "self", ",", "curveID", ")", ":", "req", "=", "TPM2_ECC_Parameters_REQUEST", "(", "curveID", ")", "respBuf", "=", "self", ".", "dispatchCommand", "(", "TPM_CC", ".", "ECC_Parameters", ",", "req", ")", "res", "=", "self", ".", "processResponse", "(", "respBuf", ",", "ECC_ParametersResponse", ")", "return", "res", ".", "parameters", "if", "res", "else", "None" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/Tpm.py#L571-L584
msftguy/ssh-rd
a5f3a79daeac5844edebf01916c9613563f1c390
_3rd/boost_1_48_0/tools/build/v2/build/virtual_target.py
python
VirtualTargetRegistry.add_suffix
(self, specified_name, file_type, prop_set)
Appends the suffix appropriate to 'type/property_set' combination to the specified name and returns the result.
Appends the suffix appropriate to 'type/property_set' combination to the specified name and returns the result.
[ "Appends", "the", "suffix", "appropriate", "to", "type", "/", "property_set", "combination", "to", "the", "specified", "name", "and", "returns", "the", "result", "." ]
def add_suffix (self, specified_name, file_type, prop_set): """ Appends the suffix appropriate to 'type/property_set' combination to the specified name and returns the result. """ suffix = b2.build.type.generated_target_suffix (file_type, prop_set) if suffix: return specified_name + '.' + suffix else: return specified_name
[ "def", "add_suffix", "(", "self", ",", "specified_name", ",", "file_type", ",", "prop_set", ")", ":", "suffix", "=", "b2", ".", "build", ".", "type", ".", "generated_target_suffix", "(", "file_type", ",", "prop_set", ")", "if", "suffix", ":", "return", "specified_name", "+", "'.'", "+", "suffix", "else", ":", "return", "specified_name" ]
https://github.com/msftguy/ssh-rd/blob/a5f3a79daeac5844edebf01916c9613563f1c390/_3rd/boost_1_48_0/tools/build/v2/build/virtual_target.py#L237-L247
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
src/python/m5/stats/__init__.py
python
_hdf5Factory
(fn, chunking=10, desc=True, formulas=True)
return _m5.stats.initHDF5(fn, chunking, desc, formulas)
Output stats in HDF5 format. The HDF5 file format is a structured binary file format. It has the multiple benefits over traditional text stat files: * Efficient storage of time series (multiple stat dumps) * Fast lookup of stats * Plenty of existing tooling (e.g., Python libraries and graphical viewers) * File format can be used to store frame buffers together with normal stats. There are some drawbacks compared to the default text format: * Large startup cost (single stat dump larger than text equivalent) * Stat dumps are slower than text Known limitations: * Distributions and histograms currently unsupported. * No support for forking. Parameters: * chunking (unsigned): Number of time steps to pre-allocate (default: 10) * desc (bool): Output stat descriptions (default: True) * formulas (bool): Output derived stats (default: True) Example: h5://stats.h5?desc=False;chunking=100;formulas=False
Output stats in HDF5 format.
[ "Output", "stats", "in", "HDF5", "format", "." ]
def _hdf5Factory(fn, chunking=10, desc=True, formulas=True): """Output stats in HDF5 format. The HDF5 file format is a structured binary file format. It has the multiple benefits over traditional text stat files: * Efficient storage of time series (multiple stat dumps) * Fast lookup of stats * Plenty of existing tooling (e.g., Python libraries and graphical viewers) * File format can be used to store frame buffers together with normal stats. There are some drawbacks compared to the default text format: * Large startup cost (single stat dump larger than text equivalent) * Stat dumps are slower than text Known limitations: * Distributions and histograms currently unsupported. * No support for forking. Parameters: * chunking (unsigned): Number of time steps to pre-allocate (default: 10) * desc (bool): Output stat descriptions (default: True) * formulas (bool): Output derived stats (default: True) Example: h5://stats.h5?desc=False;chunking=100;formulas=False """ return _m5.stats.initHDF5(fn, chunking, desc, formulas)
[ "def", "_hdf5Factory", "(", "fn", ",", "chunking", "=", "10", ",", "desc", "=", "True", ",", "formulas", "=", "True", ")", ":", "return", "_m5", ".", "stats", ".", "initHDF5", "(", "fn", ",", "chunking", ",", "desc", ",", "formulas", ")" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/src/python/m5/stats/__init__.py#L151-L184
apple/swift
469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893
utils/build_swift/build_swift/presets.py
python
_catch_duplicate_section_error
(func)
return wrapper
Decorator used to catch and rethrowing configparser's DuplicateSectionError.
Decorator used to catch and rethrowing configparser's DuplicateSectionError.
[ "Decorator", "used", "to", "catch", "and", "rethrowing", "configparser", "s", "DuplicateSectionError", "." ]
def _catch_duplicate_section_error(func): """Decorator used to catch and rethrowing configparser's DuplicateSectionError. """ @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except configparser.DuplicateSectionError as e: preset_name = _remove_prefix(e.section, _PRESET_PREFIX).strip() raise DuplicatePresetError(preset_name) return wrapper
[ "def", "_catch_duplicate_section_error", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "configparser", ".", "DuplicateSectionError", "as", "e", ":", "preset_name", "=", "_remove_prefix", "(", "e", ".", "section", ",", "_PRESET_PREFIX", ")", ".", "strip", "(", ")", "raise", "DuplicatePresetError", "(", "preset_name", ")", "return", "wrapper" ]
https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/build_swift/build_swift/presets.py#L88-L101
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
BMPHandler.__init__
(self, *args, **kwargs)
__init__(self) -> BMPHandler A `wx.ImageHandler` for \*.bmp bitmap files.
__init__(self) -> BMPHandler
[ "__init__", "(", "self", ")", "-", ">", "BMPHandler" ]
def __init__(self, *args, **kwargs): """ __init__(self) -> BMPHandler A `wx.ImageHandler` for \*.bmp bitmap files. """ _core_.BMPHandler_swiginit(self,_core_.new_BMPHandler(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_core_", ".", "BMPHandler_swiginit", "(", "self", ",", "_core_", ".", "new_BMPHandler", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L3907-L3913
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
third_party/closure_linter/closure_linter/statetracker.py
python
StateTracker.InObjectLiteral
(self)
return self._block_depth and self._block_types[-1] == self.OBJECT_LITERAL
Returns true if the current token is within an object literal. Returns: True if the current token is within an object literal.
Returns true if the current token is within an object literal.
[ "Returns", "true", "if", "the", "current", "token", "is", "within", "an", "object", "literal", "." ]
def InObjectLiteral(self): """Returns true if the current token is within an object literal. Returns: True if the current token is within an object literal. """ return self._block_depth and self._block_types[-1] == self.OBJECT_LITERAL
[ "def", "InObjectLiteral", "(", "self", ")", ":", "return", "self", ".", "_block_depth", "and", "self", ".", "_block_types", "[", "-", "1", "]", "==", "self", ".", "OBJECT_LITERAL" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/third_party/closure_linter/closure_linter/statetracker.py#L677-L683
klzgrad/naiveproxy
ed2c513637c77b18721fe428d7ed395b4d284c83
src/build/android/pylib/utils/decorators.py
python
NoRaiseException
(default_return_value=None, exception_message='')
return decorator
Returns decorator that catches and logs uncaught Exceptions. Args: default_return_value: Value to return in the case of uncaught Exception. exception_message: Message for uncaught exceptions.
Returns decorator that catches and logs uncaught Exceptions.
[ "Returns", "decorator", "that", "catches", "and", "logs", "uncaught", "Exceptions", "." ]
def NoRaiseException(default_return_value=None, exception_message=''): """Returns decorator that catches and logs uncaught Exceptions. Args: default_return_value: Value to return in the case of uncaught Exception. exception_message: Message for uncaught exceptions. """ def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): try: return f(*args, **kwargs) except Exception: # pylint: disable=broad-except logging.exception(exception_message) return default_return_value return wrapper return decorator
[ "def", "NoRaiseException", "(", "default_return_value", "=", "None", ",", "exception_message", "=", "''", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", ":", "# pylint: disable=broad-except", "logging", ".", "exception", "(", "exception_message", ")", "return", "default_return_value", "return", "wrapper", "return", "decorator" ]
https://github.com/klzgrad/naiveproxy/blob/ed2c513637c77b18721fe428d7ed395b4d284c83/src/build/android/pylib/utils/decorators.py#L21-L37
google/mediapipe
e6c19885c6d3c6f410c730952aeed2852790d306
mediapipe/python/solutions/holistic.py
python
_download_oss_pose_landmark_model
(model_complexity)
Downloads the pose landmark lite/heavy model from the MediaPipe Github repo if it doesn't exist in the package.
Downloads the pose landmark lite/heavy model from the MediaPipe Github repo if it doesn't exist in the package.
[ "Downloads", "the", "pose", "landmark", "lite", "/", "heavy", "model", "from", "the", "MediaPipe", "Github", "repo", "if", "it", "doesn", "t", "exist", "in", "the", "package", "." ]
def _download_oss_pose_landmark_model(model_complexity): """Downloads the pose landmark lite/heavy model from the MediaPipe Github repo if it doesn't exist in the package.""" if model_complexity == 0: download_utils.download_oss_model( 'mediapipe/modules/pose_landmark/pose_landmark_lite.tflite') elif model_complexity == 2: download_utils.download_oss_model( 'mediapipe/modules/pose_landmark/pose_landmark_heavy.tflite')
[ "def", "_download_oss_pose_landmark_model", "(", "model_complexity", ")", ":", "if", "model_complexity", "==", "0", ":", "download_utils", ".", "download_oss_model", "(", "'mediapipe/modules/pose_landmark/pose_landmark_lite.tflite'", ")", "elif", "model_complexity", "==", "2", ":", "download_utils", ".", "download_oss_model", "(", "'mediapipe/modules/pose_landmark/pose_landmark_heavy.tflite'", ")" ]
https://github.com/google/mediapipe/blob/e6c19885c6d3c6f410c730952aeed2852790d306/mediapipe/python/solutions/holistic.py#L55-L63
nasa/fprime
595cf3682d8365943d86c1a6fe7c78f0a116acf0
Autocoders/Python/src/fprime_ac/generators/visitors/SerialCppVisitor.py
python
SerialCppVisitor.initFilesVisit
(self, obj)
Defined to generate files for generated code products. @param args: the instance of the concrete element to operation on.
Defined to generate files for generated code products.
[ "Defined", "to", "generate", "files", "for", "generated", "code", "products", "." ]
def initFilesVisit(self, obj): """ Defined to generate files for generated code products. @param args: the instance of the concrete element to operation on. """ # Build filename here... if self.__config.get("serialize", "XMLDefaultFileName") == "True": namespace = "".join(obj.get_namespace().split("::")) filename = ( namespace + obj.get_name() + self.__config.get("serialize", "SerializableCpp") ) PRINT.info( "Generating code filename: %s, using XML namespace and name attributes..." % filename ) else: xml_file = obj.get_xml_filename() x = xml_file.split(".") s = self.__config.get("serialize", "SerializableXML").split(".") l = len(s[0]) # if (x[0][-l:] == s[0]) & (x[1] == s[1]): filename = x[0].split(s[0])[0] + self.__config.get( "serialize", "SerializableCpp" ) PRINT.info( "Generating code filename: %s, using default XML filename prefix..." % filename ) else: msg = ( "XML file naming format not allowed (must be XXXSerializableAi.xml), Filename: %s" % xml_file ) PRINT.info(msg) sys.exit(-1) # Open file for writing here... DEBUG.info("Open file: %s" % filename) self.__fp = open(filename, "w") if self.__fp is None: raise Exception("Could not open %s file.") % filename DEBUG.info("Completed")
[ "def", "initFilesVisit", "(", "self", ",", "obj", ")", ":", "# Build filename here...", "if", "self", ".", "__config", ".", "get", "(", "\"serialize\"", ",", "\"XMLDefaultFileName\"", ")", "==", "\"True\"", ":", "namespace", "=", "\"\"", ".", "join", "(", "obj", ".", "get_namespace", "(", ")", ".", "split", "(", "\"::\"", ")", ")", "filename", "=", "(", "namespace", "+", "obj", ".", "get_name", "(", ")", "+", "self", ".", "__config", ".", "get", "(", "\"serialize\"", ",", "\"SerializableCpp\"", ")", ")", "PRINT", ".", "info", "(", "\"Generating code filename: %s, using XML namespace and name attributes...\"", "%", "filename", ")", "else", ":", "xml_file", "=", "obj", ".", "get_xml_filename", "(", ")", "x", "=", "xml_file", ".", "split", "(", "\".\"", ")", "s", "=", "self", ".", "__config", ".", "get", "(", "\"serialize\"", ",", "\"SerializableXML\"", ")", ".", "split", "(", "\".\"", ")", "l", "=", "len", "(", "s", "[", "0", "]", ")", "#", "if", "(", "x", "[", "0", "]", "[", "-", "l", ":", "]", "==", "s", "[", "0", "]", ")", "&", "(", "x", "[", "1", "]", "==", "s", "[", "1", "]", ")", ":", "filename", "=", "x", "[", "0", "]", ".", "split", "(", "s", "[", "0", "]", ")", "[", "0", "]", "+", "self", ".", "__config", ".", "get", "(", "\"serialize\"", ",", "\"SerializableCpp\"", ")", "PRINT", ".", "info", "(", "\"Generating code filename: %s, using default XML filename prefix...\"", "%", "filename", ")", "else", ":", "msg", "=", "(", "\"XML file naming format not allowed (must be XXXSerializableAi.xml), Filename: %s\"", "%", "xml_file", ")", "PRINT", ".", "info", "(", "msg", ")", "sys", ".", "exit", "(", "-", "1", ")", "# Open file for writing here...", "DEBUG", ".", "info", "(", "\"Open file: %s\"", "%", "filename", ")", "self", ".", "__fp", "=", "open", "(", "filename", ",", "\"w\"", ")", "if", "self", ".", "__fp", "is", "None", ":", "raise", "Exception", "(", "\"Could not open %s file.\"", ")", "%", "filename", "DEBUG", ".", "info", "(", "\"Completed\"", ")" ]
https://github.com/nasa/fprime/blob/595cf3682d8365943d86c1a6fe7c78f0a116acf0/Autocoders/Python/src/fprime_ac/generators/visitors/SerialCppVisitor.py#L211-L255
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Text.tag_unbind
(self, tagName, sequence, funcid=None)
Unbind for all characters with TAGNAME for event SEQUENCE the function identified with FUNCID.
Unbind for all characters with TAGNAME for event SEQUENCE the function identified with FUNCID.
[ "Unbind", "for", "all", "characters", "with", "TAGNAME", "for", "event", "SEQUENCE", "the", "function", "identified", "with", "FUNCID", "." ]
def tag_unbind(self, tagName, sequence, funcid=None): """Unbind for all characters with TAGNAME for event SEQUENCE the function identified with FUNCID.""" self.tk.call(self._w, 'tag', 'bind', tagName, sequence, '') if funcid: self.deletecommand(funcid)
[ "def", "tag_unbind", "(", "self", ",", "tagName", ",", "sequence", ",", "funcid", "=", "None", ")", ":", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "'tag'", ",", "'bind'", ",", "tagName", ",", "sequence", ",", "''", ")", "if", "funcid", ":", "self", ".", "deletecommand", "(", "funcid", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/lib-tk/Tkinter.py#L3105-L3110
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/client/session.py
python
BaseSession.graph
(self)
return self._graph
The graph that was launched in this session.
The graph that was launched in this session.
[ "The", "graph", "that", "was", "launched", "in", "this", "session", "." ]
def graph(self): """The graph that was launched in this session.""" return self._graph
[ "def", "graph", "(", "self", ")", ":", "return", "self", ".", "_graph" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/client/session.py#L529-L531
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/signature_serialization.py
python
find_function_to_export
(saveable_view)
return None
Function to export, None if no suitable function was found.
Function to export, None if no suitable function was found.
[ "Function", "to", "export", "None", "if", "no", "suitable", "function", "was", "found", "." ]
def find_function_to_export(saveable_view): """Function to export, None if no suitable function was found.""" # If the user did not specify signatures, check the root object for a function # that can be made into a signature. functions = saveable_view.list_functions(saveable_view.root) signature = functions.get(DEFAULT_SIGNATURE_ATTR, None) if signature is not None: return signature # TODO(andresp): Discuss removing this behaviour. It can lead to WTFs when a # user decides to annotate more functions with tf.function and suddenly # serving that model way later in the process stops working. possible_signatures = [] for function in functions.values(): concrete = _get_signature(function) if concrete is not None and _valid_signature(concrete): possible_signatures.append(concrete) if len(possible_signatures) == 1: single_function = possible_signatures[0] signature = _get_signature(single_function) if signature and _valid_signature(signature): return signature return None
[ "def", "find_function_to_export", "(", "saveable_view", ")", ":", "# If the user did not specify signatures, check the root object for a function", "# that can be made into a signature.", "functions", "=", "saveable_view", ".", "list_functions", "(", "saveable_view", ".", "root", ")", "signature", "=", "functions", ".", "get", "(", "DEFAULT_SIGNATURE_ATTR", ",", "None", ")", "if", "signature", "is", "not", "None", ":", "return", "signature", "# TODO(andresp): Discuss removing this behaviour. It can lead to WTFs when a", "# user decides to annotate more functions with tf.function and suddenly", "# serving that model way later in the process stops working.", "possible_signatures", "=", "[", "]", "for", "function", "in", "functions", ".", "values", "(", ")", ":", "concrete", "=", "_get_signature", "(", "function", ")", "if", "concrete", "is", "not", "None", "and", "_valid_signature", "(", "concrete", ")", ":", "possible_signatures", ".", "append", "(", "concrete", ")", "if", "len", "(", "possible_signatures", ")", "==", "1", ":", "single_function", "=", "possible_signatures", "[", "0", "]", "signature", "=", "_get_signature", "(", "single_function", ")", "if", "signature", "and", "_valid_signature", "(", "signature", ")", ":", "return", "signature", "return", "None" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/saved_model/signature_serialization.py#L60-L82
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests_aws4auth/six.py
python
_add_doc
(func, doc)
Add documentation to a function.
Add documentation to a function.
[ "Add", "documentation", "to", "a", "function", "." ]
def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc
[ "def", "_add_doc", "(", "func", ",", "doc", ")", ":", "func", ".", "__doc__", "=", "doc" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/requests_aws4auth/six.py#L75-L77
google/or-tools
2cb85b4eead4c38e1c54b48044f92087cf165bce
ortools/sat/samples/interval_sample_sat.py
python
IntervalSampleSat
()
Showcases how to build interval variables.
Showcases how to build interval variables.
[ "Showcases", "how", "to", "build", "interval", "variables", "." ]
def IntervalSampleSat(): """Showcases how to build interval variables.""" model = cp_model.CpModel() horizon = 100 # An interval can be created from three affine expressions. start_var = model.NewIntVar(0, horizon, 'start') duration = 10 # Python cp/sat code accept integer variables or constants. end_var = model.NewIntVar(0, horizon, 'end') interval_var = model.NewIntervalVar(start_var, duration, end_var + 2, 'interval') print(f'interval = {repr(interval_var)}') # If the size is fixed, a simpler version uses the start expression and the # size. fixed_size_interval_var = model.NewFixedSizeIntervalVar( start_var, 10, 'fixed_size_interval_var') print(f'fixed_size_interval_var = {repr(fixed_size_interval_var)}') # A fixed interval can be created using the same API. fixed_interval = model.NewFixedSizeIntervalVar(5, 10, 'fixed_interval') print(f'fixed_interval = {repr(fixed_interval)}')
[ "def", "IntervalSampleSat", "(", ")", ":", "model", "=", "cp_model", ".", "CpModel", "(", ")", "horizon", "=", "100", "# An interval can be created from three affine expressions.", "start_var", "=", "model", ".", "NewIntVar", "(", "0", ",", "horizon", ",", "'start'", ")", "duration", "=", "10", "# Python cp/sat code accept integer variables or constants.", "end_var", "=", "model", ".", "NewIntVar", "(", "0", ",", "horizon", ",", "'end'", ")", "interval_var", "=", "model", ".", "NewIntervalVar", "(", "start_var", ",", "duration", ",", "end_var", "+", "2", ",", "'interval'", ")", "print", "(", "f'interval = {repr(interval_var)}'", ")", "# If the size is fixed, a simpler version uses the start expression and the", "# size.", "fixed_size_interval_var", "=", "model", ".", "NewFixedSizeIntervalVar", "(", "start_var", ",", "10", ",", "'fixed_size_interval_var'", ")", "print", "(", "f'fixed_size_interval_var = {repr(fixed_size_interval_var)}'", ")", "# A fixed interval can be created using the same API.", "fixed_interval", "=", "model", ".", "NewFixedSizeIntervalVar", "(", "5", ",", "10", ",", "'fixed_interval'", ")", "print", "(", "f'fixed_interval = {repr(fixed_interval)}'", ")" ]
https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/sat/samples/interval_sample_sat.py#L19-L41
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/ftplib.py
python
FTP.dir
(self, *args)
List a directory in long form. By default list current directory to stdout. Optional last argument is callback function; all non-empty arguments before it are concatenated to the LIST command. (This *should* only be used for a pathname.)
List a directory in long form. By default list current directory to stdout. Optional last argument is callback function; all non-empty arguments before it are concatenated to the LIST command. (This *should* only be used for a pathname.)
[ "List", "a", "directory", "in", "long", "form", ".", "By", "default", "list", "current", "directory", "to", "stdout", ".", "Optional", "last", "argument", "is", "callback", "function", ";", "all", "non", "-", "empty", "arguments", "before", "it", "are", "concatenated", "to", "the", "LIST", "command", ".", "(", "This", "*", "should", "*", "only", "be", "used", "for", "a", "pathname", ".", ")" ]
def dir(self, *args): '''List a directory in long form. By default list current directory to stdout. Optional last argument is callback function; all non-empty arguments before it are concatenated to the LIST command. (This *should* only be used for a pathname.)''' cmd = 'LIST' func = None if args[-1:] and type(args[-1]) != type(''): args, func = args[:-1], args[-1] for arg in args: if arg: cmd = cmd + (' ' + arg) self.retrlines(cmd, func)
[ "def", "dir", "(", "self", ",", "*", "args", ")", ":", "cmd", "=", "'LIST'", "func", "=", "None", "if", "args", "[", "-", "1", ":", "]", "and", "type", "(", "args", "[", "-", "1", "]", ")", "!=", "type", "(", "''", ")", ":", "args", ",", "func", "=", "args", "[", ":", "-", "1", "]", ",", "args", "[", "-", "1", "]", "for", "arg", "in", "args", ":", "if", "arg", ":", "cmd", "=", "cmd", "+", "(", "' '", "+", "arg", ")", "self", ".", "retrlines", "(", "cmd", ",", "func", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/ftplib.py#L562-L575
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/third_party/pyserial/serial/urlhandler/protocol_hwgrep.py
python
Serial.setPort
(self, value)
translate port name before storing it
translate port name before storing it
[ "translate", "port", "name", "before", "storing", "it" ]
def setPort(self, value): """translate port name before storing it""" if isinstance(value, basestring) and value.startswith('hwgrep://'): serial.Serial.setPort(self, self.fromURL(value)) else: serial.Serial.setPort(self, value)
[ "def", "setPort", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "basestring", ")", "and", "value", ".", "startswith", "(", "'hwgrep://'", ")", ":", "serial", ".", "Serial", ".", "setPort", "(", "self", ",", "self", ".", "fromURL", "(", "value", ")", ")", "else", ":", "serial", ".", "Serial", ".", "setPort", "(", "self", ",", "value", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/pyserial/serial/urlhandler/protocol_hwgrep.py#L20-L25
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
configs/example/read_config.py
python
ConfigManager.parse_port_name
(self, port)
return (peer, self.objects_by_name[peer], peer_port, index)
Parse the name of a port
Parse the name of a port
[ "Parse", "the", "name", "of", "a", "port" ]
def parse_port_name(self, port): """Parse the name of a port""" m = re.match('(.*)\.([^.\[]+)(\[(\d+)\])?', port) peer, peer_port, whole_index, index = m.groups() if index is not None: index = int(index) else: index = 0 return (peer, self.objects_by_name[peer], peer_port, index)
[ "def", "parse_port_name", "(", "self", ",", "port", ")", ":", "m", "=", "re", ".", "match", "(", "'(.*)\\.([^.\\[]+)(\\[(\\d+)\\])?'", ",", "port", ")", "peer", ",", "peer_port", ",", "whole_index", ",", "index", "=", "m", ".", "groups", "(", ")", "if", "index", "is", "not", "None", ":", "index", "=", "int", "(", "index", ")", "else", ":", "index", "=", "0", "return", "(", "peer", ",", "self", ".", "objects_by_name", "[", "peer", "]", ",", "peer_port", ",", "index", ")" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/configs/example/read_config.py#L261-L271
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/client/session.py
python
SessionInterface.partial_run
(self, handle, fetches, feed_dict=None)
Continues the execution with additional feeds and fetches.
Continues the execution with additional feeds and fetches.
[ "Continues", "the", "execution", "with", "additional", "feeds", "and", "fetches", "." ]
def partial_run(self, handle, fetches, feed_dict=None): """Continues the execution with additional feeds and fetches.""" raise NotImplementedError('partial_run')
[ "def", "partial_run", "(", "self", ",", "handle", ",", "fetches", ",", "feed_dict", "=", "None", ")", ":", "raise", "NotImplementedError", "(", "'partial_run'", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/client/session.py#L62-L64
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
ListEvent.GetPoint
(*args, **kwargs)
return _controls_.ListEvent_GetPoint(*args, **kwargs)
GetPoint(self) -> Point
GetPoint(self) -> Point
[ "GetPoint", "(", "self", ")", "-", ">", "Point" ]
def GetPoint(*args, **kwargs): """GetPoint(self) -> Point""" return _controls_.ListEvent_GetPoint(*args, **kwargs)
[ "def", "GetPoint", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListEvent_GetPoint", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L4329-L4331
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/math/optimize.py
python
OptimizationProblemBuilder.getBounds
(self)
return [self.variableBounds.get(v.name,((-inf,inf) if v.type.is_scalar() else ([-inf]*v.type.size,[inf]*v.type.size))) for v in self.optimizationVariables]
Returns optimization varable bounds as a list of (xmin,xmax) pairs. None is returned if the problem is unconstrained
Returns optimization varable bounds as a list of (xmin,xmax) pairs. None is returned if the problem is unconstrained
[ "Returns", "optimization", "varable", "bounds", "as", "a", "list", "of", "(", "xmin", "xmax", ")", "pairs", ".", "None", "is", "returned", "if", "the", "problem", "is", "unconstrained" ]
def getBounds(self): """Returns optimization varable bounds as a list of (xmin,xmax) pairs. None is returned if the problem is unconstrained""" inf = float('inf') if len(self.variableBounds) == 0 or not any(v.name in self.variableBounds for v in self.optimizationVariables): return None return [self.variableBounds.get(v.name,((-inf,inf) if v.type.is_scalar() else ([-inf]*v.type.size,[inf]*v.type.size))) for v in self.optimizationVariables]
[ "def", "getBounds", "(", "self", ")", ":", "inf", "=", "float", "(", "'inf'", ")", "if", "len", "(", "self", ".", "variableBounds", ")", "==", "0", "or", "not", "any", "(", "v", ".", "name", "in", "self", ".", "variableBounds", "for", "v", "in", "self", ".", "optimizationVariables", ")", ":", "return", "None", "return", "[", "self", ".", "variableBounds", ".", "get", "(", "v", ".", "name", ",", "(", "(", "-", "inf", ",", "inf", ")", "if", "v", ".", "type", ".", "is_scalar", "(", ")", "else", "(", "[", "-", "inf", "]", "*", "v", ".", "type", ".", "size", ",", "[", "inf", "]", "*", "v", ".", "type", ".", "size", ")", ")", ")", "for", "v", "in", "self", ".", "optimizationVariables", "]" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/optimize.py#L1332-L1338
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pydoc.py
python
_adjust_cli_sys_path
()
Ensures current directory is on sys.path, and __main__ directory is not. Exception: __main__ dir is left alone if it's also pydoc's directory.
Ensures current directory is on sys.path, and __main__ directory is not.
[ "Ensures", "current", "directory", "is", "on", "sys", ".", "path", "and", "__main__", "directory", "is", "not", "." ]
def _adjust_cli_sys_path(): """Ensures current directory is on sys.path, and __main__ directory is not. Exception: __main__ dir is left alone if it's also pydoc's directory. """ revised_path = _get_revised_path(sys.path, sys.argv[0]) if revised_path is not None: sys.path[:] = revised_path
[ "def", "_adjust_cli_sys_path", "(", ")", ":", "revised_path", "=", "_get_revised_path", "(", "sys", ".", "path", ",", "sys", ".", "argv", "[", "0", "]", ")", "if", "revised_path", "is", "not", "None", ":", "sys", ".", "path", "[", ":", "]", "=", "revised_path" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pydoc.py#L2650-L2657
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/target.py
python
CUDATargetContext.insert_addrspace_conv
(self, builder, ptr, addrspace)
return builder.call(conv, [ptr])
Perform addrspace conversion according to the NVVM spec
Perform addrspace conversion according to the NVVM spec
[ "Perform", "addrspace", "conversion", "according", "to", "the", "NVVM", "spec" ]
def insert_addrspace_conv(self, builder, ptr, addrspace): """ Perform addrspace conversion according to the NVVM spec """ lmod = builder.module base_type = ptr.type.pointee conv = nvvmutils.insert_addrspace_conv(lmod, base_type, addrspace) return builder.call(conv, [ptr])
[ "def", "insert_addrspace_conv", "(", "self", ",", "builder", ",", "ptr", ",", "addrspace", ")", ":", "lmod", "=", "builder", ".", "module", "base_type", "=", "ptr", ".", "type", ".", "pointee", "conv", "=", "nvvmutils", ".", "insert_addrspace_conv", "(", "lmod", ",", "base_type", ",", "addrspace", ")", "return", "builder", ".", "call", "(", "conv", ",", "[", "ptr", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/cuda/target.py#L234-L241
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
DirPickerCtrl.Create
(*args, **kwargs)
return _controls_.DirPickerCtrl_Create(*args, **kwargs)
Create(self, Window parent, int id=-1, String path=EmptyString, String message=DirSelectorPromptStr, Point pos=DefaultPosition, Size size=DefaultSize, long style=DIRP_DEFAULT_STYLE, Validator validator=DefaultValidator, String name=DirPickerCtrlNameStr) -> bool
Create(self, Window parent, int id=-1, String path=EmptyString, String message=DirSelectorPromptStr, Point pos=DefaultPosition, Size size=DefaultSize, long style=DIRP_DEFAULT_STYLE, Validator validator=DefaultValidator, String name=DirPickerCtrlNameStr) -> bool
[ "Create", "(", "self", "Window", "parent", "int", "id", "=", "-", "1", "String", "path", "=", "EmptyString", "String", "message", "=", "DirSelectorPromptStr", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "DIRP_DEFAULT_STYLE", "Validator", "validator", "=", "DefaultValidator", "String", "name", "=", "DirPickerCtrlNameStr", ")", "-", ">", "bool" ]
def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String path=EmptyString, String message=DirSelectorPromptStr, Point pos=DefaultPosition, Size size=DefaultSize, long style=DIRP_DEFAULT_STYLE, Validator validator=DefaultValidator, String name=DirPickerCtrlNameStr) -> bool """ return _controls_.DirPickerCtrl_Create(*args, **kwargs)
[ "def", "Create", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "DirPickerCtrl_Create", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L7165-L7173
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/ultimatelistctrl.py
python
UltimateListHeaderWindow.OnEnterWindow
(self, event)
Handles the ``wx.EVT_ENTER_WINDOW`` event for :class:`UltimateListHeaderWindow`. :param `event`: a :class:`MouseEvent` event to be processed.
Handles the ``wx.EVT_ENTER_WINDOW`` event for :class:`UltimateListHeaderWindow`.
[ "Handles", "the", "wx", ".", "EVT_ENTER_WINDOW", "event", "for", ":", "class", ":", "UltimateListHeaderWindow", "." ]
def OnEnterWindow(self, event): """ Handles the ``wx.EVT_ENTER_WINDOW`` event for :class:`UltimateListHeaderWindow`. :param `event`: a :class:`MouseEvent` event to be processed. """ x, y = self._owner.CalcUnscrolledPosition(*self.ScreenToClient(wx.GetMousePosition())) column = self.HitTestColumn(x, y) if _VERSION_STRING < "2.9": leftDown = wx.GetMouseState().LeftDown() else: leftDown = wx.GetMouseState().LeftIsDown() self._leftDown = leftDown self._enter = column >= 0 and column < self._owner.GetColumnCount() self._currentColumn = column self.Refresh()
[ "def", "OnEnterWindow", "(", "self", ",", "event", ")", ":", "x", ",", "y", "=", "self", ".", "_owner", ".", "CalcUnscrolledPosition", "(", "*", "self", ".", "ScreenToClient", "(", "wx", ".", "GetMousePosition", "(", ")", ")", ")", "column", "=", "self", ".", "HitTestColumn", "(", "x", ",", "y", ")", "if", "_VERSION_STRING", "<", "\"2.9\"", ":", "leftDown", "=", "wx", ".", "GetMouseState", "(", ")", ".", "LeftDown", "(", ")", "else", ":", "leftDown", "=", "wx", ".", "GetMouseState", "(", ")", ".", "LeftIsDown", "(", ")", "self", ".", "_leftDown", "=", "leftDown", "self", ".", "_enter", "=", "column", ">=", "0", "and", "column", "<", "self", ".", "_owner", ".", "GetColumnCount", "(", ")", "self", ".", "_currentColumn", "=", "column", "self", ".", "Refresh", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/ultimatelistctrl.py#L5638-L5656
simsong/bulk_extractor
738911df22b7066ca9e1662f4131fb44090a4196
python/be_grapher.py
python
plot_cpu
(*, reports, filename)
Read reports and plot the CPU
Read reports and plot the CPU
[ "Read", "reports", "and", "plot", "the", "CPU" ]
def plot_cpu(*, reports, filename): """Read reports and plot the CPU""" fig = plt.figure() ax = fig.add_axes((0.1, 0.2, 0.8, 0.7)) ax.set_ylabel("% of CPU utilized") ax.set_xlabel("Seconds from start of run") ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.set_ylim(ymin=0,ymax=400) ymax = 100 lines = [] legends = [] for report in reports: r = BulkReport(report) xyvals = r.cpu_track() # Extract timestamps and convert to seconds from beginning of run xvals = [xy[0] for xy in xyvals] xmin = min(xvals) xvals = [ (x-xmin).total_seconds() for x in xvals] # Extract CPU% and find max val yvals = [xy[1] for xy in xyvals] ymax = max([ymax] + yvals) # Plot and retain handle line, = plt.plot( xvals, yvals, label='report') lines.append(line) ax.legend( handles=lines ) # draw legends ax.set_ylim(ymin=0, ymax=math.ceil(ymax/100)*100) # set ymax plt.savefig(filename, format='pdf')
[ "def", "plot_cpu", "(", "*", ",", "reports", ",", "filename", ")", ":", "fig", "=", "plt", ".", "figure", "(", ")", "ax", "=", "fig", ".", "add_axes", "(", "(", "0.1", ",", "0.2", ",", "0.8", ",", "0.7", ")", ")", "ax", ".", "set_ylabel", "(", "\"% of CPU utilized\"", ")", "ax", ".", "set_xlabel", "(", "\"Seconds from start of run\"", ")", "ax", ".", "spines", "[", "'right'", "]", ".", "set_color", "(", "'none'", ")", "ax", ".", "spines", "[", "'top'", "]", ".", "set_color", "(", "'none'", ")", "ax", ".", "xaxis", ".", "set_ticks_position", "(", "'bottom'", ")", "ax", ".", "yaxis", ".", "set_ticks_position", "(", "'left'", ")", "ax", ".", "set_ylim", "(", "ymin", "=", "0", ",", "ymax", "=", "400", ")", "ymax", "=", "100", "lines", "=", "[", "]", "legends", "=", "[", "]", "for", "report", "in", "reports", ":", "r", "=", "BulkReport", "(", "report", ")", "xyvals", "=", "r", ".", "cpu_track", "(", ")", "# Extract timestamps and convert to seconds from beginning of run", "xvals", "=", "[", "xy", "[", "0", "]", "for", "xy", "in", "xyvals", "]", "xmin", "=", "min", "(", "xvals", ")", "xvals", "=", "[", "(", "x", "-", "xmin", ")", ".", "total_seconds", "(", ")", "for", "x", "in", "xvals", "]", "# Extract CPU% and find max val", "yvals", "=", "[", "xy", "[", "1", "]", "for", "xy", "in", "xyvals", "]", "ymax", "=", "max", "(", "[", "ymax", "]", "+", "yvals", ")", "# Plot and retain handle", "line", ",", "=", "plt", ".", "plot", "(", "xvals", ",", "yvals", ",", "label", "=", "'report'", ")", "lines", ".", "append", "(", "line", ")", "ax", ".", "legend", "(", "handles", "=", "lines", ")", "# draw legends", "ax", ".", "set_ylim", "(", "ymin", "=", "0", ",", "ymax", "=", "math", ".", "ceil", "(", "ymax", "/", "100", ")", "*", "100", ")", "# set ymax", "plt", ".", "savefig", "(", "filename", ",", "format", "=", "'pdf'", ")" ]
https://github.com/simsong/bulk_extractor/blob/738911df22b7066ca9e1662f4131fb44090a4196/python/be_grapher.py#L68-L103
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/coremodules/simulation/sumo.py
python
SumoTraci.do
(self)
Called by run after is_ready verification
Called by run after is_ready verification
[ "Called", "by", "run", "after", "is_ready", "verification" ]
def do(self): """ Called by run after is_ready verification """ Sumo.do(self)
[ "def", "do", "(", "self", ")", ":", "Sumo", ".", "do", "(", "self", ")" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/coremodules/simulation/sumo.py#L1242-L1247
yushroom/FishEngine
a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9
Script/reflect/clang/cindex.py
python
Cursor.underlying_typedef_type
(self)
return self._underlying_type
Return the underlying type of a typedef declaration. Returns a Type for the typedef this cursor is a declaration for. If the current cursor is not a typedef, this raises.
Return the underlying type of a typedef declaration.
[ "Return", "the", "underlying", "type", "of", "a", "typedef", "declaration", "." ]
def underlying_typedef_type(self): """Return the underlying type of a typedef declaration. Returns a Type for the typedef this cursor is a declaration for. If the current cursor is not a typedef, this raises. """ if not hasattr(self, '_underlying_type'): assert self.kind.is_declaration() self._underlying_type = \ conf.lib.clang_getTypedefDeclUnderlyingType(self) return self._underlying_type
[ "def", "underlying_typedef_type", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_underlying_type'", ")", ":", "assert", "self", ".", "kind", ".", "is_declaration", "(", ")", "self", ".", "_underlying_type", "=", "conf", ".", "lib", ".", "clang_getTypedefDeclUnderlyingType", "(", "self", ")", "return", "self", ".", "_underlying_type" ]
https://github.com/yushroom/FishEngine/blob/a4b9fb9b0a6dc202f7990e75f4b7d8d5163209d9/Script/reflect/clang/cindex.py#L1535-L1546
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/training/tracking/data_structures.py
python
List.__init__
(self, *args, **kwargs)
Construct a new sequence. Arguments are passed to `list()`.
Construct a new sequence. Arguments are passed to `list()`.
[ "Construct", "a", "new", "sequence", ".", "Arguments", "are", "passed", "to", "list", "()", "." ]
def __init__(self, *args, **kwargs): """Construct a new sequence. Arguments are passed to `list()`.""" super(List, self).__init__() self._storage = self._make_storage(*args, **kwargs) for index, element in enumerate(self._storage): self._storage[index] = self._track_value( element, name=self._name_element(index))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "super", "(", "List", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "_storage", "=", "self", ".", "_make_storage", "(", "*", "args", ",", "*", "*", "kwargs", ")", "for", "index", ",", "element", "in", "enumerate", "(", "self", ".", "_storage", ")", ":", "self", ".", "_storage", "[", "index", "]", "=", "self", ".", "_track_value", "(", "element", ",", "name", "=", "self", ".", "_name_element", "(", "index", ")", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/training/tracking/data_structures.py#L368-L374
microsoft/clang
86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5
tools/scan-build-py/libear/__init__.py
python
build_libear
(compiler, dst_dir)
Returns the full path to the 'libear' library.
Returns the full path to the 'libear' library.
[ "Returns", "the", "full", "path", "to", "the", "libear", "library", "." ]
def build_libear(compiler, dst_dir): """ Returns the full path to the 'libear' library. """ try: src_dir = os.path.dirname(os.path.realpath(__file__)) toolset = make_toolset(src_dir) toolset.set_compiler(compiler) toolset.set_language_standard('c99') toolset.add_definitions(['-D_GNU_SOURCE']) configure = do_configure(toolset) configure.check_function_exists('execve', 'HAVE_EXECVE') configure.check_function_exists('execv', 'HAVE_EXECV') configure.check_function_exists('execvpe', 'HAVE_EXECVPE') configure.check_function_exists('execvp', 'HAVE_EXECVP') configure.check_function_exists('execvP', 'HAVE_EXECVP2') configure.check_function_exists('exect', 'HAVE_EXECT') configure.check_function_exists('execl', 'HAVE_EXECL') configure.check_function_exists('execlp', 'HAVE_EXECLP') configure.check_function_exists('execle', 'HAVE_EXECLE') configure.check_function_exists('posix_spawn', 'HAVE_POSIX_SPAWN') configure.check_function_exists('posix_spawnp', 'HAVE_POSIX_SPAWNP') configure.check_symbol_exists('_NSGetEnviron', 'crt_externs.h', 'HAVE_NSGETENVIRON') configure.write_by_template( os.path.join(src_dir, 'config.h.in'), os.path.join(dst_dir, 'config.h')) target = create_shared_library('ear', toolset) target.add_include(dst_dir) target.add_sources('ear.c') target.link_against(toolset.dl_libraries()) target.link_against(['pthread']) target.build_release(dst_dir) return os.path.join(dst_dir, target.name) except Exception: logging.info("Could not build interception library.", exc_info=True) return None
[ "def", "build_libear", "(", "compiler", ",", "dst_dir", ")", ":", "try", ":", "src_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", "toolset", "=", "make_toolset", "(", "src_dir", ")", "toolset", ".", "set_compiler", "(", "compiler", ")", "toolset", ".", "set_language_standard", "(", "'c99'", ")", "toolset", ".", "add_definitions", "(", "[", "'-D_GNU_SOURCE'", "]", ")", "configure", "=", "do_configure", "(", "toolset", ")", "configure", ".", "check_function_exists", "(", "'execve'", ",", "'HAVE_EXECVE'", ")", "configure", ".", "check_function_exists", "(", "'execv'", ",", "'HAVE_EXECV'", ")", "configure", ".", "check_function_exists", "(", "'execvpe'", ",", "'HAVE_EXECVPE'", ")", "configure", ".", "check_function_exists", "(", "'execvp'", ",", "'HAVE_EXECVP'", ")", "configure", ".", "check_function_exists", "(", "'execvP'", ",", "'HAVE_EXECVP2'", ")", "configure", ".", "check_function_exists", "(", "'exect'", ",", "'HAVE_EXECT'", ")", "configure", ".", "check_function_exists", "(", "'execl'", ",", "'HAVE_EXECL'", ")", "configure", ".", "check_function_exists", "(", "'execlp'", ",", "'HAVE_EXECLP'", ")", "configure", ".", "check_function_exists", "(", "'execle'", ",", "'HAVE_EXECLE'", ")", "configure", ".", "check_function_exists", "(", "'posix_spawn'", ",", "'HAVE_POSIX_SPAWN'", ")", "configure", ".", "check_function_exists", "(", "'posix_spawnp'", ",", "'HAVE_POSIX_SPAWNP'", ")", "configure", ".", "check_symbol_exists", "(", "'_NSGetEnviron'", ",", "'crt_externs.h'", ",", "'HAVE_NSGETENVIRON'", ")", "configure", ".", "write_by_template", "(", "os", ".", "path", ".", "join", "(", "src_dir", ",", "'config.h.in'", ")", ",", "os", ".", "path", ".", "join", "(", "dst_dir", ",", "'config.h'", ")", ")", "target", "=", "create_shared_library", "(", "'ear'", ",", "toolset", ")", "target", ".", "add_include", "(", "dst_dir", ")", "target", ".", "add_sources", "(", "'ear.c'", ")", "target", ".", "link_against", "(", "toolset", ".", "dl_libraries", "(", ")", ")", "target", ".", "link_against", "(", "[", "'pthread'", "]", ")", "target", ".", "build_release", "(", "dst_dir", ")", "return", "os", ".", "path", ".", "join", "(", "dst_dir", ",", "target", ".", "name", ")", "except", "Exception", ":", "logging", ".", "info", "(", "\"Could not build interception library.\"", ",", "exc_info", "=", "True", ")", "return", "None" ]
https://github.com/microsoft/clang/blob/86d4513d3e0daa4d5a29b0b1de7c854ca15f9fe5/tools/scan-build-py/libear/__init__.py#L20-L59
Manu343726/siplasplas
9fae7559f87087cf8ef34f04bd1e774b84b2ea9c
reference/cindex.py
python
Cursor.location
(self)
return self._loc
Return the source location (the starting character) of the entity pointed at by the cursor.
Return the source location (the starting character) of the entity pointed at by the cursor.
[ "Return", "the", "source", "location", "(", "the", "starting", "character", ")", "of", "the", "entity", "pointed", "at", "by", "the", "cursor", "." ]
def location(self): """ Return the source location (the starting character) of the entity pointed at by the cursor. """ if not hasattr(self, '_loc'): self._loc = conf.lib.clang_getCursorLocation(self) return self._loc
[ "def", "location", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_loc'", ")", ":", "self", ".", "_loc", "=", "conf", ".", "lib", ".", "clang_getCursorLocation", "(", "self", ")", "return", "self", ".", "_loc" ]
https://github.com/Manu343726/siplasplas/blob/9fae7559f87087cf8ef34f04bd1e774b84b2ea9c/reference/cindex.py#L1284-L1292
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
benchmarks/distributed/rpc/parameter_server/server/server.py
python
ParameterServerBase.reset_state
()
return
r""" A method to be implemented by child class that will reset the server state.
r""" A method to be implemented by child class that will reset the server state.
[ "r", "A", "method", "to", "be", "implemented", "by", "child", "class", "that", "will", "reset", "the", "server", "state", "." ]
def reset_state(): r""" A method to be implemented by child class that will reset the server state. """ return
[ "def", "reset_state", "(", ")", ":", "return" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/benchmarks/distributed/rpc/parameter_server/server/server.py#L47-L52
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/lookup/lookup_ops.py
python
index_to_string
(tensor, mapping, default_value="UNK", name=None)
return table.lookup(tensor)
Maps `tensor` of indices into string values based on `mapping`. This operation converts `int64` indices into string values. The mapping is initialized from a string `mapping` tensor where each element is a value and the corresponding index within the tensor is the key. Any input which does not have a corresponding index in 'mapping' (an out-of-vocabulary entry) is assigned the `default_value` The underlying table must be initialized by calling `session.run(tf.compat.v1.tables_initializer)` once. For example: ```python mapping_string = tf.constant(["emerson", "lake", "palmer"]) indices = tf.constant([1, 5], tf.int64) values = tf.contrib.lookup.index_to_string( indices, mapping=mapping_string, default_value="UNKNOWN") ... tf.compat.v1.tables_initializer().run() values.eval() ==> ["lake", "UNKNOWN"] ``` Args: tensor: A `int64` `Tensor` with the indices to map to strings. mapping: A 1-D string `Tensor` that specifies the strings to map from indices. default_value: The string value to use for out-of-vocabulary indices. name: A name for this op (optional). Returns: The strings values associated to the indices. The resultant dense feature value tensor has the same shape as the corresponding `indices`.
Maps `tensor` of indices into string values based on `mapping`.
[ "Maps", "tensor", "of", "indices", "into", "string", "values", "based", "on", "mapping", "." ]
def index_to_string(tensor, mapping, default_value="UNK", name=None): """Maps `tensor` of indices into string values based on `mapping`. This operation converts `int64` indices into string values. The mapping is initialized from a string `mapping` tensor where each element is a value and the corresponding index within the tensor is the key. Any input which does not have a corresponding index in 'mapping' (an out-of-vocabulary entry) is assigned the `default_value` The underlying table must be initialized by calling `session.run(tf.compat.v1.tables_initializer)` once. For example: ```python mapping_string = tf.constant(["emerson", "lake", "palmer"]) indices = tf.constant([1, 5], tf.int64) values = tf.contrib.lookup.index_to_string( indices, mapping=mapping_string, default_value="UNKNOWN") ... tf.compat.v1.tables_initializer().run() values.eval() ==> ["lake", "UNKNOWN"] ``` Args: tensor: A `int64` `Tensor` with the indices to map to strings. mapping: A 1-D string `Tensor` that specifies the strings to map from indices. default_value: The string value to use for out-of-vocabulary indices. name: A name for this op (optional). Returns: The strings values associated to the indices. The resultant dense feature value tensor has the same shape as the corresponding `indices`. """ table = index_to_string_table_from_tensor( mapping=mapping, default_value=default_value, name=name) return table.lookup(tensor)
[ "def", "index_to_string", "(", "tensor", ",", "mapping", ",", "default_value", "=", "\"UNK\"", ",", "name", "=", "None", ")", ":", "table", "=", "index_to_string_table_from_tensor", "(", "mapping", "=", "mapping", ",", "default_value", "=", "default_value", ",", "name", "=", "name", ")", "return", "table", ".", "lookup", "(", "tensor", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/lookup/lookup_ops.py#L252-L291
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/misc_util.py
python
all_strings
(lst)
return True
Return True if all items in lst are string objects.
Return True if all items in lst are string objects.
[ "Return", "True", "if", "all", "items", "in", "lst", "are", "string", "objects", "." ]
def all_strings(lst): """Return True if all items in lst are string objects. """ for item in lst: if not is_string(item): return False return True
[ "def", "all_strings", "(", "lst", ")", ":", "for", "item", "in", "lst", ":", "if", "not", "is_string", "(", "item", ")", ":", "return", "False", "return", "True" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/distutils/misc_util.py#L398-L403
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/webkit.py
python
WebKitCtrl.Stop
(*args, **kwargs)
return _webkit.WebKitCtrl_Stop(*args, **kwargs)
Stop(self)
Stop(self)
[ "Stop", "(", "self", ")" ]
def Stop(*args, **kwargs): """Stop(self)""" return _webkit.WebKitCtrl_Stop(*args, **kwargs)
[ "def", "Stop", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_webkit", ".", "WebKitCtrl_Stop", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/webkit.py#L108-L110
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/plotting/_core.py
python
scatter_plot
(data, x, y, by=None, ax=None, figsize=None, grid=False, **kwargs)
return fig
Make a scatter plot from two DataFrame columns Parameters ---------- data : DataFrame x : Column name for the x-axis values y : Column name for the y-axis values ax : Matplotlib axis object figsize : A tuple (width, height) in inches grid : Setting this to True will show the grid kwargs : other plotting keyword arguments To be passed to scatter function Returns ------- fig : matplotlib.Figure
Make a scatter plot from two DataFrame columns
[ "Make", "a", "scatter", "plot", "from", "two", "DataFrame", "columns" ]
def scatter_plot(data, x, y, by=None, ax=None, figsize=None, grid=False, **kwargs): """ Make a scatter plot from two DataFrame columns Parameters ---------- data : DataFrame x : Column name for the x-axis values y : Column name for the y-axis values ax : Matplotlib axis object figsize : A tuple (width, height) in inches grid : Setting this to True will show the grid kwargs : other plotting keyword arguments To be passed to scatter function Returns ------- fig : matplotlib.Figure """ import matplotlib.pyplot as plt kwargs.setdefault('edgecolors', 'none') def plot_group(group, ax): xvals = group[x].values yvals = group[y].values ax.scatter(xvals, yvals, **kwargs) ax.grid(grid) if by is not None: fig = _grouped_plot(plot_group, data, by=by, figsize=figsize, ax=ax) else: if ax is None: fig = plt.figure() ax = fig.add_subplot(111) else: fig = ax.get_figure() plot_group(data, ax) ax.set_ylabel(pprint_thing(y)) ax.set_xlabel(pprint_thing(x)) ax.grid(grid) return fig
[ "def", "scatter_plot", "(", "data", ",", "x", ",", "y", ",", "by", "=", "None", ",", "ax", "=", "None", ",", "figsize", "=", "None", ",", "grid", "=", "False", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "kwargs", ".", "setdefault", "(", "'edgecolors'", ",", "'none'", ")", "def", "plot_group", "(", "group", ",", "ax", ")", ":", "xvals", "=", "group", "[", "x", "]", ".", "values", "yvals", "=", "group", "[", "y", "]", ".", "values", "ax", ".", "scatter", "(", "xvals", ",", "yvals", ",", "*", "*", "kwargs", ")", "ax", ".", "grid", "(", "grid", ")", "if", "by", "is", "not", "None", ":", "fig", "=", "_grouped_plot", "(", "plot_group", ",", "data", ",", "by", "=", "by", ",", "figsize", "=", "figsize", ",", "ax", "=", "ax", ")", "else", ":", "if", "ax", "is", "None", ":", "fig", "=", "plt", ".", "figure", "(", ")", "ax", "=", "fig", ".", "add_subplot", "(", "111", ")", "else", ":", "fig", "=", "ax", ".", "get_figure", "(", ")", "plot_group", "(", "data", ",", "ax", ")", "ax", ".", "set_ylabel", "(", "pprint_thing", "(", "y", ")", ")", "ax", ".", "set_xlabel", "(", "pprint_thing", "(", "x", ")", ")", "ax", ".", "grid", "(", "grid", ")", "return", "fig" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/plotting/_core.py#L2259-L2303
GJDuck/LowFat
ecf6a0f0fa1b73a27a626cf493cc39e477b6faea
llvm-4.0.0.src/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py
python
_CppLintState.SetVerboseLevel
(self, level)
return last_verbose_level
Sets the module's verbosity, and returns the previous setting.
Sets the module's verbosity, and returns the previous setting.
[ "Sets", "the", "module", "s", "verbosity", "and", "returns", "the", "previous", "setting", "." ]
def SetVerboseLevel(self, level): """Sets the module's verbosity, and returns the previous setting.""" last_verbose_level = self.verbose_level self.verbose_level = level return last_verbose_level
[ "def", "SetVerboseLevel", "(", "self", ",", "level", ")", ":", "last_verbose_level", "=", "self", ".", "verbose_level", "self", ".", "verbose_level", "=", "level", "return", "last_verbose_level" ]
https://github.com/GJDuck/LowFat/blob/ecf6a0f0fa1b73a27a626cf493cc39e477b6faea/llvm-4.0.0.src/projects/compiler-rt/lib/sanitizer_common/scripts/cpplint.py#L571-L575
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/probability/distribution/poisson.py
python
Poisson._cdf
(self, value, rate=None)
return self.select(comp, zeros, cdf)
r""" Cumulative distribution function (cdf) of Poisson distributions. Args: value (Tensor): The value to be evaluated. rate (Tensor): The rate of the distribution. Default: self.rate. Note: `value` must be greater or equal to zero. .. math:: cdf(x) = \Gamma(x + 1) if x >= 0 else 0
r""" Cumulative distribution function (cdf) of Poisson distributions.
[ "r", "Cumulative", "distribution", "function", "(", "cdf", ")", "of", "Poisson", "distributions", "." ]
def _cdf(self, value, rate=None): r""" Cumulative distribution function (cdf) of Poisson distributions. Args: value (Tensor): The value to be evaluated. rate (Tensor): The rate of the distribution. Default: self.rate. Note: `value` must be greater or equal to zero. .. math:: cdf(x) = \Gamma(x + 1) if x >= 0 else 0 """ value = self._check_value(value, 'value') value = self.cast(value, self.dtype) rate = self._check_param_type(rate) zeros = self.fill(self.dtypeop(value), self.shape(value), 0.0) comp = self.less(value, zeros) safe_x = self.select(comp, zeros, value) cdf = 1. - self.igamma(1. + safe_x, rate) return self.select(comp, zeros, cdf)
[ "def", "_cdf", "(", "self", ",", "value", ",", "rate", "=", "None", ")", ":", "value", "=", "self", ".", "_check_value", "(", "value", ",", "'value'", ")", "value", "=", "self", ".", "cast", "(", "value", ",", "self", ".", "dtype", ")", "rate", "=", "self", ".", "_check_param_type", "(", "rate", ")", "zeros", "=", "self", ".", "fill", "(", "self", ".", "dtypeop", "(", "value", ")", ",", "self", ".", "shape", "(", "value", ")", ",", "0.0", ")", "comp", "=", "self", ".", "less", "(", "value", ",", "zeros", ")", "safe_x", "=", "self", ".", "select", "(", "comp", ",", "zeros", ",", "value", ")", "cdf", "=", "1.", "-", "self", ".", "igamma", "(", "1.", "+", "safe_x", ",", "rate", ")", "return", "self", ".", "select", "(", "comp", ",", "zeros", ",", "cdf", ")" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/probability/distribution/poisson.py#L250-L271
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/pdb.py
python
Pdb.do_args
(self, arg)
a(rgs) Print the argument list of the current function.
a(rgs) Print the argument list of the current function.
[ "a", "(", "rgs", ")", "Print", "the", "argument", "list", "of", "the", "current", "function", "." ]
def do_args(self, arg): """a(rgs) Print the argument list of the current function. """ co = self.curframe.f_code dict = self.curframe_locals n = co.co_argcount + co.co_kwonlyargcount if co.co_flags & inspect.CO_VARARGS: n = n+1 if co.co_flags & inspect.CO_VARKEYWORDS: n = n+1 for i in range(n): name = co.co_varnames[i] if name in dict: self.message('%s = %r' % (name, dict[name])) else: self.message('%s = *** undefined ***' % (name,))
[ "def", "do_args", "(", "self", ",", "arg", ")", ":", "co", "=", "self", ".", "curframe", ".", "f_code", "dict", "=", "self", ".", "curframe_locals", "n", "=", "co", ".", "co_argcount", "+", "co", ".", "co_kwonlyargcount", "if", "co", ".", "co_flags", "&", "inspect", ".", "CO_VARARGS", ":", "n", "=", "n", "+", "1", "if", "co", ".", "co_flags", "&", "inspect", ".", "CO_VARKEYWORDS", ":", "n", "=", "n", "+", "1", "for", "i", "in", "range", "(", "n", ")", ":", "name", "=", "co", ".", "co_varnames", "[", "i", "]", "if", "name", "in", "dict", ":", "self", ".", "message", "(", "'%s = %r'", "%", "(", "name", ",", "dict", "[", "name", "]", ")", ")", "else", ":", "self", ".", "message", "(", "'%s = *** undefined ***'", "%", "(", "name", ",", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/pdb.py#L1128-L1142
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/configobj/configobj.py
python
Section.setdefault
(self, key, default=None)
A version of setdefault that sets sequence if appropriate.
A version of setdefault that sets sequence if appropriate.
[ "A", "version", "of", "setdefault", "that", "sets", "sequence", "if", "appropriate", "." ]
def setdefault(self, key, default=None): """A version of setdefault that sets sequence if appropriate.""" try: return self[key] except KeyError: self[key] = default return self[key]
[ "def", "setdefault", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "try", ":", "return", "self", "[", "key", "]", "except", "KeyError", ":", "self", "[", "key", "]", "=", "default", "return", "self", "[", "key", "]" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/configobj/configobj.py#L713-L719
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/telnetlib.py
python
Telnet.read_lazy
(self)
return self.read_very_lazy()
Process and return data that's already in the queues (lazy). Raise EOFError if connection closed and no data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence.
Process and return data that's already in the queues (lazy).
[ "Process", "and", "return", "data", "that", "s", "already", "in", "the", "queues", "(", "lazy", ")", "." ]
def read_lazy(self): """Process and return data that's already in the queues (lazy). Raise EOFError if connection closed and no data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence. """ self.process_rawq() return self.read_very_lazy()
[ "def", "read_lazy", "(", "self", ")", ":", "self", ".", "process_rawq", "(", ")", "return", "self", ".", "read_very_lazy", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/telnetlib.py#L434-L443
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/osx_carbon/gizmos.py
python
TreeListCtrl.Delete
(*args, **kwargs)
return _gizmos.TreeListCtrl_Delete(*args, **kwargs)
Delete(self, TreeItemId item)
Delete(self, TreeItemId item)
[ "Delete", "(", "self", "TreeItemId", "item", ")" ]
def Delete(*args, **kwargs): """Delete(self, TreeItemId item)""" return _gizmos.TreeListCtrl_Delete(*args, **kwargs)
[ "def", "Delete", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gizmos", ".", "TreeListCtrl_Delete", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_carbon/gizmos.py#L858-L860
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_controls.py
python
RadioBox.GetString
(*args, **kwargs)
return _controls_.RadioBox_GetString(*args, **kwargs)
GetString(self, int n) -> String
GetString(self, int n) -> String
[ "GetString", "(", "self", "int", "n", ")", "-", ">", "String" ]
def GetString(*args, **kwargs): """GetString(self, int n) -> String""" return _controls_.RadioBox_GetString(*args, **kwargs)
[ "def", "GetString", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "RadioBox_GetString", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_controls.py#L2619-L2621
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
python/pyarrow/types.py
python
is_int16
(t)
return t.id == lib.Type_INT16
Return True if value is an instance of an int16 type. Parameters ---------- t : DataType
Return True if value is an instance of an int16 type.
[ "Return", "True", "if", "value", "is", "an", "instance", "of", "an", "int16", "type", "." ]
def is_int16(t): """ Return True if value is an instance of an int16 type. Parameters ---------- t : DataType """ return t.id == lib.Type_INT16
[ "def", "is_int16", "(", "t", ")", ":", "return", "t", ".", "id", "==", "lib", ".", "Type_INT16" ]
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/python/pyarrow/types.py#L112-L120
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/tools/optimize_for_inference_lib.py
python
fold_batch_norms
(input_graph_def)
return result_graph_def
Removes batch normalization ops by folding them into convolutions. Batch normalization during training has multiple dynamic parameters that are updated, but once the graph is finalized these become constants. That means there's an opportunity to reduce the computations down to a scale and addition, rather than the more expensive multiple ops, and even bake the scaling into the convolution weights. This function identifies the typical pattern of batch normalization subgraphs, and performs the transformation to fold the computations down into a simpler form. It currently only spots batch normalization that's performed by the BatchNormWithGlobalNormalization op, and will need to be extended in the future to handle the newer style. Args: input_graph_def: A GraphDef containing a model. Returns: Modified graph with BN ops removed, and modified weights. Raises: ValueError: If the graph is badly formed with duplicate node names.
Removes batch normalization ops by folding them into convolutions.
[ "Removes", "batch", "normalization", "ops", "by", "folding", "them", "into", "convolutions", "." ]
def fold_batch_norms(input_graph_def): """Removes batch normalization ops by folding them into convolutions. Batch normalization during training has multiple dynamic parameters that are updated, but once the graph is finalized these become constants. That means there's an opportunity to reduce the computations down to a scale and addition, rather than the more expensive multiple ops, and even bake the scaling into the convolution weights. This function identifies the typical pattern of batch normalization subgraphs, and performs the transformation to fold the computations down into a simpler form. It currently only spots batch normalization that's performed by the BatchNormWithGlobalNormalization op, and will need to be extended in the future to handle the newer style. Args: input_graph_def: A GraphDef containing a model. Returns: Modified graph with BN ops removed, and modified weights. Raises: ValueError: If the graph is badly formed with duplicate node names. """ input_node_map = {} for node in input_graph_def.node: if node.name not in input_node_map.keys(): input_node_map[node.name] = node else: raise ValueError("Duplicate node names detected for ", node.name) nodes_to_skip = {} new_ops = [] for node in input_graph_def.node: if node.op not in ("BatchNormWithGlobalNormalization", "FusedBatchNorm"): continue conv_op = node_from_map(input_node_map, node.input[INPUT_ORDER[node.op].index("conv_op")]) if conv_op.op != "Conv2D": tf_logging.warning( "Didn't find expected Conv2D input to '%s'" % node.name) continue weights_op = node_from_map(input_node_map, conv_op.input[1]) if weights_op.op != "Const": tf_logging.warning("Didn't find expected conv Constant input to '%s'," " found %s instead. Maybe because freeze_graph wasn't" " run first?" % (conv_op.name, weights_op)) continue weights = values_from_const(weights_op) channel_count = weights.shape[3] mean_op = node_from_map(input_node_map, node.input[INPUT_ORDER[node.op].index("mean_op")]) if mean_op.op != "Const": tf_logging.warning("Didn't find expected mean Constant input to '%s'," " found %s instead. Maybe because freeze_graph wasn't" " run first?" % (node.name, mean_op)) continue mean_value = values_from_const(mean_op) if mean_value.shape != (channel_count,): tf_logging.warning("Incorrect shape for mean, found %s, expected %s," " for node %s" % (str(mean_value.shape), str( (channel_count,)), node.name)) continue var_op = node_from_map(input_node_map, node.input[INPUT_ORDER[node.op].index("var_op")]) if var_op.op != "Const": tf_logging.warning("Didn't find expected var Constant input to '%s'," " found %s instead. Maybe because freeze_graph wasn't" " run first?" % (node.name, var_op)) continue var_value = values_from_const(var_op) if var_value.shape != (channel_count,): tf_logging.warning("Incorrect shape for var, found %s, expected %s," " for node %s" % (str(var_value.shape), str( (channel_count,)), node.name)) continue beta_op = node_from_map(input_node_map, node.input[INPUT_ORDER[node.op].index("beta_op")]) if beta_op.op != "Const": tf_logging.warning("Didn't find expected beta Constant input to '%s'," " found %s instead. Maybe because freeze_graph wasn't" " run first?" % (node.name, beta_op)) continue beta_value = values_from_const(beta_op) if beta_value.shape != (channel_count,): tf_logging.warning("Incorrect shape for beta, found %s, expected %s," " for node %s" % (str(beta_value.shape), str( (channel_count,)), node.name)) continue gamma_op = node_from_map(input_node_map, node.input[INPUT_ORDER[node.op].index("gamma_op")]) if gamma_op.op != "Const": tf_logging.warning("Didn't find expected gamma Constant input to '%s'," " found %s instead. Maybe because freeze_graph wasn't" " run first?" % (node.name, gamma_op)) continue gamma_value = values_from_const(gamma_op) if gamma_value.shape != (channel_count,): tf_logging.warning("Incorrect shape for gamma, found %s, expected %s," " for node %s" % (str(gamma_value.shape), str( (channel_count,)), node.name)) continue variance_epsilon_value = node.attr[EPSILON_ATTR[node.op]].f nodes_to_skip[node.name] = True nodes_to_skip[weights_op.name] = True nodes_to_skip[mean_op.name] = True nodes_to_skip[var_op.name] = True nodes_to_skip[beta_op.name] = True nodes_to_skip[gamma_op.name] = True nodes_to_skip[conv_op.name] = True if scale_after_normalization(node): scale_value = ( (1.0 / np.vectorize(math.sqrt)(var_value + variance_epsilon_value)) * gamma_value) else: scale_value = ( 1.0 / np.vectorize(math.sqrt)(var_value + variance_epsilon_value)) offset_value = (-mean_value * scale_value) + beta_value scaled_weights = np.copy(weights) it = np.nditer( scaled_weights, flags=["multi_index"], op_flags=["readwrite"]) while not it.finished: current_scale = scale_value[it.multi_index[3]] it[0] *= current_scale it.iternext() scaled_weights_op = node_def_pb2.NodeDef() scaled_weights_op.op = "Const" scaled_weights_op.name = weights_op.name scaled_weights_op.attr["dtype"].CopyFrom(weights_op.attr["dtype"]) scaled_weights_op.attr["value"].CopyFrom( attr_value_pb2.AttrValue(tensor=tensor_util.make_tensor_proto( scaled_weights, weights.dtype.type, weights.shape))) new_conv_op = node_def_pb2.NodeDef() new_conv_op.CopyFrom(conv_op) offset_op = node_def_pb2.NodeDef() offset_op.op = "Const" offset_op.name = conv_op.name + "_bn_offset" offset_op.attr["dtype"].CopyFrom(mean_op.attr["dtype"]) offset_op.attr["value"].CopyFrom( attr_value_pb2.AttrValue(tensor=tensor_util.make_tensor_proto( offset_value, mean_value.dtype.type, offset_value.shape))) bias_add_op = node_def_pb2.NodeDef() bias_add_op.op = "BiasAdd" bias_add_op.name = node.name bias_add_op.attr["T"].CopyFrom(conv_op.attr["T"]) bias_add_op.input.extend([new_conv_op.name, offset_op.name]) new_ops.extend([scaled_weights_op, new_conv_op, offset_op, bias_add_op]) result_graph_def = graph_pb2.GraphDef() for node in input_graph_def.node: if node.name in nodes_to_skip: continue new_node = node_def_pb2.NodeDef() new_node.CopyFrom(node) result_graph_def.node.extend([new_node]) result_graph_def.node.extend(new_ops) return result_graph_def
[ "def", "fold_batch_norms", "(", "input_graph_def", ")", ":", "input_node_map", "=", "{", "}", "for", "node", "in", "input_graph_def", ".", "node", ":", "if", "node", ".", "name", "not", "in", "input_node_map", ".", "keys", "(", ")", ":", "input_node_map", "[", "node", ".", "name", "]", "=", "node", "else", ":", "raise", "ValueError", "(", "\"Duplicate node names detected for \"", ",", "node", ".", "name", ")", "nodes_to_skip", "=", "{", "}", "new_ops", "=", "[", "]", "for", "node", "in", "input_graph_def", ".", "node", ":", "if", "node", ".", "op", "not", "in", "(", "\"BatchNormWithGlobalNormalization\"", ",", "\"FusedBatchNorm\"", ")", ":", "continue", "conv_op", "=", "node_from_map", "(", "input_node_map", ",", "node", ".", "input", "[", "INPUT_ORDER", "[", "node", ".", "op", "]", ".", "index", "(", "\"conv_op\"", ")", "]", ")", "if", "conv_op", ".", "op", "!=", "\"Conv2D\"", ":", "tf_logging", ".", "warning", "(", "\"Didn't find expected Conv2D input to '%s'\"", "%", "node", ".", "name", ")", "continue", "weights_op", "=", "node_from_map", "(", "input_node_map", ",", "conv_op", ".", "input", "[", "1", "]", ")", "if", "weights_op", ".", "op", "!=", "\"Const\"", ":", "tf_logging", ".", "warning", "(", "\"Didn't find expected conv Constant input to '%s',\"", "\" found %s instead. Maybe because freeze_graph wasn't\"", "\" run first?\"", "%", "(", "conv_op", ".", "name", ",", "weights_op", ")", ")", "continue", "weights", "=", "values_from_const", "(", "weights_op", ")", "channel_count", "=", "weights", ".", "shape", "[", "3", "]", "mean_op", "=", "node_from_map", "(", "input_node_map", ",", "node", ".", "input", "[", "INPUT_ORDER", "[", "node", ".", "op", "]", ".", "index", "(", "\"mean_op\"", ")", "]", ")", "if", "mean_op", ".", "op", "!=", "\"Const\"", ":", "tf_logging", ".", "warning", "(", "\"Didn't find expected mean Constant input to '%s',\"", "\" found %s instead. Maybe because freeze_graph wasn't\"", "\" run first?\"", "%", "(", "node", ".", "name", ",", "mean_op", ")", ")", "continue", "mean_value", "=", "values_from_const", "(", "mean_op", ")", "if", "mean_value", ".", "shape", "!=", "(", "channel_count", ",", ")", ":", "tf_logging", ".", "warning", "(", "\"Incorrect shape for mean, found %s, expected %s,\"", "\" for node %s\"", "%", "(", "str", "(", "mean_value", ".", "shape", ")", ",", "str", "(", "(", "channel_count", ",", ")", ")", ",", "node", ".", "name", ")", ")", "continue", "var_op", "=", "node_from_map", "(", "input_node_map", ",", "node", ".", "input", "[", "INPUT_ORDER", "[", "node", ".", "op", "]", ".", "index", "(", "\"var_op\"", ")", "]", ")", "if", "var_op", ".", "op", "!=", "\"Const\"", ":", "tf_logging", ".", "warning", "(", "\"Didn't find expected var Constant input to '%s',\"", "\" found %s instead. Maybe because freeze_graph wasn't\"", "\" run first?\"", "%", "(", "node", ".", "name", ",", "var_op", ")", ")", "continue", "var_value", "=", "values_from_const", "(", "var_op", ")", "if", "var_value", ".", "shape", "!=", "(", "channel_count", ",", ")", ":", "tf_logging", ".", "warning", "(", "\"Incorrect shape for var, found %s, expected %s,\"", "\" for node %s\"", "%", "(", "str", "(", "var_value", ".", "shape", ")", ",", "str", "(", "(", "channel_count", ",", ")", ")", ",", "node", ".", "name", ")", ")", "continue", "beta_op", "=", "node_from_map", "(", "input_node_map", ",", "node", ".", "input", "[", "INPUT_ORDER", "[", "node", ".", "op", "]", ".", "index", "(", "\"beta_op\"", ")", "]", ")", "if", "beta_op", ".", "op", "!=", "\"Const\"", ":", "tf_logging", ".", "warning", "(", "\"Didn't find expected beta Constant input to '%s',\"", "\" found %s instead. Maybe because freeze_graph wasn't\"", "\" run first?\"", "%", "(", "node", ".", "name", ",", "beta_op", ")", ")", "continue", "beta_value", "=", "values_from_const", "(", "beta_op", ")", "if", "beta_value", ".", "shape", "!=", "(", "channel_count", ",", ")", ":", "tf_logging", ".", "warning", "(", "\"Incorrect shape for beta, found %s, expected %s,\"", "\" for node %s\"", "%", "(", "str", "(", "beta_value", ".", "shape", ")", ",", "str", "(", "(", "channel_count", ",", ")", ")", ",", "node", ".", "name", ")", ")", "continue", "gamma_op", "=", "node_from_map", "(", "input_node_map", ",", "node", ".", "input", "[", "INPUT_ORDER", "[", "node", ".", "op", "]", ".", "index", "(", "\"gamma_op\"", ")", "]", ")", "if", "gamma_op", ".", "op", "!=", "\"Const\"", ":", "tf_logging", ".", "warning", "(", "\"Didn't find expected gamma Constant input to '%s',\"", "\" found %s instead. Maybe because freeze_graph wasn't\"", "\" run first?\"", "%", "(", "node", ".", "name", ",", "gamma_op", ")", ")", "continue", "gamma_value", "=", "values_from_const", "(", "gamma_op", ")", "if", "gamma_value", ".", "shape", "!=", "(", "channel_count", ",", ")", ":", "tf_logging", ".", "warning", "(", "\"Incorrect shape for gamma, found %s, expected %s,\"", "\" for node %s\"", "%", "(", "str", "(", "gamma_value", ".", "shape", ")", ",", "str", "(", "(", "channel_count", ",", ")", ")", ",", "node", ".", "name", ")", ")", "continue", "variance_epsilon_value", "=", "node", ".", "attr", "[", "EPSILON_ATTR", "[", "node", ".", "op", "]", "]", ".", "f", "nodes_to_skip", "[", "node", ".", "name", "]", "=", "True", "nodes_to_skip", "[", "weights_op", ".", "name", "]", "=", "True", "nodes_to_skip", "[", "mean_op", ".", "name", "]", "=", "True", "nodes_to_skip", "[", "var_op", ".", "name", "]", "=", "True", "nodes_to_skip", "[", "beta_op", ".", "name", "]", "=", "True", "nodes_to_skip", "[", "gamma_op", ".", "name", "]", "=", "True", "nodes_to_skip", "[", "conv_op", ".", "name", "]", "=", "True", "if", "scale_after_normalization", "(", "node", ")", ":", "scale_value", "=", "(", "(", "1.0", "/", "np", ".", "vectorize", "(", "math", ".", "sqrt", ")", "(", "var_value", "+", "variance_epsilon_value", ")", ")", "*", "gamma_value", ")", "else", ":", "scale_value", "=", "(", "1.0", "/", "np", ".", "vectorize", "(", "math", ".", "sqrt", ")", "(", "var_value", "+", "variance_epsilon_value", ")", ")", "offset_value", "=", "(", "-", "mean_value", "*", "scale_value", ")", "+", "beta_value", "scaled_weights", "=", "np", ".", "copy", "(", "weights", ")", "it", "=", "np", ".", "nditer", "(", "scaled_weights", ",", "flags", "=", "[", "\"multi_index\"", "]", ",", "op_flags", "=", "[", "\"readwrite\"", "]", ")", "while", "not", "it", ".", "finished", ":", "current_scale", "=", "scale_value", "[", "it", ".", "multi_index", "[", "3", "]", "]", "it", "[", "0", "]", "*=", "current_scale", "it", ".", "iternext", "(", ")", "scaled_weights_op", "=", "node_def_pb2", ".", "NodeDef", "(", ")", "scaled_weights_op", ".", "op", "=", "\"Const\"", "scaled_weights_op", ".", "name", "=", "weights_op", ".", "name", "scaled_weights_op", ".", "attr", "[", "\"dtype\"", "]", ".", "CopyFrom", "(", "weights_op", ".", "attr", "[", "\"dtype\"", "]", ")", "scaled_weights_op", ".", "attr", "[", "\"value\"", "]", ".", "CopyFrom", "(", "attr_value_pb2", ".", "AttrValue", "(", "tensor", "=", "tensor_util", ".", "make_tensor_proto", "(", "scaled_weights", ",", "weights", ".", "dtype", ".", "type", ",", "weights", ".", "shape", ")", ")", ")", "new_conv_op", "=", "node_def_pb2", ".", "NodeDef", "(", ")", "new_conv_op", ".", "CopyFrom", "(", "conv_op", ")", "offset_op", "=", "node_def_pb2", ".", "NodeDef", "(", ")", "offset_op", ".", "op", "=", "\"Const\"", "offset_op", ".", "name", "=", "conv_op", ".", "name", "+", "\"_bn_offset\"", "offset_op", ".", "attr", "[", "\"dtype\"", "]", ".", "CopyFrom", "(", "mean_op", ".", "attr", "[", "\"dtype\"", "]", ")", "offset_op", ".", "attr", "[", "\"value\"", "]", ".", "CopyFrom", "(", "attr_value_pb2", ".", "AttrValue", "(", "tensor", "=", "tensor_util", ".", "make_tensor_proto", "(", "offset_value", ",", "mean_value", ".", "dtype", ".", "type", ",", "offset_value", ".", "shape", ")", ")", ")", "bias_add_op", "=", "node_def_pb2", ".", "NodeDef", "(", ")", "bias_add_op", ".", "op", "=", "\"BiasAdd\"", "bias_add_op", ".", "name", "=", "node", ".", "name", "bias_add_op", ".", "attr", "[", "\"T\"", "]", ".", "CopyFrom", "(", "conv_op", ".", "attr", "[", "\"T\"", "]", ")", "bias_add_op", ".", "input", ".", "extend", "(", "[", "new_conv_op", ".", "name", ",", "offset_op", ".", "name", "]", ")", "new_ops", ".", "extend", "(", "[", "scaled_weights_op", ",", "new_conv_op", ",", "offset_op", ",", "bias_add_op", "]", ")", "result_graph_def", "=", "graph_pb2", ".", "GraphDef", "(", ")", "for", "node", "in", "input_graph_def", ".", "node", ":", "if", "node", ".", "name", "in", "nodes_to_skip", ":", "continue", "new_node", "=", "node_def_pb2", ".", "NodeDef", "(", ")", "new_node", ".", "CopyFrom", "(", "node", ")", "result_graph_def", ".", "node", ".", "extend", "(", "[", "new_node", "]", ")", "result_graph_def", ".", "node", ".", "extend", "(", "new_ops", ")", "return", "result_graph_def" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/tools/optimize_for_inference_lib.py#L201-L364
papyrussolution/OpenPapyrus
bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91
Src/OSF/protobuf-3.19.1/python/google/protobuf/text_format.py
python
Tokenizer._ConsumeSingleByteString
(self)
return result
Consume one token of a string literal. String literals (whether bytes or text) can come in multiple adjacent tokens which are automatically concatenated, like in C or Python. This method only consumes one token. Returns: The token parsed. Raises: ParseError: When the wrong format data is found.
Consume one token of a string literal.
[ "Consume", "one", "token", "of", "a", "string", "literal", "." ]
def _ConsumeSingleByteString(self): """Consume one token of a string literal. String literals (whether bytes or text) can come in multiple adjacent tokens which are automatically concatenated, like in C or Python. This method only consumes one token. Returns: The token parsed. Raises: ParseError: When the wrong format data is found. """ text = self.token if len(text) < 1 or text[0] not in _QUOTES: raise self.ParseError('Expected string but found: %r' % (text,)) if len(text) < 2 or text[-1] != text[0]: raise self.ParseError('String missing ending quote: %r' % (text,)) try: result = text_encoding.CUnescape(text[1:-1]) except ValueError as e: raise self.ParseError(str(e)) self.NextToken() return result
[ "def", "_ConsumeSingleByteString", "(", "self", ")", ":", "text", "=", "self", ".", "token", "if", "len", "(", "text", ")", "<", "1", "or", "text", "[", "0", "]", "not", "in", "_QUOTES", ":", "raise", "self", ".", "ParseError", "(", "'Expected string but found: %r'", "%", "(", "text", ",", ")", ")", "if", "len", "(", "text", ")", "<", "2", "or", "text", "[", "-", "1", "]", "!=", "text", "[", "0", "]", ":", "raise", "self", ".", "ParseError", "(", "'String missing ending quote: %r'", "%", "(", "text", ",", ")", ")", "try", ":", "result", "=", "text_encoding", ".", "CUnescape", "(", "text", "[", "1", ":", "-", "1", "]", ")", "except", "ValueError", "as", "e", ":", "raise", "self", ".", "ParseError", "(", "str", "(", "e", ")", ")", "self", ".", "NextToken", "(", ")", "return", "result" ]
https://github.com/papyrussolution/OpenPapyrus/blob/bbfb5ec2ea2109b8e2f125edd838e12eaf7b8b91/Src/OSF/protobuf-3.19.1/python/google/protobuf/text_format.py#L1481-L1505
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/tools/graph_transforms/__init__.py
python
TransformGraph
(input_graph_def, inputs, outputs, transforms)
return output_graph_def
Python wrapper for the Graph Transform Tool. Gives access to all graph transforms available through the command line tool. See documentation at https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/graph_transforms/README.md for full details of the options available. Args: input_graph_def: GraphDef object containing a model to be transformed. inputs: List of node names for the model inputs. outputs: List of node names for the model outputs. transforms: List of strings containing transform names and parameters. Returns: New GraphDef with transforms applied.
Python wrapper for the Graph Transform Tool.
[ "Python", "wrapper", "for", "the", "Graph", "Transform", "Tool", "." ]
def TransformGraph(input_graph_def, inputs, outputs, transforms): """Python wrapper for the Graph Transform Tool. Gives access to all graph transforms available through the command line tool. See documentation at https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/graph_transforms/README.md for full details of the options available. Args: input_graph_def: GraphDef object containing a model to be transformed. inputs: List of node names for the model inputs. outputs: List of node names for the model outputs. transforms: List of strings containing transform names and parameters. Returns: New GraphDef with transforms applied. """ input_graph_def_string = input_graph_def.SerializeToString() inputs_string = compat.as_bytes(",".join(inputs)) outputs_string = compat.as_bytes(",".join(outputs)) transforms_string = compat.as_bytes(" ".join(transforms)) output_graph_def_string = TransformGraphWithStringInputs( input_graph_def_string, inputs_string, outputs_string, transforms_string) output_graph_def = graph_pb2.GraphDef() output_graph_def.ParseFromString(output_graph_def_string) return output_graph_def
[ "def", "TransformGraph", "(", "input_graph_def", ",", "inputs", ",", "outputs", ",", "transforms", ")", ":", "input_graph_def_string", "=", "input_graph_def", ".", "SerializeToString", "(", ")", "inputs_string", "=", "compat", ".", "as_bytes", "(", "\",\"", ".", "join", "(", "inputs", ")", ")", "outputs_string", "=", "compat", ".", "as_bytes", "(", "\",\"", ".", "join", "(", "outputs", ")", ")", "transforms_string", "=", "compat", ".", "as_bytes", "(", "\" \"", ".", "join", "(", "transforms", ")", ")", "output_graph_def_string", "=", "TransformGraphWithStringInputs", "(", "input_graph_def_string", ",", "inputs_string", ",", "outputs_string", ",", "transforms_string", ")", "output_graph_def", "=", "graph_pb2", ".", "GraphDef", "(", ")", "output_graph_def", ".", "ParseFromString", "(", "output_graph_def_string", ")", "return", "output_graph_def" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/tools/graph_transforms/__init__.py#L22-L47
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py
python
Index.create
(excludeDecls=False)
return Index(conf.lib.clang_createIndex(excludeDecls, 0))
Create a new Index. Parameters: excludeDecls -- Exclude local declarations from translation units.
Create a new Index. Parameters: excludeDecls -- Exclude local declarations from translation units.
[ "Create", "a", "new", "Index", ".", "Parameters", ":", "excludeDecls", "--", "Exclude", "local", "declarations", "from", "translation", "units", "." ]
def create(excludeDecls=False): """ Create a new Index. Parameters: excludeDecls -- Exclude local declarations from translation units. """ return Index(conf.lib.clang_createIndex(excludeDecls, 0))
[ "def", "create", "(", "excludeDecls", "=", "False", ")", ":", "return", "Index", "(", "conf", ".", "lib", ".", "clang_createIndex", "(", "excludeDecls", ",", "0", ")", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/clang/bindings/python/clang/cindex.py#L2421-L2427
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/lookup/lookup_ops.py
python
string_to_index
(tensor, mapping, default_value=-1, name=None)
Maps `tensor` of strings into `int64` indices based on `mapping`. This operation converts `tensor` of strings into `int64` indices. The mapping is initialized from a string `mapping` tensor where each element is a key and corresponding index within the tensor is the value. Any entry in the input which does not have a corresponding entry in 'mapping' (an out-of-vocabulary entry) is assigned the `default_value` Elements in `mapping` cannot be duplicated, otherwise the initialization will throw a FailedPreconditionError. The underlying table must be initialized by calling `tf.initialize_all_tables.run()` once. For example: ```python mapping_strings = t.constant(["emerson", "lake", "palmer") feats = tf.constant(["emerson", "lake", "and", "palmer"]) ids = tf.contrib.lookup.string_to_index( feats, mapping=mapping_strings, default_value=-1) ... tf.initialize_all_tables().run() ids.eval() ==> [0, 1, -1, 2] ``` Args: tensor: A 1-D input `Tensor` with the strings to map to indices. mapping: A 1-D string `Tensor` that specifies the mapping of strings to indices. default_value: The `int64` value to use for out-of-vocabulary strings. Defaults to -1. name: A name for this op (optional). Returns: The mapped indices. It has the same shape and tensor type (dense or sparse) as `tensor`.
Maps `tensor` of strings into `int64` indices based on `mapping`.
[ "Maps", "tensor", "of", "strings", "into", "int64", "indices", "based", "on", "mapping", "." ]
def string_to_index(tensor, mapping, default_value=-1, name=None): """Maps `tensor` of strings into `int64` indices based on `mapping`. This operation converts `tensor` of strings into `int64` indices. The mapping is initialized from a string `mapping` tensor where each element is a key and corresponding index within the tensor is the value. Any entry in the input which does not have a corresponding entry in 'mapping' (an out-of-vocabulary entry) is assigned the `default_value` Elements in `mapping` cannot be duplicated, otherwise the initialization will throw a FailedPreconditionError. The underlying table must be initialized by calling `tf.initialize_all_tables.run()` once. For example: ```python mapping_strings = t.constant(["emerson", "lake", "palmer") feats = tf.constant(["emerson", "lake", "and", "palmer"]) ids = tf.contrib.lookup.string_to_index( feats, mapping=mapping_strings, default_value=-1) ... tf.initialize_all_tables().run() ids.eval() ==> [0, 1, -1, 2] ``` Args: tensor: A 1-D input `Tensor` with the strings to map to indices. mapping: A 1-D string `Tensor` that specifies the mapping of strings to indices. default_value: The `int64` value to use for out-of-vocabulary strings. Defaults to -1. name: A name for this op (optional). Returns: The mapped indices. It has the same shape and tensor type (dense or sparse) as `tensor`. """ with ops.op_scope([tensor], name, "string_to_index") as scope: shared_name = "" keys = ops.convert_to_tensor(mapping, dtypes.string) vocab_size = array_ops.size(keys) values = math_ops.cast(math_ops.range(vocab_size), dtypes.int64) init = KeyValueTensorInitializer(keys, values, dtypes.string, dtypes.int64, name="table_init") t = HashTable(init, default_value, shared_name=shared_name, name="hash_table") return t.lookup(tensor, name=scope)
[ "def", "string_to_index", "(", "tensor", ",", "mapping", ",", "default_value", "=", "-", "1", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "op_scope", "(", "[", "tensor", "]", ",", "name", ",", "\"string_to_index\"", ")", "as", "scope", ":", "shared_name", "=", "\"\"", "keys", "=", "ops", ".", "convert_to_tensor", "(", "mapping", ",", "dtypes", ".", "string", ")", "vocab_size", "=", "array_ops", ".", "size", "(", "keys", ")", "values", "=", "math_ops", ".", "cast", "(", "math_ops", ".", "range", "(", "vocab_size", ")", ",", "dtypes", ".", "int64", ")", "init", "=", "KeyValueTensorInitializer", "(", "keys", ",", "values", ",", "dtypes", ".", "string", ",", "dtypes", ".", "int64", ",", "name", "=", "\"table_init\"", ")", "t", "=", "HashTable", "(", "init", ",", "default_value", ",", "shared_name", "=", "shared_name", ",", "name", "=", "\"hash_table\"", ")", "return", "t", ".", "lookup", "(", "tensor", ",", "name", "=", "scope", ")" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/lookup/lookup_ops.py#L577-L633
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/ttk.py
python
LabeledScale._set_value
(self, val)
Set new scale value.
Set new scale value.
[ "Set", "new", "scale", "value", "." ]
def _set_value(self, val): """Set new scale value.""" self._variable.set(val)
[ "def", "_set_value", "(", "self", ",", "val", ")", ":", "self", ".", "_variable", ".", "set", "(", "val", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/ttk.py#L1545-L1547
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/GettextCommon.py
python
_detect_msgmerge
(env)
return None
Detects *msgmerge(1)* program.
Detects *msgmerge(1)* program.
[ "Detects", "*", "msgmerge", "(", "1", ")", "*", "program", "." ]
def _detect_msgmerge(env): """ Detects *msgmerge(1)* program. """ if env.has_key('MSGMERGE'): return env['MSGMERGE'] msgmerge = env.Detect('msgmerge'); if msgmerge: return msgmerge raise SCons.Errors.StopError(MsgmergeNotFound, "Could not detect msgmerge") return None
[ "def", "_detect_msgmerge", "(", "env", ")", ":", "if", "env", ".", "has_key", "(", "'MSGMERGE'", ")", ":", "return", "env", "[", "'MSGMERGE'", "]", "msgmerge", "=", "env", ".", "Detect", "(", "'msgmerge'", ")", "if", "msgmerge", ":", "return", "msgmerge", "raise", "SCons", ".", "Errors", ".", "StopError", "(", "MsgmergeNotFound", ",", "\"Could not detect msgmerge\"", ")", "return", "None" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/GettextCommon.py#L379-L387
stack-of-tasks/pinocchio
593d4d43fded997bb9aa2421f4e55294dbd233c4
bindings/python/pinocchio/robot_wrapper.py
python
RobotWrapper.play
(self, q_trajectory, dt)
Play a trajectory with given time step
Play a trajectory with given time step
[ "Play", "a", "trajectory", "with", "given", "time", "step" ]
def play(self, q_trajectory, dt): """Play a trajectory with given time step""" self.viz.play(q_trajectory, dt)
[ "def", "play", "(", "self", ",", "q_trajectory", ",", "dt", ")", ":", "self", ".", "viz", ".", "play", "(", "q_trajectory", ",", "dt", ")" ]
https://github.com/stack-of-tasks/pinocchio/blob/593d4d43fded997bb9aa2421f4e55294dbd233c4/bindings/python/pinocchio/robot_wrapper.py#L313-L315
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/docs/utils.py
python
py_default
(type_name)
return { 'double': '123.0', 'long': '123', 'integer': '123', 'string': "'string'", 'blob': "b'bytes'", 'boolean': 'True|False', 'list': '[...]', 'map': '{...}', 'structure': '{...}', 'timestamp': 'datetime(2015, 1, 1)', }.get(type_name, '...')
Get the Python default value for a given model type. >>> py_default('string') '\'string\'' >>> py_default('list') '[...]' >>> py_default('unknown') '...' :rtype: string
Get the Python default value for a given model type.
[ "Get", "the", "Python", "default", "value", "for", "a", "given", "model", "type", "." ]
def py_default(type_name): """Get the Python default value for a given model type. >>> py_default('string') '\'string\'' >>> py_default('list') '[...]' >>> py_default('unknown') '...' :rtype: string """ return { 'double': '123.0', 'long': '123', 'integer': '123', 'string': "'string'", 'blob': "b'bytes'", 'boolean': 'True|False', 'list': '[...]', 'map': '{...}', 'structure': '{...}', 'timestamp': 'datetime(2015, 1, 1)', }.get(type_name, '...')
[ "def", "py_default", "(", "type_name", ")", ":", "return", "{", "'double'", ":", "'123.0'", ",", "'long'", ":", "'123'", ",", "'integer'", ":", "'123'", ",", "'string'", ":", "\"'string'\"", ",", "'blob'", ":", "\"b'bytes'\"", ",", "'boolean'", ":", "'True|False'", ",", "'list'", ":", "'[...]'", ",", "'map'", ":", "'{...}'", ",", "'structure'", ":", "'{...}'", ",", "'timestamp'", ":", "'datetime(2015, 1, 1)'", ",", "}", ".", "get", "(", "type_name", ",", "'...'", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/docs/utils.py#L38-L61
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/imaplib.py
python
IMAP4.create
(self, mailbox)
return self._simple_command('CREATE', mailbox)
Create new mailbox. (typ, [data]) = <instance>.create(mailbox)
Create new mailbox.
[ "Create", "new", "mailbox", "." ]
def create(self, mailbox): """Create new mailbox. (typ, [data]) = <instance>.create(mailbox) """ return self._simple_command('CREATE', mailbox)
[ "def", "create", "(", "self", ",", "mailbox", ")", ":", "return", "self", ".", "_simple_command", "(", "'CREATE'", ",", "mailbox", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/imaplib.py#L396-L401
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/dtypes/cast.py
python
construct_1d_arraylike_from_scalar
( value: Scalar, length: int, dtype: DtypeObj | None )
return subarr
create a np.ndarray / pandas type of specified shape and dtype filled with values Parameters ---------- value : scalar value length : int dtype : pandas_dtype or np.dtype Returns ------- np.ndarray / pandas type of length, filled with value
create a np.ndarray / pandas type of specified shape and dtype filled with values
[ "create", "a", "np", ".", "ndarray", "/", "pandas", "type", "of", "specified", "shape", "and", "dtype", "filled", "with", "values" ]
def construct_1d_arraylike_from_scalar( value: Scalar, length: int, dtype: DtypeObj | None ) -> ArrayLike: """ create a np.ndarray / pandas type of specified shape and dtype filled with values Parameters ---------- value : scalar value length : int dtype : pandas_dtype or np.dtype Returns ------- np.ndarray / pandas type of length, filled with value """ if dtype is None: try: dtype, value = infer_dtype_from_scalar(value, pandas_dtype=True) except OutOfBoundsDatetime: dtype = np.dtype(object) if isinstance(dtype, ExtensionDtype): cls = dtype.construct_array_type() subarr = cls._from_sequence([value] * length, dtype=dtype) else: if length and is_integer_dtype(dtype) and isna(value): # coerce if we have nan for an integer dtype dtype = np.dtype("float64") elif isinstance(dtype, np.dtype) and dtype.kind in ("U", "S"): # we need to coerce to object dtype to avoid # to allow numpy to take our string as a scalar value dtype = np.dtype("object") if not isna(value): value = ensure_str(value) elif dtype.kind in ["M", "m"]: value = maybe_unbox_datetimelike_tz_deprecation(value, dtype) subarr = np.empty(length, dtype=dtype) subarr.fill(value) return subarr
[ "def", "construct_1d_arraylike_from_scalar", "(", "value", ":", "Scalar", ",", "length", ":", "int", ",", "dtype", ":", "DtypeObj", "|", "None", ")", "->", "ArrayLike", ":", "if", "dtype", "is", "None", ":", "try", ":", "dtype", ",", "value", "=", "infer_dtype_from_scalar", "(", "value", ",", "pandas_dtype", "=", "True", ")", "except", "OutOfBoundsDatetime", ":", "dtype", "=", "np", ".", "dtype", "(", "object", ")", "if", "isinstance", "(", "dtype", ",", "ExtensionDtype", ")", ":", "cls", "=", "dtype", ".", "construct_array_type", "(", ")", "subarr", "=", "cls", ".", "_from_sequence", "(", "[", "value", "]", "*", "length", ",", "dtype", "=", "dtype", ")", "else", ":", "if", "length", "and", "is_integer_dtype", "(", "dtype", ")", "and", "isna", "(", "value", ")", ":", "# coerce if we have nan for an integer dtype", "dtype", "=", "np", ".", "dtype", "(", "\"float64\"", ")", "elif", "isinstance", "(", "dtype", ",", "np", ".", "dtype", ")", "and", "dtype", ".", "kind", "in", "(", "\"U\"", ",", "\"S\"", ")", ":", "# we need to coerce to object dtype to avoid", "# to allow numpy to take our string as a scalar value", "dtype", "=", "np", ".", "dtype", "(", "\"object\"", ")", "if", "not", "isna", "(", "value", ")", ":", "value", "=", "ensure_str", "(", "value", ")", "elif", "dtype", ".", "kind", "in", "[", "\"M\"", ",", "\"m\"", "]", ":", "value", "=", "maybe_unbox_datetimelike_tz_deprecation", "(", "value", ",", "dtype", ")", "subarr", "=", "np", ".", "empty", "(", "length", ",", "dtype", "=", "dtype", ")", "subarr", ".", "fill", "(", "value", ")", "return", "subarr" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/dtypes/cast.py#L1880-L1926
HKUST-Aerial-Robotics/Teach-Repeat-Replan
98505a7f74b13c8b501176ff838a38423dbef536
utils/quadrotor_msgs/src/quadrotor_msgs/msg/_TRPYCommand.py
python
TRPYCommand.__init__
(self, *args, **kwds)
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: header,thrust,roll,pitch,yaw,aux :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields.
Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments.
[ "Constructor", ".", "Any", "message", "fields", "that", "are", "implicitly", "/", "explicitly", "set", "to", "None", "will", "be", "assigned", "a", "default", "value", ".", "The", "recommend", "use", "is", "keyword", "arguments", "as", "this", "is", "more", "robust", "to", "future", "message", "changes", ".", "You", "cannot", "mix", "in", "-", "order", "arguments", "and", "keyword", "arguments", "." ]
def __init__(self, *args, **kwds): """ Constructor. Any message fields that are implicitly/explicitly set to None will be assigned a default value. The recommend use is keyword arguments as this is more robust to future message changes. You cannot mix in-order arguments and keyword arguments. The available fields are: header,thrust,roll,pitch,yaw,aux :param args: complete set of field values, in .msg order :param kwds: use keyword arguments corresponding to message field names to set specific fields. """ if args or kwds: super(TRPYCommand, self).__init__(*args, **kwds) #message fields cannot be None, assign default values for those that are if self.header is None: self.header = std_msgs.msg.Header() if self.thrust is None: self.thrust = 0. if self.roll is None: self.roll = 0. if self.pitch is None: self.pitch = 0. if self.yaw is None: self.yaw = 0. if self.aux is None: self.aux = quadrotor_msgs.msg.AuxCommand() else: self.header = std_msgs.msg.Header() self.thrust = 0. self.roll = 0. self.pitch = 0. self.yaw = 0. self.aux = quadrotor_msgs.msg.AuxCommand()
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "if", "args", "or", "kwds", ":", "super", "(", "TRPYCommand", ",", "self", ")", ".", "__init__", "(", "*", "args", ",", "*", "*", "kwds", ")", "#message fields cannot be None, assign default values for those that are", "if", "self", ".", "header", "is", "None", ":", "self", ".", "header", "=", "std_msgs", ".", "msg", ".", "Header", "(", ")", "if", "self", ".", "thrust", "is", "None", ":", "self", ".", "thrust", "=", "0.", "if", "self", ".", "roll", "is", "None", ":", "self", ".", "roll", "=", "0.", "if", "self", ".", "pitch", "is", "None", ":", "self", ".", "pitch", "=", "0.", "if", "self", ".", "yaw", "is", "None", ":", "self", ".", "yaw", "=", "0.", "if", "self", ".", "aux", "is", "None", ":", "self", ".", "aux", "=", "quadrotor_msgs", ".", "msg", ".", "AuxCommand", "(", ")", "else", ":", "self", ".", "header", "=", "std_msgs", ".", "msg", ".", "Header", "(", ")", "self", ".", "thrust", "=", "0.", "self", ".", "roll", "=", "0.", "self", ".", "pitch", "=", "0.", "self", ".", "yaw", "=", "0.", "self", ".", "aux", "=", "quadrotor_msgs", ".", "msg", ".", "AuxCommand", "(", ")" ]
https://github.com/HKUST-Aerial-Robotics/Teach-Repeat-Replan/blob/98505a7f74b13c8b501176ff838a38423dbef536/utils/quadrotor_msgs/src/quadrotor_msgs/msg/_TRPYCommand.py#L51-L86
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/training/summary_io.py
python
SummaryWriter.flush
(self)
Flushes the event file to disk. Call this method to make sure that all pending events have been written to disk.
Flushes the event file to disk.
[ "Flushes", "the", "event", "file", "to", "disk", "." ]
def flush(self): """Flushes the event file to disk. Call this method to make sure that all pending events have been written to disk. """ self._event_queue.join() self._ev_writer.Flush()
[ "def", "flush", "(", "self", ")", ":", "self", ".", "_event_queue", ".", "join", "(", ")", "self", ".", "_ev_writer", ".", "Flush", "(", ")" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/training/summary_io.py#L265-L272
Alexhuszagh/rust-lexical
01fcdcf8efc8850edb35d8fc65fd5f31bd0981a0
lexical-util/etc/step.py
python
find_power
(max_value, radix)
return (power, power)
Find the power of the divisor.
Find the power of the divisor.
[ "Find", "the", "power", "of", "the", "divisor", "." ]
def find_power(max_value, radix): '''Find the power of the divisor.''' # Normally we'd use a log, but the log can be inaccurate. # We use it as a guiding point, but we take the floor - 1. power = int(math.floor(math.log(max_value, radix))) - 1 while radix**power <= max_value: power += 1 power -= 1 if radix**power < max_value: # Not fully divisible return (power, power + 1) return (power, power)
[ "def", "find_power", "(", "max_value", ",", "radix", ")", ":", "# Normally we'd use a log, but the log can be inaccurate.", "# We use it as a guiding point, but we take the floor - 1.", "power", "=", "int", "(", "math", ".", "floor", "(", "math", ".", "log", "(", "max_value", ",", "radix", ")", ")", ")", "-", "1", "while", "radix", "**", "power", "<=", "max_value", ":", "power", "+=", "1", "power", "-=", "1", "if", "radix", "**", "power", "<", "max_value", ":", "# Not fully divisible", "return", "(", "power", ",", "power", "+", "1", ")", "return", "(", "power", ",", "power", ")" ]
https://github.com/Alexhuszagh/rust-lexical/blob/01fcdcf8efc8850edb35d8fc65fd5f31bd0981a0/lexical-util/etc/step.py#L23-L35
htcondor/htcondor
4829724575176d1d6c936e4693dfd78a728569b0
src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/conversion.py
python
IConversion.TextToUserStatus
(self, Text)
return self._TextTo('cus', Text)
Returns user status code. @param Text: Text, one of L{User status<enums.cusUnknown>}. @type Text: unicode @return: User status. @rtype: L{User status<enums.cusUnknown>} @note: Currently, this method only checks if the given string is one of the allowed ones and returns it or raises a C{ValueError}.
Returns user status code.
[ "Returns", "user", "status", "code", "." ]
def TextToUserStatus(self, Text): '''Returns user status code. @param Text: Text, one of L{User status<enums.cusUnknown>}. @type Text: unicode @return: User status. @rtype: L{User status<enums.cusUnknown>} @note: Currently, this method only checks if the given string is one of the allowed ones and returns it or raises a C{ValueError}. ''' return self._TextTo('cus', Text)
[ "def", "TextToUserStatus", "(", "self", ",", "Text", ")", ":", "return", "self", ".", "_TextTo", "(", "'cus'", ",", "Text", ")" ]
https://github.com/htcondor/htcondor/blob/4829724575176d1d6c936e4693dfd78a728569b0/src/condor_contrib/condor_pigeon/src/condor_pigeon_client/skype_linux_tools/Skype4Py/conversion.py#L353-L363
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/ops/math_ops.py
python
_BroadcastShape
(op)
return [common_shapes.broadcast_shape( op.inputs[0].get_shape(), op.inputs[1].get_shape())]
Common shape function for binary operators that broadcast their inputs.
Common shape function for binary operators that broadcast their inputs.
[ "Common", "shape", "function", "for", "binary", "operators", "that", "broadcast", "their", "inputs", "." ]
def _BroadcastShape(op): """Common shape function for binary operators that broadcast their inputs.""" return [common_shapes.broadcast_shape( op.inputs[0].get_shape(), op.inputs[1].get_shape())]
[ "def", "_BroadcastShape", "(", "op", ")", ":", "return", "[", "common_shapes", ".", "broadcast_shape", "(", "op", ".", "inputs", "[", "0", "]", ".", "get_shape", "(", ")", ",", "op", ".", "inputs", "[", "1", "]", ".", "get_shape", "(", ")", ")", "]" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/ops/math_ops.py#L1867-L1871
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/telemetry/third_party/png/png.py
python
Reader.asRGB
(self)
return width,height,iterrgb(),meta
Return image as RGB pixels. RGB colour images are passed through unchanged; greyscales are expanded into RGB triplets (there is a small speed overhead for doing this). An alpha channel in the source image will raise an exception. The return values are as for the :meth:`read` method except that the *metadata* reflect the returned pixels, not the source image. In particular, for this method ``metadata['greyscale']`` will be ``False``.
Return image as RGB pixels. RGB colour images are passed through unchanged; greyscales are expanded into RGB triplets (there is a small speed overhead for doing this).
[ "Return", "image", "as", "RGB", "pixels", ".", "RGB", "colour", "images", "are", "passed", "through", "unchanged", ";", "greyscales", "are", "expanded", "into", "RGB", "triplets", "(", "there", "is", "a", "small", "speed", "overhead", "for", "doing", "this", ")", "." ]
def asRGB(self): """Return image as RGB pixels. RGB colour images are passed through unchanged; greyscales are expanded into RGB triplets (there is a small speed overhead for doing this). An alpha channel in the source image will raise an exception. The return values are as for the :meth:`read` method except that the *metadata* reflect the returned pixels, not the source image. In particular, for this method ``metadata['greyscale']`` will be ``False``. """ width,height,pixels,meta = self.asDirect() if meta['alpha']: raise Error("will not convert image with alpha channel to RGB") if not meta['greyscale']: return width,height,pixels,meta meta['greyscale'] = False typecode = 'BH'[meta['bitdepth'] > 8] def iterrgb(): for row in pixels: a = array(typecode, [0]) * 3 * width for i in range(3): a[i::3] = row yield a return width,height,iterrgb(),meta
[ "def", "asRGB", "(", "self", ")", ":", "width", ",", "height", ",", "pixels", ",", "meta", "=", "self", ".", "asDirect", "(", ")", "if", "meta", "[", "'alpha'", "]", ":", "raise", "Error", "(", "\"will not convert image with alpha channel to RGB\"", ")", "if", "not", "meta", "[", "'greyscale'", "]", ":", "return", "width", ",", "height", ",", "pixels", ",", "meta", "meta", "[", "'greyscale'", "]", "=", "False", "typecode", "=", "'BH'", "[", "meta", "[", "'bitdepth'", "]", ">", "8", "]", "def", "iterrgb", "(", ")", ":", "for", "row", "in", "pixels", ":", "a", "=", "array", "(", "typecode", ",", "[", "0", "]", ")", "*", "3", "*", "width", "for", "i", "in", "range", "(", "3", ")", ":", "a", "[", "i", ":", ":", "3", "]", "=", "row", "yield", "a", "return", "width", ",", "height", ",", "iterrgb", "(", ")", ",", "meta" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/telemetry/third_party/png/png.py#L2146-L2173
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py
python
WhileContext.AddForwardCounter
(self)
return total_iterations, next_n
Adds a loop that counts the number of iterations. This is added to the forward loop at the time when we start to create the loop for backprop gradient computation. Called in the outer context of this forward context. The pseudocode is: `n = 0; while (_pivot) { n++; }` Returns: The number of iterations taken by the forward loop and the loop index.
Adds a loop that counts the number of iterations.
[ "Adds", "a", "loop", "that", "counts", "the", "number", "of", "iterations", "." ]
def AddForwardCounter(self): """Adds a loop that counts the number of iterations. This is added to the forward loop at the time when we start to create the loop for backprop gradient computation. Called in the outer context of this forward context. The pseudocode is: `n = 0; while (_pivot) { n++; }` Returns: The number of iterations taken by the forward loop and the loop index. """ n = constant_op.constant(0, name="f_count") assert n.op._get_control_flow_context() == self.outer_context self.Enter() self.AddName(n.name) enter_n = _Enter(n, self._name, is_constant=False, parallel_iterations=self._parallel_iterations, name="f_count") merge_n = merge([enter_n, enter_n])[0] switch_n = switch(merge_n, self._pivot) index = math_ops.add(switch_n[1], 1) next_n = _NextIteration(index) merge_n.op._update_input(1, next_n) total_iterations = exit(switch_n[0], name="f_count") self.ExitResult([total_iterations]) self.Exit() return total_iterations, next_n
[ "def", "AddForwardCounter", "(", "self", ")", ":", "n", "=", "constant_op", ".", "constant", "(", "0", ",", "name", "=", "\"f_count\"", ")", "assert", "n", ".", "op", ".", "_get_control_flow_context", "(", ")", "==", "self", ".", "outer_context", "self", ".", "Enter", "(", ")", "self", ".", "AddName", "(", "n", ".", "name", ")", "enter_n", "=", "_Enter", "(", "n", ",", "self", ".", "_name", ",", "is_constant", "=", "False", ",", "parallel_iterations", "=", "self", ".", "_parallel_iterations", ",", "name", "=", "\"f_count\"", ")", "merge_n", "=", "merge", "(", "[", "enter_n", ",", "enter_n", "]", ")", "[", "0", "]", "switch_n", "=", "switch", "(", "merge_n", ",", "self", ".", "_pivot", ")", "index", "=", "math_ops", ".", "add", "(", "switch_n", "[", "1", "]", ",", "1", ")", "next_n", "=", "_NextIteration", "(", "index", ")", "merge_n", ".", "op", ".", "_update_input", "(", "1", ",", "next_n", ")", "total_iterations", "=", "exit", "(", "switch_n", "[", "0", "]", ",", "name", "=", "\"f_count\"", ")", "self", ".", "ExitResult", "(", "[", "total_iterations", "]", ")", "self", ".", "Exit", "(", ")", "return", "total_iterations", ",", "next_n" ]
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/ops/control_flow_ops.py#L1558-L1589
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/stubs.py
python
mem_fence
(*args, **kargs)
OpenCL mem_fence() Example: # local memory fence hsa.mem_fence(hsa.CLK_LOCAL_MEM_FENCE) # global memory fence hsa.mem_fence(hsa.CLK_GLOBAL_MEM_FENCE)
OpenCL mem_fence()
[ "OpenCL", "mem_fence", "()" ]
def mem_fence(*args, **kargs): """ OpenCL mem_fence() Example: # local memory fence hsa.mem_fence(hsa.CLK_LOCAL_MEM_FENCE) # global memory fence hsa.mem_fence(hsa.CLK_GLOBAL_MEM_FENCE) """ raise _stub_error
[ "def", "mem_fence", "(", "*", "args", ",", "*", "*", "kargs", ")", ":", "raise", "_stub_error" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/roc/stubs.py#L74-L85
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/internal/python_message.py
python
_ReraiseTypeErrorWithFieldName
(message_name, field_name)
Re-raise the currently-handled TypeError with the field name added.
Re-raise the currently-handled TypeError with the field name added.
[ "Re", "-", "raise", "the", "currently", "-", "handled", "TypeError", "with", "the", "field", "name", "added", "." ]
def _ReraiseTypeErrorWithFieldName(message_name, field_name): """Re-raise the currently-handled TypeError with the field name added.""" exc = sys.exc_info()[1] if len(exc.args) == 1 and type(exc) is TypeError: # simple TypeError; add field name to exception message exc = TypeError('%s for field %s.%s' % (str(exc), message_name, field_name)) # re-raise possibly-amended exception with original traceback: six.reraise(type(exc), exc, sys.exc_info()[2])
[ "def", "_ReraiseTypeErrorWithFieldName", "(", "message_name", ",", "field_name", ")", ":", "exc", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "len", "(", "exc", ".", "args", ")", "==", "1", "and", "type", "(", "exc", ")", "is", "TypeError", ":", "# simple TypeError; add field name to exception message", "exc", "=", "TypeError", "(", "'%s for field %s.%s'", "%", "(", "str", "(", "exc", ")", ",", "message_name", ",", "field_name", ")", ")", "# re-raise possibly-amended exception with original traceback:", "six", ".", "reraise", "(", "type", "(", "exc", ")", ",", "exc", ",", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/internal/python_message.py#L480-L488
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/propgrid.py
python
PropertyGrid.SetupTextCtrlValue
(*args, **kwargs)
return _propgrid.PropertyGrid_SetupTextCtrlValue(*args, **kwargs)
SetupTextCtrlValue(self, String text)
SetupTextCtrlValue(self, String text)
[ "SetupTextCtrlValue", "(", "self", "String", "text", ")" ]
def SetupTextCtrlValue(*args, **kwargs): """SetupTextCtrlValue(self, String text)""" return _propgrid.PropertyGrid_SetupTextCtrlValue(*args, **kwargs)
[ "def", "SetupTextCtrlValue", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGrid_SetupTextCtrlValue", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/propgrid.py#L2444-L2446
citizenfx/fivem
88276d40cc7baf8285d02754cc5ae42ec7a8563f
vendor/chromium/tools/diagnosis/crbug_1001171.py
python
DumpStateOnLookupError
()
Prints potentially useful state info in the event of a LookupError.
Prints potentially useful state info in the event of a LookupError.
[ "Prints", "potentially", "useful", "state", "info", "in", "the", "event", "of", "a", "LookupError", "." ]
def DumpStateOnLookupError(): """Prints potentially useful state info in the event of a LookupError.""" try: yield except LookupError: print('LookupError diagnosis for crbug.com/1001171:') for path_index, path_entry in enumerate(sys.path): desc = 'unknown' if not os.path.exists(path_entry): desc = 'missing' elif os.path.islink(path_entry): desc = 'link -> %s' % os.path.realpath(path_entry) elif os.path.isfile(path_entry): desc = 'file' elif os.path.isdir(path_entry): desc = 'dir' print(' sys.path[%d]: %s (%s)' % (path_index, path_entry, desc)) real_path_entry = os.path.realpath(path_entry) if (path_entry.endswith(os.path.join('lib', 'python2.7')) and os.path.isdir(real_path_entry)): encodings_dir = os.path.realpath( os.path.join(real_path_entry, 'encodings')) if os.path.exists(encodings_dir): if os.path.isdir(encodings_dir): print(' %s contents: %s' % (encodings_dir, str(os.listdir(encodings_dir)))) else: print(' %s exists but is not a directory' % encodings_dir) else: print(' %s missing' % encodings_dir) raise
[ "def", "DumpStateOnLookupError", "(", ")", ":", "try", ":", "yield", "except", "LookupError", ":", "print", "(", "'LookupError diagnosis for crbug.com/1001171:'", ")", "for", "path_index", ",", "path_entry", "in", "enumerate", "(", "sys", ".", "path", ")", ":", "desc", "=", "'unknown'", "if", "not", "os", ".", "path", ".", "exists", "(", "path_entry", ")", ":", "desc", "=", "'missing'", "elif", "os", ".", "path", ".", "islink", "(", "path_entry", ")", ":", "desc", "=", "'link -> %s'", "%", "os", ".", "path", ".", "realpath", "(", "path_entry", ")", "elif", "os", ".", "path", ".", "isfile", "(", "path_entry", ")", ":", "desc", "=", "'file'", "elif", "os", ".", "path", ".", "isdir", "(", "path_entry", ")", ":", "desc", "=", "'dir'", "print", "(", "' sys.path[%d]: %s (%s)'", "%", "(", "path_index", ",", "path_entry", ",", "desc", ")", ")", "real_path_entry", "=", "os", ".", "path", ".", "realpath", "(", "path_entry", ")", "if", "(", "path_entry", ".", "endswith", "(", "os", ".", "path", ".", "join", "(", "'lib'", ",", "'python2.7'", ")", ")", "and", "os", ".", "path", ".", "isdir", "(", "real_path_entry", ")", ")", ":", "encodings_dir", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "real_path_entry", ",", "'encodings'", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "encodings_dir", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "encodings_dir", ")", ":", "print", "(", "' %s contents: %s'", "%", "(", "encodings_dir", ",", "str", "(", "os", ".", "listdir", "(", "encodings_dir", ")", ")", ")", ")", "else", ":", "print", "(", "' %s exists but is not a directory'", "%", "encodings_dir", ")", "else", ":", "print", "(", "' %s missing'", "%", "encodings_dir", ")", "raise" ]
https://github.com/citizenfx/fivem/blob/88276d40cc7baf8285d02754cc5ae42ec7a8563f/vendor/chromium/tools/diagnosis/crbug_1001171.py#L19-L51
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
compiler-rt/lib/asan/scripts/asan_symbolize.py
python
AsanSymbolizerPlugIn.process_cmdline_args
(self, pargs)
return True
Hook for handling parsed arguments. Implementations should not modify `pargs`. `pargs` - Instance of `argparse.Namespace` containing parsed command line arguments. Return `True` if plug-in should be used, otherwise return `False`.
Hook for handling parsed arguments. Implementations should not modify `pargs`.
[ "Hook", "for", "handling", "parsed", "arguments", ".", "Implementations", "should", "not", "modify", "pargs", "." ]
def process_cmdline_args(self, pargs): """ Hook for handling parsed arguments. Implementations should not modify `pargs`. `pargs` - Instance of `argparse.Namespace` containing parsed command line arguments. Return `True` if plug-in should be used, otherwise return `False`. """ return True
[ "def", "process_cmdline_args", "(", "self", ",", "pargs", ")", ":", "return", "True" ]
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/compiler-rt/lib/asan/scripts/asan_symbolize.py#L670-L681
google/earthenterprise
0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9
earth_enterprise/src/server/wsgi/wms/ogc/common/tilecalcs.py
python
CalcZoomLevel
(log_extent, total_log_extent, pixel_extent)
return zoom
Calculates zoom level. We want a zoom level that has enough detail to match the user's request (i.e., we do our best not to give stretched-out pixels). A bigger zoom == more pixels + detail. But, it would be wasteful to use a higher zoom level than necessary. Args: log_extent: map-space width, height. total_log_extent: total defined map-space extent (size of projection bounds, in its output coordinates). pixel_extent: desired width, height of the final pixel image. Returns: zoom level with at least as much detail as required.
Calculates zoom level.
[ "Calculates", "zoom", "level", "." ]
def CalcZoomLevel(log_extent, total_log_extent, pixel_extent): """Calculates zoom level. We want a zoom level that has enough detail to match the user's request (i.e., we do our best not to give stretched-out pixels). A bigger zoom == more pixels + detail. But, it would be wasteful to use a higher zoom level than necessary. Args: log_extent: map-space width, height. total_log_extent: total defined map-space extent (size of projection bounds, in its output coordinates). pixel_extent: desired width, height of the final pixel image. Returns: zoom level with at least as much detail as required. """ utils.Assert(isinstance(log_extent, geom.Pair)) utils.Assert(isinstance(total_log_extent, geom.Pair)) utils.Assert(isinstance(pixel_extent, geom.Pair)) # Simple, component-wise division. fraction_of_total = log_extent / total_log_extent total_pixel_extent_needed = pixel_extent / fraction_of_total logger.debug("Pixel extent needed %s", str(total_pixel_extent_needed)) # We want to round the zoom level up; ie, have /at least/ 1 tile pixel # per requested pixel. # 256 x 2^zoom >= totalpixelextent => zoom = log_2(totalpixelextent / 256) x_zoom = int(math.log(math.ceil( total_pixel_extent_needed.x / float(_TILE_PIXEL_SIZE)), 2)) y_zoom = int(math.log(math.ceil( total_pixel_extent_needed.y / float(_TILE_PIXEL_SIZE)), 2)) logger.debug("Zoom:x,y %d, %d", x_zoom, y_zoom) zoom = max(x_zoom, y_zoom) if _MAX_ZOOM < zoom: logger.warning("WHOA; wild zoom (%d - should be max %d), " "alert Google. Limiting to %d.", zoom, _MAX_ZOOM, _MAX_ZOOM) zoom = _MAX_ZOOM return zoom
[ "def", "CalcZoomLevel", "(", "log_extent", ",", "total_log_extent", ",", "pixel_extent", ")", ":", "utils", ".", "Assert", "(", "isinstance", "(", "log_extent", ",", "geom", ".", "Pair", ")", ")", "utils", ".", "Assert", "(", "isinstance", "(", "total_log_extent", ",", "geom", ".", "Pair", ")", ")", "utils", ".", "Assert", "(", "isinstance", "(", "pixel_extent", ",", "geom", ".", "Pair", ")", ")", "# Simple, component-wise division.", "fraction_of_total", "=", "log_extent", "/", "total_log_extent", "total_pixel_extent_needed", "=", "pixel_extent", "/", "fraction_of_total", "logger", ".", "debug", "(", "\"Pixel extent needed %s\"", ",", "str", "(", "total_pixel_extent_needed", ")", ")", "# We want to round the zoom level up; ie, have /at least/ 1 tile pixel", "# per requested pixel.", "# 256 x 2^zoom >= totalpixelextent => zoom = log_2(totalpixelextent / 256)", "x_zoom", "=", "int", "(", "math", ".", "log", "(", "math", ".", "ceil", "(", "total_pixel_extent_needed", ".", "x", "/", "float", "(", "_TILE_PIXEL_SIZE", ")", ")", ",", "2", ")", ")", "y_zoom", "=", "int", "(", "math", ".", "log", "(", "math", ".", "ceil", "(", "total_pixel_extent_needed", ".", "y", "/", "float", "(", "_TILE_PIXEL_SIZE", ")", ")", ",", "2", ")", ")", "logger", ".", "debug", "(", "\"Zoom:x,y %d, %d\"", ",", "x_zoom", ",", "y_zoom", ")", "zoom", "=", "max", "(", "x_zoom", ",", "y_zoom", ")", "if", "_MAX_ZOOM", "<", "zoom", ":", "logger", ".", "warning", "(", "\"WHOA; wild zoom (%d - should be max %d), \"", "\"alert Google. Limiting to %d.\"", ",", "zoom", ",", "_MAX_ZOOM", ",", "_MAX_ZOOM", ")", "zoom", "=", "_MAX_ZOOM", "return", "zoom" ]
https://github.com/google/earthenterprise/blob/0fe84e29be470cd857e3a0e52e5d0afd5bb8cee9/earth_enterprise/src/server/wsgi/wms/ogc/common/tilecalcs.py#L33-L75
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/os.py
python
renames
(old, new)
renames(old, new) Super-rename; create directories as necessary and delete any left empty. Works like rename, except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned way until either the whole path is consumed or a nonempty directory is found. Note: this function can fail with the new directory structure made if you lack permissions needed to unlink the leaf directory or file.
renames(old, new)
[ "renames", "(", "old", "new", ")" ]
def renames(old, new): """renames(old, new) Super-rename; create directories as necessary and delete any left empty. Works like rename, except creation of any intermediate directories needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost path segments of the old name will be pruned way until either the whole path is consumed or a nonempty directory is found. Note: this function can fail with the new directory structure made if you lack permissions needed to unlink the leaf directory or file. """ head, tail = path.split(new) if head and tail and not path.exists(head): makedirs(head) rename(old, new) head, tail = path.split(old) if head and tail: try: removedirs(head) except error: pass
[ "def", "renames", "(", "old", ",", "new", ")", ":", "head", ",", "tail", "=", "path", ".", "split", "(", "new", ")", "if", "head", "and", "tail", "and", "not", "path", ".", "exists", "(", "head", ")", ":", "makedirs", "(", "head", ")", "rename", "(", "old", ",", "new", ")", "head", ",", "tail", "=", "path", ".", "split", "(", "old", ")", "if", "head", "and", "tail", ":", "try", ":", "removedirs", "(", "head", ")", "except", "error", ":", "pass" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/os.py#L181-L205
mapnik/mapnik
f3da900c355e1d15059c4a91b00203dcc9d9f0ef
scons/scons-local-4.1.0/SCons/SConf.py
python
SConfBase.TryBuild
(self, builder, text=None, extension="")
return result
Low level TryBuild implementation. Normally you don't need to call that - you can use TryCompile / TryLink / TryRun instead
Low level TryBuild implementation. Normally you don't need to call that - you can use TryCompile / TryLink / TryRun instead
[ "Low", "level", "TryBuild", "implementation", ".", "Normally", "you", "don", "t", "need", "to", "call", "that", "-", "you", "can", "use", "TryCompile", "/", "TryLink", "/", "TryRun", "instead" ]
def TryBuild(self, builder, text=None, extension=""): """Low level TryBuild implementation. Normally you don't need to call that - you can use TryCompile / TryLink / TryRun instead """ global _ac_build_counter # Make sure we have a PSPAWN value, and save the current # SPAWN value. try: self.pspawn = self.env['PSPAWN'] except KeyError: raise SCons.Errors.UserError('Missing PSPAWN construction variable.') try: save_spawn = self.env['SPAWN'] except KeyError: raise SCons.Errors.UserError('Missing SPAWN construction variable.') nodesToBeBuilt = [] sourcetext = self.env.Value(text) self._set_conftest_node(sourcetext) f = "conftest" if text is not None: textSig = SCons.Util.MD5signature(sourcetext) textSigCounter = str(_ac_build_counter[textSig]) _ac_build_counter[textSig] += 1 f = "_".join([f, textSig, textSigCounter]) textFile = self.confdir.File(f + extension) self._set_conftest_node(sourcetext) textFileNode = self.env.SConfSourceBuilder(target=textFile, source=sourcetext) nodesToBeBuilt.extend(textFileNode) source = textFile target = textFile.File(f + "SConfActionsContentDummyTarget") self._set_conftest_node(target) else: source = None target = None action = builder.builder.action.get_contents(target=target, source=[source], env=self.env) actionsig = SCons.Util.MD5signature(action) f = "_".join([f, actionsig]) pref = self.env.subst( builder.builder.prefix ) suff = self.env.subst( builder.builder.suffix ) target = self.confdir.File(pref + f + suff) try: # Slide our wrapper into the construction environment as # the SPAWN function. self.env['SPAWN'] = self.pspawn_wrapper nodes = builder(target = target, source = source) if not SCons.Util.is_List(nodes): nodes = [nodes] nodesToBeBuilt.extend(nodes) result = self.BuildNodes(nodesToBeBuilt) finally: self.env['SPAWN'] = save_spawn if result: self.lastTarget = nodes[0] else: self.lastTarget = None return result
[ "def", "TryBuild", "(", "self", ",", "builder", ",", "text", "=", "None", ",", "extension", "=", "\"\"", ")", ":", "global", "_ac_build_counter", "# Make sure we have a PSPAWN value, and save the current", "# SPAWN value.", "try", ":", "self", ".", "pspawn", "=", "self", ".", "env", "[", "'PSPAWN'", "]", "except", "KeyError", ":", "raise", "SCons", ".", "Errors", ".", "UserError", "(", "'Missing PSPAWN construction variable.'", ")", "try", ":", "save_spawn", "=", "self", ".", "env", "[", "'SPAWN'", "]", "except", "KeyError", ":", "raise", "SCons", ".", "Errors", ".", "UserError", "(", "'Missing SPAWN construction variable.'", ")", "nodesToBeBuilt", "=", "[", "]", "sourcetext", "=", "self", ".", "env", ".", "Value", "(", "text", ")", "self", ".", "_set_conftest_node", "(", "sourcetext", ")", "f", "=", "\"conftest\"", "if", "text", "is", "not", "None", ":", "textSig", "=", "SCons", ".", "Util", ".", "MD5signature", "(", "sourcetext", ")", "textSigCounter", "=", "str", "(", "_ac_build_counter", "[", "textSig", "]", ")", "_ac_build_counter", "[", "textSig", "]", "+=", "1", "f", "=", "\"_\"", ".", "join", "(", "[", "f", ",", "textSig", ",", "textSigCounter", "]", ")", "textFile", "=", "self", ".", "confdir", ".", "File", "(", "f", "+", "extension", ")", "self", ".", "_set_conftest_node", "(", "sourcetext", ")", "textFileNode", "=", "self", ".", "env", ".", "SConfSourceBuilder", "(", "target", "=", "textFile", ",", "source", "=", "sourcetext", ")", "nodesToBeBuilt", ".", "extend", "(", "textFileNode", ")", "source", "=", "textFile", "target", "=", "textFile", ".", "File", "(", "f", "+", "\"SConfActionsContentDummyTarget\"", ")", "self", ".", "_set_conftest_node", "(", "target", ")", "else", ":", "source", "=", "None", "target", "=", "None", "action", "=", "builder", ".", "builder", ".", "action", ".", "get_contents", "(", "target", "=", "target", ",", "source", "=", "[", "source", "]", ",", "env", "=", "self", ".", "env", ")", "actionsig", "=", "SCons", ".", "Util", ".", "MD5signature", "(", "action", ")", "f", "=", "\"_\"", ".", "join", "(", "[", "f", ",", "actionsig", "]", ")", "pref", "=", "self", ".", "env", ".", "subst", "(", "builder", ".", "builder", ".", "prefix", ")", "suff", "=", "self", ".", "env", ".", "subst", "(", "builder", ".", "builder", ".", "suffix", ")", "target", "=", "self", ".", "confdir", ".", "File", "(", "pref", "+", "f", "+", "suff", ")", "try", ":", "# Slide our wrapper into the construction environment as", "# the SPAWN function.", "self", ".", "env", "[", "'SPAWN'", "]", "=", "self", ".", "pspawn_wrapper", "nodes", "=", "builder", "(", "target", "=", "target", ",", "source", "=", "source", ")", "if", "not", "SCons", ".", "Util", ".", "is_List", "(", "nodes", ")", ":", "nodes", "=", "[", "nodes", "]", "nodesToBeBuilt", ".", "extend", "(", "nodes", ")", "result", "=", "self", ".", "BuildNodes", "(", "nodesToBeBuilt", ")", "finally", ":", "self", ".", "env", "[", "'SPAWN'", "]", "=", "save_spawn", "if", "result", ":", "self", ".", "lastTarget", "=", "nodes", "[", "0", "]", "else", ":", "self", ".", "lastTarget", "=", "None", "return", "result" ]
https://github.com/mapnik/mapnik/blob/f3da900c355e1d15059c4a91b00203dcc9d9f0ef/scons/scons-local-4.1.0/SCons/SConf.py#L578-L646
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/traitlets/py3/traitlets/traitlets.py
python
TraitType.from_string
(self, s)
return s
Get a value from a config string such as an environment variable or CLI arguments. Traits can override this method to define their own parsing of config strings. .. seealso:: item_from_string .. versionadded:: 5.0
Get a value from a config string
[ "Get", "a", "value", "from", "a", "config", "string" ]
def from_string(self, s): """Get a value from a config string such as an environment variable or CLI arguments. Traits can override this method to define their own parsing of config strings. .. seealso:: item_from_string .. versionadded:: 5.0 """ if self.allow_none and s == 'None': return None return s
[ "def", "from_string", "(", "self", ",", "s", ")", ":", "if", "self", ".", "allow_none", "and", "s", "==", "'None'", ":", "return", "None", "return", "s" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py3/traitlets/traitlets.py#L486-L500
hszhao/PSPNet
cf7e5a99ba37e46118026e96be5821a9bc63bde0
scripts/cpp_lint.py
python
CleansedLines.NumLines
(self)
return self.num_lines
Returns the number of lines represented.
Returns the number of lines represented.
[ "Returns", "the", "number", "of", "lines", "represented", "." ]
def NumLines(self): """Returns the number of lines represented.""" return self.num_lines
[ "def", "NumLines", "(", "self", ")", ":", "return", "self", ".", "num_lines" ]
https://github.com/hszhao/PSPNet/blob/cf7e5a99ba37e46118026e96be5821a9bc63bde0/scripts/cpp_lint.py#L1204-L1206
Z3Prover/z3
d745d03afdfdf638d66093e2bfbacaf87187f35b
src/api/python/z3/z3.py
python
SeqSort
(s)
return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
Create a sequence sort over elements provided in the argument >>> s = SeqSort(IntSort()) >>> s == Unit(IntVal(1)).sort() True
Create a sequence sort over elements provided in the argument >>> s = SeqSort(IntSort()) >>> s == Unit(IntVal(1)).sort() True
[ "Create", "a", "sequence", "sort", "over", "elements", "provided", "in", "the", "argument", ">>>", "s", "=", "SeqSort", "(", "IntSort", "()", ")", ">>>", "s", "==", "Unit", "(", "IntVal", "(", "1", "))", ".", "sort", "()", "True" ]
def SeqSort(s): """Create a sequence sort over elements provided in the argument >>> s = SeqSort(IntSort()) >>> s == Unit(IntVal(1)).sort() True """ return SeqSortRef(Z3_mk_seq_sort(s.ctx_ref(), s.ast), s.ctx)
[ "def", "SeqSort", "(", "s", ")", ":", "return", "SeqSortRef", "(", "Z3_mk_seq_sort", "(", "s", ".", "ctx_ref", "(", ")", ",", "s", ".", "ast", ")", ",", "s", ".", "ctx", ")" ]
https://github.com/Z3Prover/z3/blob/d745d03afdfdf638d66093e2bfbacaf87187f35b/src/api/python/z3/z3.py#L10635-L10641
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/html5lib/html5parser.py
python
parse
(doc, treebuilder="etree", namespaceHTMLElements=True, **kwargs)
return p.parse(doc, **kwargs)
Parse an HTML document as a string or file-like object into a tree :arg doc: the document to parse as a string or file-like object :arg treebuilder: the treebuilder to use when parsing :arg namespaceHTMLElements: whether or not to namespace HTML elements :returns: parsed tree Example: >>> from html5lib.html5parser import parse >>> parse('<html><body><p>This is a doc</p></body></html>') <Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0>
Parse an HTML document as a string or file-like object into a tree
[ "Parse", "an", "HTML", "document", "as", "a", "string", "or", "file", "-", "like", "object", "into", "a", "tree" ]
def parse(doc, treebuilder="etree", namespaceHTMLElements=True, **kwargs): """Parse an HTML document as a string or file-like object into a tree :arg doc: the document to parse as a string or file-like object :arg treebuilder: the treebuilder to use when parsing :arg namespaceHTMLElements: whether or not to namespace HTML elements :returns: parsed tree Example: >>> from html5lib.html5parser import parse >>> parse('<html><body><p>This is a doc</p></body></html>') <Element u'{http://www.w3.org/1999/xhtml}html' at 0x7feac4909db0> """ tb = treebuilders.getTreeBuilder(treebuilder) p = HTMLParser(tb, namespaceHTMLElements=namespaceHTMLElements) return p.parse(doc, **kwargs)
[ "def", "parse", "(", "doc", ",", "treebuilder", "=", "\"etree\"", ",", "namespaceHTMLElements", "=", "True", ",", "*", "*", "kwargs", ")", ":", "tb", "=", "treebuilders", ".", "getTreeBuilder", "(", "treebuilder", ")", "p", "=", "HTMLParser", "(", "tb", ",", "namespaceHTMLElements", "=", "namespaceHTMLElements", ")", "return", "p", ".", "parse", "(", "doc", ",", "*", "*", "kwargs", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/html5lib/html5parser.py#L27-L47
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/strided_read.py
python
_strided_read_tbe
()
return
StridedRead TBE register
StridedRead TBE register
[ "StridedRead", "TBE", "register" ]
def _strided_read_tbe(): """StridedRead TBE register""" return
[ "def", "_strided_read_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/strided_read.py#L36-L38
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py
python
SBAddress.GetLineEntry
(self)
return _lldb.SBAddress_GetLineEntry(self)
GetLineEntry(self) -> SBLineEntry
GetLineEntry(self) -> SBLineEntry
[ "GetLineEntry", "(", "self", ")", "-", ">", "SBLineEntry" ]
def GetLineEntry(self): """GetLineEntry(self) -> SBLineEntry""" return _lldb.SBAddress_GetLineEntry(self)
[ "def", "GetLineEntry", "(", "self", ")", ":", "return", "_lldb", ".", "SBAddress_GetLineEntry", "(", "self", ")" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/scripts/Python/static-binding/lldb.py#L948-L950
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/layers/python/layers/feature_column.py
python
_BucketizedColumn.key
(self)
return "{}".format(self)
Returns a string which will be used as a key when we do sorting.
Returns a string which will be used as a key when we do sorting.
[ "Returns", "a", "string", "which", "will", "be", "used", "as", "a", "key", "when", "we", "do", "sorting", "." ]
def key(self): """Returns a string which will be used as a key when we do sorting.""" return "{}".format(self)
[ "def", "key", "(", "self", ")", ":", "return", "\"{}\"", ".", "format", "(", "self", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/layers/python/layers/feature_column.py#L2036-L2038
DGA-MI-SSI/YaCo
9b85e6ca1809114c4df1382c11255f7e38408912
deps/flatbuffers-1.8.0/python/flatbuffers/table.py
python
Table.GetVOffsetTSlot
(self, slot, d)
return off
GetVOffsetTSlot retrieves the VOffsetT that the given vtable location points to. If the vtable value is zero, the default value `d` will be returned.
GetVOffsetTSlot retrieves the VOffsetT that the given vtable location points to. If the vtable value is zero, the default value `d` will be returned.
[ "GetVOffsetTSlot", "retrieves", "the", "VOffsetT", "that", "the", "given", "vtable", "location", "points", "to", ".", "If", "the", "vtable", "value", "is", "zero", "the", "default", "value", "d", "will", "be", "returned", "." ]
def GetVOffsetTSlot(self, slot, d): """ GetVOffsetTSlot retrieves the VOffsetT that the given vtable location points to. If the vtable value is zero, the default value `d` will be returned. """ N.enforce_number(slot, N.VOffsetTFlags) N.enforce_number(d, N.VOffsetTFlags) off = self.Offset(slot) if off == 0: return d return off
[ "def", "GetVOffsetTSlot", "(", "self", ",", "slot", ",", "d", ")", ":", "N", ".", "enforce_number", "(", "slot", ",", "N", ".", "VOffsetTFlags", ")", "N", ".", "enforce_number", "(", "d", ",", "N", ".", "VOffsetTFlags", ")", "off", "=", "self", ".", "Offset", "(", "slot", ")", "if", "off", "==", "0", ":", "return", "d", "return", "off" ]
https://github.com/DGA-MI-SSI/YaCo/blob/9b85e6ca1809114c4df1382c11255f7e38408912/deps/flatbuffers-1.8.0/python/flatbuffers/table.py#L116-L129
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/util.py
python
EventMixin.remove
(self, event, subscriber)
Remove a subscriber for an event. :param event: The name of an event. :param subscriber: The subscriber to be removed.
Remove a subscriber for an event.
[ "Remove", "a", "subscriber", "for", "an", "event", "." ]
def remove(self, event, subscriber): """ Remove a subscriber for an event. :param event: The name of an event. :param subscriber: The subscriber to be removed. """ subs = self._subscribers if event not in subs: raise ValueError('No subscribers: %r' % event) subs[event].remove(subscriber)
[ "def", "remove", "(", "self", ",", "event", ",", "subscriber", ")", ":", "subs", "=", "self", ".", "_subscribers", "if", "event", "not", "in", "subs", ":", "raise", "ValueError", "(", "'No subscribers: %r'", "%", "event", ")", "subs", "[", "event", "]", ".", "remove", "(", "subscriber", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/util.py#L845-L855
ucbrise/clipper
9f25e3fc7f8edc891615e81c5b80d3d8aed72608
clipper_admin/clipper_admin/docker/docker_metric_utils.py
python
setup_metric_config
(query_frontend_metric_name, prom_config_path, CLIPPER_INTERNAL_METRIC_PORT)
Write to file prometheus.yml after frontend-metric is setup. :param query_frontend_metric_name: Corresponding image name :param prom_config_path: Prometheus config file to write in :param CLIPPER_INTERNAL_METRIC_PORT: Default port. :return: None
Write to file prometheus.yml after frontend-metric is setup. :param query_frontend_metric_name: Corresponding image name :param prom_config_path: Prometheus config file to write in :param CLIPPER_INTERNAL_METRIC_PORT: Default port. :return: None
[ "Write", "to", "file", "prometheus", ".", "yml", "after", "frontend", "-", "metric", "is", "setup", ".", ":", "param", "query_frontend_metric_name", ":", "Corresponding", "image", "name", ":", "param", "prom_config_path", ":", "Prometheus", "config", "file", "to", "write", "in", ":", "param", "CLIPPER_INTERNAL_METRIC_PORT", ":", "Default", "port", ".", ":", "return", ":", "None" ]
def setup_metric_config(query_frontend_metric_name, prom_config_path, CLIPPER_INTERNAL_METRIC_PORT): """ Write to file prometheus.yml after frontend-metric is setup. :param query_frontend_metric_name: Corresponding image name :param prom_config_path: Prometheus config file to write in :param CLIPPER_INTERNAL_METRIC_PORT: Default port. :return: None """ with open(prom_config_path, 'w') as f: prom_config = _get_prometheus_base_config() prom_config_query_frontend = { 'job_name': 'query', 'static_configs': [{ 'targets': [ '{name}:{port}'.format( name=query_frontend_metric_name, port=CLIPPER_INTERNAL_METRIC_PORT) ] }] } prom_config['scrape_configs'].append(prom_config_query_frontend) yaml.dump(prom_config, f)
[ "def", "setup_metric_config", "(", "query_frontend_metric_name", ",", "prom_config_path", ",", "CLIPPER_INTERNAL_METRIC_PORT", ")", ":", "with", "open", "(", "prom_config_path", ",", "'w'", ")", "as", "f", ":", "prom_config", "=", "_get_prometheus_base_config", "(", ")", "prom_config_query_frontend", "=", "{", "'job_name'", ":", "'query'", ",", "'static_configs'", ":", "[", "{", "'targets'", ":", "[", "'{name}:{port}'", ".", "format", "(", "name", "=", "query_frontend_metric_name", ",", "port", "=", "CLIPPER_INTERNAL_METRIC_PORT", ")", "]", "}", "]", "}", "prom_config", "[", "'scrape_configs'", "]", ".", "append", "(", "prom_config_query_frontend", ")", "yaml", ".", "dump", "(", "prom_config", ",", "f", ")" ]
https://github.com/ucbrise/clipper/blob/9f25e3fc7f8edc891615e81c5b80d3d8aed72608/clipper_admin/clipper_admin/docker/docker_metric_utils.py#L48-L73