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
perilouswithadollarsign/cstrike15_src
f82112a2388b841d72cb62ca48ab1846dfcc11c8
thirdparty/protobuf-2.5.0/python/google/protobuf/internal/python_message.py
python
_ExtensionDict.__init__
(self, extended_message)
extended_message: Message instance for which we are the Extensions dict.
extended_message: Message instance for which we are the Extensions dict.
[ "extended_message", ":", "Message", "instance", "for", "which", "we", "are", "the", "Extensions", "dict", "." ]
def __init__(self, extended_message): """extended_message: Message instance for which we are the Extensions dict. """ self._extended_message = extended_message
[ "def", "__init__", "(", "self", ",", "extended_message", ")", ":", "self", ".", "_extended_message", "=", "extended_message" ]
https://github.com/perilouswithadollarsign/cstrike15_src/blob/f82112a2388b841d72cb62ca48ab1846dfcc11c8/thirdparty/protobuf-2.5.0/python/google/protobuf/internal/python_message.py#L1058-L1062
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/python/client/timeline.py
python
_ChromeTraceFormatter.emit_obj_create
(self, category, name, timestamp, pid, tid, object_id)
Adds an object creation event to the trace. Args: category: The event category as a string. name: The event name as a string. timestamp: The timestamp of this event as a long integer. pid: Identifier of the process generating this event as an integer. tid: Identifier of the thread generating this event as an integer. object_id: Identifier of the object as an integer.
Adds an object creation event to the trace.
[ "Adds", "an", "object", "creation", "event", "to", "the", "trace", "." ]
def emit_obj_create(self, category, name, timestamp, pid, tid, object_id): """Adds an object creation event to the trace. Args: category: The event category as a string. name: The event name as a string. timestamp: The timestamp of this event as a long integer. pid: Identifier of the process generating this event as an integer. tid: Identifier of the thread generating this event as an integer. object_id: Identifier of the object as an integer. """ event = self._create_event('N', category, name, pid, tid, timestamp) event['id'] = object_id self._events.append(event)
[ "def", "emit_obj_create", "(", "self", ",", "category", ",", "name", ",", "timestamp", ",", "pid", ",", "tid", ",", "object_id", ")", ":", "event", "=", "self", ".", "_create_event", "(", "'N'", ",", "category", ",", "name", ",", "pid", ",", "tid", "...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/python/client/timeline.py#L138-L151
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_controls.py
python
TextCtrl.Create
(*args, **kwargs)
return _controls_.TextCtrl_Create(*args, **kwargs)
Create(self, Window parent, int id=-1, String value=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=TextCtrlNameStr) -> bool
Create(self, Window parent, int id=-1, String value=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=TextCtrlNameStr) -> bool
[ "Create", "(", "self", "Window", "parent", "int", "id", "=", "-", "1", "String", "value", "=", "EmptyString", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "long", "style", "=", "0", "Validator", "validator", "=", "DefaultValida...
def Create(*args, **kwargs): """ Create(self, Window parent, int id=-1, String value=EmptyString, Point pos=DefaultPosition, Size size=DefaultSize, long style=0, Validator validator=DefaultValidator, String name=TextCtrlNameStr) -> bool """ return _controls_.TextCtrl_Create(*args, **kwargs)
[ "def", "Create", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "TextCtrl_Create", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_controls.py#L2022-L2029
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/client/session.py
python
BaseSession.close
(self)
Closes this session. Calling this method frees all resources associated with the session. Raises: tf.errors.OpError: Or one of its subclasses if an error occurs while closing the TensorFlow session.
Closes this session.
[ "Closes", "this", "session", "." ]
def close(self): """Closes this session. Calling this method frees all resources associated with the session. Raises: tf.errors.OpError: Or one of its subclasses if an error occurs while closing the TensorFlow session. """ if self._created_with_new_api: if self._session and not self._closed: self._closed = True with errors.raise_exception_on_not_ok_status() as status: tf_session.TF_CloseSession(self._session, status) else: with self._extend_lock: if self._opened and not self._closed: self._closed = True with errors.raise_exception_on_not_ok_status() as status: tf_session.TF_CloseDeprecatedSession(self._session, status)
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_created_with_new_api", ":", "if", "self", ".", "_session", "and", "not", "self", ".", "_closed", ":", "self", ".", "_closed", "=", "True", "with", "errors", ".", "raise_exception_on_not_ok_status", ...
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/client/session.py#L665-L685
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/compat/__init__.py
python
is_platform_linux
()
return sys.platform == "linux2"
Checking if the running platform is linux. Returns ------- bool True if the running platform is linux.
Checking if the running platform is linux.
[ "Checking", "if", "the", "running", "platform", "is", "linux", "." ]
def is_platform_linux() -> bool: """ Checking if the running platform is linux. Returns ------- bool True if the running platform is linux. """ return sys.platform == "linux2"
[ "def", "is_platform_linux", "(", ")", "->", "bool", ":", "return", "sys", ".", "platform", "==", "\"linux2\"" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/compat/__init__.py#L63-L72
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/pickle.py
python
Pickler.clear_memo
(self)
Clears the pickler's "memo". The memo is the data structure that remembers which objects the pickler has already seen, so that shared or recursive objects are pickled by reference and not by value. This method is useful when re-using picklers.
Clears the pickler's "memo".
[ "Clears", "the", "pickler", "s", "memo", "." ]
def clear_memo(self): """Clears the pickler's "memo". The memo is the data structure that remembers which objects the pickler has already seen, so that shared or recursive objects are pickled by reference and not by value. This method is useful when re-using picklers. """ self.memo.clear()
[ "def", "clear_memo", "(", "self", ")", ":", "self", ".", "memo", ".", "clear", "(", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/pickle.py#L209-L218
verilog-to-routing/vtr-verilog-to-routing
d9719cf7374821156c3cee31d66991cb85578562
vtr_flow/scripts/python_libs/vtr/task.py
python
Job.arch
(self)
return self._arch
return the architecture file name of the job
return the architecture file name of the job
[ "return", "the", "architecture", "file", "name", "of", "the", "job" ]
def arch(self): """ return the architecture file name of the job """ return self._arch
[ "def", "arch", "(", "self", ")", ":", "return", "self", ".", "_arch" ]
https://github.com/verilog-to-routing/vtr-verilog-to-routing/blob/d9719cf7374821156c3cee31d66991cb85578562/vtr_flow/scripts/python_libs/vtr/task.py#L114-L118
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/dygraph/dygraph_to_static/convert_operators.py
python
choose_shape_attr_or_api
(attr_shape, api_shape, idx=None)
return attr_shape if idx is None else attr_shape[idx]
Input can be attribute `x.shape` or api `shape(x)`, this function chooses which one to return to use in dy2stat. Note: sometimes users write `x.shape[3]`, so attr_shape can be an integer.
Input can be attribute `x.shape` or api `shape(x)`, this function chooses which one to return to use in dy2stat.
[ "Input", "can", "be", "attribute", "x", ".", "shape", "or", "api", "shape", "(", "x", ")", "this", "function", "chooses", "which", "one", "to", "return", "to", "use", "in", "dy2stat", "." ]
def choose_shape_attr_or_api(attr_shape, api_shape, idx=None): """ Input can be attribute `x.shape` or api `shape(x)`, this function chooses which one to return to use in dy2stat. Note: sometimes users write `x.shape[3]`, so attr_shape can be an integer. """ if api_shape is None: return attr_shape if idx is None else attr_shape[idx] if not isinstance(attr_shape, (list, tuple)): # some variables like x.shape[0] is no longer a list or tuple if isinstance(attr_shape, int) and attr_shape < 0: return api_shape if idx is None else api_shape[idx] return attr_shape if idx is None else attr_shape[idx] def has_negative(list_shape, idx=None): if idx is not None: return list_shape[idx] < 0 num_negative = sum([1 if i < 0 else 0 for i in list_shape]) return num_negative > 0 if has_negative(attr_shape, idx): return api_shape if idx is None else api_shape[idx] return attr_shape if idx is None else attr_shape[idx]
[ "def", "choose_shape_attr_or_api", "(", "attr_shape", ",", "api_shape", ",", "idx", "=", "None", ")", ":", "if", "api_shape", "is", "None", ":", "return", "attr_shape", "if", "idx", "is", "None", "else", "attr_shape", "[", "idx", "]", "if", "not", "isinsta...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/dygraph/dygraph_to_static/convert_operators.py#L353-L377
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/threading.py
python
_Condition.notifyAll
(self)
Wake up all threads waiting on this condition. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised.
Wake up all threads waiting on this condition.
[ "Wake", "up", "all", "threads", "waiting", "on", "this", "condition", "." ]
def notifyAll(self): """Wake up all threads waiting on this condition. If the calling thread has not acquired the lock when this method is called, a RuntimeError is raised. """ self.notify(len(self.__waiters))
[ "def", "notifyAll", "(", "self", ")", ":", "self", ".", "notify", "(", "len", "(", "self", ".", "__waiters", ")", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/threading.py#L399-L406
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
SymbolExtractorAndRenamer/lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py
python
PaneLayout.havePane
(self, name)
return name in self.panes
Returns true if name is a registered pane, False otherwise
Returns true if name is a registered pane, False otherwise
[ "Returns", "true", "if", "name", "is", "a", "registered", "pane", "False", "otherwise" ]
def havePane(self, name): """ Returns true if name is a registered pane, False otherwise """ return name in self.panes
[ "def", "havePane", "(", "self", ",", "name", ")", ":", "return", "name", "in", "self", ".", "panes" ]
https://github.com/Polidea/SiriusObfuscator/blob/b0e590d8130e97856afe578869b83a209e2b19be/SymbolExtractorAndRenamer/lldb/utils/vim-lldb/python-vim-lldb/vim_panes.py#L151-L153
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/delete-and-earn.py
python
Solution.deleteAndEarn
(self, nums)
return val_i
:type nums: List[int] :rtype: int
:type nums: List[int] :rtype: int
[ ":", "type", "nums", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
def deleteAndEarn(self, nums): """ :type nums: List[int] :rtype: int """ vals = [0] * 10001 for num in nums: vals[num] += num val_i, val_i_1 = vals[0], 0 for i in xrange(1, len(vals)): val_i_1, val_i_2 = val_i, val_i_1 val_i = max(vals[i] + val_i_2, val_i_1) return val_i
[ "def", "deleteAndEarn", "(", "self", ",", "nums", ")", ":", "vals", "=", "[", "0", "]", "*", "10001", "for", "num", "in", "nums", ":", "vals", "[", "num", "]", "+=", "num", "val_i", ",", "val_i_1", "=", "vals", "[", "0", "]", ",", "0", "for", ...
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/delete-and-earn.py#L5-L17
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/io.py
python
open_a_file_dialog
(parent=None, default_suffix=None, directory=None, file_filter=None, accept_mode=None, file_mode=None)
return filename
Open a dialog asking for a file location and name to and return it :param parent: QWidget; The parent QWidget of the created dialog :param default_suffix: String; The default suffix to be passed :param directory: String; Directory to which the dialog will open :param file_filter: String; The filter name and file type e.g. "Python files (*.py)" :param accept_mode: enum AcceptMode; Defines the AcceptMode of the dialog, check QFileDialog Class for details :param file_mode: enum FileMode; Defines the FileMode of the dialog, check QFileDialog Class for details :return: String; The filename that was selected, it is possible to return a directory so look out for that
Open a dialog asking for a file location and name to and return it :param parent: QWidget; The parent QWidget of the created dialog :param default_suffix: String; The default suffix to be passed :param directory: String; Directory to which the dialog will open :param file_filter: String; The filter name and file type e.g. "Python files (*.py)" :param accept_mode: enum AcceptMode; Defines the AcceptMode of the dialog, check QFileDialog Class for details :param file_mode: enum FileMode; Defines the FileMode of the dialog, check QFileDialog Class for details :return: String; The filename that was selected, it is possible to return a directory so look out for that
[ "Open", "a", "dialog", "asking", "for", "a", "file", "location", "and", "name", "to", "and", "return", "it", ":", "param", "parent", ":", "QWidget", ";", "The", "parent", "QWidget", "of", "the", "created", "dialog", ":", "param", "default_suffix", ":", "...
def open_a_file_dialog(parent=None, default_suffix=None, directory=None, file_filter=None, accept_mode=None, file_mode=None): """ Open a dialog asking for a file location and name to and return it :param parent: QWidget; The parent QWidget of the created dialog :param default_suffix: String; The default suffix to be passed :param directory: String; Directory to which the dialog will open :param file_filter: String; The filter name and file type e.g. "Python files (*.py)" :param accept_mode: enum AcceptMode; Defines the AcceptMode of the dialog, check QFileDialog Class for details :param file_mode: enum FileMode; Defines the FileMode of the dialog, check QFileDialog Class for details :return: String; The filename that was selected, it is possible to return a directory so look out for that """ global _LAST_SAVE_DIRECTORY dialog = QFileDialog(parent) # It is the intention to only save the user's last used directory until workbench is restarted similar to other # applications (VSCode, Gedit etc) if _LAST_SAVE_DIRECTORY is not None and directory is None: dialog.setDirectory(_LAST_SAVE_DIRECTORY) elif directory is not None: dialog.setDirectory(directory) else: dialog.setDirectory(os.path.expanduser("~")) if file_filter is not None: dialog.setFilter(QDir.Files) dialog.setNameFilter(file_filter) if default_suffix is not None: dialog.setDefaultSuffix(default_suffix) if file_mode is not None: dialog.setFileMode(file_mode) if accept_mode is not None: dialog.setAcceptMode(accept_mode) # Connect the actual filename setter dialog.fileSelected.connect(_set_last_save) # Wait for dialog to finish before allowing continuation of code if dialog.exec_() == QDialog.Rejected: return None filename = _LAST_SAVE_DIRECTORY # Make sure that the _LAST_SAVE_DIRECTORY is set as a directory if _LAST_SAVE_DIRECTORY is not None and not os.path.isdir(_LAST_SAVE_DIRECTORY): # Remove the file for last directory _LAST_SAVE_DIRECTORY = os.path.dirname(os.path.abspath(_LAST_SAVE_DIRECTORY)) return filename
[ "def", "open_a_file_dialog", "(", "parent", "=", "None", ",", "default_suffix", "=", "None", ",", "directory", "=", "None", ",", "file_filter", "=", "None", ",", "accept_mode", "=", "None", ",", "file_mode", "=", "None", ")", ":", "global", "_LAST_SAVE_DIREC...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/io.py#L18-L69
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_gdi.py
python
FontMapper.__init__
(self, *args, **kwargs)
__init__(self) -> FontMapper
__init__(self) -> FontMapper
[ "__init__", "(", "self", ")", "-", ">", "FontMapper" ]
def __init__(self, *args, **kwargs): """__init__(self) -> FontMapper""" _gdi_.FontMapper_swiginit(self,_gdi_.new_FontMapper(*args, **kwargs))
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_gdi_", ".", "FontMapper_swiginit", "(", "self", ",", "_gdi_", ".", "new_FontMapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_gdi.py#L2005-L2007
xiaolonw/caffe-video_triplet
c39ea1ad6e937ccf7deba4510b7e555165abf05f
scripts/cpp_lint.py
python
CheckEmptyBlockBody
(filename, clean_lines, linenum, error)
Look for empty loop/conditional body with only a single semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Look for empty loop/conditional body with only a single semicolon.
[ "Look", "for", "empty", "loop", "/", "conditional", "body", "with", "only", "a", "single", "semicolon", "." ]
def CheckEmptyBlockBody(filename, clean_lines, linenum, error): """Look for empty loop/conditional body with only a single semicolon. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ # Search for loop keywords at the beginning of the line. Because only # whitespaces are allowed before the keywords, this will also ignore most # do-while-loops, since those lines should start with closing brace. # # We also check "if" blocks here, since an empty conditional block # is likely an error. line = clean_lines.elided[linenum] matched = Match(r'\s*(for|while|if)\s*\(', line) if matched: # Find the end of the conditional expression (end_line, end_linenum, end_pos) = CloseExpression( clean_lines, linenum, line.find('(')) # Output warning if what follows the condition expression is a semicolon. # No warning for all other cases, including whitespace or newline, since we # have a separate check for semicolons preceded by whitespace. if end_pos >= 0 and Match(r';', end_line[end_pos:]): if matched.group(1) == 'if': error(filename, end_linenum, 'whitespace/empty_conditional_body', 5, 'Empty conditional bodies should use {}') else: error(filename, end_linenum, 'whitespace/empty_loop_body', 5, 'Empty loop bodies should use {} or continue')
[ "def", "CheckEmptyBlockBody", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "# Search for loop keywords at the beginning of the line. Because only", "# whitespaces are allowed before the keywords, this will also ignore most", "# do-while-loops, since those...
https://github.com/xiaolonw/caffe-video_triplet/blob/c39ea1ad6e937ccf7deba4510b7e555165abf05f/scripts/cpp_lint.py#L3243-L3275
microsoft/TSS.MSR
0f2516fca2cd9929c31d5450e39301c9bde43688
TSS.Py/src/TpmTypes.py
python
TPM2_ACT_SetTimeout_REQUEST.initFromTpm
(self, buf)
TpmMarshaller method
TpmMarshaller method
[ "TpmMarshaller", "method" ]
def initFromTpm(self, buf): """ TpmMarshaller method """ self.startTimeout = buf.readInt()
[ "def", "initFromTpm", "(", "self", ",", "buf", ")", ":", "self", ".", "startTimeout", "=", "buf", ".", "readInt", "(", ")" ]
https://github.com/microsoft/TSS.MSR/blob/0f2516fca2cd9929c31d5450e39301c9bde43688/TSS.Py/src/TpmTypes.py#L17569-L17571
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/req/req_install.py
python
_strip_postfix
(req)
return req
Strip req postfix ( -dev, 0.2, etc )
Strip req postfix ( -dev, 0.2, etc )
[ "Strip", "req", "postfix", "(", "-", "dev", "0", ".", "2", "etc", ")" ]
def _strip_postfix(req): """ Strip req postfix ( -dev, 0.2, etc ) """ # FIXME: use package_to_requirement? match = re.search(r'^(.*?)(?:-dev|-\d.*)$', req) if match: # Strip off -dev, -0.2, etc. req = match.group(1) return req
[ "def", "_strip_postfix", "(", "req", ")", ":", "# FIXME: use package_to_requirement?", "match", "=", "re", ".", "search", "(", "r'^(.*?)(?:-dev|-\\d.*)$'", ",", "req", ")", "if", "match", ":", "# Strip off -dev, -0.2, etc.", "req", "=", "match", ".", "group", "(",...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/req/req_install.py#L1018-L1027
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/laguerre.py
python
lagroots
(c)
return r
Compute the roots of a Laguerre series. Return the roots (a.k.a. "zeros") of the polynomial .. math:: p(x) = \\sum_i c[i] * L_i(x). Parameters ---------- c : 1-D array_like 1-D array of coefficients. Returns ------- out : ndarray Array of the roots of the series. If all the roots are real, then `out` is also real, otherwise it is complex. See Also -------- polyroots, legroots, chebroots, hermroots, hermeroots Notes ----- The root estimates are obtained as the eigenvalues of the companion matrix, Roots far from the origin of the complex plane may have large errors due to the numerical instability of the series for such values. Roots with multiplicity greater than 1 will also show larger errors as the value of the series near such points is relatively insensitive to errors in the roots. Isolated roots near the origin can be improved by a few iterations of Newton's method. The Laguerre series basis polynomials aren't powers of `x` so the results of this function may seem unintuitive. Examples -------- >>> from numpy.polynomial.laguerre import lagroots, lagfromroots >>> coef = lagfromroots([0, 1, 2]) >>> coef array([ 2., -8., 12., -6.]) >>> lagroots(coef) array([ -4.44089210e-16, 1.00000000e+00, 2.00000000e+00])
Compute the roots of a Laguerre series.
[ "Compute", "the", "roots", "of", "a", "Laguerre", "series", "." ]
def lagroots(c): """ Compute the roots of a Laguerre series. Return the roots (a.k.a. "zeros") of the polynomial .. math:: p(x) = \\sum_i c[i] * L_i(x). Parameters ---------- c : 1-D array_like 1-D array of coefficients. Returns ------- out : ndarray Array of the roots of the series. If all the roots are real, then `out` is also real, otherwise it is complex. See Also -------- polyroots, legroots, chebroots, hermroots, hermeroots Notes ----- The root estimates are obtained as the eigenvalues of the companion matrix, Roots far from the origin of the complex plane may have large errors due to the numerical instability of the series for such values. Roots with multiplicity greater than 1 will also show larger errors as the value of the series near such points is relatively insensitive to errors in the roots. Isolated roots near the origin can be improved by a few iterations of Newton's method. The Laguerre series basis polynomials aren't powers of `x` so the results of this function may seem unintuitive. Examples -------- >>> from numpy.polynomial.laguerre import lagroots, lagfromroots >>> coef = lagfromroots([0, 1, 2]) >>> coef array([ 2., -8., 12., -6.]) >>> lagroots(coef) array([ -4.44089210e-16, 1.00000000e+00, 2.00000000e+00]) """ # c is a trimmed copy [c] = pu.as_series([c]) if len(c) <= 1 : return np.array([], dtype=c.dtype) if len(c) == 2 : return np.array([1 + c[0]/c[1]]) m = lagcompanion(c) r = la.eigvals(m) r.sort() return r
[ "def", "lagroots", "(", "c", ")", ":", "# c is a trimmed copy", "[", "c", "]", "=", "pu", ".", "as_series", "(", "[", "c", "]", ")", "if", "len", "(", "c", ")", "<=", "1", ":", "return", "np", ".", "array", "(", "[", "]", ",", "dtype", "=", "...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/polynomial/laguerre.py#L1588-L1644
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/internal/decoder.py
python
_DecodeUnknownField
(buffer, pos, wire_type)
return (data, pos)
Decode a unknown field. Returns the UnknownField and new position.
Decode a unknown field. Returns the UnknownField and new position.
[ "Decode", "a", "unknown", "field", ".", "Returns", "the", "UnknownField", "and", "new", "position", "." ]
def _DecodeUnknownField(buffer, pos, wire_type): """Decode a unknown field. Returns the UnknownField and new position.""" if wire_type == wire_format.WIRETYPE_VARINT: (data, pos) = _DecodeVarint(buffer, pos) elif wire_type == wire_format.WIRETYPE_FIXED64: (data, pos) = _DecodeFixed64(buffer, pos) elif wire_type == wire_format.WIRETYPE_FIXED32: (data, pos) = _DecodeFixed32(buffer, pos) elif wire_type == wire_format.WIRETYPE_LENGTH_DELIMITED: (size, pos) = _DecodeVarint(buffer, pos) data = buffer[pos:pos+size].tobytes() pos += size elif wire_type == wire_format.WIRETYPE_START_GROUP: (data, pos) = _DecodeUnknownFieldSet(buffer, pos) elif wire_type == wire_format.WIRETYPE_END_GROUP: return (0, -1) else: raise _DecodeError('Wrong wire type in tag.') return (data, pos)
[ "def", "_DecodeUnknownField", "(", "buffer", ",", "pos", ",", "wire_type", ")", ":", "if", "wire_type", "==", "wire_format", ".", "WIRETYPE_VARINT", ":", "(", "data", ",", "pos", ")", "=", "_DecodeVarint", "(", "buffer", ",", "pos", ")", "elif", "wire_type...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/internal/decoder.py#L975-L995
calamares/calamares
9f6f82405b3074af7c99dc26487d2e46e4ece3e5
src/modules/bootloader/main.py
python
is_btrfs_root
(partition)
return partition["mountPoint"] == "/" and partition["fs"] == "btrfs"
Returns True if the partition object refers to a btrfs root filesystem :param partition: A partition map from global storage :return: True if btrfs and root, False otherwise
Returns True if the partition object refers to a btrfs root filesystem
[ "Returns", "True", "if", "the", "partition", "object", "refers", "to", "a", "btrfs", "root", "filesystem" ]
def is_btrfs_root(partition): """ Returns True if the partition object refers to a btrfs root filesystem :param partition: A partition map from global storage :return: True if btrfs and root, False otherwise """ return partition["mountPoint"] == "/" and partition["fs"] == "btrfs"
[ "def", "is_btrfs_root", "(", "partition", ")", ":", "return", "partition", "[", "\"mountPoint\"", "]", "==", "\"/\"", "and", "partition", "[", "\"fs\"", "]", "==", "\"btrfs\"" ]
https://github.com/calamares/calamares/blob/9f6f82405b3074af7c99dc26487d2e46e4ece3e5/src/modules/bootloader/main.py#L121-L127
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/decimal.py
python
Context._regard_flags
(self, *flags)
Stop ignoring the flags, if they are raised
Stop ignoring the flags, if they are raised
[ "Stop", "ignoring", "the", "flags", "if", "they", "are", "raised" ]
def _regard_flags(self, *flags): """Stop ignoring the flags, if they are raised""" if flags and isinstance(flags[0], (tuple,list)): flags = flags[0] for flag in flags: self._ignored_flags.remove(flag)
[ "def", "_regard_flags", "(", "self", ",", "*", "flags", ")", ":", "if", "flags", "and", "isinstance", "(", "flags", "[", "0", "]", ",", "(", "tuple", ",", "list", ")", ")", ":", "flags", "=", "flags", "[", "0", "]", "for", "flag", "in", "flags", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/decimal.py#L3885-L3890
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/traceable_stack.py
python
TraceableStack.__len__
(self)
return len(self._stack)
Return number of items on the stack, and used for truth-value testing.
Return number of items on the stack, and used for truth-value testing.
[ "Return", "number", "of", "items", "on", "the", "stack", "and", "used", "for", "truth", "-", "value", "testing", "." ]
def __len__(self): """Return number of items on the stack, and used for truth-value testing.""" return len(self._stack)
[ "def", "__len__", "(", "self", ")", ":", "return", "len", "(", "self", ".", "_stack", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/traceable_stack.py#L127-L129
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/io/loader.py
python
filename_to_type
(name)
Returns one Klampt type represented by the given filename's extension. If the file is a dynamic type (.xml or .json), just 'xml' or 'json' is returned because the type will need to be determined after parsing the file. If the type is ambiguous (like .obj), the first type in EXTENSION_TO_TYPES is returned. Returns: str: The Klamp't type
Returns one Klampt type represented by the given filename's extension.
[ "Returns", "one", "Klampt", "type", "represented", "by", "the", "given", "filename", "s", "extension", "." ]
def filename_to_type(name): """Returns one Klampt type represented by the given filename's extension. If the file is a dynamic type (.xml or .json), just 'xml' or 'json' is returned because the type will need to be determined after parsing the file. If the type is ambiguous (like .obj), the first type in EXTENSION_TO_TYPES is returned. Returns: str: The Klamp't type """ fileName, fileExtension = os.path.splitext(name) fileExtension = fileExtension.lower() if fileExtension == '.xml': return 'xml' #dynamic loading elif fileExtension == '.json': return 'json' #dynamic loading elif fileExtension in EXTENSION_TO_TYPES: ftypes = EXTENSION_TO_TYPES[fileExtension] if len(ftypes) > 1 and fileExtension not in ['.path'] and (ftypes[0] != 'Geometry3D' and len(ftypes) > 2): warnings.warn("loader.filename_to_type(): filename {} is ambiguous, matches types {}".format(name,', '.join(ftypes))) return ftypes[0] else: raise RuntimeError("Cannot determine type of object from filename "+name)
[ "def", "filename_to_type", "(", "name", ")", ":", "fileName", ",", "fileExtension", "=", "os", ".", "path", ".", "splitext", "(", "name", ")", "fileExtension", "=", "fileExtension", ".", "lower", "(", ")", "if", "fileExtension", "==", "'.xml'", ":", "retur...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/io/loader.py#L126-L152
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/hypertreelist.py
python
HyperTreeList.DoGetBestSize
(self)
return wx.Size(200, 200)
Gets the size which best suits the window: for a control, it would be the minimal size which doesn't truncate the control, for a panel - the same size as it would have after a call to `Fit()`. :note: Overridden from :class:`PyControl`.
Gets the size which best suits the window: for a control, it would be the minimal size which doesn't truncate the control, for a panel - the same size as it would have after a call to `Fit()`.
[ "Gets", "the", "size", "which", "best", "suits", "the", "window", ":", "for", "a", "control", "it", "would", "be", "the", "minimal", "size", "which", "doesn", "t", "truncate", "the", "control", "for", "a", "panel", "-", "the", "same", "size", "as", "it...
def DoGetBestSize(self): """ Gets the size which best suits the window: for a control, it would be the minimal size which doesn't truncate the control, for a panel - the same size as it would have after a call to `Fit()`. :note: Overridden from :class:`PyControl`. """ # something is better than nothing... return wx.Size(200, 200)
[ "def", "DoGetBestSize", "(", "self", ")", ":", "# something is better than nothing...", "return", "wx", ".", "Size", "(", "200", ",", "200", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/hypertreelist.py#L4733-L4743
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/training/queue_runner.py
python
QueueRunner.create_threads
(self, sess, coord=None, daemon=False, start=False)
return ret_threads
Create threads to run the enqueue ops. This method requires a session in which the graph was launched. It creates a list of threads, optionally starting them. There is one thread for each op passed in `enqueue_ops`. The `coord` argument is an optional coordinator, that the threads will use to terminate together and report exceptions. If a coordinator is given, this method starts an additional thread to close the queue when the coordinator requests a stop. This method may be called again as long as all threads from a previous call have stopped. Args: sess: A `Session`. coord: Optional `Coordinator` object for reporting errors and checking stop conditions. daemon: Boolean. If `True` make the threads daemon threads. start: Boolean. If `True` starts the threads. If `False` the caller must call the `start()` method of the returned threads. Returns: A list of threads. Raises: RuntimeError: If threads from a previous call to `create_threads()` are still running.
Create threads to run the enqueue ops.
[ "Create", "threads", "to", "run", "the", "enqueue", "ops", "." ]
def create_threads(self, sess, coord=None, daemon=False, start=False): """Create threads to run the enqueue ops. This method requires a session in which the graph was launched. It creates a list of threads, optionally starting them. There is one thread for each op passed in `enqueue_ops`. The `coord` argument is an optional coordinator, that the threads will use to terminate together and report exceptions. If a coordinator is given, this method starts an additional thread to close the queue when the coordinator requests a stop. This method may be called again as long as all threads from a previous call have stopped. Args: sess: A `Session`. coord: Optional `Coordinator` object for reporting errors and checking stop conditions. daemon: Boolean. If `True` make the threads daemon threads. start: Boolean. If `True` starts the threads. If `False` the caller must call the `start()` method of the returned threads. Returns: A list of threads. Raises: RuntimeError: If threads from a previous call to `create_threads()` are still running. """ with self._lock: if self._runs > 0: # Already started: no new threads to return. return [] self._runs = len(self._enqueue_ops) self._exceptions_raised = [] ret_threads = [threading.Thread(target=self._run, args=(sess, op, coord)) for op in self._enqueue_ops] if coord: ret_threads.append(threading.Thread(target=self._close_on_stop, args=(sess, self._cancel_op, coord))) for t in ret_threads: if daemon: t.daemon = True if start: t.start() return ret_threads
[ "def", "create_threads", "(", "self", ",", "sess", ",", "coord", "=", "None", ",", "daemon", "=", "False", ",", "start", "=", "False", ")", ":", "with", "self", ".", "_lock", ":", "if", "self", ".", "_runs", ">", "0", ":", "# Already started: no new th...
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/training/queue_runner.py#L232-L279
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/dataset/engine/validators.py
python
check_project
(method)
return new_method
check the input arguments of project.
check the input arguments of project.
[ "check", "the", "input", "arguments", "of", "project", "." ]
def check_project(method): """check the input arguments of project.""" @wraps(method) def new_method(self, *args, **kwargs): [columns], _ = parse_user_args(method, *args, **kwargs) check_columns(columns, 'columns') return method(self, *args, **kwargs) return new_method
[ "def", "check_project", "(", "method", ")", ":", "@", "wraps", "(", "method", ")", "def", "new_method", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "[", "columns", "]", ",", "_", "=", "parse_user_args", "(", "method", ",", "*"...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/validators.py#L1291-L1301
KhronosGroup/SPIRV-LLVM
1eb85593f3fe2c39379b9a9b088d51eda4f42b8b
utils/lit/lit/discovery.py
python
find_tests_for_inputs
(lit_config, inputs)
return tests
find_tests_for_inputs(lit_config, inputs) -> [Test] Given a configuration object and a list of input specifiers, find all the tests to execute.
find_tests_for_inputs(lit_config, inputs) -> [Test]
[ "find_tests_for_inputs", "(", "lit_config", "inputs", ")", "-", ">", "[", "Test", "]" ]
def find_tests_for_inputs(lit_config, inputs): """ find_tests_for_inputs(lit_config, inputs) -> [Test] Given a configuration object and a list of input specifiers, find all the tests to execute. """ # Expand '@...' form in inputs. actual_inputs = [] for input in inputs: if input.startswith('@'): f = open(input[1:]) try: for ln in f: ln = ln.strip() if ln: actual_inputs.append(ln) finally: f.close() else: actual_inputs.append(input) # Load the tests from the inputs. tests = [] test_suite_cache = {} local_config_cache = {} for input in actual_inputs: prev = len(tests) tests.extend(getTests(input, lit_config, test_suite_cache, local_config_cache)[1]) if prev == len(tests): lit_config.warning('input %r contained no tests' % input) # If there were any errors during test discovery, exit now. if lit_config.numErrors: sys.stderr.write('%d errors, exiting.\n' % lit_config.numErrors) sys.exit(2) return tests
[ "def", "find_tests_for_inputs", "(", "lit_config", ",", "inputs", ")", ":", "# Expand '@...' form in inputs.", "actual_inputs", "=", "[", "]", "for", "input", "in", "inputs", ":", "if", "input", ".", "startswith", "(", "'@'", ")", ":", "f", "=", "open", "(",...
https://github.com/KhronosGroup/SPIRV-LLVM/blob/1eb85593f3fe2c39379b9a9b088d51eda4f42b8b/utils/lit/lit/discovery.py#L192-L231
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/mapreduce/mapreduce/model.py
python
ShardState.find_all_by_mapreduce_state
(cls, mapreduce_state)
Find all shard states for given mapreduce. Args: mapreduce_state: MapreduceState instance Yields: shard states sorted by shard id.
Find all shard states for given mapreduce.
[ "Find", "all", "shard", "states", "for", "given", "mapreduce", "." ]
def find_all_by_mapreduce_state(cls, mapreduce_state): """Find all shard states for given mapreduce. Args: mapreduce_state: MapreduceState instance Yields: shard states sorted by shard id. """ keys = cls.calculate_keys_by_mapreduce_state(mapreduce_state) i = 0 while i < len(keys): @db.non_transactional def no_tx_get(i): return db.get(keys[i:i+cls._MAX_STATES_IN_MEMORY]) # We need a separate function to so that we can mix non-transactional and # use be a generator states = no_tx_get(i) for s in states: i += 1 if s is not None: yield s
[ "def", "find_all_by_mapreduce_state", "(", "cls", ",", "mapreduce_state", ")", ":", "keys", "=", "cls", ".", "calculate_keys_by_mapreduce_state", "(", "mapreduce_state", ")", "i", "=", "0", "while", "i", "<", "len", "(", "keys", ")", ":", "@", "db", ".", "...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/mapreduce/mapreduce/model.py#L1106-L1127
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
media/webrtc/trunk/tools/gyp/pylib/gyp/mac_tool.py
python
MacTool._WritePkgInfo
(self, info_plist)
This writes the PkgInfo file from the data stored in Info.plist.
This writes the PkgInfo file from the data stored in Info.plist.
[ "This", "writes", "the", "PkgInfo", "file", "from", "the", "data", "stored", "in", "Info", ".", "plist", "." ]
def _WritePkgInfo(self, info_plist): """This writes the PkgInfo file from the data stored in Info.plist.""" plist = plistlib.readPlist(info_plist) if not plist: return # Only create PkgInfo for executable types. package_type = plist['CFBundlePackageType'] if package_type != 'APPL': return # The format of PkgInfo is eight characters, representing the bundle type # and bundle signature, each four characters. If that is missing, four # '?' characters are used instead. signature_code = plist.get('CFBundleSignature', '????') if len(signature_code) != 4: # Wrong length resets everything, too. signature_code = '?' * 4 dest = os.path.join(os.path.dirname(info_plist), 'PkgInfo') fp = open(dest, 'w') fp.write('%s%s' % (package_type, signature_code)) fp.close()
[ "def", "_WritePkgInfo", "(", "self", ",", "info_plist", ")", ":", "plist", "=", "plistlib", ".", "readPlist", "(", "info_plist", ")", "if", "not", "plist", ":", "return", "# Only create PkgInfo for executable types.", "package_type", "=", "plist", "[", "'CFBundleP...
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/media/webrtc/trunk/tools/gyp/pylib/gyp/mac_tool.py#L132-L153
Kitware/ParaView
f760af9124ff4634b23ebbeab95a4f56e0261955
Examples/Catalyst/CFullExample2/SampleScripts/feslicescript.py
python
DoCoProcessing
(datadescription)
Callback to do co-processing for current timestep
Callback to do co-processing for current timestep
[ "Callback", "to", "do", "co", "-", "processing", "for", "current", "timestep" ]
def DoCoProcessing(datadescription): "Callback to do co-processing for current timestep" global coprocessor # Update the coprocessor by providing it the newly generated simulation data. # If the pipeline hasn't been setup yet, this will setup the pipeline. coprocessor.UpdateProducers(datadescription) # Write output data, if appropriate. coprocessor.WriteData(datadescription); # Write image capture (Last arg: rescale lookup table), if appropriate. coprocessor.WriteImages(datadescription, rescale_lookuptable=False) # Live Visualization, if enabled. coprocessor.DoLiveVisualization(datadescription, "localhost", 22222)
[ "def", "DoCoProcessing", "(", "datadescription", ")", ":", "global", "coprocessor", "# Update the coprocessor by providing it the newly generated simulation data.", "# If the pipeline hasn't been setup yet, this will setup the pipeline.", "coprocessor", ".", "UpdateProducers", "(", "data...
https://github.com/Kitware/ParaView/blob/f760af9124ff4634b23ebbeab95a4f56e0261955/Examples/Catalyst/CFullExample2/SampleScripts/feslicescript.py#L77-L92
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/pyprogress.py
python
ProgressGauge.GetGaugeBackground
(self)
return self._background
Returns the gauge background colour.
Returns the gauge background colour.
[ "Returns", "the", "gauge", "background", "colour", "." ]
def GetGaugeBackground(self): """ Returns the gauge background colour. """ return self._background
[ "def", "GetGaugeBackground", "(", "self", ")", ":", "return", "self", ".", "_background" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/pyprogress.py#L238-L241
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/klampt/control/motion_generation.py
python
VelocityBoundedMotionGeneration.reset
(self,x0)
Resets the motion generator to the start position x0.
Resets the motion generator to the start position x0.
[ "Resets", "the", "motion", "generator", "to", "the", "start", "position", "x0", "." ]
def reset(self,x0): """Resets the motion generator to the start position x0.""" self.x = x0 self.v = [0]*len(x0) self.times = [0] self.milestones = [self.x] self.curTime = 0 self.trajTime = 0
[ "def", "reset", "(", "self", ",", "x0", ")", ":", "self", ".", "x", "=", "x0", "self", ".", "v", "=", "[", "0", "]", "*", "len", "(", "x0", ")", "self", ".", "times", "=", "[", "0", "]", "self", ".", "milestones", "=", "[", "self", ".", "...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/klampt/control/motion_generation.py#L57-L64
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_misc.py
python
PyDataObjectSimple.__init__
(self, *args, **kwargs)
__init__(self, DataFormat format=FormatInvalid) -> PyDataObjectSimple wx.PyDataObjectSimple is a version of `wx.DataObjectSimple` that is Python-aware and knows how to reflect calls to its C++ virtual methods to methods in the Python derived class. You should derive from this class and overload `GetDataSize`, `GetDataHere` and `SetData` when you need to create your own simple single-format type of `wx.DataObject`.
__init__(self, DataFormat format=FormatInvalid) -> PyDataObjectSimple
[ "__init__", "(", "self", "DataFormat", "format", "=", "FormatInvalid", ")", "-", ">", "PyDataObjectSimple" ]
def __init__(self, *args, **kwargs): """ __init__(self, DataFormat format=FormatInvalid) -> PyDataObjectSimple wx.PyDataObjectSimple is a version of `wx.DataObjectSimple` that is Python-aware and knows how to reflect calls to its C++ virtual methods to methods in the Python derived class. You should derive from this class and overload `GetDataSize`, `GetDataHere` and `SetData` when you need to create your own simple single-format type of `wx.DataObject`. """ _misc_.PyDataObjectSimple_swiginit(self,_misc_.new_PyDataObjectSimple(*args, **kwargs)) PyDataObjectSimple._setCallbackInfo(self, self, PyDataObjectSimple)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_misc_", ".", "PyDataObjectSimple_swiginit", "(", "self", ",", "_misc_", ".", "new_PyDataObjectSimple", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "PyDataObje...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_misc.py#L5078-L5090
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/containers.py
python
RepeatedCompositeFieldContainer.__delitem__
(self, key)
Deletes the item at the specified position.
Deletes the item at the specified position.
[ "Deletes", "the", "item", "at", "the", "specified", "position", "." ]
def __delitem__(self, key): """Deletes the item at the specified position.""" del self._values[key] self._message_listener.Modified()
[ "def", "__delitem__", "(", "self", ",", "key", ")", ":", "del", "self", ".", "_values", "[", "key", "]", "self", ".", "_message_listener", ".", "Modified", "(", ")" ]
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/google/protobuf/internal/containers.py#L252-L255
nileshkulkarni/csm
0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc
csm/utils/transformations.py
python
identity_matrix
()
return numpy.identity(4)
Return 4x4 identity/unit matrix. >>> I = identity_matrix() >>> numpy.allclose(I, numpy.dot(I, I)) True >>> numpy.sum(I), numpy.trace(I) (4.0, 4.0) >>> numpy.allclose(I, numpy.identity(4)) True
Return 4x4 identity/unit matrix.
[ "Return", "4x4", "identity", "/", "unit", "matrix", "." ]
def identity_matrix(): """Return 4x4 identity/unit matrix. >>> I = identity_matrix() >>> numpy.allclose(I, numpy.dot(I, I)) True >>> numpy.sum(I), numpy.trace(I) (4.0, 4.0) >>> numpy.allclose(I, numpy.identity(4)) True """ return numpy.identity(4)
[ "def", "identity_matrix", "(", ")", ":", "return", "numpy", ".", "identity", "(", "4", ")" ]
https://github.com/nileshkulkarni/csm/blob/0e6e0e7d4f725fd36f2414c0be4b9d83197aa1fc/csm/utils/transformations.py#L207-L219
PrincetonUniversity/athena-public-version
9c266692b9423743d8e23509b3ab266a232a92d2
tst/style/cpplint.py
python
_CppLintState.BackupFilters
(self)
Saves the current filter list to backup storage.
Saves the current filter list to backup storage.
[ "Saves", "the", "current", "filter", "list", "to", "backup", "storage", "." ]
def BackupFilters(self): """ Saves the current filter list to backup storage.""" self._filters_backup = self.filters[:]
[ "def", "BackupFilters", "(", "self", ")", ":", "self", ".", "_filters_backup", "=", "self", ".", "filters", "[", ":", "]" ]
https://github.com/PrincetonUniversity/athena-public-version/blob/9c266692b9423743d8e23509b3ab266a232a92d2/tst/style/cpplint.py#L1077-L1079
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
example/rnn/large_word_lm/model.py
python
rnn
(bptt, vocab_size, num_embed, nhid, num_layers, dropout, num_proj, batch_size)
return outputs, states, trainable_lstm_args, state_names
word embedding + LSTM Projected
word embedding + LSTM Projected
[ "word", "embedding", "+", "LSTM", "Projected" ]
def rnn(bptt, vocab_size, num_embed, nhid, num_layers, dropout, num_proj, batch_size): """ word embedding + LSTM Projected """ state_names = [] data = S.var('data') weight = S.var("encoder_weight", stype='row_sparse') embed = S.sparse.Embedding(data=data, weight=weight, input_dim=vocab_size, output_dim=num_embed, name='embed', sparse_grad=True) states = [] outputs = S.Dropout(embed, p=dropout) for i in range(num_layers): prefix = 'lstmp%d_' % i init_h = S.var(prefix + 'init_h', shape=(batch_size, num_proj), init=mx.init.Zero()) init_c = S.var(prefix + 'init_c', shape=(batch_size, nhid), init=mx.init.Zero()) state_names += [prefix + 'init_h', prefix + 'init_c'] lstmp = mx.gluon.contrib.rnn.LSTMPCell(nhid, num_proj, prefix=prefix) outputs, next_states = lstmp.unroll(bptt, outputs, begin_state=[init_h, init_c], \ layout='NTC', merge_outputs=True) outputs = S.Dropout(outputs, p=dropout) states += [S.stop_gradient(s) for s in next_states] outputs = S.reshape(outputs, shape=(-1, num_proj)) trainable_lstm_args = [] for arg in outputs.list_arguments(): if 'lstmp' in arg and 'init' not in arg: trainable_lstm_args.append(arg) return outputs, states, trainable_lstm_args, state_names
[ "def", "rnn", "(", "bptt", ",", "vocab_size", ",", "num_embed", ",", "nhid", ",", "num_layers", ",", "dropout", ",", "num_proj", ",", "batch_size", ")", ":", "state_names", "=", "[", "]", "data", "=", "S", ".", "var", "(", "'data'", ")", "weight", "=...
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/example/rnn/large_word_lm/model.py#L47-L72
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/html.py
python
HtmlHelpWindow.GetHtmlWindow
(*args, **kwargs)
return _html.HtmlHelpWindow_GetHtmlWindow(*args, **kwargs)
GetHtmlWindow(self) -> HtmlWindow
GetHtmlWindow(self) -> HtmlWindow
[ "GetHtmlWindow", "(", "self", ")", "-", ">", "HtmlWindow" ]
def GetHtmlWindow(*args, **kwargs): """GetHtmlWindow(self) -> HtmlWindow""" return _html.HtmlHelpWindow_GetHtmlWindow(*args, **kwargs)
[ "def", "GetHtmlWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html", ".", "HtmlHelpWindow_GetHtmlWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/html.py#L1642-L1644
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TMemIn_New
(*args)
return _snap.TMemIn_New(*args)
New(TMem Mem) -> PSIn Parameters: Mem: TMem const & TMemIn_New(PMem const & Mem) -> PSIn Parameters: Mem: PMem const &
New(TMem Mem) -> PSIn
[ "New", "(", "TMem", "Mem", ")", "-", ">", "PSIn" ]
def TMemIn_New(*args): """ New(TMem Mem) -> PSIn Parameters: Mem: TMem const & TMemIn_New(PMem const & Mem) -> PSIn Parameters: Mem: PMem const & """ return _snap.TMemIn_New(*args)
[ "def", "TMemIn_New", "(", "*", "args", ")", ":", "return", "_snap", ".", "TMemIn_New", "(", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L8381-L8394
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/wizard.py
python
Wizard.ShowPage
(*args, **kwargs)
return _wizard.Wizard_ShowPage(*args, **kwargs)
ShowPage(self, WizardPage page, bool goingForward=True) -> bool
ShowPage(self, WizardPage page, bool goingForward=True) -> bool
[ "ShowPage", "(", "self", "WizardPage", "page", "bool", "goingForward", "=", "True", ")", "-", ">", "bool" ]
def ShowPage(*args, **kwargs): """ShowPage(self, WizardPage page, bool goingForward=True) -> bool""" return _wizard.Wizard_ShowPage(*args, **kwargs)
[ "def", "ShowPage", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_wizard", ".", "Wizard_ShowPage", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/wizard.py#L443-L445
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tpu/tpu_embedding_gradient.py
python
create_dummy_table_variables
(tpu_embedding)
return (dummy_table_variables, variables.variables_initializer( dummy_table_variables.values(), name='tpu_embedding_dummy_table_variables_init'))
Create dummy embedding table variables. The sole purpose of these dummy variables are to trigger gradient calcuation wrt them so that the gradients wrt activation can be captured and later sent to TPU embedding. Args: tpu_embedding: TPUEmbedding, dummy table variables will be created for use with tpu_embedding. Returns: A tuple of dummy variables and their initializer. Raises: RuntimeError: if collection to store gradients already exists and is not empty.
Create dummy embedding table variables.
[ "Create", "dummy", "embedding", "table", "variables", "." ]
def create_dummy_table_variables(tpu_embedding): """Create dummy embedding table variables. The sole purpose of these dummy variables are to trigger gradient calcuation wrt them so that the gradients wrt activation can be captured and later sent to TPU embedding. Args: tpu_embedding: TPUEmbedding, dummy table variables will be created for use with tpu_embedding. Returns: A tuple of dummy variables and their initializer. Raises: RuntimeError: if collection to store gradients already exists and is not empty. """ dummy_table_variables = collections.OrderedDict() for table_id, table in enumerate(tpu_embedding.table_to_features_dict): dummy_table_variables[table] = ( # Explicitly specifying collections prevents this variable from # being added to the GLOBAL_VARIABLES collection, so that Saver() # ignores it. # But Tensorflow optimizer creates slot variable for these dummy # variable, e.g. tpu_embedding_dummy_table_variable_mlp_user/Adam{_1}, # which will be in GLOBAL_VARIABLES collection, variable_scope.get_variable( 'tpu_embedding_dummy_table_variable_{}'.format(table), dtype=dtypes.float32, shape=[1], use_resource=True, trainable=True, collections=['tpu_embedding_dummy_table_variables'])) g = ops.get_default_graph() table_gradients = g.get_collection_ref( 'tpu_embedding_gradients_table_{}'.format(table_id)) if table_gradients: raise RuntimeError( 'tpu_embedding_gradients_table_{} is not empty.'.format(table_id)) table_gradients.extend( [None] * len(tpu_embedding.table_to_features_dict[table])) return (dummy_table_variables, variables.variables_initializer( dummy_table_variables.values(), name='tpu_embedding_dummy_table_variables_init'))
[ "def", "create_dummy_table_variables", "(", "tpu_embedding", ")", ":", "dummy_table_variables", "=", "collections", ".", "OrderedDict", "(", ")", "for", "table_id", ",", "table", "in", "enumerate", "(", "tpu_embedding", ".", "table_to_features_dict", ")", ":", "dumm...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/tpu/tpu_embedding_gradient.py#L53-L100
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/managers.py
python
BlockManager.quantile
( self, axis=0, consolidate=True, transposed=False, interpolation="linear", qs=None, numeric_only=None, )
return SingleBlockManager( [make_block(values, ndim=1, placement=np.arange(len(values)))], axes[0] )
Iterate over blocks applying quantile reduction. This routine is intended for reduction type operations and will do inference on the generated blocks. Parameters ---------- axis: reduction axis, default 0 consolidate: boolean, default True. Join together blocks having same dtype transposed: boolean, default False we are holding transposed data interpolation : type of interpolation, default 'linear' qs : a scalar or list of the quantiles to be computed numeric_only : ignored Returns ------- Block Manager (new object)
Iterate over blocks applying quantile reduction. This routine is intended for reduction type operations and will do inference on the generated blocks.
[ "Iterate", "over", "blocks", "applying", "quantile", "reduction", ".", "This", "routine", "is", "intended", "for", "reduction", "type", "operations", "and", "will", "do", "inference", "on", "the", "generated", "blocks", "." ]
def quantile( self, axis=0, consolidate=True, transposed=False, interpolation="linear", qs=None, numeric_only=None, ): """ Iterate over blocks applying quantile reduction. This routine is intended for reduction type operations and will do inference on the generated blocks. Parameters ---------- axis: reduction axis, default 0 consolidate: boolean, default True. Join together blocks having same dtype transposed: boolean, default False we are holding transposed data interpolation : type of interpolation, default 'linear' qs : a scalar or list of the quantiles to be computed numeric_only : ignored Returns ------- Block Manager (new object) """ # Series dispatches to DataFrame for quantile, which allows us to # simplify some of the code here and in the blocks assert self.ndim >= 2 if consolidate: self._consolidate_inplace() def get_axe(block, qs, axes): # Because Series dispatches to DataFrame, we will always have # block.ndim == 2 from pandas import Float64Index if is_list_like(qs): ax = Float64Index(qs) else: ax = axes[0] return ax axes, blocks = [], [] for b in self.blocks: block = b.quantile(axis=axis, qs=qs, interpolation=interpolation) axe = get_axe(b, qs, axes=self.axes) axes.append(axe) blocks.append(block) # note that some DatetimeTZ, Categorical are always ndim==1 ndim = {b.ndim for b in blocks} assert 0 not in ndim, ndim if 2 in ndim: new_axes = list(self.axes) # multiple blocks that are reduced if len(blocks) > 1: new_axes[1] = axes[0] # reset the placement to the original for b, sb in zip(blocks, self.blocks): b.mgr_locs = sb.mgr_locs else: new_axes[axis] = Index(np.concatenate([ax.values for ax in axes])) if transposed: new_axes = new_axes[::-1] blocks = [ b.make_block(b.values.T, placement=np.arange(b.shape[1])) for b in blocks ] return type(self)(blocks, new_axes) # single block, i.e. ndim == {1} values = concat_compat([b.values for b in blocks]) # compute the orderings of our original data if len(self.blocks) > 1: indexer = np.empty(len(self.axes[0]), dtype=np.intp) i = 0 for b in self.blocks: for j in b.mgr_locs: indexer[j] = i i = i + 1 values = values.take(indexer) return SingleBlockManager( [make_block(values, ndim=1, placement=np.arange(len(values)))], axes[0] )
[ "def", "quantile", "(", "self", ",", "axis", "=", "0", ",", "consolidate", "=", "True", ",", "transposed", "=", "False", ",", "interpolation", "=", "\"linear\"", ",", "qs", "=", "None", ",", "numeric_only", "=", "None", ",", ")", ":", "# Series dispatche...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/core/internals/managers.py#L450-L552
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/ensemble/_bagging.py
python
_generate_indices
(random_state, bootstrap, n_population, n_samples)
return indices
Draw randomly sampled indices.
Draw randomly sampled indices.
[ "Draw", "randomly", "sampled", "indices", "." ]
def _generate_indices(random_state, bootstrap, n_population, n_samples): """Draw randomly sampled indices.""" # Draw sample indices if bootstrap: indices = random_state.randint(0, n_population, n_samples) else: indices = sample_without_replacement(n_population, n_samples, random_state=random_state) return indices
[ "def", "_generate_indices", "(", "random_state", ",", "bootstrap", ",", "n_population", ",", "n_samples", ")", ":", "# Draw sample indices", "if", "bootstrap", ":", "indices", "=", "random_state", ".", "randint", "(", "0", ",", "n_population", ",", "n_samples", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/ensemble/_bagging.py#L34-L43
NicknineTheEagle/TF2-Base
20459c5a7fbc995b6bf54fa85c2f62a101e9fb64
src/thirdparty/protobuf-2.3.0/python/mox.py
python
Mox.UnsetStubs
(self)
Restore stubs to their original state.
Restore stubs to their original state.
[ "Restore", "stubs", "to", "their", "original", "state", "." ]
def UnsetStubs(self): """Restore stubs to their original state.""" self.stubs.UnsetAll()
[ "def", "UnsetStubs", "(", "self", ")", ":", "self", ".", "stubs", ".", "UnsetAll", "(", ")" ]
https://github.com/NicknineTheEagle/TF2-Base/blob/20459c5a7fbc995b6bf54fa85c2f62a101e9fb64/src/thirdparty/protobuf-2.3.0/python/mox.py#L230-L233
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/framemanager.py
python
AuiManager.CreateGuideWindows
(self)
Creates the VS2005 HUD guide windows.
Creates the VS2005 HUD guide windows.
[ "Creates", "the", "VS2005", "HUD", "guide", "windows", "." ]
def CreateGuideWindows(self): """ Creates the VS2005 HUD guide windows. """ self.DestroyGuideWindows() self._guides.append(AuiDockingGuideInfo().Left(). Host(AuiSingleDockingGuide(self._frame, wx.LEFT))) self._guides.append(AuiDockingGuideInfo().Top(). Host(AuiSingleDockingGuide(self._frame, wx.TOP))) self._guides.append(AuiDockingGuideInfo().Right(). Host(AuiSingleDockingGuide(self._frame, wx.RIGHT))) self._guides.append(AuiDockingGuideInfo().Bottom(). Host(AuiSingleDockingGuide(self._frame, wx.BOTTOM))) self._guides.append(AuiDockingGuideInfo().Centre(). Host(AuiCenterDockingGuide(self._frame)))
[ "def", "CreateGuideWindows", "(", "self", ")", ":", "self", ".", "DestroyGuideWindows", "(", ")", "self", ".", "_guides", ".", "append", "(", "AuiDockingGuideInfo", "(", ")", ".", "Left", "(", ")", ".", "Host", "(", "AuiSingleDockingGuide", "(", "self", "....
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/framemanager.py#L4531-L4545
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/numpy_ops/np_array_ops.py
python
where
(condition, x=None, y=None)
Raises ValueError if exactly one of x or y is not None.
Raises ValueError if exactly one of x or y is not None.
[ "Raises", "ValueError", "if", "exactly", "one", "of", "x", "or", "y", "is", "not", "None", "." ]
def where(condition, x=None, y=None): """Raises ValueError if exactly one of x or y is not None.""" condition = asarray(condition, dtype=np.bool_) if x is None and y is None: return nonzero(condition) elif x is not None and y is not None: x, y = _promote_dtype(x, y) return array_ops.where_v2(condition, x, y) raise ValueError('Both x and y must be ndarrays, or both must be None.')
[ "def", "where", "(", "condition", ",", "x", "=", "None", ",", "y", "=", "None", ")", ":", "condition", "=", "asarray", "(", "condition", ",", "dtype", "=", "np", ".", "bool_", ")", "if", "x", "is", "None", "and", "y", "is", "None", ":", "return",...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/numpy_ops/np_array_ops.py#L925-L933
chuckcho/video-caffe
fc232b3e3a90ea22dd041b9fc5c542f170581f20
python/caffe/draw.py
python
choose_color_by_layertype
(layertype)
return color
Define colors for nodes based on the layer type.
Define colors for nodes based on the layer type.
[ "Define", "colors", "for", "nodes", "based", "on", "the", "layer", "type", "." ]
def choose_color_by_layertype(layertype): """Define colors for nodes based on the layer type. """ color = '#6495ED' # Default if layertype == 'Convolution' or layertype == 'Deconvolution': color = '#FF5050' elif layertype == 'Pooling': color = '#FF9900' elif layertype == 'InnerProduct': color = '#CC33FF' return color
[ "def", "choose_color_by_layertype", "(", "layertype", ")", ":", "color", "=", "'#6495ED'", "# Default", "if", "layertype", "==", "'Convolution'", "or", "layertype", "==", "'Deconvolution'", ":", "color", "=", "'#FF5050'", "elif", "layertype", "==", "'Pooling'", ":...
https://github.com/chuckcho/video-caffe/blob/fc232b3e3a90ea22dd041b9fc5c542f170581f20/python/caffe/draw.py#L177-L187
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/matlib.py
python
zeros
(shape, dtype=None, order='C')
return a
Return a matrix of given shape and type, filled with zeros. Parameters ---------- shape : int or sequence of ints Shape of the matrix dtype : data-type, optional The desired data-type for the matrix, default is float. order : {'C', 'F'}, optional Whether to store the result in C- or Fortran-contiguous order, default is 'C'. Returns ------- out : matrix Zero matrix of given shape, dtype, and order. See Also -------- numpy.zeros : Equivalent array function. matlib.ones : Return a matrix of ones. Notes ----- If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``, `out` becomes a single row matrix of shape ``(1,N)``. Examples -------- >>> import numpy.matlib >>> np.matlib.zeros((2, 3)) matrix([[ 0., 0., 0.], [ 0., 0., 0.]]) >>> np.matlib.zeros(2) matrix([[ 0., 0.]])
Return a matrix of given shape and type, filled with zeros.
[ "Return", "a", "matrix", "of", "given", "shape", "and", "type", "filled", "with", "zeros", "." ]
def zeros(shape, dtype=None, order='C'): """ Return a matrix of given shape and type, filled with zeros. Parameters ---------- shape : int or sequence of ints Shape of the matrix dtype : data-type, optional The desired data-type for the matrix, default is float. order : {'C', 'F'}, optional Whether to store the result in C- or Fortran-contiguous order, default is 'C'. Returns ------- out : matrix Zero matrix of given shape, dtype, and order. See Also -------- numpy.zeros : Equivalent array function. matlib.ones : Return a matrix of ones. Notes ----- If `shape` has length one i.e. ``(N,)``, or is a scalar ``N``, `out` becomes a single row matrix of shape ``(1,N)``. Examples -------- >>> import numpy.matlib >>> np.matlib.zeros((2, 3)) matrix([[ 0., 0., 0.], [ 0., 0., 0.]]) >>> np.matlib.zeros(2) matrix([[ 0., 0.]]) """ a = ndarray.__new__(matrix, shape, dtype, order=order) a.fill(0) return a
[ "def", "zeros", "(", "shape", ",", "dtype", "=", "None", ",", "order", "=", "'C'", ")", ":", "a", "=", "ndarray", ".", "__new__", "(", "matrix", ",", "shape", ",", "dtype", ",", "order", "=", "order", ")", "a", ".", "fill", "(", "0", ")", "retu...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/matlib.py#L96-L138
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py
python
Place.place_info
(self)
return dict
Return information about the placing options for this widget.
Return information about the placing options for this widget.
[ "Return", "information", "about", "the", "placing", "options", "for", "this", "widget", "." ]
def place_info(self): """Return information about the placing options for this widget.""" words = self.tk.splitlist( self.tk.call('place', 'info', self._w)) dict = {} for i in range(0, len(words), 2): key = words[i][1:] value = words[i+1] if value[:1] == '.': value = self._nametowidget(value) dict[key] = value return dict
[ "def", "place_info", "(", "self", ")", ":", "words", "=", "self", ".", "tk", ".", "splitlist", "(", "self", ".", "tk", ".", "call", "(", "'place'", ",", "'info'", ",", "self", ".", "_w", ")", ")", "dict", "=", "{", "}", "for", "i", "in", "range...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/Tkinter.py#L1925-L1937
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/inplace_ops.py
python
alias_inplace_update
(x, i, v)
return _inplace_helper(x, i, v, gen_array_ops.inplace_update)
Applies an inplace update on input x at index i with value v. Aliases x. If i is None, x and v must be the same shape. Computes x = v; If i is a scalar, x has a rank 1 higher than v's. Computes x[i, :] = v; Otherwise, x and v must have the same rank. Computes x[i, :] = v; Args: x: A Tensor. i: None, a scalar or a vector. v: A Tensor. Returns: Returns x.
Applies an inplace update on input x at index i with value v. Aliases x.
[ "Applies", "an", "inplace", "update", "on", "input", "x", "at", "index", "i", "with", "value", "v", ".", "Aliases", "x", "." ]
def alias_inplace_update(x, i, v): """Applies an inplace update on input x at index i with value v. Aliases x. If i is None, x and v must be the same shape. Computes x = v; If i is a scalar, x has a rank 1 higher than v's. Computes x[i, :] = v; Otherwise, x and v must have the same rank. Computes x[i, :] = v; Args: x: A Tensor. i: None, a scalar or a vector. v: A Tensor. Returns: Returns x. """ return _inplace_helper(x, i, v, gen_array_ops.inplace_update)
[ "def", "alias_inplace_update", "(", "x", ",", "i", ",", "v", ")", ":", "return", "_inplace_helper", "(", "x", ",", "i", ",", "v", ",", "gen_array_ops", ".", "inplace_update", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/inplace_ops.py#L67-L86
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/packages/six.py
python
_SixMetaPathImporter.is_package
(self, fullname)
return hasattr(self.__get_module(fullname), "__path__")
Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451)
Return true, if the named module is a package.
[ "Return", "true", "if", "the", "named", "module", "is", "a", "package", "." ]
def is_package(self, fullname): """ Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451) """ return hasattr(self.__get_module(fullname), "__path__")
[ "def", "is_package", "(", "self", ",", "fullname", ")", ":", "return", "hasattr", "(", "self", ".", "__get_module", "(", "fullname", ")", ",", "\"__path__\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/packages/six.py#L205-L212
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_core.py
python
TextAreaBase.ShowPosition
(*args, **kwargs)
return _core_.TextAreaBase_ShowPosition(*args, **kwargs)
ShowPosition(self, long pos)
ShowPosition(self, long pos)
[ "ShowPosition", "(", "self", "long", "pos", ")" ]
def ShowPosition(*args, **kwargs): """ShowPosition(self, long pos)""" return _core_.TextAreaBase_ShowPosition(*args, **kwargs)
[ "def", "ShowPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "TextAreaBase_ShowPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_core.py#L13448-L13450
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/computation/pytables.py
python
BinOp.conform
(self, rhs)
return rhs
inplace conform rhs
inplace conform rhs
[ "inplace", "conform", "rhs" ]
def conform(self, rhs): """inplace conform rhs""" if not is_list_like(rhs): rhs = [rhs] if isinstance(rhs, np.ndarray): rhs = rhs.ravel() return rhs
[ "def", "conform", "(", "self", ",", "rhs", ")", ":", "if", "not", "is_list_like", "(", "rhs", ")", ":", "rhs", "=", "[", "rhs", "]", "if", "isinstance", "(", "rhs", ",", "np", ".", "ndarray", ")", ":", "rhs", "=", "rhs", ".", "ravel", "(", ")",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/computation/pytables.py#L156-L162
carla-simulator/carla
8854804f4d7748e14d937ec763a2912823a7e5f5
Co-Simulation/PTV-Vissim/vissim_integration/carla_simulation.py
python
CarlaSimulation.destroy_actor
(self, actor_id)
return False
Destroys the given actor.
Destroys the given actor.
[ "Destroys", "the", "given", "actor", "." ]
def destroy_actor(self, actor_id): """ Destroys the given actor. """ actor = self.world.get_actor(actor_id) if actor is not None: return actor.destroy() return False
[ "def", "destroy_actor", "(", "self", ",", "actor_id", ")", ":", "actor", "=", "self", ".", "world", ".", "get_actor", "(", "actor_id", ")", "if", "actor", "is", "not", "None", ":", "return", "actor", ".", "destroy", "(", ")", "return", "False" ]
https://github.com/carla-simulator/carla/blob/8854804f4d7748e14d937ec763a2912823a7e5f5/Co-Simulation/PTV-Vissim/vissim_integration/carla_simulation.py#L73-L80
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py2/jinja2/nodes.py
python
Node.set_ctx
(self, ctx)
return self
Reset the context of a node and all child nodes. Per default the parser will all generate nodes that have a 'load' context as it's the most common one. This method is used in the parser to set assignment targets and other nodes to a store context.
Reset the context of a node and all child nodes. Per default the parser will all generate nodes that have a 'load' context as it's the most common one. This method is used in the parser to set assignment targets and other nodes to a store context.
[ "Reset", "the", "context", "of", "a", "node", "and", "all", "child", "nodes", ".", "Per", "default", "the", "parser", "will", "all", "generate", "nodes", "that", "have", "a", "load", "context", "as", "it", "s", "the", "most", "common", "one", ".", "Thi...
def set_ctx(self, ctx): """Reset the context of a node and all child nodes. Per default the parser will all generate nodes that have a 'load' context as it's the most common one. This method is used in the parser to set assignment targets and other nodes to a store context. """ todo = deque([self]) while todo: node = todo.popleft() if "ctx" in node.fields: node.ctx = ctx todo.extend(node.iter_child_nodes()) return self
[ "def", "set_ctx", "(", "self", ",", "ctx", ")", ":", "todo", "=", "deque", "(", "[", "self", "]", ")", "while", "todo", ":", "node", "=", "todo", ".", "popleft", "(", ")", "if", "\"ctx\"", "in", "node", ".", "fields", ":", "node", ".", "ctx", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py2/jinja2/nodes.py#L185-L197
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/ops/lookup_ops.py
python
InitializableLookupTableBase.init
(self)
return self._init
The table initialization op.
The table initialization op.
[ "The", "table", "initialization", "op", "." ]
def init(self): """The table initialization op.""" return self._init
[ "def", "init", "(", "self", ")", ":", "return", "self", ".", "_init" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/ops/lookup_ops.py#L175-L177
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/tbe/square_sum_v1.py
python
_square_sum_v1_tbe
()
return
SquareSumV1 TBE register
SquareSumV1 TBE register
[ "SquareSumV1", "TBE", "register" ]
def _square_sum_v1_tbe(): """SquareSumV1 TBE register""" return
[ "def", "_square_sum_v1_tbe", "(", ")", ":", "return" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/tbe/square_sum_v1.py#L36-L38
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py
python
DEFINE_string
(name, default, help, flag_values=FLAGS, **args)
Registers a flag whose value can be any string.
Registers a flag whose value can be any string.
[ "Registers", "a", "flag", "whose", "value", "can", "be", "any", "string", "." ]
def DEFINE_string(name, default, help, flag_values=FLAGS, **args): """Registers a flag whose value can be any string.""" parser = ArgumentParser() serializer = ArgumentSerializer() DEFINE(parser, name, default, help, flag_values, serializer, **args)
[ "def", "DEFINE_string", "(", "name", ",", "default", ",", "help", ",", "flag_values", "=", "FLAGS", ",", "*", "*", "args", ")", ":", "parser", "=", "ArgumentParser", "(", ")", "serializer", "=", "ArgumentSerializer", "(", ")", "DEFINE", "(", "parser", ",...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/external/bazel_tools/third_party/py/gflags/__init__.py#L2309-L2313
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend.py
python
_get_session
(op_input_list=())
return session
Returns the session object for the current thread.
Returns the session object for the current thread.
[ "Returns", "the", "session", "object", "for", "the", "current", "thread", "." ]
def _get_session(op_input_list=()): """Returns the session object for the current thread.""" global _SESSION default_session = ops.get_default_session() if default_session is not None: session = default_session else: if ops.inside_function(): raise RuntimeError('Cannot get session inside Tensorflow graph function.') # If we don't have a session, or that session does not match the current # graph, create and cache a new session. if (getattr(_SESSION, 'session', None) is None or _SESSION.session.graph is not _current_graph(op_input_list)): # If we are creating the Session inside a tf.distribute.Strategy scope, # we ask the strategy for the right session options to use. if distribution_strategy_context.has_strategy(): configure_and_create_distributed_session( distribution_strategy_context.get_strategy()) else: _SESSION.session = session_module.Session( config=get_default_session_config()) session = _SESSION.session return session
[ "def", "_get_session", "(", "op_input_list", "=", "(", ")", ")", ":", "global", "_SESSION", "default_session", "=", "ops", ".", "get_default_session", "(", ")", "if", "default_session", "is", "not", "None", ":", "session", "=", "default_session", "else", ":", ...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/keras/backend.py#L435-L457
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
AnyButton.GetBitmapMargins
(*args, **kwargs)
return _controls_.AnyButton_GetBitmapMargins(*args, **kwargs)
GetBitmapMargins(self) -> Size
GetBitmapMargins(self) -> Size
[ "GetBitmapMargins", "(", "self", ")", "-", ">", "Size" ]
def GetBitmapMargins(*args, **kwargs): """GetBitmapMargins(self) -> Size""" return _controls_.AnyButton_GetBitmapMargins(*args, **kwargs)
[ "def", "GetBitmapMargins", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "AnyButton_GetBitmapMargins", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L150-L152
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/util.py
python
FileOperator.copy_file
(self, infile, outfile, check=True)
Copy a file respecting dry-run and force flags.
Copy a file respecting dry-run and force flags.
[ "Copy", "a", "file", "respecting", "dry", "-", "run", "and", "force", "flags", "." ]
def copy_file(self, infile, outfile, check=True): """Copy a file respecting dry-run and force flags. """ self.ensure_dir(os.path.dirname(outfile)) logger.info('Copying %s to %s', infile, outfile) if not self.dry_run: msg = None if check: if os.path.islink(outfile): msg = '%s is a symlink' % outfile elif os.path.exists(outfile) and not os.path.isfile(outfile): msg = '%s is a non-regular file' % outfile if msg: raise ValueError(msg + ' which would be overwritten') shutil.copyfile(infile, outfile) self.record_as_written(outfile)
[ "def", "copy_file", "(", "self", ",", "infile", ",", "outfile", ",", "check", "=", "True", ")", ":", "self", ".", "ensure_dir", "(", "os", ".", "path", ".", "dirname", "(", "outfile", ")", ")", "logger", ".", "info", "(", "'Copying %s to %s'", ",", "...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/util.py#L353-L368
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/buildscripts/gdb/mongo_lock.py
python
MongoDBWaitsForGraph.mongodb_waitsfor_graph
(self, file=None)
GDB in-process python supplement
GDB in-process python supplement
[ "GDB", "in", "-", "process", "python", "supplement" ]
def mongodb_waitsfor_graph(self, file=None): """GDB in-process python supplement""" graph = Graph() try: thread_dict = get_threads_info(graph=graph) get_locks(graph=graph, thread_dict=thread_dict, show=False) graph.remove_nodes_without_edge() if graph.is_empty(): print("Not generating the digraph, since the lock graph is empty") return cycle_message = "# No cycle detected in the graph" cycle_nodes = graph.detect_cycle() if cycle_nodes: cycle_message = "# Cycle detected in the graph nodes %s" % cycle_nodes if file: print("Saving digraph to %s" % file) with open(file, 'w') as f: f.write(graph.to_graph(nodes=cycle_nodes, message=cycle_message)) print(cycle_message.split("# ")[1]) else: print(graph.to_graph(nodes=cycle_nodes, message=cycle_message)) except gdb.error as err: print("Ignoring GDB error '%s' in mongod_deadlock_graph" % str(err))
[ "def", "mongodb_waitsfor_graph", "(", "self", ",", "file", "=", "None", ")", ":", "graph", "=", "Graph", "(", ")", "try", ":", "thread_dict", "=", "get_threads_info", "(", "graph", "=", "graph", ")", "get_locks", "(", "graph", "=", "graph", ",", "thread_...
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/buildscripts/gdb/mongo_lock.py#L331-L355
H-uru/Plasma
c2140ea046e82e9c199e257a7f2e7edb42602871
Scripts/Python/xLocTools.py
python
MemberStatusString
()
return PtGetLocalizedString("Neighborhood.PlayerStatus.Member")
returns a string of what type of neighborhood member this person is
returns a string of what type of neighborhood member this person is
[ "returns", "a", "string", "of", "what", "type", "of", "neighborhood", "member", "this", "person", "is" ]
def MemberStatusString(): "returns a string of what type of neighborhood member this person is" ageInfo = ptAgeInfoStruct() ageInfo.setAgeFilename("Neighborhood") if ptVault().amAgeCzar(ageInfo): return PtGetLocalizedString("Neighborhood.PlayerStatus.Mayor") return PtGetLocalizedString("Neighborhood.PlayerStatus.Member")
[ "def", "MemberStatusString", "(", ")", ":", "ageInfo", "=", "ptAgeInfoStruct", "(", ")", "ageInfo", ".", "setAgeFilename", "(", "\"Neighborhood\"", ")", "if", "ptVault", "(", ")", ".", "amAgeCzar", "(", "ageInfo", ")", ":", "return", "PtGetLocalizedString", "(...
https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/xLocTools.py#L75-L81
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py
python
TarFile.addfile
(self, tarinfo, fileobj=None)
Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size.
Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size.
[ "Add", "the", "TarInfo", "object", "tarinfo", "to", "the", "archive", ".", "If", "fileobj", "is", "given", "tarinfo", ".", "size", "bytes", "are", "read", "from", "it", "and", "added", "to", "the", "archive", ".", "You", "can", "create", "TarInfo", "obje...
def addfile(self, tarinfo, fileobj=None): """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size. """ self._check("aw") tarinfo = copy.copy(tarinfo) buf = tarinfo.tobuf(self.format, self.encoding, self.errors) self.fileobj.write(buf) self.offset += len(buf) # If there's data to follow, append it. if fileobj is not None: copyfileobj(fileobj, self.fileobj, tarinfo.size) blocks, remainder = divmod(tarinfo.size, BLOCKSIZE) if remainder > 0: self.fileobj.write(NUL * (BLOCKSIZE - remainder)) blocks += 1 self.offset += blocks * BLOCKSIZE self.members.append(tarinfo)
[ "def", "addfile", "(", "self", ",", "tarinfo", ",", "fileobj", "=", "None", ")", ":", "self", ".", "_check", "(", "\"aw\"", ")", "tarinfo", "=", "copy", ".", "copy", "(", "tarinfo", ")", "buf", "=", "tarinfo", ".", "tobuf", "(", "self", ".", "forma...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/distlib/_backport/tarfile.py#L2100-L2124
miyosuda/TensorFlowAndroidDemo
35903e0221aa5f109ea2dbef27f20b52e317f42d
jni-build/jni/include/tensorflow/contrib/metrics/python/ops/metric_ops.py
python
streaming_mean_tensor
(values, weights=None, metrics_collections=None, updates_collections=None, name=None)
Computes the element-wise (weighted) mean of the given tensors. In contrast to the `streaming_mean` function which returns a scalar with the mean, this function returns an average tensor with the same shape as the input tensors. The `streaming_mean_tensor` function creates two local variables, `total_tensor` and `count_tensor` that are used to compute the average of `values`. This average is ultimately returned as `mean` which is an idempotent operation that simply divides `total` by `count`. To facilitate the estimation of a mean over a stream of data, the function creates an `update_op` operation whose behavior is dependent on the value of `weights`. If `weights` is None, then `update_op` increments `total` with the reduced sum of `values` and increments `count` with the number of elements in `values`. If `weights` is not `None`, then `update_op` increments `total` with the reduced sum of the product of `values` and `weights` and increments `count` with the reduced sum of weights. In addition to performing the updates, `update_op` also returns the `mean`. Args: values: A `Tensor` of arbitrary dimensions. weights: An optional set of weights of the same shape as `values`. If `weights` is not None, the function computes a weighted mean. metrics_collections: An optional list of collections that `mean` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_op_scope name. Returns: mean: A float tensor representing the current mean, the value of `total` divided by `count`. update_op: An operation that increments the `total` and `count` variables appropriately and whose value matches `mean_value`. Raises: ValueError: If `weights` is not `None` and its shape doesn't match `values` or if either `metrics_collections` or `updates_collections` are not a list or tuple.
Computes the element-wise (weighted) mean of the given tensors.
[ "Computes", "the", "element", "-", "wise", "(", "weighted", ")", "mean", "of", "the", "given", "tensors", "." ]
def streaming_mean_tensor(values, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the element-wise (weighted) mean of the given tensors. In contrast to the `streaming_mean` function which returns a scalar with the mean, this function returns an average tensor with the same shape as the input tensors. The `streaming_mean_tensor` function creates two local variables, `total_tensor` and `count_tensor` that are used to compute the average of `values`. This average is ultimately returned as `mean` which is an idempotent operation that simply divides `total` by `count`. To facilitate the estimation of a mean over a stream of data, the function creates an `update_op` operation whose behavior is dependent on the value of `weights`. If `weights` is None, then `update_op` increments `total` with the reduced sum of `values` and increments `count` with the number of elements in `values`. If `weights` is not `None`, then `update_op` increments `total` with the reduced sum of the product of `values` and `weights` and increments `count` with the reduced sum of weights. In addition to performing the updates, `update_op` also returns the `mean`. Args: values: A `Tensor` of arbitrary dimensions. weights: An optional set of weights of the same shape as `values`. If `weights` is not None, the function computes a weighted mean. metrics_collections: An optional list of collections that `mean` should be added to. updates_collections: An optional list of collections that `update_op` should be added to. name: An optional variable_op_scope name. Returns: mean: A float tensor representing the current mean, the value of `total` divided by `count`. update_op: An operation that increments the `total` and `count` variables appropriately and whose value matches `mean_value`. Raises: ValueError: If `weights` is not `None` and its shape doesn't match `values` or if either `metrics_collections` or `updates_collections` are not a list or tuple. """ with variable_scope.variable_op_scope([values, weights], name, 'mean'): total = _create_local('total_tensor', shape=values.get_shape()) count = _create_local('count_tensor', shape=values.get_shape()) if weights is not None: values.get_shape().assert_is_compatible_with(weights.get_shape()) weights = math_ops.to_float(weights) values = math_ops.mul(values, weights) num_values = weights else: num_values = array_ops.ones_like(values) total_compute_op = state_ops.assign_add(total, values) count_compute_op = state_ops.assign_add(count, num_values) def compute_mean(total, count, name): non_zero_count = math_ops.maximum(count, array_ops.ones_like(count), name=name) return math_ops.truediv(total, non_zero_count, name=name) mean = compute_mean(total, count, 'value') with ops.control_dependencies([total_compute_op, count_compute_op]): update_op = compute_mean(total, count, 'update_op') if metrics_collections: ops.add_to_collections(metrics_collections, mean) if updates_collections: ops.add_to_collections(updates_collections, update_op) return mean, update_op
[ "def", "streaming_mean_tensor", "(", "values", ",", "weights", "=", "None", ",", "metrics_collections", "=", "None", ",", "updates_collections", "=", "None", ",", "name", "=", "None", ")", ":", "with", "variable_scope", ".", "variable_op_scope", "(", "[", "val...
https://github.com/miyosuda/TensorFlowAndroidDemo/blob/35903e0221aa5f109ea2dbef27f20b52e317f42d/jni-build/jni/include/tensorflow/contrib/metrics/python/ops/metric_ops.py#L307-L380
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/pydoc.py
python
pipepager
(text, cmd)
Page through text by feeding it to another program.
Page through text by feeding it to another program.
[ "Page", "through", "text", "by", "feeding", "it", "to", "another", "program", "." ]
def pipepager(text, cmd): """Page through text by feeding it to another program.""" pipe = os.popen(cmd, 'w') try: pipe.write(_encode(text)) pipe.close() except IOError: pass
[ "def", "pipepager", "(", "text", ",", "cmd", ")", ":", "pipe", "=", "os", ".", "popen", "(", "cmd", ",", "'w'", ")", "try", ":", "pipe", ".", "write", "(", "_encode", "(", "text", ")", ")", "pipe", ".", "close", "(", ")", "except", "IOError", "...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/pydoc.py#L1415-L1422
tiny-dnn/tiny-dnn
c0f576f5cb7b35893f62127cb7aec18f77a3bcc5
third_party/gemmlowp/meta/generators/gemm_MxNxK.py
python
GenerateGemmSwitch1
(emitter, output_type, aligned)
First level of main switch, choose optimized version on rows leftover.
First level of main switch, choose optimized version on rows leftover.
[ "First", "level", "of", "main", "switch", "choose", "optimized", "version", "on", "rows", "leftover", "." ]
def GenerateGemmSwitch1(emitter, output_type, aligned): """First level of main switch, choose optimized version on rows leftover.""" emitter.EmitSwitch('m % 3') for m_mod in range(0, 3): emitter.EmitCase(m_mod) emitter.PushIndent() GenerateGemmSwitch2(emitter, output_type, aligned, m_mod) emitter.EmitBreak() emitter.PopIndent() emitter.EmitSwitchEnd()
[ "def", "GenerateGemmSwitch1", "(", "emitter", ",", "output_type", ",", "aligned", ")", ":", "emitter", ".", "EmitSwitch", "(", "'m % 3'", ")", "for", "m_mod", "in", "range", "(", "0", ",", "3", ")", ":", "emitter", ".", "EmitCase", "(", "m_mod", ")", "...
https://github.com/tiny-dnn/tiny-dnn/blob/c0f576f5cb7b35893f62127cb7aec18f77a3bcc5/third_party/gemmlowp/meta/generators/gemm_MxNxK.py#L273-L284
trailofbits/llvm-sanitizer-tutorial
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
llvm/tools/clang/bindings/python/clang/cindex.py
python
Type.get_fields
(self)
return iter(fields)
Return an iterator for accessing the fields of this type.
Return an iterator for accessing the fields of this type.
[ "Return", "an", "iterator", "for", "accessing", "the", "fields", "of", "this", "type", "." ]
def get_fields(self): """Return an iterator for accessing the fields of this type.""" def visitor(field, children): assert field != conf.lib.clang_getNullCursor() # Create reference to TU so it isn't GC'd before Cursor. field._tu = self._tu fields.append(field) return 1 # continue fields = [] conf.lib.clang_Type_visitFields(self, callbacks['fields_visit'](visitor), fields) return iter(fields)
[ "def", "get_fields", "(", "self", ")", ":", "def", "visitor", "(", "field", ",", "children", ")", ":", "assert", "field", "!=", "conf", ".", "lib", ".", "clang_getNullCursor", "(", ")", "# Create reference to TU so it isn't GC'd before Cursor.", "field", ".", "_...
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/clang/bindings/python/clang/cindex.py#L2397-L2410
macchina-io/macchina.io
ef24ba0e18379c3dd48fb84e6dbf991101cb8db0
platform/JS/V8/tools/gyp/pylib/gyp/MSVSSettings.py
python
ConvertVCMacrosToMSBuild
(s)
return s
Convert the the MSVS macros found in the string to the MSBuild equivalent. This list is probably not exhaustive. Add as needed.
Convert the the MSVS macros found in the string to the MSBuild equivalent.
[ "Convert", "the", "the", "MSVS", "macros", "found", "in", "the", "string", "to", "the", "MSBuild", "equivalent", "." ]
def ConvertVCMacrosToMSBuild(s): """Convert the the MSVS macros found in the string to the MSBuild equivalent. This list is probably not exhaustive. Add as needed. """ if '$' in s: replace_map = { '$(ConfigurationName)': '$(Configuration)', '$(InputDir)': '%(RelativeDir)', '$(InputExt)': '%(Extension)', '$(InputFileName)': '%(Filename)%(Extension)', '$(InputName)': '%(Filename)', '$(InputPath)': '%(Identity)', '$(ParentName)': '$(ProjectFileName)', '$(PlatformName)': '$(Platform)', '$(SafeInputName)': '%(Filename)', } for old, new in replace_map.iteritems(): s = s.replace(old, new) s = FixVCMacroSlashes(s) return s
[ "def", "ConvertVCMacrosToMSBuild", "(", "s", ")", ":", "if", "'$'", "in", "s", ":", "replace_map", "=", "{", "'$(ConfigurationName)'", ":", "'$(Configuration)'", ",", "'$(InputDir)'", ":", "'%(RelativeDir)'", ",", "'$(InputExt)'", ":", "'%(Extension)'", ",", "'$(I...
https://github.com/macchina-io/macchina.io/blob/ef24ba0e18379c3dd48fb84e6dbf991101cb8db0/platform/JS/V8/tools/gyp/pylib/gyp/MSVSSettings.py#L419-L439
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/metrics/python/ops/metric_ops.py
python
precision_at_recall
(labels, predictions, target_recall, weights=None, num_thresholds=200, metrics_collections=None, updates_collections=None, name=None)
Computes the precision at a given recall. This function creates variables to track the true positives, false positives, true negatives, and false negatives at a set of thresholds. Among those thresholds where recall is at least `target_recall`, precision is computed at the threshold where recall is closest to `target_recall`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the precision at `target_recall`. `update_op` increments the counts of true positives, false positives, true negatives, and false negatives with the weight of each case found in the `predictions` and `labels`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. For additional information about precision and recall, see http://en.wikipedia.org/wiki/Precision_and_recall Args: labels: The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. predictions: A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. target_recall: A scalar value in range `[0, 1]`. weights: Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). num_thresholds: The number of thresholds to use for matching the given recall. metrics_collections: An optional list of collections to which `precision` should be added. updates_collections: An optional list of collections to which `update_op` should be added. name: An optional variable_scope name. Returns: precision: A scalar `Tensor` representing the precision at the given `target_recall` value. update_op: An operation that increments the variables for tracking the true positives, false positives, true negatives, and false negatives and whose value matches `precision`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, if `weights` is not `None` and its shape doesn't match `predictions`, or if `target_recall` is not between 0 and 1, or if either `metrics_collections` or `updates_collections` are not a list or tuple. RuntimeError: If eager execution is enabled.
Computes the precision at a given recall.
[ "Computes", "the", "precision", "at", "a", "given", "recall", "." ]
def precision_at_recall(labels, predictions, target_recall, weights=None, num_thresholds=200, metrics_collections=None, updates_collections=None, name=None): """Computes the precision at a given recall. This function creates variables to track the true positives, false positives, true negatives, and false negatives at a set of thresholds. Among those thresholds where recall is at least `target_recall`, precision is computed at the threshold where recall is closest to `target_recall`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the precision at `target_recall`. `update_op` increments the counts of true positives, false positives, true negatives, and false negatives with the weight of each case found in the `predictions` and `labels`. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. For additional information about precision and recall, see http://en.wikipedia.org/wiki/Precision_and_recall Args: labels: The ground truth values, a `Tensor` whose dimensions must match `predictions`. Will be cast to `bool`. predictions: A floating point `Tensor` of arbitrary shape and whose values are in the range `[0, 1]`. target_recall: A scalar value in range `[0, 1]`. weights: Optional `Tensor` whose rank is either 0, or the same rank as `labels`, and must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). num_thresholds: The number of thresholds to use for matching the given recall. metrics_collections: An optional list of collections to which `precision` should be added. updates_collections: An optional list of collections to which `update_op` should be added. name: An optional variable_scope name. Returns: precision: A scalar `Tensor` representing the precision at the given `target_recall` value. update_op: An operation that increments the variables for tracking the true positives, false positives, true negatives, and false negatives and whose value matches `precision`. Raises: ValueError: If `predictions` and `labels` have mismatched shapes, if `weights` is not `None` and its shape doesn't match `predictions`, or if `target_recall` is not between 0 and 1, or if either `metrics_collections` or `updates_collections` are not a list or tuple. RuntimeError: If eager execution is enabled. """ if context.executing_eagerly(): raise RuntimeError('tf.metrics.precision_at_recall is not ' 'supported when eager execution is enabled.') if target_recall < 0 or target_recall > 1: raise ValueError('`target_recall` must be in the range [0, 1].') with variable_scope.variable_scope(name, 'precision_at_recall', (predictions, labels, weights)): kepsilon = 1e-7 # Used to avoid division by zero. thresholds = [ (i + 1) * 1.0 / (num_thresholds - 1) for i in range(num_thresholds - 2) ] thresholds = [0.0 - kepsilon] + thresholds + [1.0 + kepsilon] values, update_ops = _streaming_confusion_matrix_at_thresholds( predictions, labels, thresholds, weights) def compute_precision_at_recall(tp, fp, fn, name): """Computes the precision at a given recall. Args: tp: True positives. fp: False positives. fn: False negatives. name: A name for the operation. Returns: The precision at the desired recall. """ recalls = math_ops.div(tp, tp + fn + kepsilon) # Because recall is monotone decreasing as a function of the threshold, # the smallest recall exceeding target_recall occurs at the largest # threshold where recall >= target_recall. admissible_recalls = math_ops.cast( math_ops.greater_equal(recalls, target_recall), dtypes.int64) tf_index = math_ops.reduce_sum(admissible_recalls) - 1 # Now we have the threshold at which to compute precision: return math_ops.div(tp[tf_index] + kepsilon, tp[tf_index] + fp[tf_index] + kepsilon, name) precision_value = compute_precision_at_recall(values['tp'], values['fp'], values['fn'], 'value') update_op = compute_precision_at_recall(update_ops['tp'], update_ops['fp'], update_ops['fn'], 'update_op') if metrics_collections: ops.add_to_collections(metrics_collections, precision_value) if updates_collections: ops.add_to_collections(updates_collections, update_op) return precision_value, update_op
[ "def", "precision_at_recall", "(", "labels", ",", "predictions", ",", "target_recall", ",", "weights", "=", "None", ",", "num_thresholds", "=", "200", ",", "metrics_collections", "=", "None", ",", "updates_collections", "=", "None", ",", "name", "=", "None", "...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/metrics/python/ops/metric_ops.py#L2648-L2759
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/symbol/numpy/_symbol.py
python
flipud
(m)
return flip(m, 0)
r""" flipud(*args, **kwargs) Flip array in the up/down direction. Flip the entries in each column in the up/down direction. Rows are preserved, but appear in a different order than before. Parameters ---------- m : array_like Input array. Returns ------- out : array_like A view of `m` with the rows reversed. Since a view is returned, this operation is :math:`\mathcal O(1)`.
r""" flipud(*args, **kwargs)
[ "r", "flipud", "(", "*", "args", "**", "kwargs", ")" ]
def flipud(m): r""" flipud(*args, **kwargs) Flip array in the up/down direction. Flip the entries in each column in the up/down direction. Rows are preserved, but appear in a different order than before. Parameters ---------- m : array_like Input array. Returns ------- out : array_like A view of `m` with the rows reversed. Since a view is returned, this operation is :math:`\mathcal O(1)`. """ return flip(m, 0)
[ "def", "flipud", "(", "m", ")", ":", "return", "flip", "(", "m", ",", "0", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/symbol/numpy/_symbol.py#L5709-L5729
glotzerlab/hoomd-blue
f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a
hoomd/dem/pair.py
python
_DEMBase.setParams2D
(self, type, vertices, center=False)
Set the vertices for a given particle type. Args: type (str): Name of the type to set the shape of vertices (list): List of (2D) points specifying the coordinates of the shape center (bool): If True, subtract the center of mass of the shape from the vertices before setting them for the shape Shapes are specified as a list of 2D coordinates. Edges will be made between all adjacent pairs of vertices, including one between the last and first vertex.
Set the vertices for a given particle type.
[ "Set", "the", "vertices", "for", "a", "given", "particle", "type", "." ]
def setParams2D(self, type, vertices, center=False): """Set the vertices for a given particle type. Args: type (str): Name of the type to set the shape of vertices (list): List of (2D) points specifying the coordinates of the shape center (bool): If True, subtract the center of mass of the shape from the vertices before setting them for the shape Shapes are specified as a list of 2D coordinates. Edges will be made between all adjacent pairs of vertices, including one between the last and first vertex. """ itype = hoomd.context.current.system_definition.getParticleData( ).getTypeByName(type) if not len(vertices): vertices = [(0, 0)] center = False # explicitly turn into a list of tuples if center: vertices = [ (float(p[0]), float(p[1])) for p in utils.center(vertices) ] else: vertices = [(float(p[0]), float(p[1])) for p in vertices] # update the neighbor list rcutmax = 2 * (sqrt(max(x * x + y * y for (x, y) in vertices)) + self.radius * 2**(1. / 6)) self.r_cut = max(self.r_cut, rcutmax) self.vertices[type] = vertices self.cpp_force.setRcut(self.r_cut) self.cpp_force.setParams(itype, vertices)
[ "def", "setParams2D", "(", "self", ",", "type", ",", "vertices", ",", "center", "=", "False", ")", ":", "itype", "=", "hoomd", ".", "context", ".", "current", ".", "system_definition", ".", "getParticleData", "(", ")", ".", "getTypeByName", "(", "type", ...
https://github.com/glotzerlab/hoomd-blue/blob/f7f97abfa3fcc2522fa8d458d65d0aeca7ba781a/hoomd/dem/pair.py#L52-L86
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/valgrind/suppressions.py
python
ReadValgrindStyleSuppressions
(lines, supp_descriptor)
return result
Given a list of lines, returns a list of suppressions. Args: lines: a list of lines containing suppressions. supp_descriptor: should typically be a filename. Used only when printing errors.
Given a list of lines, returns a list of suppressions.
[ "Given", "a", "list", "of", "lines", "returns", "a", "list", "of", "suppressions", "." ]
def ReadValgrindStyleSuppressions(lines, supp_descriptor): """Given a list of lines, returns a list of suppressions. Args: lines: a list of lines containing suppressions. supp_descriptor: should typically be a filename. Used only when printing errors. """ result = [] cur_descr = '' cur_type = '' cur_stack = [] in_suppression = False nline = 0 for line in lines: nline += 1 line = line.strip() if line.startswith('#'): continue if not in_suppression: if not line: # empty lines between suppressions pass elif line.startswith('{'): in_suppression = True pass else: raise SuppressionError('Expected: "{"', "%s:%d" % (supp_descriptor, nline)) elif line.startswith('}'): result.append( ValgrindStyleSuppression(cur_descr, cur_type, cur_stack, "%s:%d" % (supp_descriptor, nline))) cur_descr = '' cur_type = '' cur_stack = [] in_suppression = False elif not cur_descr: cur_descr = line continue elif not cur_type: if (not line.startswith("Memcheck:") and not line.startswith("ThreadSanitizer:")): raise SuppressionError( 'Expected "Memcheck:TYPE" or "ThreadSanitizer:TYPE", ' 'got "%s"' % line, "%s:%d" % (supp_descriptor, nline)) supp_type = line.split(':')[1] if not supp_type in ["Addr1", "Addr2", "Addr4", "Addr8", "Cond", "Free", "Jump", "Leak", "Overlap", "Param", "Value1", "Value2", "Value4", "Value8", "Race", "UnlockNonLocked", "InvalidLock", "Unaddressable", "Uninitialized"]: raise SuppressionError('Unknown suppression type "%s"' % supp_type, "%s:%d" % (supp_descriptor, nline)) cur_type = line continue elif re.match("^fun:.*|^obj:.*|^\.\.\.$", line): cur_stack.append(line.strip()) elif len(cur_stack) == 0 and cur_type == "Memcheck:Param": cur_stack.append(line.strip()) else: raise SuppressionError( '"fun:function_name" or "obj:object_file" or "..." expected', "%s:%d" % (supp_descriptor, nline)) return result
[ "def", "ReadValgrindStyleSuppressions", "(", "lines", ",", "supp_descriptor", ")", ":", "result", "=", "[", "]", "cur_descr", "=", "''", "cur_type", "=", "''", "cur_stack", "=", "[", "]", "in_suppression", "=", "False", "nline", "=", "0", "for", "line", "i...
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/valgrind/suppressions.py#L258-L323
ablab/spades
3a754192b88540524ce6fb69eef5ea9273a38465
webvis/pydot.py
python
graph_from_dot_file
(path)
return graph_from_dot_data(data)
Load graph as defined by a DOT file. The file is assumed to be in DOT format. It will be loaded, parsed and a Dot class will be returned, representing the graph.
Load graph as defined by a DOT file. The file is assumed to be in DOT format. It will be loaded, parsed and a Dot class will be returned, representing the graph.
[ "Load", "graph", "as", "defined", "by", "a", "DOT", "file", ".", "The", "file", "is", "assumed", "to", "be", "in", "DOT", "format", ".", "It", "will", "be", "loaded", "parsed", "and", "a", "Dot", "class", "will", "be", "returned", "representing", "the"...
def graph_from_dot_file(path): """Load graph as defined by a DOT file. The file is assumed to be in DOT format. It will be loaded, parsed and a Dot class will be returned, representing the graph. """ fd = file(path, 'rb') data = fd.read() fd.close() return graph_from_dot_data(data)
[ "def", "graph_from_dot_file", "(", "path", ")", ":", "fd", "=", "file", "(", "path", ",", "'rb'", ")", "data", "=", "fd", ".", "read", "(", ")", "fd", ".", "close", "(", ")", "return", "graph_from_dot_data", "(", "data", ")" ]
https://github.com/ablab/spades/blob/3a754192b88540524ce6fb69eef5ea9273a38465/webvis/pydot.py#L223-L235
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/__init__.py
python
connect_cloudtrail
(aws_access_key_id=None, aws_secret_access_key=None, **kwargs)
return CloudTrailConnection( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, **kwargs )
Connect to AWS CloudTrail :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.cloudtrail.layer1.CloudtrailConnection` :return: A connection to the AWS Cloudtrail service
Connect to AWS CloudTrail
[ "Connect", "to", "AWS", "CloudTrail" ]
def connect_cloudtrail(aws_access_key_id=None, aws_secret_access_key=None, **kwargs): """ Connect to AWS CloudTrail :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.cloudtrail.layer1.CloudtrailConnection` :return: A connection to the AWS Cloudtrail service """ from boto.cloudtrail.layer1 import CloudTrailConnection return CloudTrailConnection( aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, **kwargs )
[ "def", "connect_cloudtrail", "(", "aws_access_key_id", "=", "None", ",", "aws_secret_access_key", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "boto", ".", "cloudtrail", ".", "layer1", "import", "CloudTrailConnection", "return", "CloudTrailConnection", ...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/__init__.py#L796-L816
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
Menu.IsChecked
(*args, **kwargs)
return _core_.Menu_IsChecked(*args, **kwargs)
IsChecked(self, int id) -> bool
IsChecked(self, int id) -> bool
[ "IsChecked", "(", "self", "int", "id", ")", "-", ">", "bool" ]
def IsChecked(*args, **kwargs): """IsChecked(self, int id) -> bool""" return _core_.Menu_IsChecked(*args, **kwargs)
[ "def", "IsChecked", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Menu_IsChecked", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L12162-L12164
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/math/symbolic.py
python
Function.info
(self)
return '\n'.join(items)
Returns an text string describing the Function, similar to a docstring
Returns an text string describing the Function, similar to a docstring
[ "Returns", "an", "text", "string", "describing", "the", "Function", "similar", "to", "a", "docstring" ]
def info(self): """Returns an text string describing the Function, similar to a docstring""" argstr = '...' if self.argNames is None else ','.join(self.argNames) signature = '%s(%s)'%(self.name,argstr) if isinstance(self.func,Expression): signature = signature + '\n Defined as '+str(self.func) argHelp = None if self.argTypes is not None or self.argDescriptions is not None: if self.argNames is None: argHelp = [str(self.argDescriptions)] else: argHelp= [] for i,name in enumerate(self.argNames): type = None if self.argTypes is None else self.argTypes[i] desc = None if self.argDescriptions is None else self.argDescriptions[i] if desc is None: if type is not None: desc = type.info() else: desc = 'unknown' argHelp.append('- %s: %s'%(name,desc)) returnHelp = None if self.returnTypeDescription is not None: returnHelp = "- " + self.returnTypeDescription elif self.returnType is not None: returnHelp = "- " + self.returnType.info() elif self.returnTypeFunc is not None: if self.returnTypeFunc == _propagate_returnType: returnHelp = "- same as arguments" elif self.returnTypeFunc == _promote_returnType: returnHelp = "- same as arguments" elif self.returnTypeFunc == _returnType1: returnHelp = "- same as argument 1" elif self.returnTypeFunc == _returnType2: returnHelp = "- same as argument 2" elif self.returnTypeFunc == _returnType3: returnHelp = "- same as argument 3" else: returnHelp = "- dynamic" derivHelp = None if self.deriv is not None or self.jacobian is not None: derivHelp = [] if _is_exactly(self.deriv,0): derivHelp.append('- derivative is 0 everywhere') elif callable(self.deriv): deval = None if self.argNames is not None: argTypes = [Type(None)]*len(self.argNames) if self.argTypes is None else self.argTypes vars = [expr(Variable(a,t)) for a,t in zip(self.argNames,argTypes)] dvars = [expr(Variable('d'+a,t)) for a,t in zip(self.argNames,argTypes)] try: deval = self.deriv(vars,dvars) except Exception: pass if deval: derivHelp.append('- derivative is '+str(deval)) else: derivHelp.append('- derivative is a total derivative function') elif callable(self.jacobian): derivHelp.append('- jacobian is a total derivative function') elif self.argNames is not None: argTypes = [Type(None)]*len(self.argNames) if self.argTypes is None else self.argTypes vars = [expr(Variable(a,t)) for a,t in zip(self.argNames,argTypes)] for i,a in enumerate(self.argNames): if self.deriv is not None and self.deriv[i] is not None: if _is_exactly(self.deriv[i],0): derivHelp.append('- %s: derivative is 0'%(a,)) elif isinstance(self.deriv[i],Function): derivHelp.append('- %s: available as Python df/da * da/dx function'%(a,)) else: try: deval = self.deriv[i](*(vars+[expr(Variable('d'+a,argTypes[i]))])) if is_op(deval,'subs'): deval = deval.args[0] derivHelp.append('- %s: available as df/da * da/dx function %s'%(a,str(deval))) except Exception as e: derivHelp.append('- %s: available as df/da * da/dx function, Exception %s'%(a,str(e))) elif self.jacobian is not None and self.jacobian[i] is not None: if _is_exactly(self.jacobian[i],0): derivHelp.append('- %s: jacobian is 0'%(a,)) elif isinstance(self.deriv[i],Function): derivHelp.append('- %s: available as Python jacobian df/da'%(a,)) else: try: deval = self.jacobian[i](*vars) if is_op(deval,'subs'): deval = deval.args[0] derivHelp.append('- %s: available as jacobian df/da %s'%(a,str(deval))) except Exception as e: derivHelp.append('- %s: available as jacobian df/da, Exception %s'%(a,str(e))) items = [signature] if self.description != None: items += ['',self.description,''] if argHelp is not None and len(argHelp) > 0: items += ['','Parameters','---------']+argHelp if returnHelp is not None: items += ['','Return type','-----------',returnHelp] if derivHelp is not None and len(derivHelp) > 0: items += ['','Derivatives','-----------']+derivHelp return '\n'.join(items)
[ "def", "info", "(", "self", ")", ":", "argstr", "=", "'...'", "if", "self", ".", "argNames", "is", "None", "else", "','", ".", "join", "(", "self", ".", "argNames", ")", "signature", "=", "'%s(%s)'", "%", "(", "self", ".", "name", ",", "argstr", ")...
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/math/symbolic.py#L1908-L2007
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
Event.Skip
(*args, **kwargs)
return _core_.Event_Skip(*args, **kwargs)
Skip(self, bool skip=True) This method can be used inside an event handler to control whether further event handlers bound to this event will be called after the current one returns. Without Skip() (or equivalently if Skip(False) is used), the event will not be processed any more. If Skip(True) is called, the event processing system continues searching for a further handler function for this event, even though it has been processed already in the current handler.
Skip(self, bool skip=True)
[ "Skip", "(", "self", "bool", "skip", "=", "True", ")" ]
def Skip(*args, **kwargs): """ Skip(self, bool skip=True) This method can be used inside an event handler to control whether further event handlers bound to this event will be called after the current one returns. Without Skip() (or equivalently if Skip(False) is used), the event will not be processed any more. If Skip(True) is called, the event processing system continues searching for a further handler function for this event, even though it has been processed already in the current handler. """ return _core_.Event_Skip(*args, **kwargs)
[ "def", "Skip", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "Event_Skip", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L5047-L5059
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/Chem/ChemUtils/AlignDepict.py
python
main
()
Main application
Main application
[ "Main", "application" ]
def main(): """ Main application """ parser = initParser() args = parser.parse_args() processArgs(args)
[ "def", "main", "(", ")", ":", "parser", "=", "initParser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "processArgs", "(", "args", ")" ]
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/Chem/ChemUtils/AlignDepict.py#L84-L88
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/util/nest.py
python
list_to_tuple
(structure)
return _pack_sequence_as(structure, flatten(structure), False, sequence_fn=sequence_fn)
Replace all lists with tuples. The fork of nest that tf.data uses treats lists as atoms, while tf.nest treats them as structures to recurse into. Keras has chosen to adopt the latter convention, and must therefore deeply replace all lists with tuples before passing structures to Dataset.from_generator. Args: structure: A nested structure to be remapped. Returns: structure mapped to replace all lists with tuples.
Replace all lists with tuples.
[ "Replace", "all", "lists", "with", "tuples", "." ]
def list_to_tuple(structure): """Replace all lists with tuples. The fork of nest that tf.data uses treats lists as atoms, while tf.nest treats them as structures to recurse into. Keras has chosen to adopt the latter convention, and must therefore deeply replace all lists with tuples before passing structures to Dataset.from_generator. Args: structure: A nested structure to be remapped. Returns: structure mapped to replace all lists with tuples. """ def sequence_fn(instance, args): if isinstance(instance, list): return tuple(args) return _sequence_like(instance, args) return _pack_sequence_as(structure, flatten(structure), False, sequence_fn=sequence_fn)
[ "def", "list_to_tuple", "(", "structure", ")", ":", "def", "sequence_fn", "(", "instance", ",", "args", ")", ":", "if", "isinstance", "(", "instance", ",", "list", ")", ":", "return", "tuple", "(", "args", ")", "return", "_sequence_like", "(", "instance", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/util/nest.py#L1702-L1722
numworks/epsilon
8952d2f8b1de1c3f064eec8ffcea804c5594ba4c
build/device/usb/backend/__init__.py
python
IBackend.release_interface
(self, dev_handle, intf)
r"""Release the claimed interface. dev_handle and intf are the same parameters of the claim_interface method.
r"""Release the claimed interface.
[ "r", "Release", "the", "claimed", "interface", "." ]
def release_interface(self, dev_handle, intf): r"""Release the claimed interface. dev_handle and intf are the same parameters of the claim_interface method. """ _not_implemented(self.release_interface)
[ "def", "release_interface", "(", "self", ",", "dev_handle", ",", "intf", ")", ":", "_not_implemented", "(", "self", ".", "release_interface", ")" ]
https://github.com/numworks/epsilon/blob/8952d2f8b1de1c3f064eec8ffcea804c5594ba4c/build/device/usb/backend/__init__.py#L232-L238
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gnuradio-runtime/python/gnuradio/gr/top_block.py
python
top_block.unlock
(self)
Release lock and continue execution of flow-graph.
Release lock and continue execution of flow-graph.
[ "Release", "lock", "and", "continue", "execution", "of", "flow", "-", "graph", "." ]
def unlock(self): """ Release lock and continue execution of flow-graph. """ top_block_unlock_unlocked(self._impl)
[ "def", "unlock", "(", "self", ")", ":", "top_block_unlock_unlocked", "(", "self", ".", "_impl", ")" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gnuradio-runtime/python/gnuradio/gr/top_block.py#L115-L119
smilehao/xlua-framework
a03801538be2b0e92d39332d445b22caca1ef61f
ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/encoder.py
python
StringSizer
(field_number, is_repeated, is_packed)
Returns a sizer for a string field.
Returns a sizer for a string field.
[ "Returns", "a", "sizer", "for", "a", "string", "field", "." ]
def StringSizer(field_number, is_repeated, is_packed): """Returns a sizer for a string field.""" tag_size = _TagSize(field_number) local_VarintSize = _VarintSize local_len = len assert not is_packed if is_repeated: def RepeatedFieldSize(value): result = tag_size * len(value) for element in value: l = local_len(element.encode('utf-8')) result += local_VarintSize(l) + l return result return RepeatedFieldSize else: def FieldSize(value): l = local_len(value.encode('utf-8')) return tag_size + local_VarintSize(l) + l return FieldSize
[ "def", "StringSizer", "(", "field_number", ",", "is_repeated", ",", "is_packed", ")", ":", "tag_size", "=", "_TagSize", "(", "field_number", ")", "local_VarintSize", "=", "_VarintSize", "local_len", "=", "len", "assert", "not", "is_packed", "if", "is_repeated", ...
https://github.com/smilehao/xlua-framework/blob/a03801538be2b0e92d39332d445b22caca1ef61f/ConfigData/trunk/tools/protobuf-2.5.0/protobuf-2.5.0/python/build/lib/google/protobuf/internal/encoder.py#L227-L246
luliyucoordinate/Leetcode
96afcdc54807d1d184e881a075d1dbf3371e31fb
src/0149-Max-Points-on-a-Line/0149.py
python
Solution.maxPoints
(self, points)
return result
:type points: List[Point] :rtype: int
:type points: List[Point] :rtype: int
[ ":", "type", "points", ":", "List", "[", "Point", "]", ":", "rtype", ":", "int" ]
def maxPoints(self, points): """ :type points: List[Point] :rtype: int """ slopes, result = defaultdict(int), 0 for i, point1 in enumerate(points): slopes.clear() duplicate = 1 for _, point2 in enumerate(points[i+1:]): if point1.x == point2.x and point1.y == point2.y: duplicate += 1 continue slope = float('inf') if point1.x == point2.x else \ Decimal((point1.y - point2.y))/Decimal((point1.x - point2.x)) slopes[slope] += 1 if result < duplicate: result = duplicate for _, val in slopes.items(): if val + duplicate > result: result = val + duplicate return result
[ "def", "maxPoints", "(", "self", ",", "points", ")", ":", "slopes", ",", "result", "=", "defaultdict", "(", "int", ")", ",", "0", "for", "i", ",", "point1", "in", "enumerate", "(", "points", ")", ":", "slopes", ".", "clear", "(", ")", "duplicate", ...
https://github.com/luliyucoordinate/Leetcode/blob/96afcdc54807d1d184e881a075d1dbf3371e31fb/src/0149-Max-Points-on-a-Line/0149.py#L10-L36
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/mixed_precision/python/loss_scale_manager.py
python
ExponentialUpdateLossScaleManager.__init__
(self, init_loss_scale, incr_every_n_steps, decr_every_n_nan_or_inf=2, incr_ratio=2, decr_ratio=0.8)
Constructor of exponential-update loss scale manager. Args: init_loss_scale: A Python float. The loss scale to use at the beginning. incr_every_n_steps: Increases loss scale every n consecutive steps with finite gradients. decr_every_n_nan_or_inf: Decreases loss scale every n accumulated steps with nan or inf gradients. incr_ratio: The multiplier to use when increasing the loss scale. decr_ratio: The less-than-one-multiplier to use when decreasing the loss scale.
Constructor of exponential-update loss scale manager.
[ "Constructor", "of", "exponential", "-", "update", "loss", "scale", "manager", "." ]
def __init__(self, init_loss_scale, incr_every_n_steps, decr_every_n_nan_or_inf=2, incr_ratio=2, decr_ratio=0.8): """Constructor of exponential-update loss scale manager. Args: init_loss_scale: A Python float. The loss scale to use at the beginning. incr_every_n_steps: Increases loss scale every n consecutive steps with finite gradients. decr_every_n_nan_or_inf: Decreases loss scale every n accumulated steps with nan or inf gradients. incr_ratio: The multiplier to use when increasing the loss scale. decr_ratio: The less-than-one-multiplier to use when decreasing the loss scale. """ self._incr_every_n_steps = incr_every_n_steps self._decr_every_n_nan_or_inf = decr_every_n_nan_or_inf self._incr_ratio = incr_ratio self._decr_ratio = decr_ratio self._loss_scale = variable_scope.variable( name="loss_scale", initial_value=ops.convert_to_tensor(init_loss_scale, dtypes.float32), dtype=dtypes.float32, trainable=False) self._num_good_steps = variable_scope.variable( name="good_steps", initial_value=0, dtype=dtypes.int32, trainable=False) self._num_bad_steps = variable_scope.variable( name="bad_steps", initial_value=0, dtype=dtypes.int32, trainable=False)
[ "def", "__init__", "(", "self", ",", "init_loss_scale", ",", "incr_every_n_steps", ",", "decr_every_n_nan_or_inf", "=", "2", ",", "incr_ratio", "=", "2", ",", "decr_ratio", "=", "0.8", ")", ":", "self", ".", "_incr_every_n_steps", "=", "incr_every_n_steps", "sel...
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/contrib/mixed_precision/python/loss_scale_manager.py#L118-L148
apache/arrow
af33dd1157eb8d7d9bfac25ebf61445b793b7943
dev/archery/archery/utils/git.py
python
Git.repository_root
(self, git_dir=None, **kwargs)
return stdout.decode('utf-8')
Locates the repository's root path from a subdirectory.
Locates the repository's root path from a subdirectory.
[ "Locates", "the", "repository", "s", "root", "path", "from", "a", "subdirectory", "." ]
def repository_root(self, git_dir=None, **kwargs): """ Locates the repository's root path from a subdirectory. """ stdout = self.rev_parse("--show-toplevel", git_dir=git_dir, **kwargs) return stdout.decode('utf-8')
[ "def", "repository_root", "(", "self", ",", "git_dir", "=", "None", ",", "*", "*", "kwargs", ")", ":", "stdout", "=", "self", ".", "rev_parse", "(", "\"--show-toplevel\"", ",", "git_dir", "=", "git_dir", ",", "*", "*", "kwargs", ")", "return", "stdout", ...
https://github.com/apache/arrow/blob/af33dd1157eb8d7d9bfac25ebf61445b793b7943/dev/archery/archery/utils/git.py#L94-L97
Ardour/ardour
a63a18a3387b90c0920d9b1668d2a50bd6302b83
tools/cstyle.py
python
Preprocessor.process_strings
(self, line)
return line
Given a line of C code, return a string where all literal C strings have been replaced with the empty string literal "".
Given a line of C code, return a string where all literal C strings have been replaced with the empty string literal "".
[ "Given", "a", "line", "of", "C", "code", "return", "a", "string", "where", "all", "literal", "C", "strings", "have", "been", "replaced", "with", "the", "empty", "string", "literal", "." ]
def process_strings (self, line): """ Given a line of C code, return a string where all literal C strings have been replaced with the empty string literal "". """ for k in range (0, len (line)): if line [k] == '"': start = k for k in range (start + 1, len (line)): if line [k] == '"' and line [k - 1] != '\\': return line [:start + 1] + '"' + self.process_strings (line [k + 1:]) return line
[ "def", "process_strings", "(", "self", ",", "line", ")", ":", "for", "k", "in", "range", "(", "0", ",", "len", "(", "line", ")", ")", ":", "if", "line", "[", "k", "]", "==", "'\"'", ":", "start", "=", "k", "for", "k", "in", "range", "(", "sta...
https://github.com/Ardour/ardour/blob/a63a18a3387b90c0920d9b1668d2a50bd6302b83/tools/cstyle.py#L87-L98
ziquan111/RobustPCLReconstruction
35b9518dbf9ad3f06109cc0e3aaacafdb5c86e36
py/sophus/quaternion.py
python
Quaternion.conj
(self)
return Quaternion(self.real, -self.vec)
quaternion conjugate
quaternion conjugate
[ "quaternion", "conjugate" ]
def conj(self): """ quaternion conjugate """ return Quaternion(self.real, -self.vec)
[ "def", "conj", "(", "self", ")", ":", "return", "Quaternion", "(", "self", ".", "real", ",", "-", "self", ".", "vec", ")" ]
https://github.com/ziquan111/RobustPCLReconstruction/blob/35b9518dbf9ad3f06109cc0e3aaacafdb5c86e36/py/sophus/quaternion.py#L51-L53
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
examples/python/symbolication.py
python
Image.create_target
(self)
return None
Create a target using the information in this Image object.
Create a target using the information in this Image object.
[ "Create", "a", "target", "using", "the", "information", "in", "this", "Image", "object", "." ]
def create_target(self): '''Create a target using the information in this Image object.''' if self.unavailable: return None if self.locate_module_and_debug_symbols(): resolved_path = self.get_resolved_path() path_spec = lldb.SBFileSpec(resolved_path) error = lldb.SBError() target = lldb.debugger.CreateTarget( resolved_path, self.arch, None, False, error) if target: self.module = target.FindModule(path_spec) if self.has_section_load_info(): err = self.load_module(target) if err: print('ERROR: ', err) return target else: print('error: unable to create a valid target for (%s) "%s"' % (self.arch, self.path)) else: print('error: unable to locate main executable (%s) "%s"' % (self.arch, self.path)) return None
[ "def", "create_target", "(", "self", ")", ":", "if", "self", ".", "unavailable", ":", "return", "None", "if", "self", ".", "locate_module_and_debug_symbols", "(", ")", ":", "resolved_path", "=", "self", ".", "get_resolved_path", "(", ")", "path_spec", "=", "...
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/examples/python/symbolication.py#L413-L435
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/turtle.py
python
_getscreen
()
return Turtle._screen
Create a TurtleScreen if not already present.
Create a TurtleScreen if not already present.
[ "Create", "a", "TurtleScreen", "if", "not", "already", "present", "." ]
def _getscreen(): """Create a TurtleScreen if not already present.""" if Turtle._screen is None: Turtle._screen = Screen() return Turtle._screen
[ "def", "_getscreen", "(", ")", ":", "if", "Turtle", ".", "_screen", "is", "None", ":", "Turtle", ".", "_screen", "=", "Screen", "(", ")", "return", "Turtle", ".", "_screen" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/lib-tk/turtle.py#L3717-L3721
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/cython/Cython/Plex/DFA.py
python
StateMap.new_to_old
(self, new_state)
return self.new_to_old_dict[id(new_state)]
Given a new state, return a set of corresponding old states.
Given a new state, return a set of corresponding old states.
[ "Given", "a", "new", "state", "return", "a", "set", "of", "corresponding", "old", "states", "." ]
def new_to_old(self, new_state): """Given a new state, return a set of corresponding old states.""" return self.new_to_old_dict[id(new_state)]
[ "def", "new_to_old", "(", "self", ",", "new_state", ")", ":", "return", "self", ".", "new_to_old_dict", "[", "id", "(", "new_state", ")", "]" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/cython/Cython/Plex/DFA.py#L143-L145
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/boringssl/src/util/generate_build_files.py
python
FindCMakeFiles
(directory)
return cmakefiles
Returns list of all CMakeLists.txt files recursively in directory.
Returns list of all CMakeLists.txt files recursively in directory.
[ "Returns", "list", "of", "all", "CMakeLists", ".", "txt", "files", "recursively", "in", "directory", "." ]
def FindCMakeFiles(directory): """Returns list of all CMakeLists.txt files recursively in directory.""" cmakefiles = [] for (path, _, filenames) in os.walk(directory): for filename in filenames: if filename == 'CMakeLists.txt': cmakefiles.append(os.path.join(path, filename)) return cmakefiles
[ "def", "FindCMakeFiles", "(", "directory", ")", ":", "cmakefiles", "=", "[", "]", "for", "(", "path", ",", "_", ",", "filenames", ")", "in", "os", ".", "walk", "(", "directory", ")", ":", "for", "filename", "in", "filenames", ":", "if", "filename", "...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/boringssl/src/util/generate_build_files.py#L444-L453
rdkit/rdkit
ede860ae316d12d8568daf5ee800921c3389c84e
rdkit/sping/PDF/pidPDF.py
python
PDFCanvas._updateLineWidth
(self, width)
Triggered when someone assigns to defaultLineWidth
Triggered when someone assigns to defaultLineWidth
[ "Triggered", "when", "someone", "assigns", "to", "defaultLineWidth" ]
def _updateLineWidth(self, width): """Triggered when someone assigns to defaultLineWidth""" self.pdf.setLineWidth(width)
[ "def", "_updateLineWidth", "(", "self", ",", "width", ")", ":", "self", ".", "pdf", ".", "setLineWidth", "(", "width", ")" ]
https://github.com/rdkit/rdkit/blob/ede860ae316d12d8568daf5ee800921c3389c84e/rdkit/sping/PDF/pidPDF.py#L206-L208
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
TextAreaBase.ShowPosition
(*args, **kwargs)
return _core_.TextAreaBase_ShowPosition(*args, **kwargs)
ShowPosition(self, long pos)
ShowPosition(self, long pos)
[ "ShowPosition", "(", "self", "long", "pos", ")" ]
def ShowPosition(*args, **kwargs): """ShowPosition(self, long pos)""" return _core_.TextAreaBase_ShowPosition(*args, **kwargs)
[ "def", "ShowPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "TextAreaBase_ShowPosition", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L13444-L13446
mandiant/flare-wmi
b0a5a094ff9ca7d7a1c4fc711dc00c74dec4b6b1
python-cim/cim/cim.py
python
LogicalIndexStore.root_page_number
(self)
fetch the logical page number of the index root. Returns: int: the logical page number.
fetch the logical page number of the index root. Returns: int: the logical page number.
[ "fetch", "the", "logical", "page", "number", "of", "the", "index", "root", ".", "Returns", ":", "int", ":", "the", "logical", "page", "number", "." ]
def root_page_number(self): """ fetch the logical page number of the index root. Returns: int: the logical page number. """ if self._cim.cim_type == CIM_TYPE_WIN7: return int(self._mapping.map.entries[0x0].used_space) elif self._cim.cim_type == CIM_TYPE_XP: return self.get_page(0).header.root_page else: raise RuntimeError("Unexpected CIM type: " + str(self._cim.cim_type))
[ "def", "root_page_number", "(", "self", ")", ":", "if", "self", ".", "_cim", ".", "cim_type", "==", "CIM_TYPE_WIN7", ":", "return", "int", "(", "self", ".", "_mapping", ".", "map", ".", "entries", "[", "0x0", "]", ".", "used_space", ")", "elif", "self"...
https://github.com/mandiant/flare-wmi/blob/b0a5a094ff9ca7d7a1c4fc711dc00c74dec4b6b1/python-cim/cim/cim.py#L770-L782
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/utils/data_utils.py
python
next_sample
(uid)
return next(_SHARED_SEQUENCES[uid])
Gets the next value from the generator `uid`. To allow multiple generators to be used at the same time, we use `uid` to get a specific one. A single generator would cause the validation to overwrite the training generator. Args: uid: int, generator identifier Returns: The next value of generator `uid`.
Gets the next value from the generator `uid`.
[ "Gets", "the", "next", "value", "from", "the", "generator", "uid", "." ]
def next_sample(uid): """Gets the next value from the generator `uid`. To allow multiple generators to be used at the same time, we use `uid` to get a specific one. A single generator would cause the validation to overwrite the training generator. Args: uid: int, generator identifier Returns: The next value of generator `uid`. """ return next(_SHARED_SEQUENCES[uid])
[ "def", "next_sample", "(", "uid", ")", ":", "return", "next", "(", "_SHARED_SEQUENCES", "[", "uid", "]", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/utils/data_utils.py#L797-L810
clasp-developers/clasp
5287e5eb9bbd5e8da1e3a629a03d78bd71d01969
tools-for-build/pump.py
python
SubString
(lines, start, end)
return ''.join(result_lines)
Returns a substring in lines.
Returns a substring in lines.
[ "Returns", "a", "substring", "in", "lines", "." ]
def SubString(lines, start, end): """Returns a substring in lines.""" if end == Eof(): end = Cursor(len(lines) - 1, len(lines[-1])) if start >= end: return '' if start.line == end.line: return lines[start.line][start.column:end.column] result_lines = ([lines[start.line][start.column:]] + lines[start.line + 1:end.line] + [lines[end.line][:end.column]]) return ''.join(result_lines)
[ "def", "SubString", "(", "lines", ",", "start", ",", "end", ")", ":", "if", "end", "==", "Eof", "(", ")", ":", "end", "=", "Cursor", "(", "len", "(", "lines", ")", "-", "1", ",", "len", "(", "lines", "[", "-", "1", "]", ")", ")", "if", "sta...
https://github.com/clasp-developers/clasp/blob/5287e5eb9bbd5e8da1e3a629a03d78bd71d01969/tools-for-build/pump.py#L208-L223
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/lookup_ops.py
python
LookupInterface.__init__
(self, key_dtype, value_dtype)
Construct a lookup table interface. Args: key_dtype: The table key type. value_dtype: The table value type.
Construct a lookup table interface.
[ "Construct", "a", "lookup", "table", "interface", "." ]
def __init__(self, key_dtype, value_dtype): """Construct a lookup table interface. Args: key_dtype: The table key type. value_dtype: The table value type. """ self._key_dtype = dtypes.as_dtype(key_dtype) self._value_dtype = dtypes.as_dtype(value_dtype) super(LookupInterface, self).__init__()
[ "def", "__init__", "(", "self", ",", "key_dtype", ",", "value_dtype", ")", ":", "self", ".", "_key_dtype", "=", "dtypes", ".", "as_dtype", "(", "key_dtype", ")", "self", ".", "_value_dtype", "=", "dtypes", ".", "as_dtype", "(", "value_dtype", ")", "super",...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/lookup_ops.py#L130-L139
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/http/server.py
python
SimpleHTTPRequestHandler.list_directory
(self, path)
return f
Helper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head().
Helper to produce a directory listing (absent index.html).
[ "Helper", "to", "produce", "a", "directory", "listing", "(", "absent", "index", ".", "html", ")", "." ]
def list_directory(self, path): """Helper to produce a directory listing (absent index.html). Return value is either a file object, or None (indicating an error). In either case, the headers are sent, making the interface the same as for send_head(). """ try: list = os.listdir(path) except OSError: self.send_error( HTTPStatus.NOT_FOUND, "No permission to list directory") return None list.sort(key=lambda a: a.lower()) r = [] try: displaypath = urllib.parse.unquote(self.path, errors='surrogatepass') except UnicodeDecodeError: displaypath = urllib.parse.unquote(path) displaypath = html.escape(displaypath, quote=False) enc = sys.getfilesystemencoding() title = 'Directory listing for %s' % displaypath r.append('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" ' '"http://www.w3.org/TR/html4/strict.dtd">') r.append('<html>\n<head>') r.append('<meta http-equiv="Content-Type" ' 'content="text/html; charset=%s">' % enc) r.append('<title>%s</title>\n</head>' % title) r.append('<body>\n<h1>%s</h1>' % title) r.append('<hr>\n<ul>') for name in list: fullname = os.path.join(path, name) displayname = linkname = name # Append / for directories or @ for symbolic links if os.path.isdir(fullname): displayname = name + "/" linkname = name + "/" if os.path.islink(fullname): displayname = name + "@" # Note: a link to a directory displays with @ and links with / r.append('<li><a href="%s">%s</a></li>' % (urllib.parse.quote(linkname, errors='surrogatepass'), html.escape(displayname, quote=False))) r.append('</ul>\n<hr>\n</body>\n</html>\n') encoded = '\n'.join(r).encode(enc, 'surrogateescape') f = io.BytesIO() f.write(encoded) f.seek(0) self.send_response(HTTPStatus.OK) self.send_header("Content-type", "text/html; charset=%s" % enc) self.send_header("Content-Length", str(len(encoded))) self.end_headers() return f
[ "def", "list_directory", "(", "self", ",", "path", ")", ":", "try", ":", "list", "=", "os", ".", "listdir", "(", "path", ")", "except", "OSError", ":", "self", ".", "send_error", "(", "HTTPStatus", ".", "NOT_FOUND", ",", "\"No permission to list directory\""...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/http/server.py#L742-L798
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/contrib/mixed_precision/amp_nn.py
python
check_finite_and_unscale
(x, scale, name=None, float_status=None)
return x, found_inf
Check if input X contains all finite data, if yes, scale it by input Scale. $$Out = X / scale$$ If any tensor in X contains Inf or Nan, the Out will generate a indicator. FoundInfinite will be 1 (True), and Out will not be scaled. In this case, the data of Out should not be used, and its data may not be deterministic. Otherwise, FoundInfinite will be 0 (False). Args: x(list|tuple): The input tensors of check_finite_and_unscale operator. scale: The scale of check_finite_and_unscale operator. float_status(Tensor): (Only used on NPU) The float status to check overflow.
Check if input X contains all finite data, if yes, scale it by input Scale.
[ "Check", "if", "input", "X", "contains", "all", "finite", "data", "if", "yes", "scale", "it", "by", "input", "Scale", "." ]
def check_finite_and_unscale(x, scale, name=None, float_status=None): """ Check if input X contains all finite data, if yes, scale it by input Scale. $$Out = X / scale$$ If any tensor in X contains Inf or Nan, the Out will generate a indicator. FoundInfinite will be 1 (True), and Out will not be scaled. In this case, the data of Out should not be used, and its data may not be deterministic. Otherwise, FoundInfinite will be 0 (False). Args: x(list|tuple): The input tensors of check_finite_and_unscale operator. scale: The scale of check_finite_and_unscale operator. float_status(Tensor): (Only used on NPU) The float status to check overflow. """ check_type(x, 'x', (tuple, list), 'check_finite_and_unscale') for e in x: check_variable_and_dtype(e, "x", ['float16', 'float32', 'float64'], 'check_finite_and_unscale') helper = LayerHelper("check_finite_and_unscale", **locals()) found_inf = helper.create_variable_for_type_inference(dtype='bool') inputs = {'X': x, 'Scale': scale} if core.is_compiled_with_npu(): check_variable_and_dtype(float_status, "float_status", ['float16', 'float32'], 'check_finite_and_unscale') inputs['FloatStatus'] = float_status outputs = {'Out': x, 'FoundInfinite': found_inf} helper.append_op( type='check_finite_and_unscale', inputs=inputs, outputs=outputs) return x, found_inf
[ "def", "check_finite_and_unscale", "(", "x", ",", "scale", ",", "name", "=", "None", ",", "float_status", "=", "None", ")", ":", "check_type", "(", "x", ",", "'x'", ",", "(", "tuple", ",", "list", ")", ",", "'check_finite_and_unscale'", ")", "for", "e", ...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/contrib/mixed_precision/amp_nn.py#L23-L57
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py
python
create_config_module
(module, template, content, macros=None)
Create a configuration module by replacing "@" followed by "SIP_CONFIGURATION" followed by "@" in a template file with a content string. module is the name of the module file. template is the name of the template file. content is the content string. If it is a dictionary it is first converted to a string using create_content(). macros is an optional dictionary of platform specific build macros. It is only used if create_content() is called to convert the content to a string.
Create a configuration module by replacing "@" followed by "SIP_CONFIGURATION" followed by "@" in a template file with a content string.
[ "Create", "a", "configuration", "module", "by", "replacing", "@", "followed", "by", "SIP_CONFIGURATION", "followed", "by", "@", "in", "a", "template", "file", "with", "a", "content", "string", "." ]
def create_config_module(module, template, content, macros=None): """Create a configuration module by replacing "@" followed by "SIP_CONFIGURATION" followed by "@" in a template file with a content string. module is the name of the module file. template is the name of the template file. content is the content string. If it is a dictionary it is first converted to a string using create_content(). macros is an optional dictionary of platform specific build macros. It is only used if create_content() is called to convert the content to a string. """ if type(content) == dict: content = create_content(content, macros) # Allow this file to used as a template. key = "@" + "SIP_CONFIGURATION" + "@" df = open(module, "w") sf = open(template, "r") line = sf.readline() while line: if line.find(key) >= 0: line = content df.write(line) line = sf.readline() df.close() sf.close()
[ "def", "create_config_module", "(", "module", ",", "template", ",", "content", ",", "macros", "=", "None", ")", ":", "if", "type", "(", "content", ")", "==", "dict", ":", "content", "=", "create_content", "(", "content", ",", "macros", ")", "# Allow this f...
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/sipconfig.py#L2250-L2281