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
huqinghua/pyui4win
8835b39cf6f6a78514bb263cef1033705d54c51d
Tamplate/PyFrameBase.py
python
PyFrameBase.RestoreWindow
(self)
RestoreWindow
RestoreWindow
[ "RestoreWindow" ]
def RestoreWindow(self): """ RestoreWindow """ PyWinUtils().SendMessageA(self.GetHWnd(), win32con.WM_SYSCOMMAND, win32con.SC_RESTORE, 0)
[ "def", "RestoreWindow", "(", "self", ")", ":", "PyWinUtils", "(", ")", ".", "SendMessageA", "(", "self", ".", "GetHWnd", "(", ")", ",", "win32con", ".", "WM_SYSCOMMAND", ",", "win32con", ".", "SC_RESTORE", ",", "0", ")" ]
https://github.com/huqinghua/pyui4win/blob/8835b39cf6f6a78514bb263cef1033705d54c51d/Tamplate/PyFrameBase.py#L558-L562
EOSIO/eosio.cdt
798162d323680fa6d4691bcea7928729213c7172
tools/jsoncons/build/scons/site_scons/SCutils.py
python
setup_quiet_build
(env, colorblind=False)
Will fill an SCons env object with nice colors and quiet build strings. Makes warnings evident.
Will fill an SCons env object with nice colors and quiet build strings. Makes warnings evident.
[ "Will", "fill", "an", "SCons", "env", "object", "with", "nice", "colors", "and", "quiet", "build", "strings", ".", "Makes", "warnings", "evident", "." ]
def setup_quiet_build(env, colorblind=False): """Will fill an SCons env object with nice colors and quiet build strings. Makes warnings evident.""" # colors c = dict() c['cyan'] = '\033[96m' c['purple'] = '\033[95m' c['blue'] = '\033[94m' c['bold_blue'] = '\033[94;1m' c['green'] = '\033[92m' c['yellow'] = '\033[93m' c['red'] = '\033[91m' c['magenta']= '\033[35m' c['bold_magenta']= '\033[35;1m' c['inverse']= '\033[7m' c['bold'] = '\033[1m' c['rst'] = '\033[0m' # if the output is not a terminal, remove the c # also windows console doesn't know about ansi c seems #or re.match('^win.*', plat_id())\ if not sys.stdout.isatty()\ or colorblind: for key, value in c.iteritems(): c[key] = '' compile_cxx_msg = '%s[CXX]%s %s$SOURCE%s' % \ (c['blue'], c['rst'], c['yellow'], c['rst']) compile_c_msg = '%s[CC]%s %s$SOURCE%s' % \ (c['cyan'], c['rst'], c['yellow'], c['rst']) compile_shared_msg = '%s[SHR]%s %s$SOURCE%s' % \ (c['bold_blue'], c['rst'], c['yellow'], c['rst']) link_program_msg = '%s[LNK exe]%s %s$TARGET%s' % \ (c['bold_magenta'], c['rst'], c['bold'] + c['yellow'] + c['inverse'], c['rst']) link_lib_msg = '%s[LIB st]%s %s$TARGET%s' % \ ('', c['rst'], c['cyan'], c['rst']) ranlib_library_msg = '%s[RANLIB]%s %s$TARGET%s' % \ ('', c['rst'], c['cyan'], c['rst']) link_shared_library_msg = '%s[LNK shr]%s %s$TARGET%s' % \ (c['bold_magenta'], c['rst'], c['bold'], c['rst']) pch_compile = '%s[PCH]%s %s$SOURCE%s -> %s$TARGET%s' %\ (c['bold_magenta'], c['rst'], c['bold'], c['rst'], c['bold'], c['rst']) env['CXXCOMSTR'] = compile_cxx_msg env['SHCXXCOMSTR'] = compile_shared_msg env['CCCOMSTR'] = compile_c_msg env['SHCCCOMSTR'] = compile_shared_msg env['ARCOMSTR'] = link_lib_msg env['SHLINKCOMSTR'] = link_shared_library_msg env['LINKCOMSTR'] = link_program_msg env['RANLIBCOMSTR']= ranlib_library_msg env['GCHCOMSTR'] = pch_compile
[ "def", "setup_quiet_build", "(", "env", ",", "colorblind", "=", "False", ")", ":", "# colors", "c", "=", "dict", "(", ")", "c", "[", "'cyan'", "]", "=", "'\\033[96m'", "c", "[", "'purple'", "]", "=", "'\\033[95m'", "c", "[", "'blue'", "]", "=", "'\\0...
https://github.com/EOSIO/eosio.cdt/blob/798162d323680fa6d4691bcea7928729213c7172/tools/jsoncons/build/scons/site_scons/SCutils.py#L28-L86
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py2/pandas/core/groupby/ops.py
python
BinGrouper.get_iterator
(self, data, axis=0)
Groupby iterator Returns ------- Generator yielding sequence of (name, subsetted object) for each group
Groupby iterator
[ "Groupby", "iterator" ]
def get_iterator(self, data, axis=0): """ Groupby iterator Returns ------- Generator yielding sequence of (name, subsetted object) for each group """ if isinstance(data, NDFrame): slicer = lambda start, edge: data._slice( slice(start, edge), axis=axis) length = len(data.axes[axis]) else: slicer = lambda start, edge: data[slice(start, edge)] length = len(data) start = 0 for edge, label in zip(self.bins, self.binlabels): if label is not NaT: yield label, slicer(start, edge) start = edge if start < length: yield self.binlabels[-1], slicer(start, None)
[ "def", "get_iterator", "(", "self", ",", "data", ",", "axis", "=", "0", ")", ":", "if", "isinstance", "(", "data", ",", "NDFrame", ")", ":", "slicer", "=", "lambda", "start", ",", "edge", ":", "data", ".", "_slice", "(", "slice", "(", "start", ",",...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py2/pandas/core/groupby/ops.py#L689-L713
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/indexes/base.py
python
Index.notna
(self)
return ~self.isna()
Detect existing (non-missing) values. Return a boolean same-sized object indicating if the values are not NA. Non-missing values get mapped to ``True``. Characters such as empty strings ``''`` or :attr:`numpy.inf` are not considered NA values (unless you set ``pandas.options.mode.use_inf_as_na = True``). NA values, such as None or :attr:`numpy.NaN`, get mapped to ``False`` values. Returns ------- numpy.ndarray[bool] Boolean array to indicate which entries are not NA. See Also -------- Index.notnull : Alias of notna. Index.isna: Inverse of notna. notna : Top-level notna. Examples -------- Show which entries in an Index are not NA. The result is an array. >>> idx = pd.Index([5.2, 6.0, np.NaN]) >>> idx Float64Index([5.2, 6.0, nan], dtype='float64') >>> idx.notna() array([ True, True, False]) Empty strings are not considered NA values. None is considered a NA value. >>> idx = pd.Index(['black', '', 'red', None]) >>> idx Index(['black', '', 'red', None], dtype='object') >>> idx.notna() array([ True, True, True, False])
Detect existing (non-missing) values.
[ "Detect", "existing", "(", "non", "-", "missing", ")", "values", "." ]
def notna(self) -> np.ndarray: """ Detect existing (non-missing) values. Return a boolean same-sized object indicating if the values are not NA. Non-missing values get mapped to ``True``. Characters such as empty strings ``''`` or :attr:`numpy.inf` are not considered NA values (unless you set ``pandas.options.mode.use_inf_as_na = True``). NA values, such as None or :attr:`numpy.NaN`, get mapped to ``False`` values. Returns ------- numpy.ndarray[bool] Boolean array to indicate which entries are not NA. See Also -------- Index.notnull : Alias of notna. Index.isna: Inverse of notna. notna : Top-level notna. Examples -------- Show which entries in an Index are not NA. The result is an array. >>> idx = pd.Index([5.2, 6.0, np.NaN]) >>> idx Float64Index([5.2, 6.0, nan], dtype='float64') >>> idx.notna() array([ True, True, False]) Empty strings are not considered NA values. None is considered a NA value. >>> idx = pd.Index(['black', '', 'red', None]) >>> idx Index(['black', '', 'red', None], dtype='object') >>> idx.notna() array([ True, True, True, False]) """ return ~self.isna()
[ "def", "notna", "(", "self", ")", "->", "np", ".", "ndarray", ":", "return", "~", "self", ".", "isna", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/base.py#L2513-L2555
chromiumembedded/cef
80caf947f3fe2210e5344713c5281d8af9bdc295
tools/cef_parser.py
python
obj_analysis.is_result_vector_ownptr
(self)
return self.result_value[0]['result_type'] == 'ownptr'
Returns true if this is a OwnPtr vector.
Returns true if this is a OwnPtr vector.
[ "Returns", "true", "if", "this", "is", "a", "OwnPtr", "vector", "." ]
def is_result_vector_ownptr(self): """ Returns true if this is a OwnPtr vector. """ return self.result_value[0]['result_type'] == 'ownptr'
[ "def", "is_result_vector_ownptr", "(", "self", ")", ":", "return", "self", ".", "result_value", "[", "0", "]", "[", "'result_type'", "]", "==", "'ownptr'" ]
https://github.com/chromiumembedded/cef/blob/80caf947f3fe2210e5344713c5281d8af9bdc295/tools/cef_parser.py#L1962-L1964
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/data_structures/sarray.py
python
SArray.__rtruediv__
(self, other)
Divides a scalar value by each element in the array Returned array has the same type as the array on the right hand side
Divides a scalar value by each element in the array Returned array has the same type as the array on the right hand side
[ "Divides", "a", "scalar", "value", "by", "each", "element", "in", "the", "array", "Returned", "array", "has", "the", "same", "type", "as", "the", "array", "on", "the", "right", "hand", "side" ]
def __rtruediv__(self, other): """ Divides a scalar value by each element in the array Returned array has the same type as the array on the right hand side """ with cython_context(): return SArray(_proxy = self.__proxy__.right_scalar_operator(other, '/'))
[ "def", "__rtruediv__", "(", "self", ",", "other", ")", ":", "with", "cython_context", "(", ")", ":", "return", "SArray", "(", "_proxy", "=", "self", ".", "__proxy__", ".", "right_scalar_operator", "(", "other", ",", "'/'", ")", ")" ]
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sarray.py#L1116-L1122
bairdzhang/smallhardface
76fa1d87a9602d9b13d7a7fe693fc7aec91cab80
caffe/examples/pycaffe/tools.py
python
SimpleTransformer.set_scale
(self, scale)
Set the data scaling.
Set the data scaling.
[ "Set", "the", "data", "scaling", "." ]
def set_scale(self, scale): """ Set the data scaling. """ self.scale = scale
[ "def", "set_scale", "(", "self", ",", "scale", ")", ":", "self", ".", "scale", "=", "scale" ]
https://github.com/bairdzhang/smallhardface/blob/76fa1d87a9602d9b13d7a7fe693fc7aec91cab80/caffe/examples/pycaffe/tools.py#L21-L25
google/mysql-protobuf
467cda676afaa49e762c5c9164a43f6ad31a1fbf
storage/ndb/mcc/request_handler.py
python
get_cred
(body)
return (body['ssh']['user'], body['ssh']['pwd'])
Get the credentials from the message in the form of a (user, pwd) tuple. If there is no ssh object present, or keyBased is present and True, a (None, None) tuple is returned.
Get the credentials from the message in the form of a (user, pwd) tuple. If there is no ssh object present, or keyBased is present and True, a (None, None) tuple is returned.
[ "Get", "the", "credentials", "from", "the", "message", "in", "the", "form", "of", "a", "(", "user", "pwd", ")", "tuple", ".", "If", "there", "is", "no", "ssh", "object", "present", "or", "keyBased", "is", "present", "and", "True", "a", "(", "None", "...
def get_cred(body): """Get the credentials from the message in the form of a (user, pwd) tuple. If there is no ssh object present, or keyBased is present and True, a (None, None) tuple is returned.""" if not body.has_key('ssh') or util.get_val(body['ssh'], 'keyBased', False): return (None, None) return (body['ssh']['user'], body['ssh']['pwd'])
[ "def", "get_cred", "(", "body", ")", ":", "if", "not", "body", ".", "has_key", "(", "'ssh'", ")", "or", "util", ".", "get_val", "(", "body", "[", "'ssh'", "]", ",", "'keyBased'", ",", "False", ")", ":", "return", "(", "None", ",", "None", ")", "r...
https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/storage/ndb/mcc/request_handler.py#L106-L112
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
deps/src/libxml2-2.9.1/python/libxml2class.py
python
xmlNode.newProp
(self, name, value)
return __tmp
Create a new property carried by a node.
Create a new property carried by a node.
[ "Create", "a", "new", "property", "carried", "by", "a", "node", "." ]
def newProp(self, name, value): """Create a new property carried by a node. """ ret = libxml2mod.xmlNewProp(self._o, name, value) if ret is None:raise treeError('xmlNewProp() failed') __tmp = xmlAttr(_obj=ret) return __tmp
[ "def", "newProp", "(", "self", ",", "name", ",", "value", ")", ":", "ret", "=", "libxml2mod", ".", "xmlNewProp", "(", "self", ".", "_o", ",", "name", ",", "value", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlNewProp() failed'",...
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/deps/src/libxml2-2.9.1/python/libxml2class.py#L2607-L2612
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
tools/cygprofile/patch_orderfile.py
python
_GroupSymbolInfosFromBinary
(binary_filename)
return _GroupSymbolInfos(symbol_infos)
Group all the symbols from a binary by name and offset. Args: binary_filename: path to the binary. Returns: A tuple of dict: (offset_to_symbol_infos, name_to_symbol_infos): - offset_to_symbol_infos: {offset: [symbol_info1, ...]} - name_to_symbol_infos: {name: [symbol_info1, ...]}
Group all the symbols from a binary by name and offset.
[ "Group", "all", "the", "symbols", "from", "a", "binary", "by", "name", "and", "offset", "." ]
def _GroupSymbolInfosFromBinary(binary_filename): """Group all the symbols from a binary by name and offset. Args: binary_filename: path to the binary. Returns: A tuple of dict: (offset_to_symbol_infos, name_to_symbol_infos): - offset_to_symbol_infos: {offset: [symbol_info1, ...]} - name_to_symbol_infos: {name: [symbol_info1, ...]} """ symbol_infos = symbol_extractor.SymbolInfosFromBinary(binary_filename) return _GroupSymbolInfos(symbol_infos)
[ "def", "_GroupSymbolInfosFromBinary", "(", "binary_filename", ")", ":", "symbol_infos", "=", "symbol_extractor", ".", "SymbolInfosFromBinary", "(", "binary_filename", ")", "return", "_GroupSymbolInfos", "(", "symbol_infos", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/tools/cygprofile/patch_orderfile.py#L108-L121
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/gslib/boto_translation.py
python
BotoTranslation.XmlPassThroughSetLifecycle
(self, lifecycle_text, storage_url)
See CloudApiDelegator class for function doc strings.
See CloudApiDelegator class for function doc strings.
[ "See", "CloudApiDelegator", "class", "for", "function", "doc", "strings", "." ]
def XmlPassThroughSetLifecycle(self, lifecycle_text, storage_url): """See CloudApiDelegator class for function doc strings.""" # Parse XML document and convert into lifecycle object. if storage_url.scheme == 's3': lifecycle_obj = S3Lifecycle() else: lifecycle_obj = LifecycleConfig() h = handler.XmlHandler(lifecycle_obj, None) try: xml.sax.parseString(lifecycle_text, h) except SaxExceptions.SAXParseException, e: raise CommandException( 'Requested lifecycle config is invalid: %s at line %s, column %s' % (e.getMessage(), e.getLineNumber(), e.getColumnNumber())) try: uri = boto.storage_uri( storage_url.url_string, suppress_consec_slashes=False, bucket_storage_uri_class=self.bucket_storage_uri_class, debug=self.debug) uri.configure_lifecycle(lifecycle_obj, False) except TRANSLATABLE_BOTO_EXCEPTIONS, e: self._TranslateExceptionAndRaise(e)
[ "def", "XmlPassThroughSetLifecycle", "(", "self", ",", "lifecycle_text", ",", "storage_url", ")", ":", "# Parse XML document and convert into lifecycle object.", "if", "storage_url", ".", "scheme", "==", "'s3'", ":", "lifecycle_obj", "=", "S3Lifecycle", "(", ")", "else"...
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/gslib/boto_translation.py#L1610-L1632
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqt/mantidqt/widgets/plotconfigdialog/legendtabwidget/presenter.py
python
LegendTabWidgetPresenter.check_font_in_list
(self, font)
For some reason the default matplotlib legend font isn't a system font so it's added to the font combo boxes here.
For some reason the default matplotlib legend font isn't a system font so it's added to the font combo boxes here.
[ "For", "some", "reason", "the", "default", "matplotlib", "legend", "font", "isn", "t", "a", "system", "font", "so", "it", "s", "added", "to", "the", "font", "combo", "boxes", "here", "." ]
def check_font_in_list(self, font): """For some reason the default matplotlib legend font isn't a system font so it's added to the font combo boxes here.""" if self.view.entries_font_combo_box.findText(font) == -1: self.fonts.append(font) self.fonts = sorted(self.fonts) self.view.entries_font_combo_box.clear() self.view.title_font_combo_box.clear() self.view.entries_font_combo_box.addItems(self.fonts) self.view.title_font_combo_box.addItems(self.fonts)
[ "def", "check_font_in_list", "(", "self", ",", "font", ")", ":", "if", "self", ".", "view", ".", "entries_font_combo_box", ".", "findText", "(", "font", ")", "==", "-", "1", ":", "self", ".", "fonts", ".", "append", "(", "font", ")", "self", ".", "fo...
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqt/mantidqt/widgets/plotconfigdialog/legendtabwidget/presenter.py#L158-L167
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBTrace.StopTrace
(self, error, thread_id)
return _lldb.SBTrace_StopTrace(self, error, thread_id)
StopTrace(SBTrace self, SBError error, lldb::tid_t thread_id)
StopTrace(SBTrace self, SBError error, lldb::tid_t thread_id)
[ "StopTrace", "(", "SBTrace", "self", "SBError", "error", "lldb", "::", "tid_t", "thread_id", ")" ]
def StopTrace(self, error, thread_id): """StopTrace(SBTrace self, SBError error, lldb::tid_t thread_id)""" return _lldb.SBTrace_StopTrace(self, error, thread_id)
[ "def", "StopTrace", "(", "self", ",", "error", ",", "thread_id", ")", ":", "return", "_lldb", ".", "SBTrace_StopTrace", "(", "self", ",", "error", ",", "thread_id", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L12242-L12244
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/jinja2/compiler.py
python
CodeGenerator.macro_def
(self, node, frame)
Dump the macro definition for the def created by macro_body.
Dump the macro definition for the def created by macro_body.
[ "Dump", "the", "macro", "definition", "for", "the", "def", "created", "by", "macro_body", "." ]
def macro_def(self, node, frame): """Dump the macro definition for the def created by macro_body.""" arg_tuple = ', '.join(repr(x.name) for x in node.args) name = getattr(node, 'name', None) if len(node.args) == 1: arg_tuple += ',' self.write('Macro(environment, macro, %r, (%s), (' % (name, arg_tuple)) for arg in node.defaults: self.visit(arg, frame) self.write(', ') self.write('), %r, %r, %r)' % ( bool(frame.accesses_kwargs), bool(frame.accesses_varargs), bool(frame.accesses_caller) ))
[ "def", "macro_def", "(", "self", ",", "node", ",", "frame", ")", ":", "arg_tuple", "=", "', '", ".", "join", "(", "repr", "(", "x", ".", "name", ")", "for", "x", "in", "node", ".", "args", ")", "name", "=", "getattr", "(", "node", ",", "'name'", ...
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/jinja2/compiler.py#L731-L746
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/gyp/pylib/gyp/generator/msvs.py
python
_EscapeVCProjCommandLineArgListItem
(s)
return s
Escapes command line arguments for MSVS. The VCProj format stores string lists in a single string using commas and semi-colons as separators, which must be quoted if they are to be interpreted literally. However, command-line arguments may already have quotes, and the VCProj parser is ignorant of the backslash escaping convention used by CommandLineToArgv, so the command-line quotes and the VCProj quotes may not be the same quotes. So to store a general command-line argument in a VCProj list, we need to parse the existing quoting according to VCProj's convention and quote any delimiters that are not already quoted by that convention. The quotes that we add will also be seen by CommandLineToArgv, so if backslashes precede them then we also have to escape those backslashes according to the CommandLineToArgv convention. Args: s: the string to be escaped. Returns: the escaped string.
Escapes command line arguments for MSVS.
[ "Escapes", "command", "line", "arguments", "for", "MSVS", "." ]
def _EscapeVCProjCommandLineArgListItem(s): """Escapes command line arguments for MSVS. The VCProj format stores string lists in a single string using commas and semi-colons as separators, which must be quoted if they are to be interpreted literally. However, command-line arguments may already have quotes, and the VCProj parser is ignorant of the backslash escaping convention used by CommandLineToArgv, so the command-line quotes and the VCProj quotes may not be the same quotes. So to store a general command-line argument in a VCProj list, we need to parse the existing quoting according to VCProj's convention and quote any delimiters that are not already quoted by that convention. The quotes that we add will also be seen by CommandLineToArgv, so if backslashes precede them then we also have to escape those backslashes according to the CommandLineToArgv convention. Args: s: the string to be escaped. Returns: the escaped string. """ def _Replace(match): # For a non-literal quote, CommandLineToArgv requires an even number of # backslashes preceding it, and it produces half as many literal # backslashes. So we need to produce 2n backslashes. return 2 * match.group(1) + '"' + match.group(2) + '"' segments = s.split('"') # The unquoted segments are at the even-numbered indices. for i in range(0, len(segments), 2): segments[i] = delimiters_replacer_regex.sub(_Replace, segments[i]) # Concatenate back into a single string s = '"'.join(segments) if len(segments) % 2 == 0: # String ends while still quoted according to VCProj's convention. This # means the delimiter and the next list item that follow this one in the # .vcproj file will be misinterpreted as part of this item. There is nothing # we can do about this. Adding an extra quote would correct the problem in # the VCProj but cause the same problem on the final command-line. Moving # the item to the end of the list does works, but that's only possible if # there's only one such item. Let's just warn the user. print( "Warning: MSVS may misinterpret the odd number of " + "quotes in " + s, file=sys.stderr, ) return s
[ "def", "_EscapeVCProjCommandLineArgListItem", "(", "s", ")", ":", "def", "_Replace", "(", "match", ")", ":", "# For a non-literal quote, CommandLineToArgv requires an even number of", "# backslashes preceding it, and it produces half as many literal", "# backslashes. So we need to produc...
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/gyp/pylib/gyp/generator/msvs.py#L795-L841
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/data_flow_ops.py
python
Barrier.incomplete_size
(self, name=None)
return gen_data_flow_ops._barrier_incomplete_size( self._barrier_ref, name=name)
Compute the number of incomplete elements in the given barrier. Args: name: A name for the operation (optional). Returns: A single-element tensor containing the number of incomplete elements in the given barrier.
Compute the number of incomplete elements in the given barrier.
[ "Compute", "the", "number", "of", "incomplete", "elements", "in", "the", "given", "barrier", "." ]
def incomplete_size(self, name=None): """Compute the number of incomplete elements in the given barrier. Args: name: A name for the operation (optional). Returns: A single-element tensor containing the number of incomplete elements in the given barrier. """ if name is None: name = "%s_BarrierIncompleteSize" % self._name return gen_data_flow_ops._barrier_incomplete_size( self._barrier_ref, name=name)
[ "def", "incomplete_size", "(", "self", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "\"%s_BarrierIncompleteSize\"", "%", "self", ".", "_name", "return", "gen_data_flow_ops", ".", "_barrier_incomplete_size", "(", "self", "."...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/data_flow_ops.py#L1067-L1080
bareos/bareos
56a10bb368b0a81e977bb51304033fe49d59efb0
core/src/plugins/stored/python/pyfiles/BareosSdPluginBaseclass.py
python
BareosSdPluginBaseclass.parse_plugin_definition
(self, plugindef)
return bareossd.bRC_OK
Called with the plugin options from the bareos configfiles You should overload this method with your own and do option checking here, return bRCs['bRC_Error'], if options are not ok or better call super.parse_plugin_definition in your own class and make sanity check on self.options afterwards
Called with the plugin options from the bareos configfiles You should overload this method with your own and do option checking here, return bRCs['bRC_Error'], if options are not ok or better call super.parse_plugin_definition in your own class and make sanity check on self.options afterwards
[ "Called", "with", "the", "plugin", "options", "from", "the", "bareos", "configfiles", "You", "should", "overload", "this", "method", "with", "your", "own", "and", "do", "option", "checking", "here", "return", "bRCs", "[", "bRC_Error", "]", "if", "options", "...
def parse_plugin_definition(self, plugindef): """ Called with the plugin options from the bareos configfiles You should overload this method with your own and do option checking here, return bRCs['bRC_Error'], if options are not ok or better call super.parse_plugin_definition in your own class and make sanity check on self.options afterwards """ bareossd.DebugMessage(100, "plugin def parser called with %s\n" % (plugindef)) # Parse plugin options into a dict self.options = dict() plugin_options = plugindef.split(":") for current_option in plugin_options: key, sep, val = current_option.partition("=") bareossd.DebugMessage(100, "key:val = %s:%s" % (key, val)) if val == "": continue else: self.options[key] = val return bareossd.bRC_OK
[ "def", "parse_plugin_definition", "(", "self", ",", "plugindef", ")", ":", "bareossd", ".", "DebugMessage", "(", "100", ",", "\"plugin def parser called with %s\\n\"", "%", "(", "plugindef", ")", ")", "# Parse plugin options into a dict", "self", ".", "options", "=", ...
https://github.com/bareos/bareos/blob/56a10bb368b0a81e977bb51304033fe49d59efb0/core/src/plugins/stored/python/pyfiles/BareosSdPluginBaseclass.py#L62-L81
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/cli/cmdoptions.py
python
check_install_build_global
(options, check_options=None)
Disable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options.
Disable wheels if per-setup.py call options are set.
[ "Disable", "wheels", "if", "per", "-", "setup", ".", "py", "call", "options", "are", "set", "." ]
def check_install_build_global(options, check_options=None): # type: (Values, Optional[Values]) -> None """Disable wheels if per-setup.py call options are set. :param options: The OptionParser options to update. :param check_options: The options to check, if not supplied defaults to options. """ if check_options is None: check_options = options def getname(n): # type: (str) -> Optional[Any] return getattr(check_options, n, None) names = ["build_options", "global_options", "install_options"] if any(map(getname, names)): control = options.format_control control.disallow_binaries() warnings.warn( 'Disabling all use of wheels due to the use of --build-option ' '/ --global-option / --install-option.', stacklevel=2, )
[ "def", "check_install_build_global", "(", "options", ",", "check_options", "=", "None", ")", ":", "# type: (Values, Optional[Values]) -> None", "if", "check_options", "is", "None", ":", "check_options", "=", "options", "def", "getname", "(", "n", ")", ":", "# type: ...
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/_internal/cli/cmdoptions.py#L67-L88
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/profiler/option_builder.py
python
ProfileOptionBuilder.build
(self)
return copy.deepcopy(self._options)
Build a profiling option. Returns: A dict of profiling options.
Build a profiling option.
[ "Build", "a", "profiling", "option", "." ]
def build(self): """Build a profiling option. Returns: A dict of profiling options. """ return copy.deepcopy(self._options)
[ "def", "build", "(", "self", ")", ":", "return", "copy", ".", "deepcopy", "(", "self", ".", "_options", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/profiler/option_builder.py#L191-L197
deepmind/open_spiel
4ca53bea32bb2875c7385d215424048ae92f78c8
open_spiel/python/algorithms/deep_cfr_tf2.py
python
DeepCFRSolver._reinitialize_policy_network
(self)
Reinitalize policy network and optimizer for training.
Reinitalize policy network and optimizer for training.
[ "Reinitalize", "policy", "network", "and", "optimizer", "for", "training", "." ]
def _reinitialize_policy_network(self): """Reinitalize policy network and optimizer for training.""" with tf.device(self._train_device): self._policy_network = PolicyNetwork(self._embedding_size, self._policy_network_layers, self._num_actions) self._optimizer_policy = tf.keras.optimizers.Adam( learning_rate=self._learning_rate) self._loss_policy = tf.keras.losses.MeanSquaredError()
[ "def", "_reinitialize_policy_network", "(", "self", ")", ":", "with", "tf", ".", "device", "(", "self", ".", "_train_device", ")", ":", "self", ".", "_policy_network", "=", "PolicyNetwork", "(", "self", ".", "_embedding_size", ",", "self", ".", "_policy_networ...
https://github.com/deepmind/open_spiel/blob/4ca53bea32bb2875c7385d215424048ae92f78c8/open_spiel/python/algorithms/deep_cfr_tf2.py#L376-L384
ceph/ceph
959663007321a369c83218414a29bd9dbc8bda3a
qa/tasks/mon_thrash.py
python
MonitorThrasher.should_thrash_store
(self)
return self.rng.randrange(0, 101) < self.store_thrash_probability
If allowed, indicate that we should thrash a certain percentage of the time as determined by the store_thrash_probability value.
If allowed, indicate that we should thrash a certain percentage of the time as determined by the store_thrash_probability value.
[ "If", "allowed", "indicate", "that", "we", "should", "thrash", "a", "certain", "percentage", "of", "the", "time", "as", "determined", "by", "the", "store_thrash_probability", "value", "." ]
def should_thrash_store(self): """ If allowed, indicate that we should thrash a certain percentage of the time as determined by the store_thrash_probability value. """ if not self.store_thrash: return False return self.rng.randrange(0, 101) < self.store_thrash_probability
[ "def", "should_thrash_store", "(", "self", ")", ":", "if", "not", "self", ".", "store_thrash", ":", "return", "False", "return", "self", ".", "rng", ".", "randrange", "(", "0", ",", "101", ")", "<", "self", ".", "store_thrash_probability" ]
https://github.com/ceph/ceph/blob/959663007321a369c83218414a29bd9dbc8bda3a/qa/tasks/mon_thrash.py#L158-L165
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/yaml/__init__.py
python
serialize_all
(nodes, stream=None, Dumper=Dumper, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding='utf-8', explicit_start=None, explicit_end=None, version=None, tags=None)
Serialize a sequence of representation trees into a YAML stream. If stream is None, return the produced string instead.
Serialize a sequence of representation trees into a YAML stream. If stream is None, return the produced string instead.
[ "Serialize", "a", "sequence", "of", "representation", "trees", "into", "a", "YAML", "stream", ".", "If", "stream", "is", "None", "return", "the", "produced", "string", "instead", "." ]
def serialize_all(nodes, stream=None, Dumper=Dumper, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding='utf-8', explicit_start=None, explicit_end=None, version=None, tags=None): """ Serialize a sequence of representation trees into a YAML stream. If stream is None, return the produced string instead. """ getvalue = None if stream is None: if encoding is None: from StringIO import StringIO else: from cStringIO import StringIO stream = StringIO() getvalue = stream.getvalue dumper = Dumper(stream, canonical=canonical, indent=indent, width=width, allow_unicode=allow_unicode, line_break=line_break, encoding=encoding, version=version, tags=tags, explicit_start=explicit_start, explicit_end=explicit_end) try: dumper.open() for node in nodes: dumper.serialize(node) dumper.close() finally: dumper.dispose() if getvalue: return getvalue()
[ "def", "serialize_all", "(", "nodes", ",", "stream", "=", "None", ",", "Dumper", "=", "Dumper", ",", "canonical", "=", "None", ",", "indent", "=", "None", ",", "width", "=", "None", ",", "allow_unicode", "=", "None", ",", "line_break", "=", "None", ","...
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/yaml/__init__.py#L125-L154
lammps/lammps
b75c3065430a75b1b5543a10e10f46d9b4c91913
python/lammps/pylammps.py
python
AtomList.__getitem__
(self, index)
return self._loaded[index]
Return Atom with given local index :param index: Local index of atom :type index: int :rtype: Atom or Atom2D
Return Atom with given local index
[ "Return", "Atom", "with", "given", "local", "index" ]
def __getitem__(self, index): """ Return Atom with given local index :param index: Local index of atom :type index: int :rtype: Atom or Atom2D """ if index not in self._loaded: if self.dimensions == 2: atom = Atom2D(self._pylmp, index) else: atom = Atom(self._pylmp, index) self._loaded[index] = atom return self._loaded[index]
[ "def", "__getitem__", "(", "self", ",", "index", ")", ":", "if", "index", "not", "in", "self", ".", "_loaded", ":", "if", "self", ".", "dimensions", "==", "2", ":", "atom", "=", "Atom2D", "(", "self", ".", "_pylmp", ",", "index", ")", "else", ":", ...
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/python/lammps/pylammps.py#L102-L116
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/incubate/fleet/parameter_server/pslib/__init__.py
python
_prepare_params
(input, size, is_sparse=False, is_distributed=False, padding_idx=None, param_attr=None, dtype='float32')
preprocess params, this interface is not for users. Args: input(Variable|list of Variable): Input is a Tensor<int64> Variable size(list of int): the embedding dim is_sparse(bool): whether input is sparse ids is_distributed(bool): whether in distributed mode padding_idx(int): padding idx of input param_attr(ParamAttr): To specify the weight parameter property dtype(str): data type of output
preprocess params, this interface is not for users. Args: input(Variable|list of Variable): Input is a Tensor<int64> Variable size(list of int): the embedding dim is_sparse(bool): whether input is sparse ids is_distributed(bool): whether in distributed mode padding_idx(int): padding idx of input param_attr(ParamAttr): To specify the weight parameter property dtype(str): data type of output
[ "preprocess", "params", "this", "interface", "is", "not", "for", "users", ".", "Args", ":", "input", "(", "Variable|list", "of", "Variable", ")", ":", "Input", "is", "a", "Tensor<int64", ">", "Variable", "size", "(", "list", "of", "int", ")", ":", "the",...
def _prepare_params(input, size, is_sparse=False, is_distributed=False, padding_idx=None, param_attr=None, dtype='float32'): """ preprocess params, this interface is not for users. Args: input(Variable|list of Variable): Input is a Tensor<int64> Variable size(list of int): the embedding dim is_sparse(bool): whether input is sparse ids is_distributed(bool): whether in distributed mode padding_idx(int): padding idx of input param_attr(ParamAttr): To specify the weight parameter property dtype(str): data type of output """ if param_attr is None: raise ValueError("param_attr must be set") name = param_attr.name if name is None: raise ValueError("embedding name must be set") if not isinstance(size, list) and not isinstance(size, tuple): raise ValueError("embedding size must be list or tuple") size = size[-1] global FLEET_GLOBAL_DICT FLEET_GLOBAL_DICT["enable"] = True d_table = FLEET_GLOBAL_DICT["emb_to_table"] d_accessor = FLEET_GLOBAL_DICT["emb_to_accessor"] d_size = FLEET_GLOBAL_DICT["emb_to_size"] # check embedding size if d_size.get(name) is None: d_size[name] = size elif d_size[name] != size: raise ValueError("embedding size error: %s vs %s" % (size, d_size[name])) # check embedding accessor accessor = FLEET_GLOBAL_DICT["cur_accessor"] if d_accessor.get(name) is None: d_accessor[name] = accessor elif d_accessor[name] != accessor: raise ValueError("embedding size error: %s vs %s" % (d_accessor[name], accessor)) # check embedding table id if d_table.get(name) is None: d_table[name] = FLEET_GLOBAL_DICT["cur_sparse_id"] FLEET_GLOBAL_DICT["cur_sparse_id"] += 1 # check other params if not is_sparse: raise ValueError("is_sparse must be True") elif not is_distributed: raise ValueError("is_distributed must be True") elif dtype != "float32": raise ValueError("dtype must be float32")
[ "def", "_prepare_params", "(", "input", ",", "size", ",", "is_sparse", "=", "False", ",", "is_distributed", "=", "False", ",", "padding_idx", "=", "None", ",", "param_attr", "=", "None", ",", "dtype", "=", "'float32'", ")", ":", "if", "param_attr", "is", ...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/incubate/fleet/parameter_server/pslib/__init__.py#L809-L867
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/altgraph/altgraph/Graph.py
python
Graph.number_of_edges
(self)
return len(self.edges)
Returns the number of edges
Returns the number of edges
[ "Returns", "the", "number", "of", "edges" ]
def number_of_edges(self): """ Returns the number of edges """ return len(self.edges)
[ "def", "number_of_edges", "(", "self", ")", ":", "return", "len", "(", "self", ".", "edges", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/altgraph/altgraph/Graph.py#L224-L228
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py
python
xmlTextReader.Setup
(self, input, URL, encoding, options)
return ret
Setup an XML reader with new options
Setup an XML reader with new options
[ "Setup", "an", "XML", "reader", "with", "new", "options" ]
def Setup(self, input, URL, encoding, options): """Setup an XML reader with new options """ if input is None: input__o = None else: input__o = input._o ret = libxml2mod.xmlTextReaderSetup(self._o, input__o, URL, encoding, options) return ret
[ "def", "Setup", "(", "self", ",", "input", ",", "URL", ",", "encoding", ",", "options", ")", ":", "if", "input", "is", "None", ":", "input__o", "=", "None", "else", ":", "input__o", "=", "input", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlTextRead...
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2class.py#L6137-L6142
freesurfer/freesurfer
6dbe527d43ffa611acb2cd112e9469f9bfec8e36
deeplearn_utils/unet_model.py
python
compute_level_output_shape
(filters, depth, pool_size, image_shape)
return tuple([None, filters] + [int(x) for x in output_image_shape])
Each level has a particular output shape based on the number of filters used in that level and the depth or number of max pooling operations that have been done on the data at that point. :param image_shape: shape of the 3d image. :param pool_size: the pool_size parameter used in the max pooling operation. :param filters: Number of filters used by the last node in a given level. :param depth: The number of levels down in the U-shaped model a given node is. :return: 5D vector of the shape of the output node
Each level has a particular output shape based on the number of filters used in that level and the depth or number of max pooling operations that have been done on the data at that point. :param image_shape: shape of the 3d image. :param pool_size: the pool_size parameter used in the max pooling operation. :param filters: Number of filters used by the last node in a given level. :param depth: The number of levels down in the U-shaped model a given node is. :return: 5D vector of the shape of the output node
[ "Each", "level", "has", "a", "particular", "output", "shape", "based", "on", "the", "number", "of", "filters", "used", "in", "that", "level", "and", "the", "depth", "or", "number", "of", "max", "pooling", "operations", "that", "have", "been", "done", "on",...
def compute_level_output_shape(filters, depth, pool_size, image_shape): """ Each level has a particular output shape based on the number of filters used in that level and the depth or number of max pooling operations that have been done on the data at that point. :param image_shape: shape of the 3d image. :param pool_size: the pool_size parameter used in the max pooling operation. :param filters: Number of filters used by the last node in a given level. :param depth: The number of levels down in the U-shaped model a given node is. :return: 5D vector of the shape of the output node """ if depth != 0: output_image_shape = np.divide(image_shape, np.multiply(pool_size, depth)).tolist() else: output_image_shape = image_shape return tuple([None, filters] + [int(x) for x in output_image_shape])
[ "def", "compute_level_output_shape", "(", "filters", ",", "depth", ",", "pool_size", ",", "image_shape", ")", ":", "if", "depth", "!=", "0", ":", "output_image_shape", "=", "np", ".", "divide", "(", "image_shape", ",", "np", ".", "multiply", "(", "pool_size"...
https://github.com/freesurfer/freesurfer/blob/6dbe527d43ffa611acb2cd112e9469f9bfec8e36/deeplearn_utils/unet_model.py#L132-L146
gem5/gem5
141cc37c2d4b93959d4c249b8f7e6a8b2ef75338
ext/ply/example/ansic/cparse.py
python
p_init_declarator_1
(t)
init_declarator : declarator
init_declarator : declarator
[ "init_declarator", ":", "declarator" ]
def p_init_declarator_1(t): 'init_declarator : declarator' pass
[ "def", "p_init_declarator_1", "(", "t", ")", ":", "pass" ]
https://github.com/gem5/gem5/blob/141cc37c2d4b93959d4c249b8f7e6a8b2ef75338/ext/ply/example/ansic/cparse.py#L173-L175
PX4/PX4-Autopilot
0b9f60a0370be53d683352c63fd92db3d6586e18
Tools/mavlink_px4.py
python
MAVLink.attitude_encode
(self, time_boot_ms, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed)
return msg
The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right). time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) roll : Roll angle (rad, -pi..+pi) (float) pitch : Pitch angle (rad, -pi..+pi) (float) yaw : Yaw angle (rad, -pi..+pi) (float) rollspeed : Roll angular speed (rad/s) (float) pitchspeed : Pitch angular speed (rad/s) (float) yawspeed : Yaw angular speed (rad/s) (float)
The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right).
[ "The", "attitude", "in", "the", "aeronautical", "frame", "(", "right", "-", "handed", "Z", "-", "down", "X", "-", "front", "Y", "-", "right", ")", "." ]
def attitude_encode(self, time_boot_ms, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed): ''' The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right). time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) roll : Roll angle (rad, -pi..+pi) (float) pitch : Pitch angle (rad, -pi..+pi) (float) yaw : Yaw angle (rad, -pi..+pi) (float) rollspeed : Roll angular speed (rad/s) (float) pitchspeed : Pitch angular speed (rad/s) (float) yawspeed : Yaw angular speed (rad/s) (float) ''' msg = MAVLink_attitude_message(time_boot_ms, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed) msg.pack(self) return msg
[ "def", "attitude_encode", "(", "self", ",", "time_boot_ms", ",", "roll", ",", "pitch", ",", "yaw", ",", "rollspeed", ",", "pitchspeed", ",", "yawspeed", ")", ":", "msg", "=", "MAVLink_attitude_message", "(", "time_boot_ms", ",", "roll", ",", "pitch", ",", ...
https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/mavlink_px4.py#L3043-L3059
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/MultilevelMonteCarloApplication/external_libraries/XMC/xmc/classDefs_solverWrapper/KratosSolverWrapper.py
python
KratosSolverWrapper.executeInstanceStochasticAdaptiveRefinement
(self,random_variable)
return qoi,time_for_qoi
Method executing an instance of the UQ algorithm, i.e. a single MC realization and eventually the refinement (that occurs before the simulation run). To be called if the selected refinement strategy is stochastic_adaptive_refinement. Inputs: random_variable: list. Random event in the form of list. Outputs: qoi: list. It contains the quantities of interest. time_for_qoi: float. Measure of time to generate the sample.
Method executing an instance of the UQ algorithm, i.e. a single MC realization and eventually the refinement (that occurs before the simulation run). To be called if the selected refinement strategy is stochastic_adaptive_refinement.
[ "Method", "executing", "an", "instance", "of", "the", "UQ", "algorithm", "i", ".", "e", ".", "a", "single", "MC", "realization", "and", "eventually", "the", "refinement", "(", "that", "occurs", "before", "the", "simulation", "run", ")", ".", "To", "be", ...
def executeInstanceStochasticAdaptiveRefinement(self,random_variable): """ Method executing an instance of the UQ algorithm, i.e. a single MC realization and eventually the refinement (that occurs before the simulation run). To be called if the selected refinement strategy is stochastic_adaptive_refinement. Inputs: random_variable: list. Random event in the form of list. Outputs: qoi: list. It contains the quantities of interest. time_for_qoi: float. Measure of time to generate the sample. """ # local variables current_index = self.solverWrapperIndex[0] pickled_coarse_model = self.pickled_model[0] pickled_reference_model_mapping = pickled_coarse_model pickled_coarse_project_parameters = self.pickled_project_parameters[0] pickled_custom_metric_refinement_parameters = self.pickled_custom_metric_refinement_parameters pickled_custom_remesh_refinement_parameters = self.pickled_custom_remesh_refinement_parameters current_analysis = self.analysis different_tasks = self.different_tasks mapping_flag = self.mapping_output_quantities adaptive_refinement_jump_to_finest_level = self.adaptive_refinement_jump_to_finest_level print_to_file = self.print_to_file current_local_contribution = self.current_local_contribution time_for_qoi = 0.0 if (different_tasks is False): # single task if self.is_mpi: qoi,time_for_qoi = \ mpi_mds.executeInstanceStochasticAdaptiveRefinementAllAtOnce_Wrapper(current_index,pickled_coarse_model,pickled_coarse_project_parameters,pickled_custom_metric_refinement_parameters,pickled_custom_remesh_refinement_parameters,random_variable,current_analysis,time_for_qoi,mapping_flag,adaptive_refinement_jump_to_finest_level,print_to_file,current_local_contribution) else: qoi,time_for_qoi = \ mds.executeInstanceStochasticAdaptiveRefinementAllAtOnce_Wrapper(current_index,pickled_coarse_model,pickled_coarse_project_parameters,pickled_custom_metric_refinement_parameters,pickled_custom_remesh_refinement_parameters,random_variable,current_analysis,time_for_qoi,mapping_flag,adaptive_refinement_jump_to_finest_level,print_to_file,current_local_contribution) elif (different_tasks is True): # multiple tasks if (current_index == 0): # index = 0 current_local_index = 0 if self.is_mpi: qoi,pickled_current_model,time_for_qoi = \ mpi_mds.executeInstanceStochasticAdaptiveRefinementMultipleTasks_Wrapper(current_index,pickled_coarse_model,pickled_coarse_project_parameters,pickled_custom_metric_refinement_parameters,pickled_custom_remesh_refinement_parameters,random_variable,current_local_index,current_analysis,time_for_qoi,mapping_flag,print_to_file,current_local_contribution) else: qoi,pickled_current_model,time_for_qoi = \ mds.executeInstanceStochasticAdaptiveRefinementMultipleTasks_Wrapper(current_index,pickled_coarse_model,pickled_coarse_project_parameters,pickled_custom_metric_refinement_parameters,pickled_custom_remesh_refinement_parameters,random_variable,current_local_index,current_analysis,time_for_qoi,mapping_flag,print_to_file,current_local_contribution) delete_object(pickled_current_model) else: # index > 0 for current_local_index in range(current_index+1): if ((adaptive_refinement_jump_to_finest_level is False) or (adaptive_refinement_jump_to_finest_level is True and (current_local_index == 0 or current_local_index == current_index))): if (mapping_flag is False): qoi,pickled_current_model,time_for_qoi = \ mds.executeInstanceStochasticAdaptiveRefinementMultipleTasks_Wrapper(current_index,pickled_coarse_model,pickled_coarse_project_parameters,pickled_custom_metric_refinement_parameters,pickled_custom_remesh_refinement_parameters,random_variable,current_local_index,current_analysis,time_for_qoi,mapping_flag,print_to_file,current_local_contribution) elif (mapping_flag is True): qoi,pickled_current_model,time_for_qoi = \ mds.executeInstanceStochasticAdaptiveRefinementMultipleTasks_Wrapper(current_index,pickled_coarse_model,pickled_coarse_project_parameters,pickled_custom_metric_refinement_parameters,pickled_custom_remesh_refinement_parameters,random_variable,current_local_index,current_analysis,time_for_qoi,mapping_flag,print_to_file,current_local_contribution,pickled_mapping_reference_model=pickled_reference_model_mapping) delete_object(pickled_coarse_model) del(pickled_coarse_model) pickled_coarse_model = pickled_current_model del(pickled_current_model) else: # not running since we jump from coarsest to finest level pass delete_object(pickled_coarse_model) else: raise Exception ("Boolean variable different task is not a boolean, instead is equal to",different_tasks) return qoi,time_for_qoi
[ "def", "executeInstanceStochasticAdaptiveRefinement", "(", "self", ",", "random_variable", ")", ":", "# local variables", "current_index", "=", "self", ".", "solverWrapperIndex", "[", "0", "]", "pickled_coarse_model", "=", "self", ".", "pickled_model", "[", "0", "]", ...
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/MultilevelMonteCarloApplication/external_libraries/XMC/xmc/classDefs_solverWrapper/KratosSolverWrapper.py#L246-L312
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/python/turicreate/data_structures/sarray.py
python
SArray.where
(cls, condition, istrue, isfalse, dtype=None)
return cls( _proxy=condition.__proxy__.ternary_operator( istrue.__proxy__, isfalse.__proxy__ ) )
Selects elements from either istrue or isfalse depending on the value of the condition SArray. Parameters ---------- condition : SArray An SArray of values such that for each value, if non-zero, yields a value from istrue, otherwise from isfalse. istrue : SArray or constant The elements selected if condition is true. If istrue is an SArray, this must be of the same length as condition. isfalse : SArray or constant The elements selected if condition is false. If istrue is an SArray, this must be of the same length as condition. dtype : type The type of result SArray. This is required if both istrue and isfalse are constants of ambiguous types. Examples -------- Returns an SArray with the same values as g with values above 10 clipped to 10 >>> g = SArray([6,7,8,9,10,11,12,13]) >>> SArray.where(g > 10, 10, g) dtype: int Rows: 8 [6, 7, 8, 9, 10, 10, 10, 10] Returns an SArray with the same values as g with values below 10 clipped to 10 >>> SArray.where(g > 10, g, 10) dtype: int Rows: 8 [10, 10, 10, 10, 10, 11, 12, 13] Returns an SArray with the same values of g with all values == 1 replaced by None >>> g = SArray([1,2,3,4,1,2,3,4]) >>> SArray.where(g == 1, None, g) dtype: int Rows: 8 [None, 2, 3, 4, None, 2, 3, 4] Returns an SArray with the same values of g, but with each missing value replaced by its corresponding element in replace_none >>> g = SArray([1,2,None,None]) >>> replace_none = SArray([3,3,2,2]) >>> SArray.where(g != None, g, replace_none) dtype: int Rows: 4 [1, 2, 2, 2]
Selects elements from either istrue or isfalse depending on the value of the condition SArray.
[ "Selects", "elements", "from", "either", "istrue", "or", "isfalse", "depending", "on", "the", "value", "of", "the", "condition", "SArray", "." ]
def where(cls, condition, istrue, isfalse, dtype=None): """ Selects elements from either istrue or isfalse depending on the value of the condition SArray. Parameters ---------- condition : SArray An SArray of values such that for each value, if non-zero, yields a value from istrue, otherwise from isfalse. istrue : SArray or constant The elements selected if condition is true. If istrue is an SArray, this must be of the same length as condition. isfalse : SArray or constant The elements selected if condition is false. If istrue is an SArray, this must be of the same length as condition. dtype : type The type of result SArray. This is required if both istrue and isfalse are constants of ambiguous types. Examples -------- Returns an SArray with the same values as g with values above 10 clipped to 10 >>> g = SArray([6,7,8,9,10,11,12,13]) >>> SArray.where(g > 10, 10, g) dtype: int Rows: 8 [6, 7, 8, 9, 10, 10, 10, 10] Returns an SArray with the same values as g with values below 10 clipped to 10 >>> SArray.where(g > 10, g, 10) dtype: int Rows: 8 [10, 10, 10, 10, 10, 11, 12, 13] Returns an SArray with the same values of g with all values == 1 replaced by None >>> g = SArray([1,2,3,4,1,2,3,4]) >>> SArray.where(g == 1, None, g) dtype: int Rows: 8 [None, 2, 3, 4, None, 2, 3, 4] Returns an SArray with the same values of g, but with each missing value replaced by its corresponding element in replace_none >>> g = SArray([1,2,None,None]) >>> replace_none = SArray([3,3,2,2]) >>> SArray.where(g != None, g, replace_none) dtype: int Rows: 4 [1, 2, 2, 2] """ true_is_sarray = isinstance(istrue, SArray) false_is_sarray = isinstance(isfalse, SArray) if not true_is_sarray and false_is_sarray: istrue = cls(_proxy=condition.__proxy__.to_const(istrue, isfalse.dtype)) if true_is_sarray and not false_is_sarray: isfalse = cls(_proxy=condition.__proxy__.to_const(isfalse, istrue.dtype)) if not true_is_sarray and not false_is_sarray: if dtype is None: if istrue is None: dtype = type(isfalse) elif isfalse is None: dtype = type(istrue) elif type(istrue) != type(isfalse): raise TypeError("true and false inputs are of different types") elif type(istrue) == type(isfalse): dtype = type(istrue) if dtype is None: raise TypeError( "Both true and false are None. Resultant type cannot be inferred." ) istrue = cls(_proxy=condition.__proxy__.to_const(istrue, dtype)) isfalse = cls(_proxy=condition.__proxy__.to_const(isfalse, dtype)) return cls( _proxy=condition.__proxy__.ternary_operator( istrue.__proxy__, isfalse.__proxy__ ) )
[ "def", "where", "(", "cls", ",", "condition", ",", "istrue", ",", "isfalse", ",", "dtype", "=", "None", ")", ":", "true_is_sarray", "=", "isinstance", "(", "istrue", ",", "SArray", ")", "false_is_sarray", "=", "isinstance", "(", "isfalse", ",", "SArray", ...
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/python/turicreate/data_structures/sarray.py#L682-L770
google/or-tools
2cb85b4eead4c38e1c54b48044f92087cf165bce
ortools/constraint_solver/doc/routing_svg.py
python
DataModel.depot
(self)
return self._depot
Gets the depot node index.
Gets the depot node index.
[ "Gets", "the", "depot", "node", "index", "." ]
def depot(self): """Gets the depot node index.""" return self._depot
[ "def", "depot", "(", "self", ")", ":", "return", "self", ".", "_depot" ]
https://github.com/google/or-tools/blob/2cb85b4eead4c38e1c54b48044f92087cf165bce/ortools/constraint_solver/doc/routing_svg.py#L234-L236
Yelp/MOE
5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c
moe/easy_interface/experiment.py
python
Experiment.build_json_payload
(self)
return { 'domain_info': self.domain.get_json_serializable_info(), 'gp_historical_info': self.historical_data.json_payload(), }
Construct a json serializeable and MOE REST recognizeable dictionary of the experiment.
Construct a json serializeable and MOE REST recognizeable dictionary of the experiment.
[ "Construct", "a", "json", "serializeable", "and", "MOE", "REST", "recognizeable", "dictionary", "of", "the", "experiment", "." ]
def build_json_payload(self): """Construct a json serializeable and MOE REST recognizeable dictionary of the experiment.""" return { 'domain_info': self.domain.get_json_serializable_info(), 'gp_historical_info': self.historical_data.json_payload(), }
[ "def", "build_json_payload", "(", "self", ")", ":", "return", "{", "'domain_info'", ":", "self", ".", "domain", ".", "get_json_serializable_info", "(", ")", ",", "'gp_historical_info'", ":", "self", ".", "historical_data", ".", "json_payload", "(", ")", ",", "...
https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/easy_interface/experiment.py#L35-L40
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/rnn/python/ops/lstm_ops.py
python
LSTMBlockCell.__init__
(self, num_units, forget_bias=1.0, cell_clip=None, use_peephole=False, reuse=None)
Initialize the basic LSTM cell. Args: num_units: int, The number of units in the LSTM cell. forget_bias: float, The bias added to forget gates (see above). cell_clip: An optional `float`. Defaults to `-1` (no clipping). use_peephole: Whether to use peephole connections or not. reuse: (optional) boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised. When restoring from CudnnLSTM-trained checkpoints, must use CudnnCompatibleLSTMBlockCell instead.
Initialize the basic LSTM cell.
[ "Initialize", "the", "basic", "LSTM", "cell", "." ]
def __init__(self, num_units, forget_bias=1.0, cell_clip=None, use_peephole=False, reuse=None): """Initialize the basic LSTM cell. Args: num_units: int, The number of units in the LSTM cell. forget_bias: float, The bias added to forget gates (see above). cell_clip: An optional `float`. Defaults to `-1` (no clipping). use_peephole: Whether to use peephole connections or not. reuse: (optional) boolean describing whether to reuse variables in an existing scope. If not `True`, and the existing scope already has the given variables, an error is raised. When restoring from CudnnLSTM-trained checkpoints, must use CudnnCompatibleLSTMBlockCell instead. """ super(LSTMBlockCell, self).__init__(_reuse=reuse) self._num_units = num_units self._forget_bias = forget_bias self._use_peephole = use_peephole self._cell_clip = cell_clip if cell_clip is not None else -1 self._names = { "W": "kernel", "b": "bias", "wci": "w_i_diag", "wcf": "w_f_diag", "wco": "w_o_diag", "scope": "lstm_cell" }
[ "def", "__init__", "(", "self", ",", "num_units", ",", "forget_bias", "=", "1.0", ",", "cell_clip", "=", "None", ",", "use_peephole", "=", "False", ",", "reuse", "=", "None", ")", ":", "super", "(", "LSTMBlockCell", ",", "self", ")", ".", "__init__", "...
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/rnn/python/ops/lstm_ops.py#L343-L375
netket/netket
0d534e54ecbf25b677ea72af6b85947979420652
netket/hilbert/continuous_hilbert.py
python
ContinuousHilbert.__init__
(self, domain: Tuple[float, ...], pbc: Union[bool, Tuple[bool, ...]])
Constructs new ``Particles`` given specifications of the continuous space they are defined in. Args: domain: range of the continuous quantum numbers
Constructs new ``Particles`` given specifications of the continuous space they are defined in.
[ "Constructs", "new", "Particles", "given", "specifications", "of", "the", "continuous", "space", "they", "are", "defined", "in", "." ]
def __init__(self, domain: Tuple[float, ...], pbc: Union[bool, Tuple[bool, ...]]): """ Constructs new ``Particles`` given specifications of the continuous space they are defined in. Args: domain: range of the continuous quantum numbers """ self._extent = domain self._pbc = pbc if not len(self._extent) == len(self._pbc): raise ValueError( """`pbc` must be either a bool or a tuple indicating the periodicity of each spatial dimension.""" ) super().__init__()
[ "def", "__init__", "(", "self", ",", "domain", ":", "Tuple", "[", "float", ",", "...", "]", ",", "pbc", ":", "Union", "[", "bool", ",", "Tuple", "[", "bool", ",", "...", "]", "]", ")", ":", "self", ".", "_extent", "=", "domain", "self", ".", "_...
https://github.com/netket/netket/blob/0d534e54ecbf25b677ea72af6b85947979420652/netket/hilbert/continuous_hilbert.py#L27-L41
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/tarfile.py
python
TarFile.extractfile
(self, member)
Extract a member from the archive as a file object. `member' may be a filename or a TarInfo object. If `member' is a regular file, a file-like object is returned. If `member' is a link, a file-like object is constructed from the link's target. If `member' is none of the above, None is returned. The file-like object is read-only and provides the following methods: read(), readline(), readlines(), seek() and tell()
Extract a member from the archive as a file object. `member' may be a filename or a TarInfo object. If `member' is a regular file, a file-like object is returned. If `member' is a link, a file-like object is constructed from the link's target. If `member' is none of the above, None is returned. The file-like object is read-only and provides the following methods: read(), readline(), readlines(), seek() and tell()
[ "Extract", "a", "member", "from", "the", "archive", "as", "a", "file", "object", ".", "member", "may", "be", "a", "filename", "or", "a", "TarInfo", "object", ".", "If", "member", "is", "a", "regular", "file", "a", "file", "-", "like", "object", "is", ...
def extractfile(self, member): """Extract a member from the archive as a file object. `member' may be a filename or a TarInfo object. If `member' is a regular file, a file-like object is returned. If `member' is a link, a file-like object is constructed from the link's target. If `member' is none of the above, None is returned. The file-like object is read-only and provides the following methods: read(), readline(), readlines(), seek() and tell() """ self._check("r") if isinstance(member, str): tarinfo = self.getmember(member) else: tarinfo = member if tarinfo.isreg(): return self.fileobject(self, tarinfo) elif tarinfo.type not in SUPPORTED_TYPES: # If a member's type is unknown, it is treated as a # regular file. return self.fileobject(self, tarinfo) elif tarinfo.islnk() or tarinfo.issym(): if isinstance(self.fileobj, _Stream): # A small but ugly workaround for the case that someone tries # to extract a (sym)link as a file-object from a non-seekable # stream of tar blocks. raise StreamError("cannot extract (sym)link as file object") else: # A (sym)link's file object is its target's file object. return self.extractfile(self._find_link_target(tarinfo)) else: # If there's no data associated with the member (directory, chrdev, # blkdev, etc.), return None instead of a file object. return None
[ "def", "extractfile", "(", "self", ",", "member", ")", ":", "self", ".", "_check", "(", "\"r\"", ")", "if", "isinstance", "(", "member", ",", "str", ")", ":", "tarinfo", "=", "self", ".", "getmember", "(", "member", ")", "else", ":", "tarinfo", "=", ...
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/distlib/_backport/tarfile.py#L2199-L2235
esa/pagmo
80281d549c8f1b470e1489a5d37c8f06b2e429c0
PyGMO/problem/_pl2pl.py
python
py_pl2pl.pretty
(self, x)
Decodes the decision vector x
Decodes the decision vector x
[ "Decodes", "the", "decision", "vector", "x" ]
def pretty(self, x): """Decodes the decision vector x""" import PyKEP start = PyKEP.epoch(x[0]) end = PyKEP.epoch(x[0] + x[1]) r, v = self.__departure.eph(start) v_list = list(v) v_list[0] += x[3] v_list[1] += x[4] v_list[2] += x[5] x0 = PyKEP.sims_flanagan.sc_state(r, v_list, self.__sc.mass) r, v = self.__target.eph(end) xe = PyKEP.sims_flanagan.sc_state(r, v, x[2]) self.__leg.set(start, x0, x[-3 * self.__nseg:], end, xe) print("A direct interplantary transfer\n") print("FROM:") print(self.__departure) print("TO:") print(self.__target) print(self.__leg)
[ "def", "pretty", "(", "self", ",", "x", ")", ":", "import", "PyKEP", "start", "=", "PyKEP", ".", "epoch", "(", "x", "[", "0", "]", ")", "end", "=", "PyKEP", ".", "epoch", "(", "x", "[", "0", "]", "+", "x", "[", "1", "]", ")", "r", ",", "v...
https://github.com/esa/pagmo/blob/80281d549c8f1b470e1489a5d37c8f06b2e429c0/PyGMO/problem/_pl2pl.py#L134-L153
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/stc.py
python
StyledTextEvent.SetLength
(*args, **kwargs)
return _stc.StyledTextEvent_SetLength(*args, **kwargs)
SetLength(self, int len)
SetLength(self, int len)
[ "SetLength", "(", "self", "int", "len", ")" ]
def SetLength(*args, **kwargs): """SetLength(self, int len)""" return _stc.StyledTextEvent_SetLength(*args, **kwargs)
[ "def", "SetLength", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_stc", ".", "StyledTextEvent_SetLength", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/stc.py#L7046-L7048
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_base_original.py
python
DraftTool.commit
(self, name, func)
Store actions in the commit list to be run later. Parameters ---------- name: str An arbitrary string that indicates the name of the operation to run. func: list of str Each element of the list is a string that will be run by `Gui.doCommand`. See the complete information in the `draftutils.todo.ToDo` class.
Store actions in the commit list to be run later.
[ "Store", "actions", "in", "the", "commit", "list", "to", "be", "run", "later", "." ]
def commit(self, name, func): """Store actions in the commit list to be run later. Parameters ---------- name: str An arbitrary string that indicates the name of the operation to run. func: list of str Each element of the list is a string that will be run by `Gui.doCommand`. See the complete information in the `draftutils.todo.ToDo` class. """ self.commitList.append((name, func))
[ "def", "commit", "(", "self", ",", "name", ",", "func", ")", ":", "self", ".", "commitList", ".", "append", "(", "(", "name", ",", "func", ")", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_base_original.py#L197-L212
daijifeng001/caffe-rfcn
543f8f6a4b7c88256ea1445ae951a12d1ad9cffd
python/caffe/pycaffe.py
python
_Net_forward_backward_all
(self, blobs=None, diffs=None, **kwargs)
return all_outs, all_diffs
Run net forward + backward in batches. Parameters ---------- blobs: list of blobs to extract as in forward() diffs: list of diffs to extract as in backward() kwargs: Keys are input (for forward) and output (for backward) blob names and values are ndarrays. Refer to forward() and backward(). Prefilled variants are called for lack of input or output blobs. Returns ------- all_blobs: {blob name: blob ndarray} dict. all_diffs: {blob name: diff ndarray} dict.
Run net forward + backward in batches.
[ "Run", "net", "forward", "+", "backward", "in", "batches", "." ]
def _Net_forward_backward_all(self, blobs=None, diffs=None, **kwargs): """ Run net forward + backward in batches. Parameters ---------- blobs: list of blobs to extract as in forward() diffs: list of diffs to extract as in backward() kwargs: Keys are input (for forward) and output (for backward) blob names and values are ndarrays. Refer to forward() and backward(). Prefilled variants are called for lack of input or output blobs. Returns ------- all_blobs: {blob name: blob ndarray} dict. all_diffs: {blob name: diff ndarray} dict. """ # Batch blobs and diffs. all_outs = {out: [] for out in set(self.outputs + (blobs or []))} all_diffs = {diff: [] for diff in set(self.inputs + (diffs or []))} forward_batches = self._batch({in_: kwargs[in_] for in_ in self.inputs if in_ in kwargs}) backward_batches = self._batch({out: kwargs[out] for out in self.outputs if out in kwargs}) # Collect outputs from batches (and heed lack of forward/backward batches). for fb, bb in izip_longest(forward_batches, backward_batches, fillvalue={}): batch_blobs = self.forward(blobs=blobs, **fb) batch_diffs = self.backward(diffs=diffs, **bb) for out, out_blobs in six.iteritems(batch_blobs): all_outs[out].extend(out_blobs.copy()) for diff, out_diffs in six.iteritems(batch_diffs): all_diffs[diff].extend(out_diffs.copy()) # Package in ndarray. for out, diff in zip(all_outs, all_diffs): all_outs[out] = np.asarray(all_outs[out]) all_diffs[diff] = np.asarray(all_diffs[diff]) # Discard padding at the end and package in ndarray. pad = len(six.next(six.itervalues(all_outs))) - len(six.next(six.itervalues(kwargs))) if pad: for out, diff in zip(all_outs, all_diffs): all_outs[out] = all_outs[out][:-pad] all_diffs[diff] = all_diffs[diff][:-pad] return all_outs, all_diffs
[ "def", "_Net_forward_backward_all", "(", "self", ",", "blobs", "=", "None", ",", "diffs", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Batch blobs and diffs.", "all_outs", "=", "{", "out", ":", "[", "]", "for", "out", "in", "set", "(", "self", "....
https://github.com/daijifeng001/caffe-rfcn/blob/543f8f6a4b7c88256ea1445ae951a12d1ad9cffd/python/caffe/pycaffe.py#L206-L248
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/findertools.py
python
Print
(file)
return finder._print(fss)
Print a file thru the finder. Specify file by name or fsspec
Print a file thru the finder. Specify file by name or fsspec
[ "Print", "a", "file", "thru", "the", "finder", ".", "Specify", "file", "by", "name", "or", "fsspec" ]
def Print(file): """Print a file thru the finder. Specify file by name or fsspec""" finder = _getfinder() fss = Carbon.File.FSSpec(file) return finder._print(fss)
[ "def", "Print", "(", "file", ")", ":", "finder", "=", "_getfinder", "(", ")", "fss", "=", "Carbon", ".", "File", ".", "FSSpec", "(", "file", ")", "return", "finder", ".", "_print", "(", "fss", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/plat-mac/findertools.py#L51-L55
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/src/extern/aui/auibar.py
python
AuiToolBar.AddSimpleTool
(self, tool_id, label, bitmap, short_help_string="", kind=ITEM_NORMAL, target=None)
return self.AddTool(tool_id, label, bitmap, wx.NullBitmap, kind, short_help_string, "", None, target)
Adds a tool to the toolbar. This is the simplest method you can use to ass an item to the :class:`AuiToolBar`. :param integer `tool_id`: an integer by which the tool may be identified in subsequent operations; :param string `label`: the toolbar tool label; :param Bitmap `bitmap`: the primary tool bitmap; :param string `short_help_string`: this string is used for the tools tooltip; :param integer `kind`: the item kind. Can be one of the following: ======================== ============================= Item Kind Description ======================== ============================= ``ITEM_CONTROL`` The item in the :class:`AuiToolBar` is a control ``ITEM_LABEL`` The item in the :class:`AuiToolBar` is a text label ``ITEM_SPACER`` The item in the :class:`AuiToolBar` is a spacer ``ITEM_SEPARATOR`` The item in the :class:`AuiToolBar` is a separator ``ITEM_CHECK`` The item in the :class:`AuiToolBar` is a toolbar check item ``ITEM_NORMAL`` The item in the :class:`AuiToolBar` is a standard toolbar item ``ITEM_RADIO`` The item in the :class:`AuiToolBar` is a toolbar radio item ======================== ============================= :param `target`: a custom string indicating that an instance of :class:`~lib.agw.aui.framemanager.AuiPaneInfo` has been minimized into this toolbar.
Adds a tool to the toolbar. This is the simplest method you can use to ass an item to the :class:`AuiToolBar`.
[ "Adds", "a", "tool", "to", "the", "toolbar", ".", "This", "is", "the", "simplest", "method", "you", "can", "use", "to", "ass", "an", "item", "to", "the", ":", "class", ":", "AuiToolBar", "." ]
def AddSimpleTool(self, tool_id, label, bitmap, short_help_string="", kind=ITEM_NORMAL, target=None): """ Adds a tool to the toolbar. This is the simplest method you can use to ass an item to the :class:`AuiToolBar`. :param integer `tool_id`: an integer by which the tool may be identified in subsequent operations; :param string `label`: the toolbar tool label; :param Bitmap `bitmap`: the primary tool bitmap; :param string `short_help_string`: this string is used for the tools tooltip; :param integer `kind`: the item kind. Can be one of the following: ======================== ============================= Item Kind Description ======================== ============================= ``ITEM_CONTROL`` The item in the :class:`AuiToolBar` is a control ``ITEM_LABEL`` The item in the :class:`AuiToolBar` is a text label ``ITEM_SPACER`` The item in the :class:`AuiToolBar` is a spacer ``ITEM_SEPARATOR`` The item in the :class:`AuiToolBar` is a separator ``ITEM_CHECK`` The item in the :class:`AuiToolBar` is a toolbar check item ``ITEM_NORMAL`` The item in the :class:`AuiToolBar` is a standard toolbar item ``ITEM_RADIO`` The item in the :class:`AuiToolBar` is a toolbar radio item ======================== ============================= :param `target`: a custom string indicating that an instance of :class:`~lib.agw.aui.framemanager.AuiPaneInfo` has been minimized into this toolbar. """ return self.AddTool(tool_id, label, bitmap, wx.NullBitmap, kind, short_help_string, "", None, target)
[ "def", "AddSimpleTool", "(", "self", ",", "tool_id", ",", "label", ",", "bitmap", ",", "short_help_string", "=", "\"\"", ",", "kind", "=", "ITEM_NORMAL", ",", "target", "=", "None", ")", ":", "return", "self", ".", "AddTool", "(", "tool_id", ",", "label"...
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/src/extern/aui/auibar.py#L1719-L1746
seqan/seqan
f5f658343c366c9c3d44ba358ffc9317e78a09ed
apps/ngs_roi/tool_shed/ctd2galaxy.py
python
main
()
return 0
Main function.
Main function.
[ "Main", "function", "." ]
def main(): """Main function.""" # Setup argument parser. parser = argparse.ArgumentParser(description='Convert CTD to Galaxy XML') parser.add_argument('-i', '--in-file', metavar='FILE', help='CTD file to read.', dest='in_file', required=True) parser.add_argument('-o', '--out-file', metavar='FILE', help='File to write. Output type depends on extension.', dest='out_file', required=True) args = parser.parse_args() # Parse input. sys.stderr.write('Parsing %s...\n' % args.in_file) ctd_parser = CTDParser() tool = ctd_parser.parse(args.in_file) # Write output. sys.stderr.write('Writing to %s...\n' % args.out_file) if args.out_file.endswith('.ctd'): writer = CTDWriter() else: writer = GalaxyWriter() with open(args.out_file, 'wb') as f: writer.run(tool, f) return 0
[ "def", "main", "(", ")", ":", "# Setup argument parser.", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Convert CTD to Galaxy XML'", ")", "parser", ".", "add_argument", "(", "'-i'", ",", "'--in-file'", ",", "metavar", "=", "'FILE'", ...
https://github.com/seqan/seqan/blob/f5f658343c366c9c3d44ba358ffc9317e78a09ed/apps/ngs_roi/tool_shed/ctd2galaxy.py#L575-L602
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/nccl/python/ops/nccl_ops.py
python
all_prod
(tensors)
return _apply_all_reduce('prod', tensors)
Returns a list of tensors with the all-reduce product across `tensors`. The computation is done with an all-reduce operation, so if only some of the returned tensors are evaluated then the computation will hang. Args: tensors: The input tensors across which to multiply; must be assigned to GPU devices. Returns: List of tensors, each with the product of the input tensors, where tensor i has the same device as `tensors[i]`.
Returns a list of tensors with the all-reduce product across `tensors`.
[ "Returns", "a", "list", "of", "tensors", "with", "the", "all", "-", "reduce", "product", "across", "tensors", "." ]
def all_prod(tensors): """Returns a list of tensors with the all-reduce product across `tensors`. The computation is done with an all-reduce operation, so if only some of the returned tensors are evaluated then the computation will hang. Args: tensors: The input tensors across which to multiply; must be assigned to GPU devices. Returns: List of tensors, each with the product of the input tensors, where tensor i has the same device as `tensors[i]`. """ return _apply_all_reduce('prod', tensors)
[ "def", "all_prod", "(", "tensors", ")", ":", "return", "_apply_all_reduce", "(", "'prod'", ",", "tensors", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/nccl/python/ops/nccl_ops.py#L79-L93
redpony/cdec
f7c4899b174d86bc70b40b1cae68dcad364615cb
python/cdec/configobj.py
python
Section.walk
(self, function, raise_errors=True, call_on_sections=False, **keywargs)
return out
Walk every member and call a function on the keyword and value. Return a dictionary of the return values If the function raises an exception, raise the errror unless ``raise_errors=False``, in which case set the return value to ``False``. Any unrecognised keyword arguments you pass to walk, will be pased on to the function you pass in. Note: if ``call_on_sections`` is ``True`` then - on encountering a subsection, *first* the function is called for the *whole* subsection, and then recurses into it's members. This means your function must be able to handle strings, dictionaries and lists. This allows you to change the key of subsections as well as for ordinary members. The return value when called on the whole subsection has to be discarded. See the encode and decode methods for examples, including functions. .. admonition:: caution You can use ``walk`` to transform the names of members of a section but you mustn't add or delete members. >>> config = '''[XXXXsection] ... XXXXkey = XXXXvalue'''.splitlines() >>> cfg = ConfigObj(config) >>> cfg ConfigObj({'XXXXsection': {'XXXXkey': 'XXXXvalue'}}) >>> def transform(section, key): ... val = section[key] ... newkey = key.replace('XXXX', 'CLIENT1') ... section.rename(key, newkey) ... if isinstance(val, (tuple, list, dict)): ... pass ... else: ... val = val.replace('XXXX', 'CLIENT1') ... section[newkey] = val >>> cfg.walk(transform, call_on_sections=True) {'CLIENT1section': {'CLIENT1key': None}} >>> cfg ConfigObj({'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}})
Walk every member and call a function on the keyword and value. Return a dictionary of the return values If the function raises an exception, raise the errror unless ``raise_errors=False``, in which case set the return value to ``False``. Any unrecognised keyword arguments you pass to walk, will be pased on to the function you pass in. Note: if ``call_on_sections`` is ``True`` then - on encountering a subsection, *first* the function is called for the *whole* subsection, and then recurses into it's members. This means your function must be able to handle strings, dictionaries and lists. This allows you to change the key of subsections as well as for ordinary members. The return value when called on the whole subsection has to be discarded. See the encode and decode methods for examples, including functions. .. admonition:: caution You can use ``walk`` to transform the names of members of a section but you mustn't add or delete members. >>> config = '''[XXXXsection] ... XXXXkey = XXXXvalue'''.splitlines() >>> cfg = ConfigObj(config) >>> cfg ConfigObj({'XXXXsection': {'XXXXkey': 'XXXXvalue'}}) >>> def transform(section, key): ... val = section[key] ... newkey = key.replace('XXXX', 'CLIENT1') ... section.rename(key, newkey) ... if isinstance(val, (tuple, list, dict)): ... pass ... else: ... val = val.replace('XXXX', 'CLIENT1') ... section[newkey] = val >>> cfg.walk(transform, call_on_sections=True) {'CLIENT1section': {'CLIENT1key': None}} >>> cfg ConfigObj({'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}})
[ "Walk", "every", "member", "and", "call", "a", "function", "on", "the", "keyword", "and", "value", ".", "Return", "a", "dictionary", "of", "the", "return", "values", "If", "the", "function", "raises", "an", "exception", "raise", "the", "errror", "unless", ...
def walk(self, function, raise_errors=True, call_on_sections=False, **keywargs): """ Walk every member and call a function on the keyword and value. Return a dictionary of the return values If the function raises an exception, raise the errror unless ``raise_errors=False``, in which case set the return value to ``False``. Any unrecognised keyword arguments you pass to walk, will be pased on to the function you pass in. Note: if ``call_on_sections`` is ``True`` then - on encountering a subsection, *first* the function is called for the *whole* subsection, and then recurses into it's members. This means your function must be able to handle strings, dictionaries and lists. This allows you to change the key of subsections as well as for ordinary members. The return value when called on the whole subsection has to be discarded. See the encode and decode methods for examples, including functions. .. admonition:: caution You can use ``walk`` to transform the names of members of a section but you mustn't add or delete members. >>> config = '''[XXXXsection] ... XXXXkey = XXXXvalue'''.splitlines() >>> cfg = ConfigObj(config) >>> cfg ConfigObj({'XXXXsection': {'XXXXkey': 'XXXXvalue'}}) >>> def transform(section, key): ... val = section[key] ... newkey = key.replace('XXXX', 'CLIENT1') ... section.rename(key, newkey) ... if isinstance(val, (tuple, list, dict)): ... pass ... else: ... val = val.replace('XXXX', 'CLIENT1') ... section[newkey] = val >>> cfg.walk(transform, call_on_sections=True) {'CLIENT1section': {'CLIENT1key': None}} >>> cfg ConfigObj({'CLIENT1section': {'CLIENT1key': 'CLIENT1value'}}) """ out = {} # scalars first for i in range(len(self.scalars)): entry = self.scalars[i] try: val = function(self, entry, **keywargs) # bound again in case name has changed entry = self.scalars[i] out[entry] = val except Exception: if raise_errors: raise else: entry = self.scalars[i] out[entry] = False # then sections for i in range(len(self.sections)): entry = self.sections[i] if call_on_sections: try: function(self, entry, **keywargs) except Exception: if raise_errors: raise else: entry = self.sections[i] out[entry] = False # bound again in case name has changed entry = self.sections[i] # previous result is discarded out[entry] = self[entry].walk( function, raise_errors=raise_errors, call_on_sections=call_on_sections, **keywargs) return out
[ "def", "walk", "(", "self", ",", "function", ",", "raise_errors", "=", "True", ",", "call_on_sections", "=", "False", ",", "*", "*", "keywargs", ")", ":", "out", "=", "{", "}", "# scalars first", "for", "i", "in", "range", "(", "len", "(", "self", "....
https://github.com/redpony/cdec/blob/f7c4899b174d86bc70b40b1cae68dcad364615cb/python/cdec/configobj.py#L855-L937
H-uru/Plasma
c2140ea046e82e9c199e257a7f2e7edb42602871
Scripts/Python/plasma/Plasma.py
python
PtFileExists
(filename)
Returns true if the specified file exists
Returns true if the specified file exists
[ "Returns", "true", "if", "the", "specified", "file", "exists" ]
def PtFileExists(filename): """Returns true if the specified file exists""" pass
[ "def", "PtFileExists", "(", "filename", ")", ":", "pass" ]
https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/plasma/Plasma.py#L305-L307
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
contrib/gizmos/osx_carbon/gizmos.py
python
TreeListCtrl.SetColumnShown
(*args, **kwargs)
return _gizmos.TreeListCtrl_SetColumnShown(*args, **kwargs)
SetColumnShown(self, int column, bool shown=True)
SetColumnShown(self, int column, bool shown=True)
[ "SetColumnShown", "(", "self", "int", "column", "bool", "shown", "=", "True", ")" ]
def SetColumnShown(*args, **kwargs): """SetColumnShown(self, int column, bool shown=True)""" return _gizmos.TreeListCtrl_SetColumnShown(*args, **kwargs)
[ "def", "SetColumnShown", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gizmos", ".", "TreeListCtrl_SetColumnShown", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/contrib/gizmos/osx_carbon/gizmos.py#L634-L636
PX4/PX4-Autopilot
0b9f60a0370be53d683352c63fd92db3d6586e18
Tools/px4moduledoc/srcparser.py
python
SourceParser.GetModuleGroups
(self)
return groups
Returns a dictionary of all categories with a dictonary of subcategories that contain a list of associated modules.
Returns a dictionary of all categories with a dictonary of subcategories that contain a list of associated modules.
[ "Returns", "a", "dictionary", "of", "all", "categories", "with", "a", "dictonary", "of", "subcategories", "that", "contain", "a", "list", "of", "associated", "modules", "." ]
def GetModuleGroups(self): """ Returns a dictionary of all categories with a dictonary of subcategories that contain a list of associated modules. """ groups = {} for module_name in self._modules: module = self._modules[module_name] subcategory = module.subcategory() if module.category() in groups: if subcategory in groups[module.category()]: groups[module.category()][subcategory].append(module) else: groups[module.category()][subcategory] = [module] else: groups[module.category()] = {subcategory: [module]} # sort by module name for category in groups: group = groups[category] for subcategory in group: group[subcategory] = sorted(group[subcategory], key=lambda x: x.name()) return groups
[ "def", "GetModuleGroups", "(", "self", ")", ":", "groups", "=", "{", "}", "for", "module_name", "in", "self", ".", "_modules", ":", "module", "=", "self", ".", "_modules", "[", "module_name", "]", "subcategory", "=", "module", ".", "subcategory", "(", ")...
https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/px4moduledoc/srcparser.py#L541-L563
ZhouWeikuan/DouDiZhu
0d84ff6c0bc54dba6ae37955de9ae9307513dc99
code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
Cursor.type
(self)
return self._type
Retrieve the Type (if any) of the entity pointed at by the cursor.
Retrieve the Type (if any) of the entity pointed at by the cursor.
[ "Retrieve", "the", "Type", "(", "if", "any", ")", "of", "the", "entity", "pointed", "at", "by", "the", "cursor", "." ]
def type(self): """ Retrieve the Type (if any) of the entity pointed at by the cursor. """ if not hasattr(self, '_type'): self._type = conf.lib.clang_getCursorType(self) return self._type
[ "def", "type", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_type'", ")", ":", "self", ".", "_type", "=", "conf", ".", "lib", ".", "clang_getCursorType", "(", "self", ")", "return", "self", ".", "_type" ]
https://github.com/ZhouWeikuan/DouDiZhu/blob/0d84ff6c0bc54dba6ae37955de9ae9307513dc99/code/frameworks/cocos2d-x/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L1151-L1158
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
Validation/Tools/python/GenObject.py
python
GenObject.__call__
(self, key)
return object.__getattribute__ (self, key)
Makes object callable
Makes object callable
[ "Makes", "object", "callable" ]
def __call__ (self, key): """Makes object callable""" return object.__getattribute__ (self, key)
[ "def", "__call__", "(", "self", ",", "key", ")", ":", "return", "object", ".", "__getattribute__", "(", "self", ",", "key", ")" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/Validation/Tools/python/GenObject.py#L1617-L1619
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/telemetry/third_party/pyfakefs/pyfakefs/fake_filesystem.py
python
FakePathModule.join
(self, *p)
return self.filesystem.JoinPaths(*p)
Returns the completed path with a separator of the parts.
Returns the completed path with a separator of the parts.
[ "Returns", "the", "completed", "path", "with", "a", "separator", "of", "the", "parts", "." ]
def join(self, *p): """Returns the completed path with a separator of the parts.""" return self.filesystem.JoinPaths(*p)
[ "def", "join", "(", "self", ",", "*", "p", ")", ":", "return", "self", ".", "filesystem", ".", "JoinPaths", "(", "*", "p", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/telemetry/third_party/pyfakefs/pyfakefs/fake_filesystem.py#L1115-L1117
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/combo.py
python
BitmapComboBox.GetItemBitmap
(*args, **kwargs)
return _combo.BitmapComboBox_GetItemBitmap(*args, **kwargs)
GetItemBitmap(self, int n) -> Bitmap Returns the image of the item with the given index.
GetItemBitmap(self, int n) -> Bitmap
[ "GetItemBitmap", "(", "self", "int", "n", ")", "-", ">", "Bitmap" ]
def GetItemBitmap(*args, **kwargs): """ GetItemBitmap(self, int n) -> Bitmap Returns the image of the item with the given index. """ return _combo.BitmapComboBox_GetItemBitmap(*args, **kwargs)
[ "def", "GetItemBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_combo", ".", "BitmapComboBox_GetItemBitmap", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/combo.py#L981-L987
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/fluid/layers/layer_function_generator.py
python
add_sample_code
(func, sample_code)
Append sample code for dynamically generated functions. Args: func: The function of the function to be append sample code to. sample_code: sample code session in rst format.
Append sample code for dynamically generated functions.
[ "Append", "sample", "code", "for", "dynamically", "generated", "functions", "." ]
def add_sample_code(func, sample_code): """ Append sample code for dynamically generated functions. Args: func: The function of the function to be append sample code to. sample_code: sample code session in rst format. """ func.__doc__ = func.__doc__ + sample_code
[ "def", "add_sample_code", "(", "func", ",", "sample_code", ")", ":", "func", ".", "__doc__", "=", "func", ".", "__doc__", "+", "sample_code" ]
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/fluid/layers/layer_function_generator.py#L384-L392
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/ops/_op_impl/_custom_op/transpose02314_impl.py
python
shape0
(tik_instance, input_x, res, dtype)
return tik_instance, res
input shape (32, 4, 112, 112, 16)
input shape (32, 4, 112, 112, 16)
[ "input", "shape", "(", "32", "4", "112", "112", "16", ")" ]
def shape0(tik_instance, input_x, res, dtype): """input shape (32, 4, 112, 112, 16)""" with tik_instance.for_range(0, 32, block_num=32) as block_idx, tik_instance.for_range(0, 14) as cc1_db, \ tik_instance.for_range(0, 2, thread_num=2) as db_idx: input_1_local_ub = tik_instance.Tensor(dtype, [28672], name="input_1_local_ub", scope=tik.scope_ubuf) t_transpose_local_ub = tik_instance.Tensor(dtype, [28672], name="t_transpose_local_ub", scope=tik.scope_ubuf) zero = tik_instance.Scalar(dtype="float16", init_value=0) tik_instance.data_move(input_1_local_ub, input_x[block_idx * 802816 + cc1_db * 14336 + 7168 * db_idx], 0, 4, 448, 12096, 0) with tik_instance.for_range(0, 448) as cc7, tik_instance.for_range(0, 4) as cc8: tik_instance.vadds(16, t_transpose_local_ub[cc7 * 64 + cc8 * 16], input_1_local_ub[7168 * cc8 + cc7 * 16], zero, 1, 1, 1, 0, 0) tik_instance.data_move(res[block_idx * 802816 + cc1_db * 57344 + 28672 * db_idx], t_transpose_local_ub, 0, 1, 1792, 0, 0) return tik_instance, res
[ "def", "shape0", "(", "tik_instance", ",", "input_x", ",", "res", ",", "dtype", ")", ":", "with", "tik_instance", ".", "for_range", "(", "0", ",", "32", ",", "block_num", "=", "32", ")", "as", "block_idx", ",", "tik_instance", ".", "for_range", "(", "0...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/ops/_op_impl/_custom_op/transpose02314_impl.py#L104-L121
ricardoquesada/Spidermonkey
4a75ea2543408bd1b2c515aa95901523eeef7858
python/lldbutils/lldbutils/layout.py
python
frametreelimited
(debugger, command, result, dict)
Dumps the subtree of a frame tree rooted at the given nsIFrame*.
Dumps the subtree of a frame tree rooted at the given nsIFrame*.
[ "Dumps", "the", "subtree", "of", "a", "frame", "tree", "rooted", "at", "the", "given", "nsIFrame", "*", "." ]
def frametreelimited(debugger, command, result, dict): """Dumps the subtree of a frame tree rooted at the given nsIFrame*.""" debugger.HandleCommand('expr (' + command + ')->DumpFrameTreeLimited()')
[ "def", "frametreelimited", "(", "debugger", ",", "command", ",", "result", ",", "dict", ")", ":", "debugger", ".", "HandleCommand", "(", "'expr ('", "+", "command", "+", "')->DumpFrameTreeLimited()'", ")" ]
https://github.com/ricardoquesada/Spidermonkey/blob/4a75ea2543408bd1b2c515aa95901523eeef7858/python/lldbutils/lldbutils/layout.py#L7-L9
google/syzygy
8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5
third_party/numpy/files/numpy/numarray/alter_code1.py
python
converttree
(direc=os.path.curdir)
Convert all .py files in the tree given
Convert all .py files in the tree given
[ "Convert", "all", ".", "py", "files", "in", "the", "tree", "given" ]
def converttree(direc=os.path.curdir): """Convert all .py files in the tree given """ os.path.walk(direc, _func, None)
[ "def", "converttree", "(", "direc", "=", "os", ".", "path", ".", "curdir", ")", ":", "os", ".", "path", ".", "walk", "(", "direc", ",", "_func", ",", "None", ")" ]
https://github.com/google/syzygy/blob/8164b24ebde9c5649c9a09e88a7fc0b0fcbd1bc5/third_party/numpy/files/numpy/numarray/alter_code1.py#L257-L261
Constellation/iv
64c3a9c7c517063f29d90d449180ea8f6f4d946f
tools/cpplint.py
python
_GetTextInside
(text, start_pattern)
return text[start_position:position - 1]
r"""Retrieves all the text between matching open and close parentheses. Given a string of lines and a regular expression string, retrieve all the text following the expression and between opening punctuation symbols like (, [, or {, and the matching close-punctuation symbol. This properly nested occurrences of the punctuations, so for the text like printf(a(), b(c())); a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'. start_pattern must match string having an open punctuation symbol at the end. Args: text: The lines to extract text. Its comments and strings must be elided. It can be single line and can span multiple lines. start_pattern: The regexp string indicating where to start extracting the text. Returns: The extracted text. None if either the opening string or ending punctuation could not be found.
r"""Retrieves all the text between matching open and close parentheses.
[ "r", "Retrieves", "all", "the", "text", "between", "matching", "open", "and", "close", "parentheses", "." ]
def _GetTextInside(text, start_pattern): r"""Retrieves all the text between matching open and close parentheses. Given a string of lines and a regular expression string, retrieve all the text following the expression and between opening punctuation symbols like (, [, or {, and the matching close-punctuation symbol. This properly nested occurrences of the punctuations, so for the text like printf(a(), b(c())); a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'. start_pattern must match string having an open punctuation symbol at the end. Args: text: The lines to extract text. Its comments and strings must be elided. It can be single line and can span multiple lines. start_pattern: The regexp string indicating where to start extracting the text. Returns: The extracted text. None if either the opening string or ending punctuation could not be found. """ # TODO(sugawarayu): Audit cpplint.py to see what places could be profitably # rewritten to use _GetTextInside (and use inferior regexp matching today). # Give opening punctuations to get the matching close-punctuations. matching_punctuation = {'(': ')', '{': '}', '[': ']'} closing_punctuation = set(matching_punctuation.itervalues()) # Find the position to start extracting text. match = re.search(start_pattern, text, re.M) if not match: # start_pattern not found in text. return None start_position = match.end(0) assert start_position > 0, ( 'start_pattern must ends with an opening punctuation.') assert text[start_position - 1] in matching_punctuation, ( 'start_pattern must ends with an opening punctuation.') # Stack of closing punctuations we expect to have in text after position. punctuation_stack = [matching_punctuation[text[start_position - 1]]] position = start_position while punctuation_stack and position < len(text): if text[position] == punctuation_stack[-1]: punctuation_stack.pop() elif text[position] in closing_punctuation: # A closing punctuation without matching opening punctuations. return None elif text[position] in matching_punctuation: punctuation_stack.append(matching_punctuation[text[position]]) position += 1 if punctuation_stack: # Opening punctuations left without matching close-punctuations. return None # punctuations match. return text[start_position:position - 1]
[ "def", "_GetTextInside", "(", "text", ",", "start_pattern", ")", ":", "# TODO(sugawarayu): Audit cpplint.py to see what places could be profitably", "# rewritten to use _GetTextInside (and use inferior regexp matching today).", "# Give opening punctuations to get the matching close-punctuations....
https://github.com/Constellation/iv/blob/64c3a9c7c517063f29d90d449180ea8f6f4d946f/tools/cpplint.py#L3640-L3693
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pathlib.py
python
Path.is_socket
(self)
Whether this path is a socket.
Whether this path is a socket.
[ "Whether", "this", "path", "is", "a", "socket", "." ]
def is_socket(self): """ Whether this path is a socket. """ try: return S_ISSOCK(self.stat().st_mode) except OSError as e: if not _ignore_error(e): raise # Path doesn't exist or is a broken symlink # (see https://bitbucket.org/pitrou/pathlib/issue/12/) return False
[ "def", "is_socket", "(", "self", ")", ":", "try", ":", "return", "S_ISSOCK", "(", "self", ".", "stat", "(", ")", ".", "st_mode", ")", "except", "OSError", "as", "e", ":", "if", "not", "_ignore_error", "(", "e", ")", ":", "raise", "# Path doesn't exist ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/pathlib.py#L1467-L1478
apache/madlib
be297fe6beada0640f93317e8948834032718e32
src/madpack/yaml/__init__.py
python
dump
(data, stream=None, Dumper=Dumper, **kwds)
return dump_all([data], stream, Dumper=Dumper, **kwds)
Serialize a Python object into a YAML stream. If stream is None, return the produced string instead.
Serialize a Python object into a YAML stream. If stream is None, return the produced string instead.
[ "Serialize", "a", "Python", "object", "into", "a", "YAML", "stream", ".", "If", "stream", "is", "None", "return", "the", "produced", "string", "instead", "." ]
def dump(data, stream=None, Dumper=Dumper, **kwds): """ Serialize a Python object into a YAML stream. If stream is None, return the produced string instead. """ return dump_all([data], stream, Dumper=Dumper, **kwds)
[ "def", "dump", "(", "data", ",", "stream", "=", "None", ",", "Dumper", "=", "Dumper", ",", "*", "*", "kwds", ")", ":", "return", "dump_all", "(", "[", "data", "]", ",", "stream", ",", "Dumper", "=", "Dumper", ",", "*", "*", "kwds", ")" ]
https://github.com/apache/madlib/blob/be297fe6beada0640f93317e8948834032718e32/src/madpack/yaml/__init__.py#L172-L177
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/ipaddress.py
python
_find_address_range
(addresses)
Find a sequence of sorted deduplicated IPv#Address. Args: addresses: a list of IPv#Address objects. Yields: A tuple containing the first and last IP addresses in the sequence.
Find a sequence of sorted deduplicated IPv#Address.
[ "Find", "a", "sequence", "of", "sorted", "deduplicated", "IPv#Address", "." ]
def _find_address_range(addresses): """Find a sequence of sorted deduplicated IPv#Address. Args: addresses: a list of IPv#Address objects. Yields: A tuple containing the first and last IP addresses in the sequence. """ it = iter(addresses) first = last = next(it) for ip in it: if ip._ip != last._ip + 1: yield first, last first = ip last = ip yield first, last
[ "def", "_find_address_range", "(", "addresses", ")", ":", "it", "=", "iter", "(", "addresses", ")", "first", "=", "last", "=", "next", "(", "it", ")", "for", "ip", "in", "it", ":", "if", "ip", ".", "_ip", "!=", "last", ".", "_ip", "+", "1", ":", ...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/ipaddress.py#L286-L303
bulletphysics/bullet3
f0f2a952e146f016096db6f85cf0c44ed75b0b9a
examples/pybullet/gym/pybullet_envs/minitaur/agents/ppo/algorithm.py
python
PPOAlgorithm._define_end_episode
(self, agent_indices)
Implement the branch of end_episode() entered during training.
Implement the branch of end_episode() entered during training.
[ "Implement", "the", "branch", "of", "end_episode", "()", "entered", "during", "training", "." ]
def _define_end_episode(self, agent_indices): """Implement the branch of end_episode() entered during training.""" episodes, length = self._episodes.data(agent_indices) space_left = self._config.update_every - self._memory_index use_episodes = tf.range(tf.minimum(tf.shape(agent_indices)[0], space_left)) episodes = [tf.gather(elem, use_episodes) for elem in episodes] append = self._memory.replace(episodes, tf.gather(length, use_episodes), use_episodes + self._memory_index) with tf.control_dependencies([append]): inc_index = self._memory_index.assign_add(tf.shape(use_episodes)[0]) with tf.control_dependencies([inc_index]): memory_full = self._memory_index >= self._config.update_every return tf.cond(memory_full, self._training, str)
[ "def", "_define_end_episode", "(", "self", ",", "agent_indices", ")", ":", "episodes", ",", "length", "=", "self", ".", "_episodes", ".", "data", "(", "agent_indices", ")", "space_left", "=", "self", ".", "_config", ".", "update_every", "-", "self", ".", "...
https://github.com/bulletphysics/bullet3/blob/f0f2a952e146f016096db6f85cf0c44ed75b0b9a/examples/pybullet/gym/pybullet_envs/minitaur/agents/ppo/algorithm.py#L205-L217
junhyukoh/caffe-lstm
598d45456fa2a1b127a644f4aa38daa8fb9fc722
scripts/cpp_lint.py
python
FileInfo.RepositoryName
(self)
return fullname
FullName after removing the local path to the repository. If we have a real absolute path name here we can try to do something smart: detecting the root of the checkout and truncating /path/to/checkout from the name so that we get header guards that don't include things like "C:\Documents and Settings\..." or "/home/username/..." in them and thus people on different computers who have checked the source out to different locations won't see bogus errors.
FullName after removing the local path to the repository.
[ "FullName", "after", "removing", "the", "local", "path", "to", "the", "repository", "." ]
def RepositoryName(self): """FullName after removing the local path to the repository. If we have a real absolute path name here we can try to do something smart: detecting the root of the checkout and truncating /path/to/checkout from the name so that we get header guards that don't include things like "C:\Documents and Settings\..." or "/home/username/..." in them and thus people on different computers who have checked the source out to different locations won't see bogus errors. """ fullname = self.FullName() if os.path.exists(fullname): project_dir = os.path.dirname(fullname) if os.path.exists(os.path.join(project_dir, ".svn")): # If there's a .svn file in the current directory, we recursively look # up the directory tree for the top of the SVN checkout root_dir = project_dir one_up_dir = os.path.dirname(root_dir) while os.path.exists(os.path.join(one_up_dir, ".svn")): root_dir = os.path.dirname(root_dir) one_up_dir = os.path.dirname(one_up_dir) prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by # searching up from the current path. root_dir = os.path.dirname(fullname) while (root_dir != os.path.dirname(root_dir) and not os.path.exists(os.path.join(root_dir, ".git")) and not os.path.exists(os.path.join(root_dir, ".hg")) and not os.path.exists(os.path.join(root_dir, ".svn"))): root_dir = os.path.dirname(root_dir) if (os.path.exists(os.path.join(root_dir, ".git")) or os.path.exists(os.path.join(root_dir, ".hg")) or os.path.exists(os.path.join(root_dir, ".svn"))): prefix = os.path.commonprefix([root_dir, project_dir]) return fullname[len(prefix) + 1:] # Don't know what to do; header guard warnings may be wrong... return fullname
[ "def", "RepositoryName", "(", "self", ")", ":", "fullname", "=", "self", ".", "FullName", "(", ")", "if", "os", ".", "path", ".", "exists", "(", "fullname", ")", ":", "project_dir", "=", "os", ".", "path", ".", "dirname", "(", "fullname", ")", "if", ...
https://github.com/junhyukoh/caffe-lstm/blob/598d45456fa2a1b127a644f4aa38daa8fb9fc722/scripts/cpp_lint.py#L885-L928
deepmodeling/deepmd-kit
159e45d248b0429844fb6a8cb3b3a201987c8d79
deepmd/fit/polar.py
python
GlobalPolarFittingSeA.build
(self, input_d, rot_mat, natoms, reuse = None, suffix = '')
return tf.reshape(outs, [-1])
Build the computational graph for fitting net Parameters ---------- input_d The input descriptor rot_mat The rotation matrix from the descriptor. natoms The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms reuse The weights in the networks should be reused when get the variable. suffix Name suffix to identify this descriptor Returns ------- polar The system polarizability
Build the computational graph for fitting net Parameters ---------- input_d The input descriptor rot_mat The rotation matrix from the descriptor. natoms The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms reuse The weights in the networks should be reused when get the variable. suffix Name suffix to identify this descriptor
[ "Build", "the", "computational", "graph", "for", "fitting", "net", "Parameters", "----------", "input_d", "The", "input", "descriptor", "rot_mat", "The", "rotation", "matrix", "from", "the", "descriptor", ".", "natoms", "The", "number", "of", "atoms", ".", "This...
def build (self, input_d, rot_mat, natoms, reuse = None, suffix = '') -> tf.Tensor: """ Build the computational graph for fitting net Parameters ---------- input_d The input descriptor rot_mat The rotation matrix from the descriptor. natoms The number of atoms. This tensor has the length of Ntypes + 2 natoms[0]: number of local atoms natoms[1]: total number of atoms held by this processor natoms[i]: 2 <= i < Ntypes+2, number of type i atoms reuse The weights in the networks should be reused when get the variable. suffix Name suffix to identify this descriptor Returns ------- polar The system polarizability """ inputs = tf.reshape(input_d, [-1, self.dim_descrpt * natoms[0]]) outs = self.polar_fitting.build(input_d, rot_mat, natoms, reuse, suffix) # nframes x natoms x 9 outs = tf.reshape(outs, [tf.shape(inputs)[0], -1, 9]) outs = tf.reduce_sum(outs, axis = 1) tf.summary.histogram('fitting_net_output', outs) return tf.reshape(outs, [-1])
[ "def", "build", "(", "self", ",", "input_d", ",", "rot_mat", ",", "natoms", ",", "reuse", "=", "None", ",", "suffix", "=", "''", ")", "->", "tf", ".", "Tensor", ":", "inputs", "=", "tf", ".", "reshape", "(", "input_d", ",", "[", "-", "1", ",", ...
https://github.com/deepmodeling/deepmd-kit/blob/159e45d248b0429844fb6a8cb3b3a201987c8d79/deepmd/fit/polar.py#L446-L482
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
build/android/pylib/android_commands.py
python
AndroidCommands.GetMonitoredLogCat
(self)
return self._logcat
Returns an "adb logcat" command as created by pexpected.spawn.
Returns an "adb logcat" command as created by pexpected.spawn.
[ "Returns", "an", "adb", "logcat", "command", "as", "created", "by", "pexpected", ".", "spawn", "." ]
def GetMonitoredLogCat(self): """Returns an "adb logcat" command as created by pexpected.spawn.""" if not self._logcat: self.StartMonitoringLogcat(clear=False) return self._logcat
[ "def", "GetMonitoredLogCat", "(", "self", ")", ":", "if", "not", "self", ".", "_logcat", ":", "self", ".", "StartMonitoringLogcat", "(", "clear", "=", "False", ")", "return", "self", ".", "_logcat" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/build/android/pylib/android_commands.py#L1289-L1293
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Code/Tools/waf-1.7.13/waflib/Tools/tex.py
python
tex.scan_aux
(self, node)
return nodes
A recursive regex-based scanner that finds included auxiliary files.
A recursive regex-based scanner that finds included auxiliary files.
[ "A", "recursive", "regex", "-", "based", "scanner", "that", "finds", "included", "auxiliary", "files", "." ]
def scan_aux(self, node): """ A recursive regex-based scanner that finds included auxiliary files. """ nodes = [node] re_aux = re.compile(r'\\@input{(?P<file>[^{}]*)}', re.M) def parse_node(node): code = node.read() for match in re_aux.finditer(code): path = match.group('file') found = node.parent.find_or_declare(path) if found and found not in nodes: Logs.debug('tex: found aux node ' + found.abspath()) nodes.append(found) parse_node(found) parse_node(node) return nodes
[ "def", "scan_aux", "(", "self", ",", "node", ")", ":", "nodes", "=", "[", "node", "]", "re_aux", "=", "re", ".", "compile", "(", "r'\\\\@input{(?P<file>[^{}]*)}'", ",", "re", ".", "M", ")", "def", "parse_node", "(", "node", ")", ":", "code", "=", "no...
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Code/Tools/waf-1.7.13/waflib/Tools/tex.py#L109-L127
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/multicall.py
python
MultiCallCreator
(widget)
return MultiCall
Return a MultiCall class which inherits its methods from the given widget class (for example, Tkinter.Text). This is used instead of a templating mechanism.
Return a MultiCall class which inherits its methods from the given widget class (for example, Tkinter.Text). This is used instead of a templating mechanism.
[ "Return", "a", "MultiCall", "class", "which", "inherits", "its", "methods", "from", "the", "given", "widget", "class", "(", "for", "example", "Tkinter", ".", "Text", ")", ".", "This", "is", "used", "instead", "of", "a", "templating", "mechanism", "." ]
def MultiCallCreator(widget): """Return a MultiCall class which inherits its methods from the given widget class (for example, Tkinter.Text). This is used instead of a templating mechanism. """ if widget in _multicall_dict: return _multicall_dict[widget] class MultiCall (widget): assert issubclass(widget, tkinter.Misc) def __init__(self, *args, **kwargs): widget.__init__(self, *args, **kwargs) # a dictionary which maps a virtual event to a tuple with: # 0. the function binded # 1. a list of triplets - the sequences it is binded to self.__eventinfo = {} self.__binders = [_binder_classes[i](i, widget, self) for i in range(len(_types))] def bind(self, sequence=None, func=None, add=None): #print("bind(%s, %s, %s)" % (sequence, func, add), # file=sys.__stderr__) if type(sequence) is str and len(sequence) > 2 and \ sequence[:2] == "<<" and sequence[-2:] == ">>": if sequence in self.__eventinfo: ei = self.__eventinfo[sequence] if ei[0] is not None: for triplet in ei[1]: self.__binders[triplet[1]].unbind(triplet, ei[0]) ei[0] = func if ei[0] is not None: for triplet in ei[1]: self.__binders[triplet[1]].bind(triplet, func) else: self.__eventinfo[sequence] = [func, []] return widget.bind(self, sequence, func, add) def unbind(self, sequence, funcid=None): if type(sequence) is str and len(sequence) > 2 and \ sequence[:2] == "<<" and sequence[-2:] == ">>" and \ sequence in self.__eventinfo: func, triplets = self.__eventinfo[sequence] if func is not None: for triplet in triplets: self.__binders[triplet[1]].unbind(triplet, func) self.__eventinfo[sequence][0] = None return widget.unbind(self, sequence, funcid) def event_add(self, virtual, *sequences): #print("event_add(%s, %s)" % (repr(virtual), repr(sequences)), # file=sys.__stderr__) if virtual not in self.__eventinfo: self.__eventinfo[virtual] = [None, []] func, triplets = self.__eventinfo[virtual] for seq in sequences: triplet = _parse_sequence(seq) if triplet is None: #print("Tkinter event_add(%s)" % seq, file=sys.__stderr__) widget.event_add(self, virtual, seq) else: if func is not None: self.__binders[triplet[1]].bind(triplet, func) triplets.append(triplet) def event_delete(self, virtual, *sequences): if virtual not in self.__eventinfo: return func, triplets = self.__eventinfo[virtual] for seq in sequences: triplet = _parse_sequence(seq) if triplet is None: #print("Tkinter event_delete: %s" % seq, file=sys.__stderr__) widget.event_delete(self, virtual, seq) else: if func is not None: self.__binders[triplet[1]].unbind(triplet, func) triplets.remove(triplet) def event_info(self, virtual=None): if virtual is None or virtual not in self.__eventinfo: return widget.event_info(self, virtual) else: return tuple(map(_triplet_to_sequence, self.__eventinfo[virtual][1])) + \ widget.event_info(self, virtual) def __del__(self): for virtual in self.__eventinfo: func, triplets = self.__eventinfo[virtual] if func: for triplet in triplets: try: self.__binders[triplet[1]].unbind(triplet, func) except tkinter.TclError as e: if not APPLICATION_GONE in e.args[0]: raise _multicall_dict[widget] = MultiCall return MultiCall
[ "def", "MultiCallCreator", "(", "widget", ")", ":", "if", "widget", "in", "_multicall_dict", ":", "return", "_multicall_dict", "[", "widget", "]", "class", "MultiCall", "(", "widget", ")", ":", "assert", "issubclass", "(", "widget", ",", "tkinter", ".", "Mis...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/idlelib/multicall.py#L314-L414
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/dataset/engine/datasets.py
python
_NumpySlicesDataset.process_dict
(self, input_data)
return data
Convert the dict like data into tuple format, when input is a tuple of dicts then compose it into a dict first.
Convert the dict like data into tuple format, when input is a tuple of dicts then compose it into a dict first.
[ "Convert", "the", "dict", "like", "data", "into", "tuple", "format", "when", "input", "is", "a", "tuple", "of", "dicts", "then", "compose", "it", "into", "a", "dict", "first", "." ]
def process_dict(self, input_data): """ Convert the dict like data into tuple format, when input is a tuple of dicts then compose it into a dict first. """ # Convert pandas like dict(has "values" column) into General dict data_keys = list(input_data.keys()) data_col = input_data[data_keys[0]] if hasattr(data_col, "values"): new_dict = {} for key in data_keys: item1 = input_data.pop(key) new_dict[key] = item1.values input_data = new_dict # Convert the data in dict into tuple data = () keys = list(input_data.keys()) self.column_list = keys for key in keys: value = input_data[key] data = data + (list(value),) return data
[ "def", "process_dict", "(", "self", ",", "input_data", ")", ":", "# Convert pandas like dict(has \"values\" column) into General dict", "data_keys", "=", "list", "(", "input_data", ".", "keys", "(", ")", ")", "data_col", "=", "input_data", "[", "data_keys", "[", "0"...
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/engine/datasets.py#L8472-L8494
OPAE/opae-sdk
221124343c8275243a249eb72d69e0ea2d568d1b
binaries/qpafilter/qpafilter.py
python
qpamap.values_for
(self, ident)
return (self.id_map[ident]['filtered_warning'], self.id_map[ident]['filtered_fatal'])
Return a tuple of the filtered warning and filtered fatal values.
Return a tuple of the filtered warning and filtered fatal values.
[ "Return", "a", "tuple", "of", "the", "filtered", "warning", "and", "filtered", "fatal", "values", "." ]
def values_for(self, ident): """Return a tuple of the filtered warning and filtered fatal values.""" return (self.id_map[ident]['filtered_warning'], self.id_map[ident]['filtered_fatal'])
[ "def", "values_for", "(", "self", ",", "ident", ")", ":", "return", "(", "self", ".", "id_map", "[", "ident", "]", "[", "'filtered_warning'", "]", ",", "self", ".", "id_map", "[", "ident", "]", "[", "'filtered_fatal'", "]", ")" ]
https://github.com/OPAE/opae-sdk/blob/221124343c8275243a249eb72d69e0ea2d568d1b/binaries/qpafilter/qpafilter.py#L389-L392
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/keras/utils/tf_utils.py
python
is_extension_type
(tensor)
return isinstance(tensor, composite_tensor.CompositeTensor)
Returns whether a tensor is of an ExtensionType. github.com/tensorflow/community/pull/269 Currently it works by checking if `tensor` is a `CompositeTensor` instance, but this will be changed to use an appropriate extensiontype protocol check once ExtensionType is made public. Args: tensor: An object to test Returns: True if the tensor is an extension type object, false if not.
Returns whether a tensor is of an ExtensionType.
[ "Returns", "whether", "a", "tensor", "is", "of", "an", "ExtensionType", "." ]
def is_extension_type(tensor): """Returns whether a tensor is of an ExtensionType. github.com/tensorflow/community/pull/269 Currently it works by checking if `tensor` is a `CompositeTensor` instance, but this will be changed to use an appropriate extensiontype protocol check once ExtensionType is made public. Args: tensor: An object to test Returns: True if the tensor is an extension type object, false if not. """ return isinstance(tensor, composite_tensor.CompositeTensor)
[ "def", "is_extension_type", "(", "tensor", ")", ":", "return", "isinstance", "(", "tensor", ",", "composite_tensor", ".", "CompositeTensor", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/keras/utils/tf_utils.py#L288-L302
neoml-lib/neoml
a0d370fba05269a1b2258cef126f77bbd2054a3e
NeoML/Python/neoml/Dnn/Conv.py
python
TimeConv.filter
(self, blob)
Sets the filters. The dimensions: - **BatchLength** * **BatchWidth** * **ListSize** is filter_count - **Height**, **Width** are taken from filter_size - **Depth**, **Channels** are equal to the inputs' dimensions :param neoml.Blob.Blob blob: blob to be used as filter
Sets the filters. The dimensions: - **BatchLength** * **BatchWidth** * **ListSize** is filter_count - **Height**, **Width** are taken from filter_size - **Depth**, **Channels** are equal to the inputs' dimensions
[ "Sets", "the", "filters", ".", "The", "dimensions", ":", "-", "**", "BatchLength", "**", "*", "**", "BatchWidth", "**", "*", "**", "ListSize", "**", "is", "filter_count", "-", "**", "Height", "**", "**", "Width", "**", "are", "taken", "from", "filter_siz...
def filter(self, blob): """Sets the filters. The dimensions: - **BatchLength** * **BatchWidth** * **ListSize** is filter_count - **Height**, **Width** are taken from filter_size - **Depth**, **Channels** are equal to the inputs' dimensions :param neoml.Blob.Blob blob: blob to be used as filter """ if not isinstance(blob, Blob.Blob): raise ValueError('The `blob` must be neoml.Blob.Blob.') self._internal.set_filter(blob._internal)
[ "def", "filter", "(", "self", ",", "blob", ")", ":", "if", "not", "isinstance", "(", "blob", ",", "Blob", ".", "Blob", ")", ":", "raise", "ValueError", "(", "'The `blob` must be neoml.Blob.Blob.'", ")", "self", ".", "_internal", ".", "set_filter", "(", "bl...
https://github.com/neoml-lib/neoml/blob/a0d370fba05269a1b2258cef126f77bbd2054a3e/NeoML/Python/neoml/Dnn/Conv.py#L1170-L1181
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
lldb/third_party/Python/module/pexpect-4.6/pexpect/FSM.py
python
FSM.__init__
(self, initial_state, memory=None)
This creates the FSM. You set the initial state here. The "memory" attribute is any object that you want to pass along to the action functions. It is not used by the FSM. For parsing you would typically pass a list to be used as a stack.
This creates the FSM. You set the initial state here. The "memory" attribute is any object that you want to pass along to the action functions. It is not used by the FSM. For parsing you would typically pass a list to be used as a stack.
[ "This", "creates", "the", "FSM", ".", "You", "set", "the", "initial", "state", "here", ".", "The", "memory", "attribute", "is", "any", "object", "that", "you", "want", "to", "pass", "along", "to", "the", "action", "functions", ".", "It", "is", "not", "...
def __init__(self, initial_state, memory=None): '''This creates the FSM. You set the initial state here. The "memory" attribute is any object that you want to pass along to the action functions. It is not used by the FSM. For parsing you would typically pass a list to be used as a stack. ''' # Map (input_symbol, current_state) --> (action, next_state). self.state_transitions = {} # Map (current_state) --> (action, next_state). self.state_transitions_any = {} self.default_transition = None self.input_symbol = None self.initial_state = initial_state self.current_state = self.initial_state self.next_state = None self.action = None self.memory = memory
[ "def", "__init__", "(", "self", ",", "initial_state", ",", "memory", "=", "None", ")", ":", "# Map (input_symbol, current_state) --> (action, next_state).", "self", ".", "state_transitions", "=", "{", "}", "# Map (current_state) --> (action, next_state).", "self", ".", "s...
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/lldb/third_party/Python/module/pexpect-4.6/pexpect/FSM.py#L102-L120
sfzhang15/FaceBoxes
b52cc92f9362d3adc08d54666aeb9ebb62fdb7da
scripts/cpp_lint.py
python
CleansedLines._CollapseStrings
(elided)
return elided
Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings.
Collapses strings and chars on a line to simple "" or '' blocks.
[ "Collapses", "strings", "and", "chars", "on", "a", "line", "to", "simple", "or", "blocks", "." ]
def _CollapseStrings(elided): """Collapses strings and chars on a line to simple "" or '' blocks. We nix strings first so we're not fooled by text like '"http://"' Args: elided: The line being processed. Returns: The line with collapsed strings. """ if not _RE_PATTERN_INCLUDE.match(elided): # Remove escaped characters first to make quote/single quote collapsing # basic. Things that look like escaped characters shouldn't occur # outside of strings and chars. elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided) elided = _RE_PATTERN_CLEANSE_LINE_SINGLE_QUOTES.sub("''", elided) elided = _RE_PATTERN_CLEANSE_LINE_DOUBLE_QUOTES.sub('""', elided) return elided
[ "def", "_CollapseStrings", "(", "elided", ")", ":", "if", "not", "_RE_PATTERN_INCLUDE", ".", "match", "(", "elided", ")", ":", "# Remove escaped characters first to make quote/single quote collapsing", "# basic. Things that look like escaped characters shouldn't occur", "# outside...
https://github.com/sfzhang15/FaceBoxes/blob/b52cc92f9362d3adc08d54666aeb9ebb62fdb7da/scripts/cpp_lint.py#L1209-L1227
apiaryio/snowcrash
b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3
tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings._DefaultSdkRoot
(self)
return ''
Returns the default SDKROOT to use. Prior to version 5.0.0, if SDKROOT was not explicitly set in the Xcode project, then the environment variable was empty. Starting with this version, Xcode uses the name of the newest SDK installed.
Returns the default SDKROOT to use.
[ "Returns", "the", "default", "SDKROOT", "to", "use", "." ]
def _DefaultSdkRoot(self): """Returns the default SDKROOT to use. Prior to version 5.0.0, if SDKROOT was not explicitly set in the Xcode project, then the environment variable was empty. Starting with this version, Xcode uses the name of the newest SDK installed. """ xcode_version, xcode_build = XcodeVersion() if xcode_version < '0500': return '' default_sdk_path = self._XcodeSdkPath('') default_sdk_root = XcodeSettings._sdk_root_cache.get(default_sdk_path) if default_sdk_root: return default_sdk_root try: all_sdks = GetStdout(['xcodebuild', '-showsdks']) except: # If xcodebuild fails, there will be no valid SDKs return '' for line in all_sdks.splitlines(): items = line.split() if len(items) >= 3 and items[-2] == '-sdk': sdk_root = items[-1] sdk_path = self._XcodeSdkPath(sdk_root) if sdk_path == default_sdk_path: return sdk_root return ''
[ "def", "_DefaultSdkRoot", "(", "self", ")", ":", "xcode_version", ",", "xcode_build", "=", "XcodeVersion", "(", ")", "if", "xcode_version", "<", "'0500'", ":", "return", "''", "default_sdk_path", "=", "self", ".", "_XcodeSdkPath", "(", "''", ")", "default_sdk_...
https://github.com/apiaryio/snowcrash/blob/b5b39faa85f88ee17459edf39fdc6fe4fc70d2e3/tools/gyp/pylib/gyp/xcode_emulation.py#L1139-L1165
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/clustering_ops.py
python
_InitializeClustersOpFactory._kmc2_multiple_centers
(self)
return num_remaining
Adds new initial cluster centers using the k-MC2 algorithm. In each call to the op, the provided batch is split into subsets based on the specified `kmc2_chain_length`. On each subset, a single Markov chain of the k-MC2 algorithm is used to add *one* new center cluster center. If there are less than `kmc2_chain_length` points in the subset, a single center is added using one Markov chain on the full input. It is assumed that the provided batch has previously been randomly permuted. Otherwise, k-MC2 may return suboptimal centers. Returns: An op that adds new cluster centers.
Adds new initial cluster centers using the k-MC2 algorithm.
[ "Adds", "new", "initial", "cluster", "centers", "using", "the", "k", "-", "MC2", "algorithm", "." ]
def _kmc2_multiple_centers(self): """Adds new initial cluster centers using the k-MC2 algorithm. In each call to the op, the provided batch is split into subsets based on the specified `kmc2_chain_length`. On each subset, a single Markov chain of the k-MC2 algorithm is used to add *one* new center cluster center. If there are less than `kmc2_chain_length` points in the subset, a single center is added using one Markov chain on the full input. It is assumed that the provided batch has previously been randomly permuted. Otherwise, k-MC2 may return suboptimal centers. Returns: An op that adds new cluster centers. """ # The op only operates on the first shard of data. first_shard = self._inputs[0] # Number of points in the input that can be used. batch_size = array_ops.shape(first_shard)[0] # Maximum number of subsets such that the size of each subset is at least # `kmc2_chain_length`. Final subsets may be larger. max_to_sample = math_ops.cast( batch_size / self._kmc2_chain_length, dtype=dtypes.int32) # We sample at least one new center and at most all remaining centers. num_to_sample = math_ops.maximum( math_ops.minimum(self._num_remaining, max_to_sample), 1) def _cond(i, _): """Stopping condition for the while loop.""" return math_ops.less(i, num_to_sample) def _body(i, _): """Body that adds a single new center based on a subset.""" def _sample_random(): """Returns a random point as a cluster center.""" # By assumption the batch is reshuffled and _sample_random is always # called for i=0. Hence, we simply return the first point. new_center = array_ops.reshape(first_shard[0], [1, -1]) if self._distance_metric == COSINE_DISTANCE: new_center = nn_impl.l2_normalize(new_center, dim=1) return new_center def _sample_kmc2_chain(): """Returns previous centers as well as a new center sampled using k-MC2.""" # Extract the subset from the underlying batch. start = i * self._kmc2_chain_length end = start + self._kmc2_chain_length subset = first_shard[start:end] # Compute the distances from points in the subset to previous centers. _, distances = gen_clustering_ops.nearest_neighbors( subset, self._cluster_centers, 1) # Sample index of new center using k-MC2 Markov chain. new_center_index = gen_clustering_ops.kmc2_chain_initialization( array_ops.squeeze(distances), self._seed) # Extract actual new center. newly_sampled_center = array_ops.reshape(subset[new_center_index], [1, -1]) # Return concatenation with previously sampled centers. if self._distance_metric == COSINE_DISTANCE: newly_sampled_center = nn_impl.l2_normalize( newly_sampled_center, dim=1) return array_ops.concat([self._cluster_centers, newly_sampled_center], 0) # Obtain a random point if there are no previously sampled centers. # Otherwise, construct a k-MC2 Markov chain. new_centers = control_flow_ops.cond( math_ops.equal(self._num_selected, 0), _sample_random, _sample_kmc2_chain) # Assign new cluster centers to underlying variable. assigned_centers = state_ops.assign( self._cluster_centers, new_centers, validate_shape=False) if self._cluster_centers_updated is not self._cluster_centers: assigned_centers = state_ops.assign( self._cluster_centers_updated, assigned_centers, validate_shape=False) return i + 1, self._num_clusters - array_ops.shape(assigned_centers)[0] # Add num_to_sample new data points. _, num_remaining = control_flow_ops.while_loop(_cond, _body, [0, 0]) return num_remaining
[ "def", "_kmc2_multiple_centers", "(", "self", ")", ":", "# The op only operates on the first shard of data.", "first_shard", "=", "self", ".", "_inputs", "[", "0", "]", "# Number of points in the input that can be used.", "batch_size", "=", "array_ops", ".", "shape", "(", ...
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/clustering_ops.py#L623-L704
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/decimal.py
python
_group_lengths
(grouping)
Convert a localeconv-style grouping into a (possibly infinite) iterable of integers representing group lengths.
Convert a localeconv-style grouping into a (possibly infinite) iterable of integers representing group lengths.
[ "Convert", "a", "localeconv", "-", "style", "grouping", "into", "a", "(", "possibly", "infinite", ")", "iterable", "of", "integers", "representing", "group", "lengths", "." ]
def _group_lengths(grouping): """Convert a localeconv-style grouping into a (possibly infinite) iterable of integers representing group lengths. """ # The result from localeconv()['grouping'], and the input to this # function, should be a list of integers in one of the # following three forms: # # (1) an empty list, or # (2) nonempty list of positive integers + [0] # (3) list of positive integers + [locale.CHAR_MAX], or from itertools import chain, repeat if not grouping: return [] elif grouping[-1] == 0 and len(grouping) >= 2: return chain(grouping[:-1], repeat(grouping[-2])) elif grouping[-1] == _locale.CHAR_MAX: return grouping[:-1] else: raise ValueError('unrecognised format for grouping')
[ "def", "_group_lengths", "(", "grouping", ")", ":", "# The result from localeconv()['grouping'], and the input to this", "# function, should be a list of integers in one of the", "# following three forms:", "#", "# (1) an empty list, or", "# (2) nonempty list of positive integers + [0]", ...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/decimal.py#L6096-L6117
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py
python
CommandBit.parsesquare
(self, pos)
return bracket
Parse a square bracket
Parse a square bracket
[ "Parse", "a", "square", "bracket" ]
def parsesquare(self, pos): "Parse a square bracket" self.factory.clearskipped(pos) if not self.factory.detecttype(SquareBracket, pos): return None bracket = self.factory.parsetype(SquareBracket, pos) self.add(bracket) return bracket
[ "def", "parsesquare", "(", "self", ",", "pos", ")", ":", "self", ".", "factory", ".", "clearskipped", "(", "pos", ")", "if", "not", "self", ".", "factory", ".", "detecttype", "(", "SquareBracket", ",", "pos", ")", ":", "return", "None", "bracket", "=",...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L4147-L4154
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/util/deprecation.py
python
silence
()
Temporarily silence deprecation warnings.
Temporarily silence deprecation warnings.
[ "Temporarily", "silence", "deprecation", "warnings", "." ]
def silence(): """Temporarily silence deprecation warnings.""" global _PRINT_DEPRECATION_WARNINGS print_deprecation_warnings = _PRINT_DEPRECATION_WARNINGS _PRINT_DEPRECATION_WARNINGS = False yield _PRINT_DEPRECATION_WARNINGS = print_deprecation_warnings
[ "def", "silence", "(", ")", ":", "global", "_PRINT_DEPRECATION_WARNINGS", "print_deprecation_warnings", "=", "_PRINT_DEPRECATION_WARNINGS", "_PRINT_DEPRECATION_WARNINGS", "=", "False", "yield", "_PRINT_DEPRECATION_WARNINGS", "=", "print_deprecation_warnings" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/util/deprecation.py#L651-L657
greg7mdp/parallel-hashmap
bf2d3fe7a276401cb2494eb93696930c001d8de7
phmap_lldb.py
python
_get_function_name
(instance=None)
return class_name + sys._getframe(1).f_code.co_name
Return the name of the calling function
Return the name of the calling function
[ "Return", "the", "name", "of", "the", "calling", "function" ]
def _get_function_name(instance=None): """Return the name of the calling function""" class_name = f"{type(instance).__name__}." if instance else "" return class_name + sys._getframe(1).f_code.co_name
[ "def", "_get_function_name", "(", "instance", "=", "None", ")", ":", "class_name", "=", "f\"{type(instance).__name__}.\"", "if", "instance", "else", "\"\"", "return", "class_name", "+", "sys", ".", "_getframe", "(", "1", ")", ".", "f_code", ".", "co_name" ]
https://github.com/greg7mdp/parallel-hashmap/blob/bf2d3fe7a276401cb2494eb93696930c001d8de7/phmap_lldb.py#L18-L21
TheLegendAli/DeepLab-Context
fb04e9e2fc2682490ad9f60533b9d6c4c0e0479c
examples/web_demo/app.py
python
embed_image_html
(image)
return 'data:image/png;base64,' + data
Creates an image embedded in HTML base64 format.
Creates an image embedded in HTML base64 format.
[ "Creates", "an", "image", "embedded", "in", "HTML", "base64", "format", "." ]
def embed_image_html(image): """Creates an image embedded in HTML base64 format.""" image_pil = PILImage.fromarray((255 * image).astype('uint8')) image_pil = image_pil.resize((256, 256)) string_buf = StringIO.StringIO() image_pil.save(string_buf, format='png') data = string_buf.getvalue().encode('base64').replace('\n', '') return 'data:image/png;base64,' + data
[ "def", "embed_image_html", "(", "image", ")", ":", "image_pil", "=", "PILImage", ".", "fromarray", "(", "(", "255", "*", "image", ")", ".", "astype", "(", "'uint8'", ")", ")", "image_pil", "=", "image_pil", ".", "resize", "(", "(", "256", ",", "256", ...
https://github.com/TheLegendAli/DeepLab-Context/blob/fb04e9e2fc2682490ad9f60533b9d6c4c0e0479c/examples/web_demo/app.py#L81-L88
apache/singa
93fd9da72694e68bfe3fb29d0183a65263d238a1
python/singa/autograd.py
python
acos
(x)
return Acos()(x)[0]
Calculates the arccosine (inverse of cosine) of the given input tensor, element-wise. Args: x (Tensor): Input tensor Returns: Tensor, the output
Calculates the arccosine (inverse of cosine) of the given input tensor, element-wise. Args: x (Tensor): Input tensor Returns: Tensor, the output
[ "Calculates", "the", "arccosine", "(", "inverse", "of", "cosine", ")", "of", "the", "given", "input", "tensor", "element", "-", "wise", ".", "Args", ":", "x", "(", "Tensor", ")", ":", "Input", "tensor", "Returns", ":", "Tensor", "the", "output" ]
def acos(x): """ Calculates the arccosine (inverse of cosine) of the given input tensor, element-wise. Args: x (Tensor): Input tensor Returns: Tensor, the output """ return Acos()(x)[0]
[ "def", "acos", "(", "x", ")", ":", "return", "Acos", "(", ")", "(", "x", ")", "[", "0", "]" ]
https://github.com/apache/singa/blob/93fd9da72694e68bfe3fb29d0183a65263d238a1/python/singa/autograd.py#L2088-L2097
jsupancic/deep_hand_pose
22cbeae1a8410ff5d37c060c7315719d0a5d608f
tools/extra/resize_and_crop_images.py
python
OpenCVResizeCrop.resize_and_crop_image
(self, input_file, output_file, output_side_length = 256)
Takes an image name, resize it and crop the center square
Takes an image name, resize it and crop the center square
[ "Takes", "an", "image", "name", "resize", "it", "and", "crop", "the", "center", "square" ]
def resize_and_crop_image(self, input_file, output_file, output_side_length = 256): '''Takes an image name, resize it and crop the center square ''' img = cv2.imread(input_file) height, width, depth = img.shape new_height = output_side_length new_width = output_side_length if height > width: new_height = output_side_length * height / width else: new_width = output_side_length * width / height resized_img = cv2.resize(img, (new_width, new_height)) height_offset = (new_height - output_side_length) / 2 width_offset = (new_width - output_side_length) / 2 cropped_img = resized_img[height_offset:height_offset + output_side_length, width_offset:width_offset + output_side_length] cv2.imwrite(output_file, cropped_img)
[ "def", "resize_and_crop_image", "(", "self", ",", "input_file", ",", "output_file", ",", "output_side_length", "=", "256", ")", ":", "img", "=", "cv2", ".", "imread", "(", "input_file", ")", "height", ",", "width", ",", "depth", "=", "img", ".", "shape", ...
https://github.com/jsupancic/deep_hand_pose/blob/22cbeae1a8410ff5d37c060c7315719d0a5d608f/tools/extra/resize_and_crop_images.py#L20-L36
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/ParenMatch.py
python
ParenMatch.create_tag_default
(self, indices)
Highlight the single paren that matches
Highlight the single paren that matches
[ "Highlight", "the", "single", "paren", "that", "matches" ]
def create_tag_default(self, indices): """Highlight the single paren that matches""" self.text.tag_add("paren", indices[0]) self.text.tag_config("paren", self.HILITE_CONFIG)
[ "def", "create_tag_default", "(", "self", ",", "indices", ")", ":", "self", ".", "text", ".", "tag_add", "(", "\"paren\"", ",", "indices", "[", "0", "]", ")", "self", ".", "text", ".", "tag_config", "(", "\"paren\"", ",", "self", ".", "HILITE_CONFIG", ...
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/idlelib/ParenMatch.py#L133-L136
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py3/sklearn/cluster/_agglomerative.py
python
_fix_connectivity
(X, connectivity, affinity)
return connectivity, n_connected_components
Fixes the connectivity matrix - copies it - makes it symmetric - converts it to LIL if necessary - completes it if necessary
Fixes the connectivity matrix
[ "Fixes", "the", "connectivity", "matrix" ]
def _fix_connectivity(X, connectivity, affinity): """ Fixes the connectivity matrix - copies it - makes it symmetric - converts it to LIL if necessary - completes it if necessary """ n_samples = X.shape[0] if (connectivity.shape[0] != n_samples or connectivity.shape[1] != n_samples): raise ValueError('Wrong shape for connectivity matrix: %s ' 'when X is %s' % (connectivity.shape, X.shape)) # Make the connectivity matrix symmetric: connectivity = connectivity + connectivity.T # Convert connectivity matrix to LIL if not sparse.isspmatrix_lil(connectivity): if not sparse.isspmatrix(connectivity): connectivity = sparse.lil_matrix(connectivity) else: connectivity = connectivity.tolil() # Compute the number of nodes n_connected_components, labels = connected_components(connectivity) if n_connected_components > 1: warnings.warn("the number of connected components of the " "connectivity matrix is %d > 1. Completing it to avoid " "stopping the tree early." % n_connected_components, stacklevel=2) # XXX: Can we do without completing the matrix? for i in range(n_connected_components): idx_i = np.where(labels == i)[0] Xi = X[idx_i] for j in range(i): idx_j = np.where(labels == j)[0] Xj = X[idx_j] D = pairwise_distances(Xi, Xj, metric=affinity) ii, jj = np.where(D == np.min(D)) ii = ii[0] jj = jj[0] connectivity[idx_i[ii], idx_j[jj]] = True connectivity[idx_j[jj], idx_i[ii]] = True return connectivity, n_connected_components
[ "def", "_fix_connectivity", "(", "X", ",", "connectivity", ",", "affinity", ")", ":", "n_samples", "=", "X", ".", "shape", "[", "0", "]", "if", "(", "connectivity", ".", "shape", "[", "0", "]", "!=", "n_samples", "or", "connectivity", ".", "shape", "["...
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py3/sklearn/cluster/_agglomerative.py#L32-L79
forkineye/ESPixelStick
22926f1c0d1131f1369fc7cad405689a095ae3cb
dist/bin/esptool/serial/tools/list_ports_osx.py
python
get_string_property
(device_type, property)
return output
Search the given device for the specified string property @param device_type Type of Device @param property String to search for @return Python string containing the value, or None if not found.
Search the given device for the specified string property
[ "Search", "the", "given", "device", "for", "the", "specified", "string", "property" ]
def get_string_property(device_type, property): """ Search the given device for the specified string property @param device_type Type of Device @param property String to search for @return Python string containing the value, or None if not found. """ key = cf.CFStringCreateWithCString( kCFAllocatorDefault, property.encode("mac_roman"), kCFStringEncodingMacRoman) CFContainer = iokit.IORegistryEntryCreateCFProperty( device_type, key, kCFAllocatorDefault, 0) output = None if CFContainer: output = cf.CFStringGetCStringPtr(CFContainer, 0) if output is not None: output = output.decode('mac_roman') cf.CFRelease(CFContainer) return output
[ "def", "get_string_property", "(", "device_type", ",", "property", ")", ":", "key", "=", "cf", ".", "CFStringCreateWithCString", "(", "kCFAllocatorDefault", ",", "property", ".", "encode", "(", "\"mac_roman\"", ")", ",", "kCFStringEncodingMacRoman", ")", "CFContaine...
https://github.com/forkineye/ESPixelStick/blob/22926f1c0d1131f1369fc7cad405689a095ae3cb/dist/bin/esptool/serial/tools/list_ports_osx.py#L79-L104
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/propgrid.py
python
PropertyGrid.IsMainButtonEvent
(*args, **kwargs)
return _propgrid.PropertyGrid_IsMainButtonEvent(*args, **kwargs)
IsMainButtonEvent(self, Event event) -> bool
IsMainButtonEvent(self, Event event) -> bool
[ "IsMainButtonEvent", "(", "self", "Event", "event", ")", "-", ">", "bool" ]
def IsMainButtonEvent(*args, **kwargs): """IsMainButtonEvent(self, Event event) -> bool""" return _propgrid.PropertyGrid_IsMainButtonEvent(*args, **kwargs)
[ "def", "IsMainButtonEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_propgrid", ".", "PropertyGrid_IsMainButtonEvent", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/propgrid.py#L2431-L2433
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_groups.py
python
SetAutoGroup.proceed
(self, labelname)
Set the defined autogroup, or create a new layer. Parameters ---------- labelname: str The passed string with the name of the group or layer.
Set the defined autogroup, or create a new layer.
[ "Set", "the", "defined", "autogroup", "or", "create", "a", "new", "layer", "." ]
def proceed(self, labelname): """Set the defined autogroup, or create a new layer. Parameters ---------- labelname: str The passed string with the name of the group or layer. """ # Deactivate the source command of the `DraftToolBar` class # so that it doesn't do more with this command # when it finishes. self.ui.sourceCmd = None if labelname in self.labels: if labelname == self.labels[0]: # First option "None" deactivates autogrouping self.ui.setAutoGroup(None) elif labelname == self.labels[-1]: # Last option "Add new layer" creates new layer Gui.runCommand("Draft_Layer") else: # Set autogroup to the chosen layer i = self.labels.index(labelname) self.ui.setAutoGroup(self.groups[i])
[ "def", "proceed", "(", "self", ",", "labelname", ")", ":", "# Deactivate the source command of the `DraftToolBar` class", "# so that it doesn't do more with this command", "# when it finishes.", "self", ".", "ui", ".", "sourceCmd", "=", "None", "if", "labelname", "in", "sel...
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_groups.py#L261-L284
rbgirshick/caffe-fast-rcnn
28a579eaf0668850705598b3075b8969f22226d9
scripts/cpp_lint.py
python
ProcessFile
(filename, vlevel, extra_check_functions=[])
Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error
Does google-lint on a single file.
[ "Does", "google", "-", "lint", "on", "a", "single", "file", "." ]
def ProcessFile(filename, vlevel, extra_check_functions=[]): """Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ _SetVerboseLevel(vlevel) try: # Support the UNIX convention of using "-" for stdin. Note that # we are not opening the file with universal newline support # (which codecs doesn't support anyway), so the resulting lines do # contain trailing '\r' characters if we are reading a file that # has CRLF endings. # If after the split a trailing '\r' is present, it is removed # below. If it is not expected to be present (i.e. os.linesep != # '\r\n' as in Windows), a warning is issued below if this file # is processed. if filename == '-': lines = codecs.StreamReaderWriter(sys.stdin, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace').read().split('\n') else: lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n') carriage_return_found = False # Remove trailing '\r'. for linenum in range(len(lines)): if lines[linenum].endswith('\r'): lines[linenum] = lines[linenum].rstrip('\r') carriage_return_found = True except IOError: sys.stderr.write( "Skipping input '%s': Can't open for reading\n" % filename) return # Note, if no dot is found, this will give the entire filename as the ext. file_extension = filename[filename.rfind('.') + 1:] # When reading from stdin, the extension is unknown, so no cpplint tests # should rely on the extension. if filename != '-' and file_extension not in _valid_extensions: sys.stderr.write('Ignoring %s; not a valid file name ' '(%s)\n' % (filename, ', '.join(_valid_extensions))) else: ProcessFileData(filename, file_extension, lines, Error, extra_check_functions) if carriage_return_found and os.linesep != '\r\n': # Use 0 for linenum since outputting only one error for potentially # several lines. Error(filename, 0, 'whitespace/newline', 1, 'One or more unexpected \\r (^M) found;' 'better to use only a \\n') sys.stderr.write('Done processing %s\n' % filename)
[ "def", "ProcessFile", "(", "filename", ",", "vlevel", ",", "extra_check_functions", "=", "[", "]", ")", ":", "_SetVerboseLevel", "(", "vlevel", ")", "try", ":", "# Support the UNIX convention of using \"-\" for stdin. Note that", "# we are not opening the file with universal...
https://github.com/rbgirshick/caffe-fast-rcnn/blob/28a579eaf0668850705598b3075b8969f22226d9/scripts/cpp_lint.py#L4689-L4754
BSVino/DoubleAction
c550b168a3e919926c198c30240f506538b92e75
mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/containers.py
python
BaseContainer.__init__
(self, message_listener)
Args: message_listener: A MessageListener implementation. The RepeatedScalarFieldContainer will call this object's Modified() method when it is modified.
Args: message_listener: A MessageListener implementation. The RepeatedScalarFieldContainer will call this object's Modified() method when it is modified.
[ "Args", ":", "message_listener", ":", "A", "MessageListener", "implementation", ".", "The", "RepeatedScalarFieldContainer", "will", "call", "this", "object", "s", "Modified", "()", "method", "when", "it", "is", "modified", "." ]
def __init__(self, message_listener): """ Args: message_listener: A MessageListener implementation. The RepeatedScalarFieldContainer will call this object's Modified() method when it is modified. """ self._message_listener = message_listener self._values = []
[ "def", "__init__", "(", "self", ",", "message_listener", ")", ":", "self", ".", "_message_listener", "=", "message_listener", "self", ".", "_values", "=", "[", "]" ]
https://github.com/BSVino/DoubleAction/blob/c550b168a3e919926c198c30240f506538b92e75/mp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/internal/containers.py#L52-L60
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/sans/command_interface/command_interface_state_director.py
python
CommandInterfaceStateDirector._get_data_commands
(self)
return data_commands
Grabs and removes the data commands from the command queue. @return: a list of data commands
Grabs and removes the data commands from the command queue.
[ "Grabs", "and", "removes", "the", "data", "commands", "from", "the", "command", "queue", "." ]
def _get_data_commands(self): """ Grabs and removes the data commands from the command queue. @return: a list of data commands """ # Grab the data commands data_commands = [element for element in self._commands if isinstance(element, DataCommand)] return data_commands
[ "def", "_get_data_commands", "(", "self", ")", ":", "# Grab the data commands", "data_commands", "=", "[", "element", "for", "element", "in", "self", ".", "_commands", "if", "isinstance", "(", "element", ",", "DataCommand", ")", "]", "return", "data_commands" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/sans/command_interface/command_interface_state_director.py#L198-L206
H-uru/Plasma
c2140ea046e82e9c199e257a7f2e7edb42602871
Scripts/Python/xAvatarCustomization.py
python
xAvatarCustomization.IMorphOneItem
(self,knobID,itemName)
Morph a specific item
Morph a specific item
[ "Morph", "a", "specific", "item" ]
def IMorphOneItem(self,knobID,itemName): "Morph a specific item" global TheCloset if knobID < kMorphSliderOffset or knobID >= kMorphSliderOffset+kNumberOfMorphs: return morphKnob = ptGUIControlValue(AvCustGUI.dialog.getControlFromTag(knobID)) morphVal = self.ISliderToMorph(morphKnob.getValue()) avatar = PtGetLocalAvatar() item = TheCloset.getItemByName(itemName) if item == None: return gender = avatar.avatar.getAvatarClothingGroup() #save state if gender == kFemaleClothingGroup: avatar.avatar.setMorph("FFace",knobID-kMorphSliderOffset,morphVal) else: avatar.avatar.setMorph("MFace",knobID-kMorphSliderOffset,morphVal)
[ "def", "IMorphOneItem", "(", "self", ",", "knobID", ",", "itemName", ")", ":", "global", "TheCloset", "if", "knobID", "<", "kMorphSliderOffset", "or", "knobID", ">=", "kMorphSliderOffset", "+", "kNumberOfMorphs", ":", "return", "morphKnob", "=", "ptGUIControlValue...
https://github.com/H-uru/Plasma/blob/c2140ea046e82e9c199e257a7f2e7edb42602871/Scripts/Python/xAvatarCustomization.py#L1614-L1632
kungfu-origin/kungfu
90c84b2b590855654cb9a6395ed050e0f7763512
core/deps/SQLiteCpp-2.3.0/cpplint.py
python
FindNextMultiLineCommentEnd
(lines, lineix)
return len(lines)
We are inside a comment, find the end marker.
We are inside a comment, find the end marker.
[ "We", "are", "inside", "a", "comment", "find", "the", "end", "marker", "." ]
def FindNextMultiLineCommentEnd(lines, lineix): """We are inside a comment, find the end marker.""" while lineix < len(lines): if lines[lineix].strip().endswith('*/'): return lineix lineix += 1 return len(lines)
[ "def", "FindNextMultiLineCommentEnd", "(", "lines", ",", "lineix", ")", ":", "while", "lineix", "<", "len", "(", "lines", ")", ":", "if", "lines", "[", "lineix", "]", ".", "strip", "(", ")", ".", "endswith", "(", "'*/'", ")", ":", "return", "lineix", ...
https://github.com/kungfu-origin/kungfu/blob/90c84b2b590855654cb9a6395ed050e0f7763512/core/deps/SQLiteCpp-2.3.0/cpplint.py#L1138-L1144
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/mailbox.py
python
Babyl.__init__
(self, path, factory=None, create=True)
Initialize a Babyl mailbox.
Initialize a Babyl mailbox.
[ "Initialize", "a", "Babyl", "mailbox", "." ]
def __init__(self, path, factory=None, create=True): """Initialize a Babyl mailbox.""" _singlefileMailbox.__init__(self, path, factory, create) self._labels = {}
[ "def", "__init__", "(", "self", ",", "path", ",", "factory", "=", "None", ",", "create", "=", "True", ")", ":", "_singlefileMailbox", ".", "__init__", "(", "self", ",", "path", ",", "factory", ",", "create", ")", "self", ".", "_labels", "=", "{", "}"...
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/mailbox.py#L1122-L1125
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/tools/inspector_protocol/jinja2/environment.py
python
Template.is_up_to_date
(self)
return self._uptodate()
If this variable is `False` there is a newer version available.
If this variable is `False` there is a newer version available.
[ "If", "this", "variable", "is", "False", "there", "is", "a", "newer", "version", "available", "." ]
def is_up_to_date(self): """If this variable is `False` there is a newer version available.""" if self._uptodate is None: return True return self._uptodate()
[ "def", "is_up_to_date", "(", "self", ")", ":", "if", "self", ".", "_uptodate", "is", "None", ":", "return", "True", "return", "self", ".", "_uptodate", "(", ")" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/tools/inspector_protocol/jinja2/environment.py#L1118-L1122
GoSSIP-SJTU/TripleDoggy
03648d6b19c812504b14e8b98c8c7b3f443f4e54
tools/clang/bindings/python/clang/cindex.py
python
CursorKind.is_reference
(self)
return conf.lib.clang_isReference(self)
Test if this is a reference kind.
Test if this is a reference kind.
[ "Test", "if", "this", "is", "a", "reference", "kind", "." ]
def is_reference(self): """Test if this is a reference kind.""" return conf.lib.clang_isReference(self)
[ "def", "is_reference", "(", "self", ")", ":", "return", "conf", ".", "lib", ".", "clang_isReference", "(", "self", ")" ]
https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/tools/clang/bindings/python/clang/cindex.py#L661-L663
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/codecs.py
python
IncrementalDecoder.setstate
(self, state)
Set the current state of the decoder. state must have been returned by getstate(). The effect of setstate((b"", 0)) must be equivalent to reset().
Set the current state of the decoder.
[ "Set", "the", "current", "state", "of", "the", "decoder", "." ]
def setstate(self, state): """ Set the current state of the decoder. state must have been returned by getstate(). The effect of setstate((b"", 0)) must be equivalent to reset(). """
[ "def", "setstate", "(", "self", ",", "state", ")", ":" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/codecs.py#L288-L294
PaddlePaddle/Paddle
1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c
python/paddle/distributed/ps/utils/public.py
python
find_heter_ops
(program, default_device="cpu")
return origin_porgram, heter_ops, default_ops, program_block_ops
re-place sum op to fix bug for union forward backward op
re-place sum op to fix bug for union forward backward op
[ "re", "-", "place", "sum", "op", "to", "fix", "bug", "for", "union", "forward", "backward", "op" ]
def find_heter_ops(program, default_device="cpu"): if default_device not in DEVICE_LIST: raise ValueError("Given device {} is not in device list {}".format( default_device, DEVICE_LIST)) def _is_heter_op(op, current_heter_device, default_device="cpu"): heter_devices = list(DEVICE_LIST) heter_devices.remove(default_device) op_device = op.attr("op_device") op_type = op.type if op_device in heter_devices: return True elif op_type in COMMUNICATE_OPS_TYPE and current_heter_device != default_device: # for distributed communciate ops: send & recv & barrier etc. # Todo: need update this method #op._set_attr('op_device', current_heter_device) return True elif op_device == None or op_device == default_device: op._set_attr('op_device', default_device) return False return False def _is_same_device(op, pre_device, default_device="cpu"): op_device = op.attr("op_device") if op_device == pre_device: return True if pre_device == default_device: return True return False def _append_heter_op(op, current_heter_block_ops, heter_ops): op_device = op.attr("op_device") if op_device not in heter_ops: heter_ops[op_device] = {} current_heter_block_ops.append(op) origin_porgram = program.clone() block = program.global_block() ''' re-place sum op to fix bug for union forward backward op ''' var2idx = {} op_list = list(block.ops) op_size = len(op_list) for i in range(op_size - 1, -1, -1): op_list = list(block.ops) op = op_list[i] if "_grad" in op.type: forward_op_type = op.type.split("_grad")[0] if forward_op_type in SPARSE_OP_TYPE_DICT.keys() \ and op.attr('remote_prefetch') is True: param_name = op.input(SPARSE_OP_TYPE_DICT[forward_op_type])[0] if param_name in var2idx: ## insert sum op & remove sum op from var2idx and origin place op_list = list(block.ops) sum_op = op_list[var2idx[param_name]] sum_op_inputs = { sum_op.input_names[0]: [ block.vars[input] for input in sum_op.input_arg_names ] } sum_op_outputs = { sum_op.output_names[0]: [ block.vars[output] for output in sum_op.output_arg_names ] } block._insert_op( index=i + 1, type=sum_op.type, inputs=sum_op_inputs, outputs=sum_op_outputs, attrs=sum_op.all_attrs()) block._remove_op(var2idx[param_name] + 1) var2idx.pop(param_name) for var_ in var2idx: var2idx[var_] += 1 elif forward_op_type == "elementwise_mul": """ get output varname of pre op """ output_vars_no_grad = [] for key in op.output_names: for varname in op.output(key): if varname == "@EMPTY@": continue if "lod_tensor_blocking_queue" in varname: continue output_vars_no_grad.append(varname.split("@GRAD")[0]) for no_grad_var in output_vars_no_grad: if no_grad_var in var2idx: """ insert sum op & remove sum op from var2idx and origin place """ op_list = list(block.ops) sum_op = op_list[var2idx[no_grad_var]] sum_op_inputs = { sum_op.input_names[0]: [ block.vars[input] for input in sum_op.input_arg_names ] } sum_op_outputs = { sum_op.output_names[0]: [ block.vars[output] for output in sum_op.output_arg_names ] } block._insert_op( index=i + 1, type=sum_op.type, inputs=sum_op_inputs, outputs=sum_op_outputs, attrs=sum_op.all_attrs()) block._remove_op(var2idx[no_grad_var] + 1) var2idx.pop(no_grad_var) for var_ in var2idx: var2idx[var_] += 1 else: if op.type == "sum": var = op.output("Out")[0] if "@GRAD" in var: origin_var = var.split("@GRAD")[0] pre_op = op_list[i - 1] if "_grad" in pre_op.type: forward_op_type = pre_op.type.split("_grad")[0] if forward_op_type in SPARSE_OP_TYPE_DICT.keys() \ and pre_op.attr('remote_prefetch') is True: param_name = pre_op.input(SPARSE_OP_TYPE_DICT[ forward_op_type])[0] if param_name == origin_var and op.attr( "op_device") == pre_op.attr("op_device"): continue else: var2idx[origin_var] = i elif forward_op_type == "elementwise_mul": output_vars = [] for key in pre_op.output_names: for varname in pre_op.output(key): if varname == "@EMPTY@": continue if "lod_tensor_blocking_queue" in varname: continue output_vars.append(varname) input_vars = [] for key in op.input_names: for varname in op.input(key): if varname == "@EMPTY@": continue if "lod_tensor_blocking_queue" in varname: continue input_vars.append(varname) is_match = False for varname in output_vars: if varname in input_vars: is_match = True break if is_match: continue else: var2idx[origin_var] = i else: var2idx[origin_var] = i origin_porgram = program.clone() block = program.global_block() program_block_ops = [] default_ops = {default_device: {}} heter_ops = {} block_index = 0 current_heter_block_ops = [] current_default_block_ops = [] current_heter_device = default_device is_heter = False for op in block.ops: if _is_heter_op(op, current_heter_device, default_device): # for gpu/xpu-op is_heter = True # for cpu-op block append if len(current_default_block_ops) > 1: default_ops[default_device][ block_index] = current_default_block_ops program_block_ops.append(current_default_block_ops) current_default_block_ops = [] block_index += 1 if _is_same_device(op, current_heter_device, default_device): # for gpu-op, gpu-op -> gpu-op,... current_heter_device = op.attr("op_device") _append_heter_op(op, current_heter_block_ops, heter_ops) else: # for gpu-op -> xpu-op, ... op_device = current_heter_block_ops[0].attr("op_device") heter_ops[op_device][block_index] = current_heter_block_ops program_block_ops.append(current_heter_block_ops) block_index += 1 current_heter_block_ops = [] current_heter_device = op.attr("op_device") _append_heter_op(op, current_heter_block_ops, heter_ops) elif is_heter: # for gpu/xpu-op -> cpu-op op_device = current_heter_block_ops[0].attr("op_device") heter_ops[op_device][block_index] = current_heter_block_ops program_block_ops.append(current_heter_block_ops) block_index += 1 current_heter_block_ops = [] current_heter_device = default_device is_heter = False current_default_block_ops.append(op) else: # for cpu-op current_default_block_ops.append(op) if current_default_block_ops != []: default_ops[default_device][block_index] = current_default_block_ops program_block_ops.append(current_default_block_ops) if current_heter_block_ops != []: op_device = current_heter_block_ops[0].attr("op_device") heter_ops[op_device][block_index] = current_heter_block_ops program_block_ops.append(current_heter_block_ops) if len(heter_ops) == 0: warnings.warn( "No heterogeneous OP was found in your program , " " please using fluid.device_guard() to run OPs on different device.") total_heter_ops = 0 heter_blocks = 0 for device in heter_ops.keys(): heter_block_dict = heter_ops[device] heter_blocks += len(heter_block_dict) for _, heter_block in heter_block_dict.items(): total_heter_ops += len(heter_block) print( "There are {} OPs in your main_program, and contains {} heter-OPs which is made up of {} heter-blocks.". format(len(block.ops), total_heter_ops, heter_blocks)) return origin_porgram, heter_ops, default_ops, program_block_ops
[ "def", "find_heter_ops", "(", "program", ",", "default_device", "=", "\"cpu\"", ")", ":", "if", "default_device", "not", "in", "DEVICE_LIST", ":", "raise", "ValueError", "(", "\"Given device {} is not in device list {}\"", ".", "format", "(", "default_device", ",", ...
https://github.com/PaddlePaddle/Paddle/blob/1252f4bb3e574df80aa6d18c7ddae1b3a90bd81c/python/paddle/distributed/ps/utils/public.py#L331-L577
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/unicode.py
python
unicode_partition
(data, sep)
return impl
Implements str.partition()
Implements str.partition()
[ "Implements", "str", ".", "partition", "()" ]
def unicode_partition(data, sep): """Implements str.partition()""" thety = sep # if the type is omitted, the concrete type is the value if isinstance(sep, types.Omitted): thety = sep.value # if the type is optional, the concrete type is the captured type elif isinstance(sep, types.Optional): thety = sep.type accepted = (types.UnicodeType, types.UnicodeCharSeq) if thety is not None and not isinstance(thety, accepted): msg = '"{}" must be {}, not {}'.format('sep', accepted, sep) raise TypingError(msg) def impl(data, sep): # https://github.com/python/cpython/blob/1d4b6ba19466aba0eb91c4ba01ba509acf18c723/Objects/stringlib/partition.h#L7-L60 # noqa: E501 empty_str = _empty_string(data._kind, 0, data._is_ascii) sep_length = len(sep) if data._kind < sep._kind or len(data) < sep_length: return data, empty_str, empty_str if sep_length == 0: raise ValueError('empty separator') pos = data.find(sep) if pos < 0: return data, empty_str, empty_str return data[0:pos], sep, data[pos + sep_length:len(data)] return impl
[ "def", "unicode_partition", "(", "data", ",", "sep", ")", ":", "thety", "=", "sep", "# if the type is omitted, the concrete type is the value", "if", "isinstance", "(", "sep", ",", "types", ".", "Omitted", ")", ":", "thety", "=", "sep", ".", "value", "# if the t...
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/unicode.py#L671-L702
SFTtech/openage
d6a08c53c48dc1e157807471df92197f6ca9e04d
openage/log/__init__.py
python
verbosity_to_level
(verbosity)
return levels[clamp(-verbosity + 3, 0, len(levels) - 1)]
Translates an integer verbosity to a log level.
Translates an integer verbosity to a log level.
[ "Translates", "an", "integer", "verbosity", "to", "a", "log", "level", "." ]
def verbosity_to_level(verbosity): """ Translates an integer verbosity to a log level. """ levels = [logging.getLevelName("MIN"), logging.getLevelName("SPAM"), logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL, logging.getLevelName("MAX")] # return INFO when verbosity is 0 return levels[clamp(-verbosity + 3, 0, len(levels) - 1)]
[ "def", "verbosity_to_level", "(", "verbosity", ")", ":", "levels", "=", "[", "logging", ".", "getLevelName", "(", "\"MIN\"", ")", ",", "logging", ".", "getLevelName", "(", "\"SPAM\"", ")", ",", "logging", ".", "DEBUG", ",", "logging", ".", "INFO", ",", "...
https://github.com/SFTtech/openage/blob/d6a08c53c48dc1e157807471df92197f6ca9e04d/openage/log/__init__.py#L129-L142
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
example/ssd/dataset/pascal_voc.py
python
PascalVoc._get_imsize
(self, im_name)
return (img.shape[0], img.shape[1])
get image size info Returns: ---------- tuple of (height, width)
get image size info Returns: ---------- tuple of (height, width)
[ "get", "image", "size", "info", "Returns", ":", "----------", "tuple", "of", "(", "height", "width", ")" ]
def _get_imsize(self, im_name): """ get image size info Returns: ---------- tuple of (height, width) """ img = cv2.imread(im_name) return (img.shape[0], img.shape[1])
[ "def", "_get_imsize", "(", "self", ",", "im_name", ")", ":", "img", "=", "cv2", ".", "imread", "(", "im_name", ")", "return", "(", "img", ".", "shape", "[", "0", "]", ",", "img", ".", "shape", "[", "1", "]", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/example/ssd/dataset/pascal_voc.py#L278-L286
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/boost/boost_1_68_0/tools/litre/cplusplus.py
python
CPlusPlusTranslator._execute
(self, code)
Override of litre._execute; sets up variable context before evaluating code
Override of litre._execute; sets up variable context before evaluating code
[ "Override", "of", "litre", ".", "_execute", ";", "sets", "up", "variable", "context", "before", "evaluating", "code" ]
def _execute(self, code): """Override of litre._execute; sets up variable context before evaluating code """ self.globals['example'] = self.example eval(code, self.globals)
[ "def", "_execute", "(", "self", ",", "code", ")", ":", "self", ".", "globals", "[", "'example'", "]", "=", "self", ".", "example", "eval", "(", "code", ",", "self", ".", "globals", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/boost/boost_1_68_0/tools/litre/cplusplus.py#L320-L325