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
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py
python
xmlDoc.copyDoc
(self, recursive)
return __tmp
Do a copy of the document info. If recursive, the content tree will be copied too as well as DTD, namespaces and entities.
Do a copy of the document info. If recursive, the content tree will be copied too as well as DTD, namespaces and entities.
[ "Do", "a", "copy", "of", "the", "document", "info", ".", "If", "recursive", "the", "content", "tree", "will", "be", "copied", "too", "as", "well", "as", "DTD", "namespaces", "and", "entities", "." ]
def copyDoc(self, recursive): """Do a copy of the document info. If recursive, the content tree will be copied too as well as DTD, namespaces and entities. """ ret = libxml2mod.xmlCopyDoc(self._o, recursive) if ret is None:raise treeError('xmlCopyDoc() failed') __tmp = xmlDoc(_obj=ret) return __tmp
[ "def", "copyDoc", "(", "self", ",", "recursive", ")", ":", "ret", "=", "libxml2mod", ".", "xmlCopyDoc", "(", "self", ".", "_o", ",", "recursive", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'xmlCopyDoc() failed'", ")", "__tmp", "=", "xmlDoc", "(", "_obj", "=", "ret", ")", "return", "__tmp" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/libs/libxml2-2.9.4/python/libxml2.py#L4227-L4234
mhammond/pywin32
44afd86ba8485194df93234639243252deeb40d5
win32/Lib/regutil.py
python
UnregisterModule
(modName)
Unregister an explicit module in the registry. modName -- The name of the module, as used by import.
Unregister an explicit module in the registry.
[ "Unregister", "an", "explicit", "module", "in", "the", "registry", "." ]
def UnregisterModule(modName): """Unregister an explicit module in the registry. modName -- The name of the module, as used by import. """ try: win32api.RegDeleteKey( GetRootKey(), BuildDefaultPythonKey() + "\\Modules\\%s" % modName ) except win32api.error as exc: import winerror if exc.winerror != winerror.ERROR_FILE_NOT_FOUND: raise
[ "def", "UnregisterModule", "(", "modName", ")", ":", "try", ":", "win32api", ".", "RegDeleteKey", "(", "GetRootKey", "(", ")", ",", "BuildDefaultPythonKey", "(", ")", "+", "\"\\\\Modules\\\\%s\"", "%", "modName", ")", "except", "win32api", ".", "error", "as", "exc", ":", "import", "winerror", "if", "exc", ".", "winerror", "!=", "winerror", ".", "ERROR_FILE_NOT_FOUND", ":", "raise" ]
https://github.com/mhammond/pywin32/blob/44afd86ba8485194df93234639243252deeb40d5/win32/Lib/regutil.py#L163-L176
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/protobuf/py2/google/protobuf/internal/_parameterized.py
python
TestCase.id
(self)
return '%s.%s%s' % (_StrClass(self.__class__), self._OriginalName(), self._id_suffix.get(self._testMethodName, ''))
Returns the descriptive ID of the test. This is used internally by the unittesting framework to get a name for the test to be used in reports. Returns: The test id.
Returns the descriptive ID of the test.
[ "Returns", "the", "descriptive", "ID", "of", "the", "test", "." ]
def id(self): # pylint: disable=invalid-name """Returns the descriptive ID of the test. This is used internally by the unittesting framework to get a name for the test to be used in reports. Returns: The test id. """ return '%s.%s%s' % (_StrClass(self.__class__), self._OriginalName(), self._id_suffix.get(self._testMethodName, ''))
[ "def", "id", "(", "self", ")", ":", "# pylint: disable=invalid-name", "return", "'%s.%s%s'", "%", "(", "_StrClass", "(", "self", ".", "__class__", ")", ",", "self", ".", "_OriginalName", "(", ")", ",", "self", ".", "_id_suffix", ".", "get", "(", "self", ".", "_testMethodName", ",", "''", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/protobuf/py2/google/protobuf/internal/_parameterized.py#L404-L415
panda3d/panda3d
833ad89ebad58395d0af0b7ec08538e5e4308265
direct/src/actor/Actor.py
python
Actor.getPartBundle
(self, partName, lodName="lodRoot")
return None
Find the named part in the optional named lod and return its associated PartBundle, or return None if not present
Find the named part in the optional named lod and return its associated PartBundle, or return None if not present
[ "Find", "the", "named", "part", "in", "the", "optional", "named", "lod", "and", "return", "its", "associated", "PartBundle", "or", "return", "None", "if", "not", "present" ]
def getPartBundle(self, partName, lodName="lodRoot"): """ Find the named part in the optional named lod and return its associated PartBundle, or return None if not present """ partBundleDict = self.__partBundleDict.get(lodName) if not partBundleDict: Actor.notify.warning("no lod named: %s" % (lodName)) return None subpartDef = self.__subpartDict.get(partName, Actor.SubpartDef(partName)) partDef = partBundleDict.get(subpartDef.truePartName) if partDef is not None: return partDef.getBundle() return None
[ "def", "getPartBundle", "(", "self", ",", "partName", ",", "lodName", "=", "\"lodRoot\"", ")", ":", "partBundleDict", "=", "self", ".", "__partBundleDict", ".", "get", "(", "lodName", ")", "if", "not", "partBundleDict", ":", "Actor", ".", "notify", ".", "warning", "(", "\"no lod named: %s\"", "%", "(", "lodName", ")", ")", "return", "None", "subpartDef", "=", "self", ".", "__subpartDict", ".", "get", "(", "partName", ",", "Actor", ".", "SubpartDef", "(", "partName", ")", ")", "partDef", "=", "partBundleDict", ".", "get", "(", "subpartDef", ".", "truePartName", ")", "if", "partDef", "is", "not", "None", ":", "return", "partDef", ".", "getBundle", "(", ")", "return", "None" ]
https://github.com/panda3d/panda3d/blob/833ad89ebad58395d0af0b7ec08538e5e4308265/direct/src/actor/Actor.py#L983-L996
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/decimal.py
python
Decimal.__hash__
(self)
return hash((self._sign, self._exp+len(self._int), self._int.rstrip('0')))
x.__hash__() <==> hash(x)
x.__hash__() <==> hash(x)
[ "x", ".", "__hash__", "()", "<", "==", ">", "hash", "(", "x", ")" ]
def __hash__(self): """x.__hash__() <==> hash(x)""" # Decimal integers must hash the same as the ints # # The hash of a nonspecial noninteger Decimal must depend only # on the value of that Decimal, and not on its representation. # For example: hash(Decimal('100E-1')) == hash(Decimal('10')). # Equality comparisons involving signaling nans can raise an # exception; since equality checks are implicitly and # unpredictably used when checking set and dict membership, we # prevent signaling nans from being used as set elements or # dict keys by making __hash__ raise an exception. if self._is_special: if self.is_snan(): raise TypeError('Cannot hash a signaling NaN value.') elif self.is_nan(): # 0 to match hash(float('nan')) return 0 else: # values chosen to match hash(float('inf')) and # hash(float('-inf')). if self._sign: return -271828 else: return 314159 # In Python 2.7, we're allowing comparisons (but not # arithmetic operations) between floats and Decimals; so if # a Decimal instance is exactly representable as a float then # its hash should match that of the float. self_as_float = float(self) if Decimal.from_float(self_as_float) == self: return hash(self_as_float) if self._isinteger(): op = _WorkRep(self.to_integral_value()) # to make computation feasible for Decimals with large # exponent, we use the fact that hash(n) == hash(m) for # any two nonzero integers n and m such that (i) n and m # have the same sign, and (ii) n is congruent to m modulo # 2**64-1. So we can replace hash((-1)**s*c*10**e) with # hash((-1)**s*c*pow(10, e, 2**64-1). return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1)) # The value of a nonzero nonspecial Decimal instance is # faithfully represented by the triple consisting of its sign, # its adjusted exponent, and its coefficient with trailing # zeros removed. return hash((self._sign, self._exp+len(self._int), self._int.rstrip('0')))
[ "def", "__hash__", "(", "self", ")", ":", "# Decimal integers must hash the same as the ints", "#", "# The hash of a nonspecial noninteger Decimal must depend only", "# on the value of that Decimal, and not on its representation.", "# For example: hash(Decimal('100E-1')) == hash(Decimal('10')).", "# Equality comparisons involving signaling nans can raise an", "# exception; since equality checks are implicitly and", "# unpredictably used when checking set and dict membership, we", "# prevent signaling nans from being used as set elements or", "# dict keys by making __hash__ raise an exception.", "if", "self", ".", "_is_special", ":", "if", "self", ".", "is_snan", "(", ")", ":", "raise", "TypeError", "(", "'Cannot hash a signaling NaN value.'", ")", "elif", "self", ".", "is_nan", "(", ")", ":", "# 0 to match hash(float('nan'))", "return", "0", "else", ":", "# values chosen to match hash(float('inf')) and", "# hash(float('-inf')).", "if", "self", ".", "_sign", ":", "return", "-", "271828", "else", ":", "return", "314159", "# In Python 2.7, we're allowing comparisons (but not", "# arithmetic operations) between floats and Decimals; so if", "# a Decimal instance is exactly representable as a float then", "# its hash should match that of the float.", "self_as_float", "=", "float", "(", "self", ")", "if", "Decimal", ".", "from_float", "(", "self_as_float", ")", "==", "self", ":", "return", "hash", "(", "self_as_float", ")", "if", "self", ".", "_isinteger", "(", ")", ":", "op", "=", "_WorkRep", "(", "self", ".", "to_integral_value", "(", ")", ")", "# to make computation feasible for Decimals with large", "# exponent, we use the fact that hash(n) == hash(m) for", "# any two nonzero integers n and m such that (i) n and m", "# have the same sign, and (ii) n is congruent to m modulo", "# 2**64-1. So we can replace hash((-1)**s*c*10**e) with", "# hash((-1)**s*c*pow(10, e, 2**64-1).", "return", "hash", "(", "(", "-", "1", ")", "**", "op", ".", "sign", "*", "op", ".", "int", "*", "pow", "(", "10", ",", "op", ".", "exp", ",", "2", "**", "64", "-", "1", ")", ")", "# The value of a nonzero nonspecial Decimal instance is", "# faithfully represented by the triple consisting of its sign,", "# its adjusted exponent, and its coefficient with trailing", "# zeros removed.", "return", "hash", "(", "(", "self", ".", "_sign", ",", "self", ".", "_exp", "+", "len", "(", "self", ".", "_int", ")", ",", "self", ".", "_int", ".", "rstrip", "(", "'0'", ")", ")", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/decimal.py#L935-L985
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/build/pymake/pymake/command.py
python
main
(args, env, cwd, cb)
Start a single makefile execution, given a command line, working directory, and environment. @param cb a callback to notify with an exit code when make execution is finished.
Start a single makefile execution, given a command line, working directory, and environment.
[ "Start", "a", "single", "makefile", "execution", "given", "a", "command", "line", "working", "directory", "and", "environment", "." ]
def main(args, env, cwd, cb): """ Start a single makefile execution, given a command line, working directory, and environment. @param cb a callback to notify with an exit code when make execution is finished. """ try: makelevel = int(env.get('MAKELEVEL', '0')) op = OptionParser() op.add_option('-f', '--file', '--makefile', action='append', dest='makefiles', default=[]) op.add_option('-d', action="store_true", dest="verbose", default=False) op.add_option('-k', '--keep-going', action="store_true", dest="keepgoing", default=False) op.add_option('--debug-log', dest="debuglog", default=None) op.add_option('-C', '--directory', dest="directory", default=None) op.add_option('-v', '--version', action="store_true", dest="printversion", default=False) op.add_option('-j', '--jobs', type="int", dest="jobcount", default=1) op.add_option('-w', '--print-directory', action="store_true", dest="printdir") op.add_option('--no-print-directory', action="store_false", dest="printdir", default=True) op.add_option('-s', '--silent', action="store_true", dest="silent", default=False) op.add_option('-n', '--just-print', '--dry-run', '--recon', action="store_true", dest="justprint", default=False) options, arguments1 = op.parse_args(parsemakeflags(env)) options, arguments2 = op.parse_args(args, values=options) op.destroy() arguments = arguments1 + arguments2 if options.printversion: _version() cb(0) return shortflags = [] longflags = [] if options.keepgoing: shortflags.append('k') if options.printdir: shortflags.append('w') if options.silent: shortflags.append('s') options.printdir = False if options.justprint: shortflags.append('n') loglevel = logging.WARNING if options.verbose: loglevel = logging.DEBUG shortflags.append('d') logkwargs = {} if options.debuglog: logkwargs['filename'] = options.debuglog longflags.append('--debug-log=%s' % options.debuglog) if options.directory is None: workdir = cwd else: workdir = util.normaljoin(cwd, options.directory) if options.jobcount != 1: longflags.append('-j%i' % (options.jobcount,)) makeflags = ''.join(shortflags) if len(longflags): makeflags += ' ' + ' '.join(longflags) logging.basicConfig(level=loglevel, **logkwargs) context = process.getcontext(options.jobcount) if options.printdir: print "make.py[%i]: Entering directory '%s'" % (makelevel, workdir) sys.stdout.flush() if len(options.makefiles) == 0: if os.path.exists(util.normaljoin(workdir, 'Makefile')): options.makefiles.append('Makefile') else: print "No makefile found" cb(2) return ostmts, targets, overrides = parserdata.parsecommandlineargs(arguments) _MakeContext(makeflags, makelevel, workdir, context, env, targets, options, ostmts, overrides, cb) except (util.MakeError), e: print e if options.printdir: print "make.py[%i]: Leaving directory '%s'" % (makelevel, workdir) sys.stdout.flush() cb(2) return
[ "def", "main", "(", "args", ",", "env", ",", "cwd", ",", "cb", ")", ":", "try", ":", "makelevel", "=", "int", "(", "env", ".", "get", "(", "'MAKELEVEL'", ",", "'0'", ")", ")", "op", "=", "OptionParser", "(", ")", "op", ".", "add_option", "(", "'-f'", ",", "'--file'", ",", "'--makefile'", ",", "action", "=", "'append'", ",", "dest", "=", "'makefiles'", ",", "default", "=", "[", "]", ")", "op", ".", "add_option", "(", "'-d'", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"verbose\"", ",", "default", "=", "False", ")", "op", ".", "add_option", "(", "'-k'", ",", "'--keep-going'", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"keepgoing\"", ",", "default", "=", "False", ")", "op", ".", "add_option", "(", "'--debug-log'", ",", "dest", "=", "\"debuglog\"", ",", "default", "=", "None", ")", "op", ".", "add_option", "(", "'-C'", ",", "'--directory'", ",", "dest", "=", "\"directory\"", ",", "default", "=", "None", ")", "op", ".", "add_option", "(", "'-v'", ",", "'--version'", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"printversion\"", ",", "default", "=", "False", ")", "op", ".", "add_option", "(", "'-j'", ",", "'--jobs'", ",", "type", "=", "\"int\"", ",", "dest", "=", "\"jobcount\"", ",", "default", "=", "1", ")", "op", ".", "add_option", "(", "'-w'", ",", "'--print-directory'", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"printdir\"", ")", "op", ".", "add_option", "(", "'--no-print-directory'", ",", "action", "=", "\"store_false\"", ",", "dest", "=", "\"printdir\"", ",", "default", "=", "True", ")", "op", ".", "add_option", "(", "'-s'", ",", "'--silent'", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"silent\"", ",", "default", "=", "False", ")", "op", ".", "add_option", "(", "'-n'", ",", "'--just-print'", ",", "'--dry-run'", ",", "'--recon'", ",", "action", "=", "\"store_true\"", ",", "dest", "=", "\"justprint\"", ",", "default", "=", "False", ")", "options", ",", "arguments1", "=", "op", ".", "parse_args", "(", "parsemakeflags", "(", "env", ")", ")", "options", ",", "arguments2", "=", "op", ".", "parse_args", "(", "args", ",", "values", "=", "options", ")", "op", ".", "destroy", "(", ")", "arguments", "=", "arguments1", "+", "arguments2", "if", "options", ".", "printversion", ":", "_version", "(", ")", "cb", "(", "0", ")", "return", "shortflags", "=", "[", "]", "longflags", "=", "[", "]", "if", "options", ".", "keepgoing", ":", "shortflags", ".", "append", "(", "'k'", ")", "if", "options", ".", "printdir", ":", "shortflags", ".", "append", "(", "'w'", ")", "if", "options", ".", "silent", ":", "shortflags", ".", "append", "(", "'s'", ")", "options", ".", "printdir", "=", "False", "if", "options", ".", "justprint", ":", "shortflags", ".", "append", "(", "'n'", ")", "loglevel", "=", "logging", ".", "WARNING", "if", "options", ".", "verbose", ":", "loglevel", "=", "logging", ".", "DEBUG", "shortflags", ".", "append", "(", "'d'", ")", "logkwargs", "=", "{", "}", "if", "options", ".", "debuglog", ":", "logkwargs", "[", "'filename'", "]", "=", "options", ".", "debuglog", "longflags", ".", "append", "(", "'--debug-log=%s'", "%", "options", ".", "debuglog", ")", "if", "options", ".", "directory", "is", "None", ":", "workdir", "=", "cwd", "else", ":", "workdir", "=", "util", ".", "normaljoin", "(", "cwd", ",", "options", ".", "directory", ")", "if", "options", ".", "jobcount", "!=", "1", ":", "longflags", ".", "append", "(", "'-j%i'", "%", "(", "options", ".", "jobcount", ",", ")", ")", "makeflags", "=", "''", ".", "join", "(", "shortflags", ")", "if", "len", "(", "longflags", ")", ":", "makeflags", "+=", "' '", "+", "' '", ".", "join", "(", "longflags", ")", "logging", ".", "basicConfig", "(", "level", "=", "loglevel", ",", "*", "*", "logkwargs", ")", "context", "=", "process", ".", "getcontext", "(", "options", ".", "jobcount", ")", "if", "options", ".", "printdir", ":", "print", "\"make.py[%i]: Entering directory '%s'\"", "%", "(", "makelevel", ",", "workdir", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "if", "len", "(", "options", ".", "makefiles", ")", "==", "0", ":", "if", "os", ".", "path", ".", "exists", "(", "util", ".", "normaljoin", "(", "workdir", ",", "'Makefile'", ")", ")", ":", "options", ".", "makefiles", ".", "append", "(", "'Makefile'", ")", "else", ":", "print", "\"No makefile found\"", "cb", "(", "2", ")", "return", "ostmts", ",", "targets", ",", "overrides", "=", "parserdata", ".", "parsecommandlineargs", "(", "arguments", ")", "_MakeContext", "(", "makeflags", ",", "makelevel", ",", "workdir", ",", "context", ",", "env", ",", "targets", ",", "options", ",", "ostmts", ",", "overrides", ",", "cb", ")", "except", "(", "util", ".", "MakeError", ")", ",", "e", ":", "print", "e", "if", "options", ".", "printdir", ":", "print", "\"make.py[%i]: Leaving directory '%s'\"", "%", "(", "makelevel", ",", "workdir", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "cb", "(", "2", ")", "return" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/build/pymake/pymake/command.py#L164-L278
hpi-xnor/BMXNet-v2
af2b1859eafc5c721b1397cef02f946aaf2ce20d
python/mxnet/executor_manager.py
python
DataParallelExecutorGroup.backward
(self)
Perform a backward pass on each executor.
Perform a backward pass on each executor.
[ "Perform", "a", "backward", "pass", "on", "each", "executor", "." ]
def backward(self): """Perform a backward pass on each executor.""" for texec in self.train_execs: texec.backward()
[ "def", "backward", "(", "self", ")", ":", "for", "texec", "in", "self", ".", "train_execs", ":", "texec", ".", "backward", "(", ")" ]
https://github.com/hpi-xnor/BMXNet-v2/blob/af2b1859eafc5c721b1397cef02f946aaf2ce20d/python/mxnet/executor_manager.py#L284-L287
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/contrib/graph_editor/select.py
python
filter_ts
(ops, positive_filter)
return ts
Get all the tensors which are input or output of an op in ops. Args: ops: an object convertible to a list of `tf.Operation`. positive_filter: a function deciding whether to keep a tensor or not. If `True`, all the tensors are returned. Returns: A list of `tf.Tensor`. Raises: TypeError: if ops cannot be converted to a list of `tf.Operation`.
Get all the tensors which are input or output of an op in ops.
[ "Get", "all", "the", "tensors", "which", "are", "input", "or", "output", "of", "an", "op", "in", "ops", "." ]
def filter_ts(ops, positive_filter): """Get all the tensors which are input or output of an op in ops. Args: ops: an object convertible to a list of `tf.Operation`. positive_filter: a function deciding whether to keep a tensor or not. If `True`, all the tensors are returned. Returns: A list of `tf.Tensor`. Raises: TypeError: if ops cannot be converted to a list of `tf.Operation`. """ ops = util.make_list_of_op(ops) ts = _get_input_ts(ops) util.concatenate_unique(ts, _get_output_ts(ops)) if positive_filter is not True: ts = [t for t in ts if positive_filter(t)] return ts
[ "def", "filter_ts", "(", "ops", ",", "positive_filter", ")", ":", "ops", "=", "util", ".", "make_list_of_op", "(", "ops", ")", "ts", "=", "_get_input_ts", "(", "ops", ")", "util", ".", "concatenate_unique", "(", "ts", ",", "_get_output_ts", "(", "ops", ")", ")", "if", "positive_filter", "is", "not", "True", ":", "ts", "=", "[", "t", "for", "t", "in", "ts", "if", "positive_filter", "(", "t", ")", "]", "return", "ts" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/contrib/graph_editor/select.py#L114-L131
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_core.py
python
FileSystem_FileNameToURL
(*args, **kwargs)
return _core_.FileSystem_FileNameToURL(*args, **kwargs)
FileSystem_FileNameToURL(String filename) -> String
FileSystem_FileNameToURL(String filename) -> String
[ "FileSystem_FileNameToURL", "(", "String", "filename", ")", "-", ">", "String" ]
def FileSystem_FileNameToURL(*args, **kwargs): """FileSystem_FileNameToURL(String filename) -> String""" return _core_.FileSystem_FileNameToURL(*args, **kwargs)
[ "def", "FileSystem_FileNameToURL", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "FileSystem_FileNameToURL", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_core.py#L2476-L2478
JaDogg/expressPython
960854d7f7ddfec959371cd32064c80095fb4448
ep_runner.py
python
quit
(*args, **kwargs)
Pseudo quit function
Pseudo quit function
[ "Pseudo", "quit", "function" ]
def quit(*args, **kwargs): """ Pseudo quit function """ pass
[ "def", "quit", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "pass" ]
https://github.com/JaDogg/expressPython/blob/960854d7f7ddfec959371cd32064c80095fb4448/ep_runner.py#L61-L65
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/_lib/_threadsafety.py
python
non_reentrant
(err_msg=None)
return decorator
Decorate a function with a threading lock and prevent reentrant calls.
Decorate a function with a threading lock and prevent reentrant calls.
[ "Decorate", "a", "function", "with", "a", "threading", "lock", "and", "prevent", "reentrant", "calls", "." ]
def non_reentrant(err_msg=None): """ Decorate a function with a threading lock and prevent reentrant calls. """ def decorator(func): msg = err_msg if msg is None: msg = "%s is not re-entrant" % func.__name__ lock = ReentrancyLock(msg) return lock.decorate(func) return decorator
[ "def", "non_reentrant", "(", "err_msg", "=", "None", ")", ":", "def", "decorator", "(", "func", ")", ":", "msg", "=", "err_msg", "if", "msg", "is", "None", ":", "msg", "=", "\"%s is not re-entrant\"", "%", "func", ".", "__name__", "lock", "=", "ReentrancyLock", "(", "msg", ")", "return", "lock", ".", "decorate", "(", "func", ")", "return", "decorator" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/_lib/_threadsafety.py#L50-L60
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/cookies.py
python
RequestsCookieJar.get
(self, name, default=None, domain=None, path=None)
Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. .. warning:: operation is O(n), not O(1).
Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains.
[ "Dict", "-", "like", "get", "()", "that", "also", "supports", "optional", "domain", "and", "path", "args", "in", "order", "to", "resolve", "naming", "collisions", "from", "using", "one", "cookie", "jar", "over", "multiple", "domains", "." ]
def get(self, name, default=None, domain=None, path=None): """Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. .. warning:: operation is O(n), not O(1).""" try: return self._find_no_duplicates(name, domain, path) except KeyError: return default
[ "def", "get", "(", "self", ",", "name", ",", "default", "=", "None", ",", "domain", "=", "None", ",", "path", "=", "None", ")", ":", "try", ":", "return", "self", ".", "_find_no_duplicates", "(", "name", ",", "domain", ",", "path", ")", "except", "KeyError", ":", "return", "default" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/requests/cookies.py#L177-L186
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/operator.py
python
isub
(a, b)
return a
Same as a -= b.
Same as a -= b.
[ "Same", "as", "a", "-", "=", "b", "." ]
def isub(a, b): "Same as a -= b." a -= b return a
[ "def", "isub", "(", "a", ",", "b", ")", ":", "a", "-=", "b", "return", "a" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/operator.py#L395-L398
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/grid.py
python
Grid.GetCellSize
(*args, **kwargs)
return _grid.Grid_GetCellSize(*args, **kwargs)
GetCellSize(int row, int col) -> (num_rows, num_cols)
GetCellSize(int row, int col) -> (num_rows, num_cols)
[ "GetCellSize", "(", "int", "row", "int", "col", ")", "-", ">", "(", "num_rows", "num_cols", ")" ]
def GetCellSize(*args, **kwargs): """GetCellSize(int row, int col) -> (num_rows, num_cols)""" return _grid.Grid_GetCellSize(*args, **kwargs)
[ "def", "GetCellSize", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_grid", ".", "Grid_GetCellSize", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/grid.py#L1810-L1812
rsocket/rsocket-cpp
45ed594ebd6701f40795c31ec922d784ec7fc921
build/fbcode_builder/getdeps.py
python
CachedProject.is_cacheable
(self)
return self.cache and self.m.shipit_project is None
We only cache third party projects
We only cache third party projects
[ "We", "only", "cache", "third", "party", "projects" ]
def is_cacheable(self): """We only cache third party projects""" return self.cache and self.m.shipit_project is None
[ "def", "is_cacheable", "(", "self", ")", ":", "return", "self", ".", "cache", "and", "self", ".", "m", ".", "shipit_project", "is", "None" ]
https://github.com/rsocket/rsocket-cpp/blob/45ed594ebd6701f40795c31ec922d784ec7fc921/build/fbcode_builder/getdeps.py#L237-L239
lmb-freiburg/ogn
974f72ef4bf840d6f6693d22d1843a79223e77ce
scripts/cpp_lint.py
python
CloseExpression
(clean_lines, linenum, pos)
return (line, clean_lines.NumLines(), -1)
If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum.
If input points to ( or { or [ or <, finds the position that closes it.
[ "If", "input", "points", "to", "(", "or", "{", "or", "[", "or", "<", "finds", "the", "position", "that", "closes", "it", "." ]
def CloseExpression(clean_lines, linenum, pos): """If input points to ( or { or [ or <, finds the position that closes it. If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the linenum/pos that correspond to the closing of the expression. Args: clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. pos: A position on the line. Returns: A tuple (line, linenum, pos) pointer *past* the closing brace, or (line, len(lines), -1) if we never find a close. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] startchar = line[pos] if startchar not in '({[<': return (line, clean_lines.NumLines(), -1) if startchar == '(': endchar = ')' if startchar == '[': endchar = ']' if startchar == '{': endchar = '}' if startchar == '<': endchar = '>' # Check first line (end_pos, num_open) = FindEndOfExpressionInLine( line, pos, 0, startchar, endchar) if end_pos > -1: return (line, linenum, end_pos) # Continue scanning forward while linenum < clean_lines.NumLines() - 1: linenum += 1 line = clean_lines.elided[linenum] (end_pos, num_open) = FindEndOfExpressionInLine( line, 0, num_open, startchar, endchar) if end_pos > -1: return (line, linenum, end_pos) # Did not find endchar before end of file, give up return (line, clean_lines.NumLines(), -1)
[ "def", "CloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "startchar", "=", "line", "[", "pos", "]", "if", "startchar", "not", "in", "'({[<'", ":", "return", "(", "line", ",", "clean_lines", ".", "NumLines", "(", ")", ",", "-", "1", ")", "if", "startchar", "==", "'('", ":", "endchar", "=", "')'", "if", "startchar", "==", "'['", ":", "endchar", "=", "']'", "if", "startchar", "==", "'{'", ":", "endchar", "=", "'}'", "if", "startchar", "==", "'<'", ":", "endchar", "=", "'>'", "# Check first line", "(", "end_pos", ",", "num_open", ")", "=", "FindEndOfExpressionInLine", "(", "line", ",", "pos", ",", "0", ",", "startchar", ",", "endchar", ")", "if", "end_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "end_pos", ")", "# Continue scanning forward", "while", "linenum", "<", "clean_lines", ".", "NumLines", "(", ")", "-", "1", ":", "linenum", "+=", "1", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "(", "end_pos", ",", "num_open", ")", "=", "FindEndOfExpressionInLine", "(", "line", ",", "0", ",", "num_open", ",", "startchar", ",", "endchar", ")", "if", "end_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "end_pos", ")", "# Did not find endchar before end of file, give up", "return", "(", "line", ",", "clean_lines", ".", "NumLines", "(", ")", ",", "-", "1", ")" ]
https://github.com/lmb-freiburg/ogn/blob/974f72ef4bf840d6f6693d22d1843a79223e77ce/scripts/cpp_lint.py#L1254-L1297
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
gr-digital/python/digital/qam_constellations.py
python
sd_qam_16_0x1_0_1_2_3
(x, Es=1)
return [b3, b2, b1, b0]
| Soft bit LUT generator for constellation: | | 0011 0111 | 1111 1011 | | 0010 0110 | 1110 1010 | ----------------------- | 0000 0100 | 1100 1000 | | 0001 0101 | 1101 1001
| Soft bit LUT generator for constellation: | | 0011 0111 | 1111 1011 | | 0010 0110 | 1110 1010 | ----------------------- | 0000 0100 | 1100 1000 | | 0001 0101 | 1101 1001
[ "|", "Soft", "bit", "LUT", "generator", "for", "constellation", ":", "|", "|", "0011", "0111", "|", "1111", "1011", "|", "|", "0010", "0110", "|", "1110", "1010", "|", "-----------------------", "|", "0000", "0100", "|", "1100", "1000", "|", "|", "0001", "0101", "|", "1101", "1001" ]
def sd_qam_16_0x1_0_1_2_3(x, Es=1): ''' | Soft bit LUT generator for constellation: | | 0011 0111 | 1111 1011 | | 0010 0110 | 1110 1010 | ----------------------- | 0000 0100 | 1100 1000 | | 0001 0101 | 1101 1001 ''' x_re = 3 * x.real x_im = 3 * x.imag if x_re < -2: b3 = 2 * (x_re + 1) elif x_re < 2: b3 = x_re else: b3 = 2 * (x_re - 1) if x_im < -2: b1 = 2 * (x_im + 1) elif x_im < 2: b1 = x_im else: b1 = 2 * (x_im - 1) b2 = -abs(x_re) + 2 b0 = +abs(x_im) - 2 return [b3, b2, b1, b0]
[ "def", "sd_qam_16_0x1_0_1_2_3", "(", "x", ",", "Es", "=", "1", ")", ":", "x_re", "=", "3", "*", "x", ".", "real", "x_im", "=", "3", "*", "x", ".", "imag", "if", "x_re", "<", "-", "2", ":", "b3", "=", "2", "*", "(", "x_re", "+", "1", ")", "elif", "x_re", "<", "2", ":", "b3", "=", "x_re", "else", ":", "b3", "=", "2", "*", "(", "x_re", "-", "1", ")", "if", "x_im", "<", "-", "2", ":", "b1", "=", "2", "*", "(", "x_im", "+", "1", ")", "elif", "x_im", "<", "2", ":", "b1", "=", "x_im", "else", ":", "b1", "=", "2", "*", "(", "x_im", "-", "1", ")", "b2", "=", "-", "abs", "(", "x_re", ")", "+", "2", "b0", "=", "+", "abs", "(", "x_im", ")", "-", "2", "return", "[", "b3", ",", "b2", ",", "b1", ",", "b0", "]" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/gr-digital/python/digital/qam_constellations.py#L291-L323
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/dataset/vision/py_transforms_util.py
python
to_pil
(img)
return img
Convert the input image to PIL format. Args: img: Image to be converted. Returns: img (PIL image), Converted image.
Convert the input image to PIL format.
[ "Convert", "the", "input", "image", "to", "PIL", "format", "." ]
def to_pil(img): """ Convert the input image to PIL format. Args: img: Image to be converted. Returns: img (PIL image), Converted image. """ if not is_pil(img): if not isinstance(img, np.ndarray): raise TypeError("The input of ToPIL should be ndarray. Got {}".format(type(img))) return Image.fromarray(img) return img
[ "def", "to_pil", "(", "img", ")", ":", "if", "not", "is_pil", "(", "img", ")", ":", "if", "not", "isinstance", "(", "img", ",", "np", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "\"The input of ToPIL should be ndarray. Got {}\"", ".", "format", "(", "type", "(", "img", ")", ")", ")", "return", "Image", ".", "fromarray", "(", "img", ")", "return", "img" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/dataset/vision/py_transforms_util.py#L158-L172
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/ircbot.py
python
SingleServerIRCBot.disconnect
(self, msg="I'll be back!")
Disconnect the bot. The bot will try to reconnect after a while. Arguments: msg -- Quit message.
Disconnect the bot.
[ "Disconnect", "the", "bot", "." ]
def disconnect(self, msg="I'll be back!"): """Disconnect the bot. The bot will try to reconnect after a while. Arguments: msg -- Quit message. """ self.connection.disconnect(msg)
[ "def", "disconnect", "(", "self", ",", "msg", "=", "\"I'll be back!\"", ")", ":", "self", ".", "connection", ".", "disconnect", "(", "msg", ")" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Tools/Scripts/webkitpy/thirdparty/irc/ircbot.py#L195-L204
trailofbits/llvm-sanitizer-tutorial
d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99
llvm/tools/sancov/coverage-report-server.py
python
SymcovData.compute_filecoverage
(self)
return result
Build a filename->pct coverage.
Build a filename->pct coverage.
[ "Build", "a", "filename", "-", ">", "pct", "coverage", "." ]
def compute_filecoverage(self): """Build a filename->pct coverage.""" result = dict() for filename, fns in self.point_symbol_info.items(): file_points = [] for fn, points in fns.items(): file_points.extend(points.keys()) covered_points = self.covered_points & set(file_points) result[filename] = int(math.ceil( len(covered_points) * 100 / len(file_points))) return result
[ "def", "compute_filecoverage", "(", "self", ")", ":", "result", "=", "dict", "(", ")", "for", "filename", ",", "fns", "in", "self", ".", "point_symbol_info", ".", "items", "(", ")", ":", "file_points", "=", "[", "]", "for", "fn", ",", "points", "in", "fns", ".", "items", "(", ")", ":", "file_points", ".", "extend", "(", "points", ".", "keys", "(", ")", ")", "covered_points", "=", "self", ".", "covered_points", "&", "set", "(", "file_points", ")", "result", "[", "filename", "]", "=", "int", "(", "math", ".", "ceil", "(", "len", "(", "covered_points", ")", "*", "100", "/", "len", "(", "file_points", ")", ")", ")", "return", "result" ]
https://github.com/trailofbits/llvm-sanitizer-tutorial/blob/d29dfeec7f51fbf234fd0080f28f2b30cd0b6e99/llvm/tools/sancov/coverage-report-server.py#L107-L117
esa/pagmo
80281d549c8f1b470e1489a5d37c8f06b2e429c0
PyGMO/problem/__init__.py
python
_sch_ctor
(self)
Constructs a Schaffer's study problem (Box-Constrained Continuous Multi-Objective) NOTE: K Deb, A Pratap, S Agarwal: A fast and elitist multiobjective genetic algorithm: NSGA-II, IEEE Transactions on, 2002 USAGE: problem.sch()
Constructs a Schaffer's study problem (Box-Constrained Continuous Multi-Objective)
[ "Constructs", "a", "Schaffer", "s", "study", "problem", "(", "Box", "-", "Constrained", "Continuous", "Multi", "-", "Objective", ")" ]
def _sch_ctor(self): """ Constructs a Schaffer's study problem (Box-Constrained Continuous Multi-Objective) NOTE: K Deb, A Pratap, S Agarwal: A fast and elitist multiobjective genetic algorithm: NSGA-II, IEEE Transactions on, 2002 USAGE: problem.sch() """ arg_list = [] self._orig_init(*arg_list)
[ "def", "_sch_ctor", "(", "self", ")", ":", "arg_list", "=", "[", "]", "self", ".", "_orig_init", "(", "*", "arg_list", ")" ]
https://github.com/esa/pagmo/blob/80281d549c8f1b470e1489a5d37c8f06b2e429c0/PyGMO/problem/__init__.py#L345-L354
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/reductions/canonicalization.py
python
Canonicalization.apply
(self, problem)
return new_problem, inverse_data
Recursively canonicalize the objective and every constraint.
Recursively canonicalize the objective and every constraint.
[ "Recursively", "canonicalize", "the", "objective", "and", "every", "constraint", "." ]
def apply(self, problem): """Recursively canonicalize the objective and every constraint.""" inverse_data = InverseData(problem) canon_objective, canon_constraints = self.canonicalize_tree( problem.objective) for constraint in problem.constraints: # canon_constr is the constraint rexpressed in terms of # its canonicalized arguments, and aux_constr are the constraints # generated while canonicalizing the arguments of the original # constraint canon_constr, aux_constr = self.canonicalize_tree( constraint) canon_constraints += aux_constr + [canon_constr] inverse_data.cons_id_map.update({constraint.id: canon_constr.id}) new_problem = problems.problem.Problem(canon_objective, canon_constraints) return new_problem, inverse_data
[ "def", "apply", "(", "self", ",", "problem", ")", ":", "inverse_data", "=", "InverseData", "(", "problem", ")", "canon_objective", ",", "canon_constraints", "=", "self", ".", "canonicalize_tree", "(", "problem", ".", "objective", ")", "for", "constraint", "in", "problem", ".", "constraints", ":", "# canon_constr is the constraint rexpressed in terms of", "# its canonicalized arguments, and aux_constr are the constraints", "# generated while canonicalizing the arguments of the original", "# constraint", "canon_constr", ",", "aux_constr", "=", "self", ".", "canonicalize_tree", "(", "constraint", ")", "canon_constraints", "+=", "aux_constr", "+", "[", "canon_constr", "]", "inverse_data", ".", "cons_id_map", ".", "update", "(", "{", "constraint", ".", "id", ":", "canon_constr", ".", "id", "}", ")", "new_problem", "=", "problems", ".", "problem", ".", "Problem", "(", "canon_objective", ",", "canon_constraints", ")", "return", "new_problem", ",", "inverse_data" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/reductions/canonicalization.py#L55-L74
gv22ga/dlib-face-recognition-android
42d6305cbd85833f2b85bb79b70ab9ab004153c9
tools/lint/cpplint.py
python
NestingState.InNamespaceBody
(self)
return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise.
Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise.
[ "Check", "if", "we", "are", "currently", "one", "level", "inside", "a", "namespace", "body", ".", "Returns", ":", "True", "if", "top", "of", "the", "stack", "is", "a", "namespace", "block", "False", "otherwise", "." ]
def InNamespaceBody(self): """Check if we are currently one level inside a namespace body. Returns: True if top of the stack is a namespace block, False otherwise. """ return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
[ "def", "InNamespaceBody", "(", "self", ")", ":", "return", "self", ".", "stack", "and", "isinstance", "(", "self", ".", "stack", "[", "-", "1", "]", ",", "_NamespaceInfo", ")" ]
https://github.com/gv22ga/dlib-face-recognition-android/blob/42d6305cbd85833f2b85bb79b70ab9ab004153c9/tools/lint/cpplint.py#L2222-L2227
echronos/echronos
c996f1d2c8af6c6536205eb319c1bf1d4d84569c
external_tools/pystache/init.py
python
render
(template, context=None, name=None, **kwargs)
return renderer.render(parsed_template, context, **kwargs)
Return the given template string rendered using the given context.
Return the given template string rendered using the given context.
[ "Return", "the", "given", "template", "string", "rendered", "using", "the", "given", "context", "." ]
def render(template, context=None, name=None, **kwargs): """ Return the given template string rendered using the given context. """ renderer = Renderer() parsed_template = parse(template, name=name) return renderer.render(parsed_template, context, **kwargs)
[ "def", "render", "(", "template", ",", "context", "=", "None", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "renderer", "=", "Renderer", "(", ")", "parsed_template", "=", "parse", "(", "template", ",", "name", "=", "name", ")", "return", "renderer", ".", "render", "(", "parsed_template", ",", "context", ",", "*", "*", "kwargs", ")" ]
https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/pystache/init.py#L13-L20
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/sort-array-by-increasing-frequency.py
python
Solution.frequencySort
(self, nums)
return sorted(nums, key=lambda x: (count[x], -x))
:type nums: List[int] :rtype: List[int]
:type nums: List[int] :rtype: List[int]
[ ":", "type", "nums", ":", "List", "[", "int", "]", ":", "rtype", ":", "List", "[", "int", "]" ]
def frequencySort(self, nums): """ :type nums: List[int] :rtype: List[int] """ count = collections.Counter(nums) return sorted(nums, key=lambda x: (count[x], -x))
[ "def", "frequencySort", "(", "self", ",", "nums", ")", ":", "count", "=", "collections", ".", "Counter", "(", "nums", ")", "return", "sorted", "(", "nums", ",", "key", "=", "lambda", "x", ":", "(", "count", "[", "x", "]", ",", "-", "x", ")", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/sort-array-by-increasing-frequency.py#L8-L14
root-project/root
fcd3583bb14852bf2e8cd2415717cbaac0e75896
bindings/pyroot/cppyy/cppyy-backend/cling/python/cppyy_backend/_cppyy_generator.py
python
CppyyGenerator.create_file_mapping
(self, h_file)
return info
Generate a dict describing the given source header file. This is the main entry point for this class. :param h_file: The source header file of interest. :returns: A dict corresponding to the h_file.
Generate a dict describing the given source header file. This is the main entry point for this class.
[ "Generate", "a", "dict", "describing", "the", "given", "source", "header", "file", ".", "This", "is", "the", "main", "entry", "point", "for", "this", "class", "." ]
def create_file_mapping(self, h_file): """ Generate a dict describing the given source header file. This is the main entry point for this class. :param h_file: The source header file of interest. :returns: A dict corresponding to the h_file. """ # # Use Clang to parse the source and return its AST. # self.tu = self.source_processor.compile(h_file) m = (logging.ERROR - logging.WARNING) // (Diagnostic.Error - Diagnostic.Warning) c = logging.ERROR - (Diagnostic.Error * m) for diag in self.tu.diagnostics: # # We expect to be run over hundreds of files. Any parsing issues are likely to be very repetitive. # So, to avoid bothering the user, we suppress duplicates. # loc = diag.location msg = "{}:{}[{}] {}".format(loc.file, loc.line, loc.column, diag.spelling) if diag.spelling == "#pragma once in main file": continue if msg in self.diagnostics: continue self.diagnostics.add(msg) logger.log(m * diag.severity + c, "While parsing: {}".format(msg)) if self.dump_includes: logger.info(_("File {}").format(h_file)) for include in sorted(set(self.tu.get_includes())): logger.info(_(" #includes {}").format(include.include.name)) # # Run through the top level children in the translation unit. # info = self._container_get(self.tu.cursor, [], h_file) return info
[ "def", "create_file_mapping", "(", "self", ",", "h_file", ")", ":", "#", "# Use Clang to parse the source and return its AST.", "#", "self", ".", "tu", "=", "self", ".", "source_processor", ".", "compile", "(", "h_file", ")", "m", "=", "(", "logging", ".", "ERROR", "-", "logging", ".", "WARNING", ")", "//", "(", "Diagnostic", ".", "Error", "-", "Diagnostic", ".", "Warning", ")", "c", "=", "logging", ".", "ERROR", "-", "(", "Diagnostic", ".", "Error", "*", "m", ")", "for", "diag", "in", "self", ".", "tu", ".", "diagnostics", ":", "#", "# We expect to be run over hundreds of files. Any parsing issues are likely to be very repetitive.", "# So, to avoid bothering the user, we suppress duplicates.", "#", "loc", "=", "diag", ".", "location", "msg", "=", "\"{}:{}[{}] {}\"", ".", "format", "(", "loc", ".", "file", ",", "loc", ".", "line", ",", "loc", ".", "column", ",", "diag", ".", "spelling", ")", "if", "diag", ".", "spelling", "==", "\"#pragma once in main file\"", ":", "continue", "if", "msg", "in", "self", ".", "diagnostics", ":", "continue", "self", ".", "diagnostics", ".", "add", "(", "msg", ")", "logger", ".", "log", "(", "m", "*", "diag", ".", "severity", "+", "c", ",", "\"While parsing: {}\"", ".", "format", "(", "msg", ")", ")", "if", "self", ".", "dump_includes", ":", "logger", ".", "info", "(", "_", "(", "\"File {}\"", ")", ".", "format", "(", "h_file", ")", ")", "for", "include", "in", "sorted", "(", "set", "(", "self", ".", "tu", ".", "get_includes", "(", ")", ")", ")", ":", "logger", ".", "info", "(", "_", "(", "\" #includes {}\"", ")", ".", "format", "(", "include", ".", "include", ".", "name", ")", ")", "#", "# Run through the top level children in the translation unit.", "#", "info", "=", "self", ".", "_container_get", "(", "self", ".", "tu", ".", "cursor", ",", "[", "]", ",", "h_file", ")", "return", "info" ]
https://github.com/root-project/root/blob/fcd3583bb14852bf2e8cd2415717cbaac0e75896/bindings/pyroot/cppyy/cppyy-backend/cling/python/cppyy_backend/_cppyy_generator.py#L219-L254
apple/swift
469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893
utils/jobstats/jobstats.py
python
JobStats.driver_jobs_total
(self)
return self.driver_jobs_ran() + self.driver_jobs_skipped()
Return the total count of a driver job's ran + skipped sub-jobs
Return the total count of a driver job's ran + skipped sub-jobs
[ "Return", "the", "total", "count", "of", "a", "driver", "job", "s", "ran", "+", "skipped", "sub", "-", "jobs" ]
def driver_jobs_total(self): """Return the total count of a driver job's ran + skipped sub-jobs""" assert(self.is_driver_job()) return self.driver_jobs_ran() + self.driver_jobs_skipped()
[ "def", "driver_jobs_total", "(", "self", ")", ":", "assert", "(", "self", ".", "is_driver_job", "(", ")", ")", "return", "self", ".", "driver_jobs_ran", "(", ")", "+", "self", ".", "driver_jobs_skipped", "(", ")" ]
https://github.com/apple/swift/blob/469f72fdae2ea828b3b6c0d7d62d7e4cf98c4893/utils/jobstats/jobstats.py#L77-L80
Dobiasd/frugally-deep
99d9378c6ef537a209bcb2a102e953899a6ab0e3
keras_export/convert_model.py
python
are_embedding_layer_positions_ok_for_testing
(model)
return embedding_layer_names(model) == embedding_layer_names_at_input_nodes(model)
Test data can only be generated if all embeddings layers are positioned directly behind the input nodes
Test data can only be generated if all embeddings layers are positioned directly behind the input nodes
[ "Test", "data", "can", "only", "be", "generated", "if", "all", "embeddings", "layers", "are", "positioned", "directly", "behind", "the", "input", "nodes" ]
def are_embedding_layer_positions_ok_for_testing(model): """ Test data can only be generated if all embeddings layers are positioned directly behind the input nodes """ def embedding_layer_names(model): layers = model.layers result = set() for layer in layers: if isinstance(layer, Embedding): result.add(layer.name) layer_type = type(layer).__name__ if layer_type in ['Model', 'Sequential', 'Functional']: result.union(embedding_layer_names(layer)) return result def embedding_layer_names_at_input_nodes(model): result = set() for input_layer in get_model_input_layers(model): if input_layer._outbound_nodes and isinstance( input_layer._outbound_nodes[0].outbound_layer, Embedding): result.add(input_layer._outbound_nodes[0].outbound_layer.name) return set(result) return embedding_layer_names(model) == embedding_layer_names_at_input_nodes(model)
[ "def", "are_embedding_layer_positions_ok_for_testing", "(", "model", ")", ":", "def", "embedding_layer_names", "(", "model", ")", ":", "layers", "=", "model", ".", "layers", "result", "=", "set", "(", ")", "for", "layer", "in", "layers", ":", "if", "isinstance", "(", "layer", ",", "Embedding", ")", ":", "result", ".", "add", "(", "layer", ".", "name", ")", "layer_type", "=", "type", "(", "layer", ")", ".", "__name__", "if", "layer_type", "in", "[", "'Model'", ",", "'Sequential'", ",", "'Functional'", "]", ":", "result", ".", "union", "(", "embedding_layer_names", "(", "layer", ")", ")", "return", "result", "def", "embedding_layer_names_at_input_nodes", "(", "model", ")", ":", "result", "=", "set", "(", ")", "for", "input_layer", "in", "get_model_input_layers", "(", "model", ")", ":", "if", "input_layer", ".", "_outbound_nodes", "and", "isinstance", "(", "input_layer", ".", "_outbound_nodes", "[", "0", "]", ".", "outbound_layer", ",", "Embedding", ")", ":", "result", ".", "add", "(", "input_layer", ".", "_outbound_nodes", "[", "0", "]", ".", "outbound_layer", ".", "name", ")", "return", "set", "(", "result", ")", "return", "embedding_layer_names", "(", "model", ")", "==", "embedding_layer_names_at_input_nodes", "(", "model", ")" ]
https://github.com/Dobiasd/frugally-deep/blob/99d9378c6ef537a209bcb2a102e953899a6ab0e3/keras_export/convert_model.py#L116-L141
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/cmd.py
python
Command.finalize_options
(self)
Set final values for all the options that this command supports. This is always called as late as possible, ie. after any option assignments from the command-line or from other commands have been done. Thus, this is the place to code option dependencies: if 'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as long as 'foo' still has the same value it was assigned in 'initialize_options()'. This method must be implemented by all command classes.
Set final values for all the options that this command supports. This is always called as late as possible, ie. after any option assignments from the command-line or from other commands have been done. Thus, this is the place to code option dependencies: if 'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as long as 'foo' still has the same value it was assigned in 'initialize_options()'.
[ "Set", "final", "values", "for", "all", "the", "options", "that", "this", "command", "supports", ".", "This", "is", "always", "called", "as", "late", "as", "possible", "ie", ".", "after", "any", "option", "assignments", "from", "the", "command", "-", "line", "or", "from", "other", "commands", "have", "been", "done", ".", "Thus", "this", "is", "the", "place", "to", "code", "option", "dependencies", ":", "if", "foo", "depends", "on", "bar", "then", "it", "is", "safe", "to", "set", "foo", "from", "bar", "as", "long", "as", "foo", "still", "has", "the", "same", "value", "it", "was", "assigned", "in", "initialize_options", "()", "." ]
def finalize_options(self): """Set final values for all the options that this command supports. This is always called as late as possible, ie. after any option assignments from the command-line or from other commands have been done. Thus, this is the place to code option dependencies: if 'foo' depends on 'bar', then it is safe to set 'foo' from 'bar' as long as 'foo' still has the same value it was assigned in 'initialize_options()'. This method must be implemented by all command classes. """ raise RuntimeError, \ "abstract method -- subclass %s must override" % self.__class__
[ "def", "finalize_options", "(", "self", ")", ":", "raise", "RuntimeError", ",", "\"abstract method -- subclass %s must override\"", "%", "self", ".", "__class__" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/distutils/cmd.py#L138-L150
OpenMined/PyDP
a88ee73053aa2bdc1be327a77109dd5907ab41d6
examples/Tutorial_2-restaurant_demo/restaurant.py
python
RestaurantStatistics.get_private_counts_per_day
(self, epsilon: float = None)
return day_counts
Compute an anonymized (within a given threshold of epsilon) version of the number of visits per day. Return a dictionary mapping days to number of visits
Compute an anonymized (within a given threshold of epsilon) version of the number of visits per day.
[ "Compute", "an", "anonymized", "(", "within", "a", "given", "threshold", "of", "epsilon", ")", "version", "of", "the", "number", "of", "visits", "per", "day", "." ]
def get_private_counts_per_day(self, epsilon: float = None) -> dict: """Compute an anonymized (within a given threshold of epsilon) version of the number of visits per day. Return a dictionary mapping days to number of visits """ # Pre-process the data set: limit the number of days contributed by a visitor to COUNT_MAX_CONTRIBUTED_DAYS day_visits = bound_visits_per_week(self._day_visits, COUNT_MAX_CONTRIBUTED_DAYS) day_counts = dict() # Use the default epsilon value if it is not given as an argument if not epsilon: x = Count( epsilon=self._epsilon, l0_sensitivity=COUNT_MAX_CONTRIBUTED_DAYS, dtype="int", ) else: x = Count( epsilon=epsilon, l0_sensitivity=COUNT_MAX_CONTRIBUTED_DAYS, dtype="int" ) for day in day_visits["Day"].unique(): # Can use either quick_result or a combination of add_entries() and result() day_counts[day] = x.quick_result( data=list(day_visits[day_visits["Day"] == day]["Day"]) ) return day_counts
[ "def", "get_private_counts_per_day", "(", "self", ",", "epsilon", ":", "float", "=", "None", ")", "->", "dict", ":", "# Pre-process the data set: limit the number of days contributed by a visitor to COUNT_MAX_CONTRIBUTED_DAYS", "day_visits", "=", "bound_visits_per_week", "(", "self", ".", "_day_visits", ",", "COUNT_MAX_CONTRIBUTED_DAYS", ")", "day_counts", "=", "dict", "(", ")", "# Use the default epsilon value if it is not given as an argument", "if", "not", "epsilon", ":", "x", "=", "Count", "(", "epsilon", "=", "self", ".", "_epsilon", ",", "l0_sensitivity", "=", "COUNT_MAX_CONTRIBUTED_DAYS", ",", "dtype", "=", "\"int\"", ",", ")", "else", ":", "x", "=", "Count", "(", "epsilon", "=", "epsilon", ",", "l0_sensitivity", "=", "COUNT_MAX_CONTRIBUTED_DAYS", ",", "dtype", "=", "\"int\"", ")", "for", "day", "in", "day_visits", "[", "\"Day\"", "]", ".", "unique", "(", ")", ":", "# Can use either quick_result or a combination of add_entries() and result()", "day_counts", "[", "day", "]", "=", "x", ".", "quick_result", "(", "data", "=", "list", "(", "day_visits", "[", "day_visits", "[", "\"Day\"", "]", "==", "day", "]", "[", "\"Day\"", "]", ")", ")", "return", "day_counts" ]
https://github.com/OpenMined/PyDP/blob/a88ee73053aa2bdc1be327a77109dd5907ab41d6/examples/Tutorial_2-restaurant_demo/restaurant.py#L181-L209
esa/pagmo
80281d549c8f1b470e1489a5d37c8f06b2e429c0
PyGMO/problem/__init__.py
python
_con2uncon_ctor
(self, problem=cec2006(4), method='optimality')
Implements a meta-problem class that wraps constrained problems, resulting in an unconstrained problem. Two methods are available for definig the objective function of the meta-problem: 'optimality' and 'feasibility'. The 'optimality' uses as objective function the original objective function, it basically removes the constraints from the original problem. The 'feasibility' uses as objective function the sum of the violation of the constraints, the meta-problem hence optimize just the level of infeasibility. Implements a meta-problem class that wraps some other constrained problems, resulting in multi-objective problem. USAGE: problem.con2uncon(problem=PyGMO.cec2006(4), method='optimality') * problem: original PyGMO constrained problem * method: one of 'optimality', 'feasibility'.
Implements a meta-problem class that wraps constrained problems, resulting in an unconstrained problem. Two methods are available for definig the objective function of the meta-problem: 'optimality' and 'feasibility'. The 'optimality' uses as objective function the original objective function, it basically removes the constraints from the original problem. The 'feasibility' uses as objective function the sum of the violation of the constraints, the meta-problem hence optimize just the level of infeasibility.
[ "Implements", "a", "meta", "-", "problem", "class", "that", "wraps", "constrained", "problems", "resulting", "in", "an", "unconstrained", "problem", ".", "Two", "methods", "are", "available", "for", "definig", "the", "objective", "function", "of", "the", "meta", "-", "problem", ":", "optimality", "and", "feasibility", ".", "The", "optimality", "uses", "as", "objective", "function", "the", "original", "objective", "function", "it", "basically", "removes", "the", "constraints", "from", "the", "original", "problem", ".", "The", "feasibility", "uses", "as", "objective", "function", "the", "sum", "of", "the", "violation", "of", "the", "constraints", "the", "meta", "-", "problem", "hence", "optimize", "just", "the", "level", "of", "infeasibility", "." ]
def _con2uncon_ctor(self, problem=cec2006(4), method='optimality'): """ Implements a meta-problem class that wraps constrained problems, resulting in an unconstrained problem. Two methods are available for definig the objective function of the meta-problem: 'optimality' and 'feasibility'. The 'optimality' uses as objective function the original objective function, it basically removes the constraints from the original problem. The 'feasibility' uses as objective function the sum of the violation of the constraints, the meta-problem hence optimize just the level of infeasibility. Implements a meta-problem class that wraps some other constrained problems, resulting in multi-objective problem. USAGE: problem.con2uncon(problem=PyGMO.cec2006(4), method='optimality') * problem: original PyGMO constrained problem * method: one of 'optimality', 'feasibility'. """ # We construct the arg list for the original constructor exposed by # boost_python METHOD_TYPE = { 'optimality': _problem_meta._con2uncon_method_type.OPTIMALITY, 'feasibility': _problem_meta._con2uncon_method_type.FEASIBILITY, } arg_list = [] arg_list.append(problem) arg_list.append(METHOD_TYPE[method.lower()]) self._orig_init(*arg_list)
[ "def", "_con2uncon_ctor", "(", "self", ",", "problem", "=", "cec2006", "(", "4", ")", ",", "method", "=", "'optimality'", ")", ":", "# We construct the arg list for the original constructor exposed by", "# boost_python", "METHOD_TYPE", "=", "{", "'optimality'", ":", "_problem_meta", ".", "_con2uncon_method_type", ".", "OPTIMALITY", ",", "'feasibility'", ":", "_problem_meta", ".", "_con2uncon_method_type", ".", "FEASIBILITY", ",", "}", "arg_list", "=", "[", "]", "arg_list", ".", "append", "(", "problem", ")", "arg_list", ".", "append", "(", "METHOD_TYPE", "[", "method", ".", "lower", "(", ")", "]", ")", "self", ".", "_orig_init", "(", "*", "arg_list", ")" ]
https://github.com/esa/pagmo/blob/80281d549c8f1b470e1489a5d37c8f06b2e429c0/PyGMO/problem/__init__.py#L873-L900
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/bisect_utils.py
python
RunRepo
(params)
return SubprocessCall(cmd)
Runs cros repo command with specified parameters. Args: params: A list of parameters to pass to gclient. Returns: The return code of the call.
Runs cros repo command with specified parameters.
[ "Runs", "cros", "repo", "command", "with", "specified", "parameters", "." ]
def RunRepo(params): """Runs cros repo command with specified parameters. Args: params: A list of parameters to pass to gclient. Returns: The return code of the call. """ cmd = ['repo'] + params return SubprocessCall(cmd)
[ "def", "RunRepo", "(", "params", ")", ":", "cmd", "=", "[", "'repo'", "]", "+", "params", "return", "SubprocessCall", "(", "cmd", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/bisect_utils.py#L181-L192
larroy/clearskies_core
3574ddf0edc8555454c7044126e786a6c29444dc
tools/gyp/pylib/gyp/win_tool.py
python
WinTool.ExecLinkWithManifests
(self, arch, embed_manifest, out, ldcmd, resname, mt, rc, intermediate_manifest, *manifests)
A wrapper for handling creating a manifest resource and then executing a link command.
A wrapper for handling creating a manifest resource and then executing a link command.
[ "A", "wrapper", "for", "handling", "creating", "a", "manifest", "resource", "and", "then", "executing", "a", "link", "command", "." ]
def ExecLinkWithManifests(self, arch, embed_manifest, out, ldcmd, resname, mt, rc, intermediate_manifest, *manifests): """A wrapper for handling creating a manifest resource and then executing a link command.""" # The 'normal' way to do manifests is to have link generate a manifest # based on gathering dependencies from the object files, then merge that # manifest with other manifests supplied as sources, convert the merged # manifest to a resource, and then *relink*, including the compiled # version of the manifest resource. This breaks incremental linking, and # is generally overly complicated. Instead, we merge all the manifests # provided (along with one that includes what would normally be in the # linker-generated one, see msvs_emulation.py), and include that into the # first and only link. We still tell link to generate a manifest, but we # only use that to assert that our simpler process did not miss anything. variables = { 'python': sys.executable, 'arch': arch, 'out': out, 'ldcmd': ldcmd, 'resname': resname, 'mt': mt, 'rc': rc, 'intermediate_manifest': intermediate_manifest, 'manifests': ' '.join(manifests), } add_to_ld = '' if manifests: subprocess.check_call( '%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo ' '-manifest %(manifests)s -out:%(out)s.manifest' % variables) if embed_manifest == 'True': subprocess.check_call( '%(python)s gyp-win-tool manifest-to-rc %(arch)s %(out)s.manifest' ' %(out)s.manifest.rc %(resname)s' % variables) subprocess.check_call( '%(python)s gyp-win-tool rc-wrapper %(arch)s %(rc)s ' '%(out)s.manifest.rc' % variables) add_to_ld = ' %(out)s.manifest.res' % variables subprocess.check_call(ldcmd + add_to_ld) # Run mt.exe on the theoretically complete manifest we generated, merging # it with the one the linker generated to confirm that the linker # generated one does not add anything. This is strictly unnecessary for # correctness, it's only to verify that e.g. /MANIFESTDEPENDENCY was not # used in a #pragma comment. if manifests: # Merge the intermediate one with ours to .assert.manifest, then check # that .assert.manifest is identical to ours. subprocess.check_call( '%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo ' '-manifest %(out)s.manifest %(intermediate_manifest)s ' '-out:%(out)s.assert.manifest' % variables) assert_manifest = '%(out)s.assert.manifest' % variables our_manifest = '%(out)s.manifest' % variables # Load and normalize the manifests. mt.exe sometimes removes whitespace, # and sometimes doesn't unfortunately. with open(our_manifest, 'rb') as our_f: with open(assert_manifest, 'rb') as assert_f: our_data = our_f.read().translate(None, string.whitespace) assert_data = assert_f.read().translate(None, string.whitespace) if our_data != assert_data: os.unlink(out) def dump(filename): sys.stderr.write('%s\n-----\n' % filename) with open(filename, 'rb') as f: sys.stderr.write(f.read() + '\n-----\n') dump(intermediate_manifest) dump(our_manifest) dump(assert_manifest) sys.stderr.write( 'Linker generated manifest "%s" added to final manifest "%s" ' '(result in "%s"). ' 'Were /MANIFEST switches used in #pragma statements? ' % ( intermediate_manifest, our_manifest, assert_manifest)) return 1
[ "def", "ExecLinkWithManifests", "(", "self", ",", "arch", ",", "embed_manifest", ",", "out", ",", "ldcmd", ",", "resname", ",", "mt", ",", "rc", ",", "intermediate_manifest", ",", "*", "manifests", ")", ":", "# The 'normal' way to do manifests is to have link generate a manifest", "# based on gathering dependencies from the object files, then merge that", "# manifest with other manifests supplied as sources, convert the merged", "# manifest to a resource, and then *relink*, including the compiled", "# version of the manifest resource. This breaks incremental linking, and", "# is generally overly complicated. Instead, we merge all the manifests", "# provided (along with one that includes what would normally be in the", "# linker-generated one, see msvs_emulation.py), and include that into the", "# first and only link. We still tell link to generate a manifest, but we", "# only use that to assert that our simpler process did not miss anything.", "variables", "=", "{", "'python'", ":", "sys", ".", "executable", ",", "'arch'", ":", "arch", ",", "'out'", ":", "out", ",", "'ldcmd'", ":", "ldcmd", ",", "'resname'", ":", "resname", ",", "'mt'", ":", "mt", ",", "'rc'", ":", "rc", ",", "'intermediate_manifest'", ":", "intermediate_manifest", ",", "'manifests'", ":", "' '", ".", "join", "(", "manifests", ")", ",", "}", "add_to_ld", "=", "''", "if", "manifests", ":", "subprocess", ".", "check_call", "(", "'%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '", "'-manifest %(manifests)s -out:%(out)s.manifest'", "%", "variables", ")", "if", "embed_manifest", "==", "'True'", ":", "subprocess", ".", "check_call", "(", "'%(python)s gyp-win-tool manifest-to-rc %(arch)s %(out)s.manifest'", "' %(out)s.manifest.rc %(resname)s'", "%", "variables", ")", "subprocess", ".", "check_call", "(", "'%(python)s gyp-win-tool rc-wrapper %(arch)s %(rc)s '", "'%(out)s.manifest.rc'", "%", "variables", ")", "add_to_ld", "=", "' %(out)s.manifest.res'", "%", "variables", "subprocess", ".", "check_call", "(", "ldcmd", "+", "add_to_ld", ")", "# Run mt.exe on the theoretically complete manifest we generated, merging", "# it with the one the linker generated to confirm that the linker", "# generated one does not add anything. This is strictly unnecessary for", "# correctness, it's only to verify that e.g. /MANIFESTDEPENDENCY was not", "# used in a #pragma comment.", "if", "manifests", ":", "# Merge the intermediate one with ours to .assert.manifest, then check", "# that .assert.manifest is identical to ours.", "subprocess", ".", "check_call", "(", "'%(python)s gyp-win-tool manifest-wrapper %(arch)s %(mt)s -nologo '", "'-manifest %(out)s.manifest %(intermediate_manifest)s '", "'-out:%(out)s.assert.manifest'", "%", "variables", ")", "assert_manifest", "=", "'%(out)s.assert.manifest'", "%", "variables", "our_manifest", "=", "'%(out)s.manifest'", "%", "variables", "# Load and normalize the manifests. mt.exe sometimes removes whitespace,", "# and sometimes doesn't unfortunately.", "with", "open", "(", "our_manifest", ",", "'rb'", ")", "as", "our_f", ":", "with", "open", "(", "assert_manifest", ",", "'rb'", ")", "as", "assert_f", ":", "our_data", "=", "our_f", ".", "read", "(", ")", ".", "translate", "(", "None", ",", "string", ".", "whitespace", ")", "assert_data", "=", "assert_f", ".", "read", "(", ")", ".", "translate", "(", "None", ",", "string", ".", "whitespace", ")", "if", "our_data", "!=", "assert_data", ":", "os", ".", "unlink", "(", "out", ")", "def", "dump", "(", "filename", ")", ":", "sys", ".", "stderr", ".", "write", "(", "'%s\\n-----\\n'", "%", "filename", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "sys", ".", "stderr", ".", "write", "(", "f", ".", "read", "(", ")", "+", "'\\n-----\\n'", ")", "dump", "(", "intermediate_manifest", ")", "dump", "(", "our_manifest", ")", "dump", "(", "assert_manifest", ")", "sys", ".", "stderr", ".", "write", "(", "'Linker generated manifest \"%s\" added to final manifest \"%s\" '", "'(result in \"%s\"). '", "'Were /MANIFEST switches used in #pragma statements? '", "%", "(", "intermediate_manifest", ",", "our_manifest", ",", "assert_manifest", ")", ")", "return", "1" ]
https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/win_tool.py#L119-L193
mindspore-ai/mindspore
fb8fd3338605bb34fa5cea054e535a8b1d753fab
mindspore/python/mindspore/nn/transformer/loss.py
python
CrossEntropyLoss._check_input
(self, logits, label, input_mask)
return True
r"""Check the input tensor shape and type
r"""Check the input tensor shape and type
[ "r", "Check", "the", "input", "tensor", "shape", "and", "type" ]
def _check_input(self, logits, label, input_mask): r"""Check the input tensor shape and type""" _check_is_tensor('logits', logits, self.cls_name) _check_is_tensor('label', label, self.cls_name) _check_is_tensor('input_mask', input_mask, self.cls_name) _check_input_dtype(F.dtype(logits), "logits", [mstype.float32, mstype.float16], self.cls_name) _check_input_dtype(F.dtype(label), "label", [mstype.int32], self.cls_name) _check_input_dtype(F.dtype(input_mask), "input_mask", [mstype.float32], self.cls_name) _check_input_shape(F.shape(logits), "logits", self.cls_name, 2) _check_input_shape(F.shape(label), "label", self.cls_name, 1) _check_input_shape(F.shape(input_mask), "input_mask", self.cls_name, 1) return True
[ "def", "_check_input", "(", "self", ",", "logits", ",", "label", ",", "input_mask", ")", ":", "_check_is_tensor", "(", "'logits'", ",", "logits", ",", "self", ".", "cls_name", ")", "_check_is_tensor", "(", "'label'", ",", "label", ",", "self", ".", "cls_name", ")", "_check_is_tensor", "(", "'input_mask'", ",", "input_mask", ",", "self", ".", "cls_name", ")", "_check_input_dtype", "(", "F", ".", "dtype", "(", "logits", ")", ",", "\"logits\"", ",", "[", "mstype", ".", "float32", ",", "mstype", ".", "float16", "]", ",", "self", ".", "cls_name", ")", "_check_input_dtype", "(", "F", ".", "dtype", "(", "label", ")", ",", "\"label\"", ",", "[", "mstype", ".", "int32", "]", ",", "self", ".", "cls_name", ")", "_check_input_dtype", "(", "F", ".", "dtype", "(", "input_mask", ")", ",", "\"input_mask\"", ",", "[", "mstype", ".", "float32", "]", ",", "self", ".", "cls_name", ")", "_check_input_shape", "(", "F", ".", "shape", "(", "logits", ")", ",", "\"logits\"", ",", "self", ".", "cls_name", ",", "2", ")", "_check_input_shape", "(", "F", ".", "shape", "(", "label", ")", ",", "\"label\"", ",", "self", ".", "cls_name", ",", "1", ")", "_check_input_shape", "(", "F", ".", "shape", "(", "input_mask", ")", ",", "\"input_mask\"", ",", "self", ".", "cls_name", ",", "1", ")", "return", "True" ]
https://github.com/mindspore-ai/mindspore/blob/fb8fd3338605bb34fa5cea054e535a8b1d753fab/mindspore/python/mindspore/nn/transformer/loss.py#L128-L139
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py
python
HFIRSANSReduction._save_output
(self, iq_output, iqxy_output, output_dir, property_manager)
return output_msg
Save the I(Q) and I(QxQy) output to file. @param iq_output: name of the I(Q) workspace @param iqxy_output: name of the I(QxQy) workspace @param output_dir: output director path @param property_manager: property manager object
Save the I(Q) and I(QxQy) output to file.
[ "Save", "the", "I", "(", "Q", ")", "and", "I", "(", "QxQy", ")", "output", "to", "file", "." ]
def _save_output(self, iq_output, iqxy_output, output_dir, property_manager): """ Save the I(Q) and I(QxQy) output to file. @param iq_output: name of the I(Q) workspace @param iqxy_output: name of the I(QxQy) workspace @param output_dir: output director path @param property_manager: property manager object """ output_msg = "" def _save_ws(iq_ws): if AnalysisDataService.doesExist(iq_ws): proc_xml = "" if property_manager.existsProperty("ProcessInfo"): process_file = property_manager.getProperty("ProcessInfo").value if os.path.isfile(process_file): proc = open(process_file, 'r') proc_xml = "<SASprocessnote>\n%s</SASprocessnote>\n" % proc.read() elif len(process_file)>0: Logger("HFIRSANSReduction").error("Could not read %s\n" % process_file) if property_manager.existsProperty("SetupAlgorithm"): setup_info = property_manager.getProperty("SetupAlgorithm").value proc_xml += "\n<SASprocessnote>\n<Reduction>\n" # The instrument name refers to the UI, which is named BIOSANS for all HFIR SANS proc_xml += " <instrument_name>BIOSANS</instrument_name>\n" proc_xml += " <SetupInfo>%s</SetupInfo>\n" % setup_info filename = self.getProperty("Filename").value proc_xml += " <Filename>%s</Filename>\n" % filename proc_xml += "</Reduction>\n</SASprocessnote>\n" filename = os.path.join(output_dir, iq_ws+'.txt') alg = AlgorithmManager.create("SaveAscii") alg.initialize() alg.setChild(True) alg.setProperty("Filename", filename) alg.setProperty("InputWorkspace", iq_ws) alg.setProperty("Separator", "Tab") alg.setProperty("CommentIndicator", "# ") alg.setProperty("WriteXError", True) alg.setProperty("WriteSpectrumID", False) alg.execute() filename = os.path.join(output_dir, iq_ws+'.xml') alg = AlgorithmManager.create("SaveCanSAS1D") alg.initialize() alg.setChild(True) alg.setProperty("Filename", filename) alg.setProperty("InputWorkspace", iq_ws) alg.setProperty("Process", proc_xml) alg.execute() return filename else: Logger("HFIRSANSReduction").error("No I(Q) output found for %s" % iq_ws) # Save I(Q), including all wedges ws_list = AnalysisDataService.getObjectNames() for item in ws_list: if iq_output is not None and item.startswith(iq_output) and \ (iqxy_output is None or not item.startswith(iqxy_output)): filename = _save_ws(item) if filename is not None: output_msg += "I(Q) saved in %s\n" % (filename) # Save I(Qx,Qy) if iqxy_output is not None: if AnalysisDataService.doesExist(iqxy_output): filename = os.path.join(output_dir, iqxy_output+'.dat') alg = AlgorithmManager.create("SaveNISTDAT") alg.initialize() alg.setChild(True) alg.setProperty("Filename", filename) alg.setProperty("InputWorkspace", iqxy_output) alg.execute() #api.SaveNISTDAT(InputWorkspace=iqxy_output, Filename=filename) output_msg += "I(Qx,Qy) saved in %s\n" % (filename) else: Logger("HFIRSANSReduction").error("No I(Qx,Qy) output found") return output_msg
[ "def", "_save_output", "(", "self", ",", "iq_output", ",", "iqxy_output", ",", "output_dir", ",", "property_manager", ")", ":", "output_msg", "=", "\"\"", "def", "_save_ws", "(", "iq_ws", ")", ":", "if", "AnalysisDataService", ".", "doesExist", "(", "iq_ws", ")", ":", "proc_xml", "=", "\"\"", "if", "property_manager", ".", "existsProperty", "(", "\"ProcessInfo\"", ")", ":", "process_file", "=", "property_manager", ".", "getProperty", "(", "\"ProcessInfo\"", ")", ".", "value", "if", "os", ".", "path", ".", "isfile", "(", "process_file", ")", ":", "proc", "=", "open", "(", "process_file", ",", "'r'", ")", "proc_xml", "=", "\"<SASprocessnote>\\n%s</SASprocessnote>\\n\"", "%", "proc", ".", "read", "(", ")", "elif", "len", "(", "process_file", ")", ">", "0", ":", "Logger", "(", "\"HFIRSANSReduction\"", ")", ".", "error", "(", "\"Could not read %s\\n\"", "%", "process_file", ")", "if", "property_manager", ".", "existsProperty", "(", "\"SetupAlgorithm\"", ")", ":", "setup_info", "=", "property_manager", ".", "getProperty", "(", "\"SetupAlgorithm\"", ")", ".", "value", "proc_xml", "+=", "\"\\n<SASprocessnote>\\n<Reduction>\\n\"", "# The instrument name refers to the UI, which is named BIOSANS for all HFIR SANS", "proc_xml", "+=", "\" <instrument_name>BIOSANS</instrument_name>\\n\"", "proc_xml", "+=", "\" <SetupInfo>%s</SetupInfo>\\n\"", "%", "setup_info", "filename", "=", "self", ".", "getProperty", "(", "\"Filename\"", ")", ".", "value", "proc_xml", "+=", "\" <Filename>%s</Filename>\\n\"", "%", "filename", "proc_xml", "+=", "\"</Reduction>\\n</SASprocessnote>\\n\"", "filename", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "iq_ws", "+", "'.txt'", ")", "alg", "=", "AlgorithmManager", ".", "create", "(", "\"SaveAscii\"", ")", "alg", ".", "initialize", "(", ")", "alg", ".", "setChild", "(", "True", ")", "alg", ".", "setProperty", "(", "\"Filename\"", ",", "filename", ")", "alg", ".", "setProperty", "(", "\"InputWorkspace\"", ",", "iq_ws", ")", "alg", ".", "setProperty", "(", "\"Separator\"", ",", "\"Tab\"", ")", "alg", ".", "setProperty", "(", "\"CommentIndicator\"", ",", "\"# \"", ")", "alg", ".", "setProperty", "(", "\"WriteXError\"", ",", "True", ")", "alg", ".", "setProperty", "(", "\"WriteSpectrumID\"", ",", "False", ")", "alg", ".", "execute", "(", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "iq_ws", "+", "'.xml'", ")", "alg", "=", "AlgorithmManager", ".", "create", "(", "\"SaveCanSAS1D\"", ")", "alg", ".", "initialize", "(", ")", "alg", ".", "setChild", "(", "True", ")", "alg", ".", "setProperty", "(", "\"Filename\"", ",", "filename", ")", "alg", ".", "setProperty", "(", "\"InputWorkspace\"", ",", "iq_ws", ")", "alg", ".", "setProperty", "(", "\"Process\"", ",", "proc_xml", ")", "alg", ".", "execute", "(", ")", "return", "filename", "else", ":", "Logger", "(", "\"HFIRSANSReduction\"", ")", ".", "error", "(", "\"No I(Q) output found for %s\"", "%", "iq_ws", ")", "# Save I(Q), including all wedges", "ws_list", "=", "AnalysisDataService", ".", "getObjectNames", "(", ")", "for", "item", "in", "ws_list", ":", "if", "iq_output", "is", "not", "None", "and", "item", ".", "startswith", "(", "iq_output", ")", "and", "(", "iqxy_output", "is", "None", "or", "not", "item", ".", "startswith", "(", "iqxy_output", ")", ")", ":", "filename", "=", "_save_ws", "(", "item", ")", "if", "filename", "is", "not", "None", ":", "output_msg", "+=", "\"I(Q) saved in %s\\n\"", "%", "(", "filename", ")", "# Save I(Qx,Qy)", "if", "iqxy_output", "is", "not", "None", ":", "if", "AnalysisDataService", ".", "doesExist", "(", "iqxy_output", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "iqxy_output", "+", "'.dat'", ")", "alg", "=", "AlgorithmManager", ".", "create", "(", "\"SaveNISTDAT\"", ")", "alg", ".", "initialize", "(", ")", "alg", ".", "setChild", "(", "True", ")", "alg", ".", "setProperty", "(", "\"Filename\"", ",", "filename", ")", "alg", ".", "setProperty", "(", "\"InputWorkspace\"", ",", "iqxy_output", ")", "alg", ".", "execute", "(", ")", "#api.SaveNISTDAT(InputWorkspace=iqxy_output, Filename=filename)", "output_msg", "+=", "\"I(Qx,Qy) saved in %s\\n\"", "%", "(", "filename", ")", "else", ":", "Logger", "(", "\"HFIRSANSReduction\"", ")", ".", "error", "(", "\"No I(Qx,Qy) output found\"", ")", "return", "output_msg" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py#L399-L479
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
ImageList.GetImageCount
(*args, **kwargs)
return _gdi_.ImageList_GetImageCount(*args, **kwargs)
GetImageCount(self) -> int
GetImageCount(self) -> int
[ "GetImageCount", "(", "self", ")", "-", ">", "int" ]
def GetImageCount(*args, **kwargs): """GetImageCount(self) -> int""" return _gdi_.ImageList_GetImageCount(*args, **kwargs)
[ "def", "GetImageCount", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "ImageList_GetImageCount", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L6950-L6952
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pkg_resources/_vendor/six.py
python
add_move
(move)
Add an item to six.moves.
Add an item to six.moves.
[ "Add", "an", "item", "to", "six", ".", "moves", "." ]
def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move)
[ "def", "add_move", "(", "move", ")", ":", "setattr", "(", "_MovedItems", ",", "move", ".", "name", ",", "move", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pkg_resources/_vendor/six.py#L486-L488
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/dashboard/dashboard/__init__.py
python
_CatapultThirdPartyLibraryPaths
()
return paths
Returns a list of required third-party libraries in catapult.
Returns a list of required third-party libraries in catapult.
[ "Returns", "a", "list", "of", "required", "third", "-", "party", "libraries", "in", "catapult", "." ]
def _CatapultThirdPartyLibraryPaths(): """Returns a list of required third-party libraries in catapult.""" paths = [] for library in THIRD_PARTY_LIBRARIES: paths.append(os.path.join(_CATAPULT_PATH, 'third_party', library)) return paths
[ "def", "_CatapultThirdPartyLibraryPaths", "(", ")", ":", "paths", "=", "[", "]", "for", "library", "in", "THIRD_PARTY_LIBRARIES", ":", "paths", ".", "append", "(", "os", ".", "path", ".", "join", "(", "_CATAPULT_PATH", ",", "'third_party'", ",", "library", ")", ")", "return", "paths" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/dashboard/dashboard/__init__.py#L86-L91
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Arch/ArchNesting.py
python
Nester.clear
(self)
clear(): Removes all objects and shape from the nester
clear(): Removes all objects and shape from the nester
[ "clear", "()", ":", "Removes", "all", "objects", "and", "shape", "from", "the", "nester" ]
def clear(self): """clear(): Removes all objects and shape from the nester""" self.objects = None self.shapes = None
[ "def", "clear", "(", "self", ")", ":", "self", ".", "objects", "=", "None", "self", ".", "shapes", "=", "None" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Arch/ArchNesting.py#L95-L100
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py
python
Wm.wm_grid
(self, baseWidth=None, baseHeight=None, widthInc=None, heightInc=None)
return self._getints(self.tk.call( 'wm', 'grid', self._w, baseWidth, baseHeight, widthInc, heightInc))
Instruct the window manager that this widget shall only be resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the number of grid units requested in Tk_GeometryRequest.
Instruct the window manager that this widget shall only be resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the number of grid units requested in Tk_GeometryRequest.
[ "Instruct", "the", "window", "manager", "that", "this", "widget", "shall", "only", "be", "resized", "on", "grid", "boundaries", ".", "WIDTHINC", "and", "HEIGHTINC", "are", "the", "width", "and", "height", "of", "a", "grid", "unit", "in", "pixels", ".", "BASEWIDTH", "and", "BASEHEIGHT", "are", "the", "number", "of", "grid", "units", "requested", "in", "Tk_GeometryRequest", "." ]
def wm_grid(self, baseWidth=None, baseHeight=None, widthInc=None, heightInc=None): """Instruct the window manager that this widget shall only be resized on grid boundaries. WIDTHINC and HEIGHTINC are the width and height of a grid unit in pixels. BASEWIDTH and BASEHEIGHT are the number of grid units requested in Tk_GeometryRequest.""" return self._getints(self.tk.call( 'wm', 'grid', self._w, baseWidth, baseHeight, widthInc, heightInc))
[ "def", "wm_grid", "(", "self", ",", "baseWidth", "=", "None", ",", "baseHeight", "=", "None", ",", "widthInc", "=", "None", ",", "heightInc", "=", "None", ")", ":", "return", "self", ".", "_getints", "(", "self", ".", "tk", ".", "call", "(", "'wm'", ",", "'grid'", ",", "self", ".", "_w", ",", "baseWidth", ",", "baseHeight", ",", "widthInc", ",", "heightInc", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L1843-L1852
RLBot/RLBot
34332b12cf158b3ef8dbf174ae67c53683368a9d
src/main/python/rlbot/base_extension.py
python
BaseExtension.onGoalScored
(self, team)
Called when a goal has been scored. :param team: Which team scored the goal.
Called when a goal has been scored. :param team: Which team scored the goal.
[ "Called", "when", "a", "goal", "has", "been", "scored", ".", ":", "param", "team", ":", "Which", "team", "scored", "the", "goal", "." ]
def onGoalScored(self, team): """ Called when a goal has been scored. :param team: Which team scored the goal. """
[ "def", "onGoalScored", "(", "self", ",", "team", ")", ":" ]
https://github.com/RLBot/RLBot/blob/34332b12cf158b3ef8dbf174ae67c53683368a9d/src/main/python/rlbot/base_extension.py#L20-L24
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/Jinja2/py3/jinja2/runtime.py
python
LoopContext.__call__
(self, iterable: t.Iterable[V])
return self._recurse(iterable, self._recurse, depth=self.depth)
When iterating over nested data, render the body of the loop recursively with the given inner iterable data. The loop must have the ``recursive`` marker for this to work.
When iterating over nested data, render the body of the loop recursively with the given inner iterable data.
[ "When", "iterating", "over", "nested", "data", "render", "the", "body", "of", "the", "loop", "recursively", "with", "the", "given", "inner", "iterable", "data", "." ]
def __call__(self, iterable: t.Iterable[V]) -> str: """When iterating over nested data, render the body of the loop recursively with the given inner iterable data. The loop must have the ``recursive`` marker for this to work. """ if self._recurse is None: raise TypeError( "The loop must have the 'recursive' marker to be called recursively." ) return self._recurse(iterable, self._recurse, depth=self.depth)
[ "def", "__call__", "(", "self", ",", "iterable", ":", "t", ".", "Iterable", "[", "V", "]", ")", "->", "str", ":", "if", "self", ".", "_recurse", "is", "None", ":", "raise", "TypeError", "(", "\"The loop must have the 'recursive' marker to be called recursively.\"", ")", "return", "self", ".", "_recurse", "(", "iterable", ",", "self", ".", "_recurse", ",", "depth", "=", "self", ".", "depth", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/Jinja2/py3/jinja2/runtime.py#L618-L629
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/typing/templates.py
python
_OverloadFunctionTemplate._get_impl
(self, args, kws)
return impl, args
Get implementation given the argument types. Returning a Dispatcher object. The Dispatcher object is cached internally in `self._impl_cache`.
Get implementation given the argument types.
[ "Get", "implementation", "given", "the", "argument", "types", "." ]
def _get_impl(self, args, kws): """Get implementation given the argument types. Returning a Dispatcher object. The Dispatcher object is cached internally in `self._impl_cache`. """ cache_key = self.context, tuple(args), tuple(kws.items()) try: impl, args = self._impl_cache[cache_key] except KeyError: impl, args = self._build_impl(cache_key, args, kws) return impl, args
[ "def", "_get_impl", "(", "self", ",", "args", ",", "kws", ")", ":", "cache_key", "=", "self", ".", "context", ",", "tuple", "(", "args", ")", ",", "tuple", "(", "kws", ".", "items", "(", ")", ")", "try", ":", "impl", ",", "args", "=", "self", ".", "_impl_cache", "[", "cache_key", "]", "except", "KeyError", ":", "impl", ",", "args", "=", "self", ".", "_build_impl", "(", "cache_key", ",", "args", ",", "kws", ")", "return", "impl", ",", "args" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/typing/templates.py#L498-L509
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/contrib/learn/python/learn/preprocessing/text.py
python
ByteProcessor.reverse
(self, x)
Reverses output of transform back to text. Args: x: iterator or matrix of integers. Document representation in bytes. Yields: Iterators of utf-8 strings.
Reverses output of transform back to text.
[ "Reverses", "output", "of", "transform", "back", "to", "text", "." ]
def reverse(self, x): """Reverses output of transform back to text. Args: x: iterator or matrix of integers. Document representation in bytes. Yields: Iterators of utf-8 strings. """ for data in x: document = np.trim_zeros(data.astype(np.int8), trim='b').tostring() try: yield document.decode('utf-8') except UnicodeDecodeError: yield ''
[ "def", "reverse", "(", "self", ",", "x", ")", ":", "for", "data", "in", "x", ":", "document", "=", "np", ".", "trim_zeros", "(", "data", ".", "astype", "(", "np", ".", "int8", ")", ",", "trim", "=", "'b'", ")", ".", "tostring", "(", ")", "try", ":", "yield", "document", ".", "decode", "(", "'utf-8'", ")", "except", "UnicodeDecodeError", ":", "yield", "''" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/contrib/learn/python/learn/preprocessing/text.py#L69-L83
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/pyparsing.py
python
nestedExpr
(opener="(", closer=")", content=None, ignoreExpr=quotedString.copy())
return ret
Helper method for defining nested lists enclosed in opening and closing delimiters ("(" and ")" are the default). Parameters: - opener - opening character for a nested list (default=C{"("}); can also be a pyparsing expression - closer - closing character for a nested list (default=C{")"}); can also be a pyparsing expression - content - expression for items within the nested lists (default=C{None}) - ignoreExpr - expression for ignoring opening and closing delimiters (default=C{quotedString}) If an expression is not provided for the content argument, the nested expression will capture all whitespace-delimited content between delimiters as a list of separate values. Use the C{ignoreExpr} argument to define expressions that may contain opening or closing characters that should not be treated as opening or closing characters for nesting, such as quotedString or a comment expression. Specify multiple expressions using an C{L{Or}} or C{L{MatchFirst}}. The default is L{quotedString}, but if no expressions are to be ignored, then pass C{None} for this argument. Example:: data_type = oneOf("void int short long char float double") decl_data_type = Combine(data_type + Optional(Word('*'))) ident = Word(alphas+'_', alphanums+'_') number = pyparsing_common.number arg = Group(decl_data_type + ident) LPAR,RPAR = map(Suppress, "()") code_body = nestedExpr('{', '}', ignoreExpr=(quotedString | cStyleComment)) c_function = (decl_data_type("type") + ident("name") + LPAR + Optional(delimitedList(arg), [])("args") + RPAR + code_body("body")) c_function.ignore(cStyleComment) source_code = ''' int is_odd(int x) { return (x%2); } int dec_to_hex(char hchar) { if (hchar >= '0' && hchar <= '9') { return (ord(hchar)-ord('0')); } else { return (10+ord(hchar)-ord('A')); } } ''' for func in c_function.searchString(source_code): print("%(name)s (%(type)s) args: %(args)s" % func) prints:: is_odd (int) args: [['int', 'x']] dec_to_hex (int) args: [['char', 'hchar']]
Helper method for defining nested lists enclosed in opening and closing delimiters ("(" and ")" are the default).
[ "Helper", "method", "for", "defining", "nested", "lists", "enclosed", "in", "opening", "and", "closing", "delimiters", "(", "(", "and", ")", "are", "the", "default", ")", "." ]
def nestedExpr(opener="(", closer=")", content=None, ignoreExpr=quotedString.copy()): """ Helper method for defining nested lists enclosed in opening and closing delimiters ("(" and ")" are the default). Parameters: - opener - opening character for a nested list (default=C{"("}); can also be a pyparsing expression - closer - closing character for a nested list (default=C{")"}); can also be a pyparsing expression - content - expression for items within the nested lists (default=C{None}) - ignoreExpr - expression for ignoring opening and closing delimiters (default=C{quotedString}) If an expression is not provided for the content argument, the nested expression will capture all whitespace-delimited content between delimiters as a list of separate values. Use the C{ignoreExpr} argument to define expressions that may contain opening or closing characters that should not be treated as opening or closing characters for nesting, such as quotedString or a comment expression. Specify multiple expressions using an C{L{Or}} or C{L{MatchFirst}}. The default is L{quotedString}, but if no expressions are to be ignored, then pass C{None} for this argument. Example:: data_type = oneOf("void int short long char float double") decl_data_type = Combine(data_type + Optional(Word('*'))) ident = Word(alphas+'_', alphanums+'_') number = pyparsing_common.number arg = Group(decl_data_type + ident) LPAR,RPAR = map(Suppress, "()") code_body = nestedExpr('{', '}', ignoreExpr=(quotedString | cStyleComment)) c_function = (decl_data_type("type") + ident("name") + LPAR + Optional(delimitedList(arg), [])("args") + RPAR + code_body("body")) c_function.ignore(cStyleComment) source_code = ''' int is_odd(int x) { return (x%2); } int dec_to_hex(char hchar) { if (hchar >= '0' && hchar <= '9') { return (ord(hchar)-ord('0')); } else { return (10+ord(hchar)-ord('A')); } } ''' for func in c_function.searchString(source_code): print("%(name)s (%(type)s) args: %(args)s" % func) prints:: is_odd (int) args: [['int', 'x']] dec_to_hex (int) args: [['char', 'hchar']] """ if opener == closer: raise ValueError("opening and closing strings cannot be the same") if content is None: if isinstance(opener,basestring) and isinstance(closer,basestring): if len(opener) == 1 and len(closer)==1: if ignoreExpr is not None: content = (Combine(OneOrMore(~ignoreExpr + CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS,exact=1)) ).setParseAction(lambda t:t[0].strip())) else: content = (empty.copy()+CharsNotIn(opener+closer+ParserElement.DEFAULT_WHITE_CHARS ).setParseAction(lambda t:t[0].strip())) else: if ignoreExpr is not None: content = (Combine(OneOrMore(~ignoreExpr + ~Literal(opener) + ~Literal(closer) + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1)) ).setParseAction(lambda t:t[0].strip())) else: content = (Combine(OneOrMore(~Literal(opener) + ~Literal(closer) + CharsNotIn(ParserElement.DEFAULT_WHITE_CHARS,exact=1)) ).setParseAction(lambda t:t[0].strip())) else: raise ValueError("opening and closing arguments must be strings if no content expression is given") ret = Forward() if ignoreExpr is not None: ret <<= Group( Suppress(opener) + ZeroOrMore( ignoreExpr | ret | content ) + Suppress(closer) ) else: ret <<= Group( Suppress(opener) + ZeroOrMore( ret | content ) + Suppress(closer) ) ret.setName('nested %s%s expression' % (opener,closer)) return ret
[ "def", "nestedExpr", "(", "opener", "=", "\"(\"", ",", "closer", "=", "\")\"", ",", "content", "=", "None", ",", "ignoreExpr", "=", "quotedString", ".", "copy", "(", ")", ")", ":", "if", "opener", "==", "closer", ":", "raise", "ValueError", "(", "\"opening and closing strings cannot be the same\"", ")", "if", "content", "is", "None", ":", "if", "isinstance", "(", "opener", ",", "basestring", ")", "and", "isinstance", "(", "closer", ",", "basestring", ")", ":", "if", "len", "(", "opener", ")", "==", "1", "and", "len", "(", "closer", ")", "==", "1", ":", "if", "ignoreExpr", "is", "not", "None", ":", "content", "=", "(", "Combine", "(", "OneOrMore", "(", "~", "ignoreExpr", "+", "CharsNotIn", "(", "opener", "+", "closer", "+", "ParserElement", ".", "DEFAULT_WHITE_CHARS", ",", "exact", "=", "1", ")", ")", ")", ".", "setParseAction", "(", "lambda", "t", ":", "t", "[", "0", "]", ".", "strip", "(", ")", ")", ")", "else", ":", "content", "=", "(", "empty", ".", "copy", "(", ")", "+", "CharsNotIn", "(", "opener", "+", "closer", "+", "ParserElement", ".", "DEFAULT_WHITE_CHARS", ")", ".", "setParseAction", "(", "lambda", "t", ":", "t", "[", "0", "]", ".", "strip", "(", ")", ")", ")", "else", ":", "if", "ignoreExpr", "is", "not", "None", ":", "content", "=", "(", "Combine", "(", "OneOrMore", "(", "~", "ignoreExpr", "+", "~", "Literal", "(", "opener", ")", "+", "~", "Literal", "(", "closer", ")", "+", "CharsNotIn", "(", "ParserElement", ".", "DEFAULT_WHITE_CHARS", ",", "exact", "=", "1", ")", ")", ")", ".", "setParseAction", "(", "lambda", "t", ":", "t", "[", "0", "]", ".", "strip", "(", ")", ")", ")", "else", ":", "content", "=", "(", "Combine", "(", "OneOrMore", "(", "~", "Literal", "(", "opener", ")", "+", "~", "Literal", "(", "closer", ")", "+", "CharsNotIn", "(", "ParserElement", ".", "DEFAULT_WHITE_CHARS", ",", "exact", "=", "1", ")", ")", ")", ".", "setParseAction", "(", "lambda", "t", ":", "t", "[", "0", "]", ".", "strip", "(", ")", ")", ")", "else", ":", "raise", "ValueError", "(", "\"opening and closing arguments must be strings if no content expression is given\"", ")", "ret", "=", "Forward", "(", ")", "if", "ignoreExpr", "is", "not", "None", ":", "ret", "<<=", "Group", "(", "Suppress", "(", "opener", ")", "+", "ZeroOrMore", "(", "ignoreExpr", "|", "ret", "|", "content", ")", "+", "Suppress", "(", "closer", ")", ")", "else", ":", "ret", "<<=", "Group", "(", "Suppress", "(", "opener", ")", "+", "ZeroOrMore", "(", "ret", "|", "content", ")", "+", "Suppress", "(", "closer", ")", ")", "ret", ".", "setName", "(", "'nested %s%s expression'", "%", "(", "opener", ",", "closer", ")", ")", "return", "ret" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/resource-manager-code/lib/setuptools/_vendor/pyparsing.py#L5157-L5245
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/util/protobuf/compare.py
python
NormalizeNumberFields
(pb)
return pb
Normalizes types and precisions of number fields in a protocol buffer. Due to subtleties in the python protocol buffer implementation, it is possible for values to have different types and precision depending on whether they were set and retrieved directly or deserialized from a protobuf. This function normalizes integer values to ints and longs based on width, 32-bit floats to five digits of precision to account for python always storing them as 64-bit, and ensures doubles are floating point for when they're set to integers. Modifies pb in place. Recurses into nested objects. Args: pb: proto2 message Returns: the given pb, modified in place
Normalizes types and precisions of number fields in a protocol buffer.
[ "Normalizes", "types", "and", "precisions", "of", "number", "fields", "in", "a", "protocol", "buffer", "." ]
def NormalizeNumberFields(pb): """Normalizes types and precisions of number fields in a protocol buffer. Due to subtleties in the python protocol buffer implementation, it is possible for values to have different types and precision depending on whether they were set and retrieved directly or deserialized from a protobuf. This function normalizes integer values to ints and longs based on width, 32-bit floats to five digits of precision to account for python always storing them as 64-bit, and ensures doubles are floating point for when they're set to integers. Modifies pb in place. Recurses into nested objects. Args: pb: proto2 message Returns: the given pb, modified in place """ for desc, values in pb.ListFields(): is_repeated = True if desc.label is not descriptor.FieldDescriptor.LABEL_REPEATED: is_repeated = False values = [values] normalized_values = None # We force 32-bit values to int and 64-bit values to long to make # alternate implementations where the distinction is more significant # (e.g. the C++ implementation) simpler. if desc.type in (descriptor.FieldDescriptor.TYPE_INT64, descriptor.FieldDescriptor.TYPE_UINT64, descriptor.FieldDescriptor.TYPE_SINT64): normalized_values = [int(x) for x in values] elif desc.type in (descriptor.FieldDescriptor.TYPE_INT32, descriptor.FieldDescriptor.TYPE_UINT32, descriptor.FieldDescriptor.TYPE_SINT32, descriptor.FieldDescriptor.TYPE_ENUM): normalized_values = [int(x) for x in values] elif desc.type == descriptor.FieldDescriptor.TYPE_FLOAT: normalized_values = [round(x, 6) for x in values] elif desc.type == descriptor.FieldDescriptor.TYPE_DOUBLE: normalized_values = [round(float(x), 7) for x in values] if normalized_values is not None: if is_repeated: pb.ClearField(desc.name) getattr(pb, desc.name).extend(normalized_values) else: setattr(pb, desc.name, normalized_values[0]) if (desc.type == descriptor.FieldDescriptor.TYPE_MESSAGE or desc.type == descriptor.FieldDescriptor.TYPE_GROUP): if (desc.type == descriptor.FieldDescriptor.TYPE_MESSAGE and desc.message_type.has_options and desc.message_type.GetOptions().map_entry): # This is a map, only recurse if the values have a message type. if (desc.message_type.fields_by_number[2].type == descriptor.FieldDescriptor.TYPE_MESSAGE): for v in six.itervalues(values): NormalizeNumberFields(v) else: for v in values: # recursive step NormalizeNumberFields(v) return pb
[ "def", "NormalizeNumberFields", "(", "pb", ")", ":", "for", "desc", ",", "values", "in", "pb", ".", "ListFields", "(", ")", ":", "is_repeated", "=", "True", "if", "desc", ".", "label", "is", "not", "descriptor", ".", "FieldDescriptor", ".", "LABEL_REPEATED", ":", "is_repeated", "=", "False", "values", "=", "[", "values", "]", "normalized_values", "=", "None", "# We force 32-bit values to int and 64-bit values to long to make", "# alternate implementations where the distinction is more significant", "# (e.g. the C++ implementation) simpler.", "if", "desc", ".", "type", "in", "(", "descriptor", ".", "FieldDescriptor", ".", "TYPE_INT64", ",", "descriptor", ".", "FieldDescriptor", ".", "TYPE_UINT64", ",", "descriptor", ".", "FieldDescriptor", ".", "TYPE_SINT64", ")", ":", "normalized_values", "=", "[", "int", "(", "x", ")", "for", "x", "in", "values", "]", "elif", "desc", ".", "type", "in", "(", "descriptor", ".", "FieldDescriptor", ".", "TYPE_INT32", ",", "descriptor", ".", "FieldDescriptor", ".", "TYPE_UINT32", ",", "descriptor", ".", "FieldDescriptor", ".", "TYPE_SINT32", ",", "descriptor", ".", "FieldDescriptor", ".", "TYPE_ENUM", ")", ":", "normalized_values", "=", "[", "int", "(", "x", ")", "for", "x", "in", "values", "]", "elif", "desc", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_FLOAT", ":", "normalized_values", "=", "[", "round", "(", "x", ",", "6", ")", "for", "x", "in", "values", "]", "elif", "desc", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_DOUBLE", ":", "normalized_values", "=", "[", "round", "(", "float", "(", "x", ")", ",", "7", ")", "for", "x", "in", "values", "]", "if", "normalized_values", "is", "not", "None", ":", "if", "is_repeated", ":", "pb", ".", "ClearField", "(", "desc", ".", "name", ")", "getattr", "(", "pb", ",", "desc", ".", "name", ")", ".", "extend", "(", "normalized_values", ")", "else", ":", "setattr", "(", "pb", ",", "desc", ".", "name", ",", "normalized_values", "[", "0", "]", ")", "if", "(", "desc", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_MESSAGE", "or", "desc", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_GROUP", ")", ":", "if", "(", "desc", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_MESSAGE", "and", "desc", ".", "message_type", ".", "has_options", "and", "desc", ".", "message_type", ".", "GetOptions", "(", ")", ".", "map_entry", ")", ":", "# This is a map, only recurse if the values have a message type.", "if", "(", "desc", ".", "message_type", ".", "fields_by_number", "[", "2", "]", ".", "type", "==", "descriptor", ".", "FieldDescriptor", ".", "TYPE_MESSAGE", ")", ":", "for", "v", "in", "six", ".", "itervalues", "(", "values", ")", ":", "NormalizeNumberFields", "(", "v", ")", "else", ":", "for", "v", "in", "values", ":", "# recursive step", "NormalizeNumberFields", "(", "v", ")", "return", "pb" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/util/protobuf/compare.py#L107-L172
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/foldpanelbar.py
python
CaptionBarStyle.__init__
(self)
Default constructor for this class.
Default constructor for this class.
[ "Default", "constructor", "for", "this", "class", "." ]
def __init__(self): """ Default constructor for this class. """ self.ResetDefaults()
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "ResetDefaults", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/foldpanelbar.py#L310-L313
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/pdb.py
python
Pdb.do_display
(self, arg)
display [expression] Display the value of the expression if it changed, each time execution stops in the current frame. Without expression, list all display expressions for the current frame.
display [expression]
[ "display", "[", "expression", "]" ]
def do_display(self, arg): """display [expression] Display the value of the expression if it changed, each time execution stops in the current frame. Without expression, list all display expressions for the current frame. """ if not arg: self.message('Currently displaying:') for item in self.displaying.get(self.curframe, {}).items(): self.message('%s: %r' % item) else: val = self._getval_except(arg) self.displaying.setdefault(self.curframe, {})[arg] = val self.message('display %s: %r' % (arg, val))
[ "def", "do_display", "(", "self", ",", "arg", ")", ":", "if", "not", "arg", ":", "self", ".", "message", "(", "'Currently displaying:'", ")", "for", "item", "in", "self", ".", "displaying", ".", "get", "(", "self", ".", "curframe", ",", "{", "}", ")", ".", "items", "(", ")", ":", "self", ".", "message", "(", "'%s: %r'", "%", "item", ")", "else", ":", "val", "=", "self", ".", "_getval_except", "(", "arg", ")", "self", ".", "displaying", ".", "setdefault", "(", "self", ".", "curframe", ",", "{", "}", ")", "[", "arg", "]", "=", "val", "self", ".", "message", "(", "'display %s: %r'", "%", "(", "arg", ",", "val", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/pdb.py#L1334-L1349
ycm-core/ycmd
fc0fb7e5e15176cc5a2a30c80956335988c6b59a
ycmd/completers/language_server/language_server_protocol.py
python
CodepointsToUTF16CodeUnits
( line_value, codepoint_offset )
return len( value_as_utf16 ) // 2
Return the 1-based UTF-16 code unit offset equivalent to the 1-based unicode codepoint offset |codepoint_offset| in the Unicode string |line_value|
Return the 1-based UTF-16 code unit offset equivalent to the 1-based unicode codepoint offset |codepoint_offset| in the Unicode string |line_value|
[ "Return", "the", "1", "-", "based", "UTF", "-", "16", "code", "unit", "offset", "equivalent", "to", "the", "1", "-", "based", "unicode", "codepoint", "offset", "|codepoint_offset|", "in", "the", "Unicode", "string", "|line_value|" ]
def CodepointsToUTF16CodeUnits( line_value, codepoint_offset ): """Return the 1-based UTF-16 code unit offset equivalent to the 1-based unicode codepoint offset |codepoint_offset| in the Unicode string |line_value|""" # Language server protocol requires offsets to be in utf16 code _units_. # Each code unit is 2 bytes. # So we re-encode the line as utf-16 and divide the length in bytes by 2. # # Of course, this is a terrible API, but until all the servers support any # change out of # https://github.com/Microsoft/language-server-protocol/issues/376 then we # have to jump through hoops. if codepoint_offset > len( line_value ): return ( len( line_value.encode( 'utf-16-le' ) ) + 2 ) // 2 value_as_utf16 = line_value[ : codepoint_offset ].encode( 'utf-16-le' ) return len( value_as_utf16 ) // 2
[ "def", "CodepointsToUTF16CodeUnits", "(", "line_value", ",", "codepoint_offset", ")", ":", "# Language server protocol requires offsets to be in utf16 code _units_.", "# Each code unit is 2 bytes.", "# So we re-encode the line as utf-16 and divide the length in bytes by 2.", "#", "# Of course, this is a terrible API, but until all the servers support any", "# change out of", "# https://github.com/Microsoft/language-server-protocol/issues/376 then we", "# have to jump through hoops.", "if", "codepoint_offset", ">", "len", "(", "line_value", ")", ":", "return", "(", "len", "(", "line_value", ".", "encode", "(", "'utf-16-le'", ")", ")", "+", "2", ")", "//", "2", "value_as_utf16", "=", "line_value", "[", ":", "codepoint_offset", "]", ".", "encode", "(", "'utf-16-le'", ")", "return", "len", "(", "value_as_utf16", ")", "//", "2" ]
https://github.com/ycm-core/ycmd/blob/fc0fb7e5e15176cc5a2a30c80956335988c6b59a/ycmd/completers/language_server/language_server_protocol.py#L691-L707
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/contrib/learn/python/learn/dataframe/dataframe.py
python
DataFrame.exclude_columns
(self, exclude_keys)
return result
Returns a new DataFrame with all columns not excluded via exclude_keys. Args: exclude_keys: A list of strings. Each should be the name of a column in the DataFrame. These columns will be excluded from the result. Returns: A new DataFrame containing all columns except those specified.
Returns a new DataFrame with all columns not excluded via exclude_keys.
[ "Returns", "a", "new", "DataFrame", "with", "all", "columns", "not", "excluded", "via", "exclude_keys", "." ]
def exclude_columns(self, exclude_keys): """Returns a new DataFrame with all columns not excluded via exclude_keys. Args: exclude_keys: A list of strings. Each should be the name of a column in the DataFrame. These columns will be excluded from the result. Returns: A new DataFrame containing all columns except those specified. """ result = type(self)() for key, value in self._columns.items(): if key not in exclude_keys: result[key] = value return result
[ "def", "exclude_columns", "(", "self", ",", "exclude_keys", ")", ":", "result", "=", "type", "(", "self", ")", "(", ")", "for", "key", ",", "value", "in", "self", ".", "_columns", ".", "items", "(", ")", ":", "if", "key", "not", "in", "exclude_keys", ":", "result", "[", "key", "]", "=", "value", "return", "result" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/contrib/learn/python/learn/dataframe/dataframe.py#L90-L103
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/rnn/python/ops/rnn_cell.py
python
HighwayWrapper.__init__
(self, cell, couple_carry_transform_gates=True, carry_bias_init=1.0)
Constructs a `HighwayWrapper` for `cell`. Args: cell: An instance of `RNNCell`. couple_carry_transform_gates: boolean, should the Carry and Transform gate be coupled. carry_bias_init: float, carry gates bias initialization.
Constructs a `HighwayWrapper` for `cell`.
[ "Constructs", "a", "HighwayWrapper", "for", "cell", "." ]
def __init__(self, cell, couple_carry_transform_gates=True, carry_bias_init=1.0): """Constructs a `HighwayWrapper` for `cell`. Args: cell: An instance of `RNNCell`. couple_carry_transform_gates: boolean, should the Carry and Transform gate be coupled. carry_bias_init: float, carry gates bias initialization. """ self._cell = cell self._couple_carry_transform_gates = couple_carry_transform_gates self._carry_bias_init = carry_bias_init
[ "def", "__init__", "(", "self", ",", "cell", ",", "couple_carry_transform_gates", "=", "True", ",", "carry_bias_init", "=", "1.0", ")", ":", "self", ".", "_cell", "=", "cell", "self", ".", "_couple_carry_transform_gates", "=", "couple_carry_transform_gates", "self", ".", "_carry_bias_init", "=", "carry_bias_init" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/rnn/python/ops/rnn_cell.py#L1173-L1186
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_distutils/archive_util.py
python
_get_uid
(name)
return None
Returns an uid, given a user name.
Returns an uid, given a user name.
[ "Returns", "an", "uid", "given", "a", "user", "name", "." ]
def _get_uid(name): """Returns an uid, given a user name.""" if getpwnam is None or name is None: return None try: result = getpwnam(name) except KeyError: result = None if result is not None: return result[2] return None
[ "def", "_get_uid", "(", "name", ")", ":", "if", "getpwnam", "is", "None", "or", "name", "is", "None", ":", "return", "None", "try", ":", "result", "=", "getpwnam", "(", "name", ")", "except", "KeyError", ":", "result", "=", "None", "if", "result", "is", "not", "None", ":", "return", "result", "[", "2", "]", "return", "None" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_distutils/archive_util.py#L43-L53
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/DiamondAttenuationCorrection/FitTransReadUB.py
python
pkintread
(hkl, loc)
return pkint
%reads calculated Fcalc and converts to %Fobs using Buras-Gerard Eqn. %inputs are hkl(nref,3) and % loc(nref,3), which contains, lambda, d-spacing and ttheta for % each of the nref reflections. % get Fcalcs for diamond, generated by GSAS (using lattice parameter 3.5668 % and Uiso(C) = 0.0038 % disp('in pkintread'); returns pkint = np. array - 1D vector
%reads calculated Fcalc and converts to %Fobs using Buras-Gerard Eqn. %inputs are hkl(nref,3) and % loc(nref,3), which contains, lambda, d-spacing and ttheta for % each of the nref reflections.
[ "%reads", "calculated", "Fcalc", "and", "converts", "to", "%Fobs", "using", "Buras", "-", "Gerard", "Eqn", ".", "%inputs", "are", "hkl", "(", "nref", "3", ")", "and", "%", "loc", "(", "nref", "3", ")", "which", "contains", "lambda", "d", "-", "spacing", "and", "ttheta", "for", "%", "each", "of", "the", "nref", "reflections", "." ]
def pkintread(hkl, loc): ''' %reads calculated Fcalc and converts to %Fobs using Buras-Gerard Eqn. %inputs are hkl(nref,3) and % loc(nref,3), which contains, lambda, d-spacing and ttheta for % each of the nref reflections. % get Fcalcs for diamond, generated by GSAS (using lattice parameter 3.5668 % and Uiso(C) = 0.0038 % disp('in pkintread'); returns pkint = np. array - 1D vector ''' # A = np.genfromtxt('diamond_reflist.csv', delimiter=',', skip_header=True) # print A A = np.array([[1.00000000e+00, 1.00000000e+00, 1.00000000e+00, 8.00000000e+00, 2.06110000e+00, 5.54000000e+04], [2.00000000e+00, 2.00000000e+00, 0.00000000e+00, 1.20000000e+01, 1.26220000e+00, 7.52000000e+04], [3.00000000e+00, 1.00000000e+00, 1.00000000e+00, 2.40000000e+01, 1.07640000e+00, 2.98000000e+04], [2.00000000e+00, 2.00000000e+00, 2.00000000e+00, 8.00000000e+00, 1.03060000e+00, 2.50000000e-25], [4.00000000e+00, 0.00000000e+00, 0.00000000e+00, 6.00000000e+00, 8.92500000e-01, 4.05000000e+04], [3.00000000e+00, 3.00000000e+00, 1.00000000e+00, 2.40000000e+01, 8.19000000e-01, 1.61000000e+04], [4.00000000e+00, 2.00000000e+00, 2.00000000e+00, 2.40000000e+01, 7.28700000e-01, 2.18000000e+04], [5.00000000e+00, 1.00000000e+00, 1.00000000e+00, 2.40000000e+01, 6.87000000e-01, 8.64000000e+03], [3.00000000e+00, 3.00000000e+00, 3.00000000e+00, 8.00000000e+00, 6.87000000e-01, 8.64000000e+03], [4.00000000e+00, 4.00000000e+00, 0.00000000e+00, 1.20000000e+01, 6.31100000e-01, 1.17000000e+04], [5.00000000e+00, 3.00000000e+00, 1.00000000e+00, 4.80000000e+01, 6.03400000e-01, 4.65000000e+03], [4.00000000e+00, 4.00000000e+00, 2.00000000e+00, 2.40000000e+01, 5.95000000e-01, 1.83000000e-12], [6.00000000e+00, 2.00000000e+00, 0.00000000e+00, 2.40000000e+01, 5.64500000e-01, 6.31000000e+03], [5.00000000e+00, 3.00000000e+00, 3.00000000e+00, 2.40000000e+01, 5.44400000e-01, 2.50000000e+03], [6.00000000e+00, 2.00000000e+00, 2.00000000e+00, 2.40000000e+01, 5.38200000e-01, 8.80000000e-26], [4.00000000e+00, 4.00000000e+00, 4.00000000e+00, 8.00000000e+00, 5.15300000e-01, 3.40000000e+03], [5.00000000e+00, 5.00000000e+00, 1.00000000e+00, 2.40000000e+01, 4.99900000e-01, 1.35000000e+03], [7.00000000e+00, 1.00000000e+00, 1.00000000e+00, 2.40000000e+01, 4.99900000e-01, 1.35000000e+03], [6.00000000e+00, 4.00000000e+00, 2.00000000e+00, 4.80000000e+01, 4.77100000e-01, 1.83000000e+03], [7.00000000e+00, 3.00000000e+00, 1.00000000e+00, 4.80000000e+01, 4.64800000e-01, 7.25000000e+02], [5.00000000e+00, 5.00000000e+00, 3.00000000e+00, 2.40000000e+01, 4.64800000e-01, 7.25000000e+02], [8.00000000e+00, 0.00000000e+00, 0.00000000e+00, 6.00000000e+00, 4.46200000e-01, 9.84000000e+02], [7.00000000e+00, 3.00000000e+00, 3.00000000e+00, 2.40000000e+01, 4.36100000e-01, 3.90000000e+02], [6.00000000e+00, 4.00000000e+00, 4.00000000e+00, 2.40000000e+01, 4.32900000e-01, 1.53000000e-13], [6.00000000e+00, 6.00000000e+00, 0.00000000e+00, 1.20000000e+01, 4.20700000e-01, 5.30000000e+02], [8.00000000e+00, 2.00000000e+00, 2.00000000e+00, 2.40000000e+01, 4.20700000e-01, 5.30000000e+02], [5.00000000e+00, 5.00000000e+00, 5.00000000e+00, 8.00000000e+00, 4.12200000e-01, 2.10000000e+02], [7.00000000e+00, 5.00000000e+00, 1.00000000e+00, 4.80000000e+01, 4.12200000e-01, 2.10000000e+02], [6.00000000e+00, 6.00000000e+00, 2.00000000e+00, 2.40000000e+01, 4.09500000e-01, 1.98000000e-26], [8.00000000e+00, 4.00000000e+00, 0.00000000e+00, 2.40000000e+01, 3.99100000e-01, 2.85000000e+02], [7.00000000e+00, 5.00000000e+00, 3.00000000e+00, 4.80000000e+01, 3.91900000e-01, 1.13000000e+02], [9.00000000e+00, 1.00000000e+00, 1.00000000e+00, 2.40000000e+01, 3.91900000e-01, 1.13000000e+02], [8.00000000e+00, 4.00000000e+00, 2.00000000e+00, 4.80000000e+01, 3.89500000e-01, 4.44000000e-14], [6.00000000e+00, 6.00000000e+00, 4.00000000e+00, 2.40000000e+01, 3.80600000e-01, 1.53000000e+02], [9.00000000e+00, 3.00000000e+00, 1.00000000e+00, 4.80000000e+01, 3.74200000e-01, 6.08000000e+01], [8.00000000e+00, 4.00000000e+00, 4.00000000e+00, 2.40000000e+01, 3.64400000e-01, 8.26000000e+01], [9.00000000e+00, 3.00000000e+00, 3.00000000e+00, 2.40000000e+01, 3.58800000e-01, 3.27000000e+01], [7.00000000e+00, 5.00000000e+00, 5.00000000e+00, 2.40000000e+01, 3.58800000e-01, 3.27000000e+01], [7.00000000e+00, 7.00000000e+00, 1.00000000e+00, 2.40000000e+01, 3.58800000e-01, 3.27000000e+01]]) diamd = A[:, 4] # diamMult = A[:, 3] # unused variable diamFCalcSq = A[:, 5] nref = hkl.shape[0] # % disp(['there are: ' num2str(nref) ' reflections']); # % whos loc ''' % [i,j] = size(x); % dipspec = zeros(i,j); %array containing dip spectrum % difspec = zeros(i,j); %array containing diffraction spectrum % d = x/sqrt(2); %dspacings for this lamda range at 90 degrees % In order to calculate the scattered intensity I from the Fcalc^2, need to % apply the Buras-Gerward formula: % % Fcalc^2 = I*2*sin(theta)^2/(lamda^2*A*E*incFlux*detEffic) ''' pkint = np.zeros(nref) for i in range(nref): if loc[i][0] > 0: # % satisfies Bragg condition (otherwise ignore) Fsq = Fsqcalc(loc[i][1], diamd, diamFCalcSq) # % Fsq = 1; L = (np.sin(np.radians(loc[i][2] / 2.0))) ** 2 # Lorentz correction R = 1.0 # %dipLam(i)^4; %reflectivity correction A = 1.0 # %Absorption correction Ecor = 1 pkint[i] = Fsq * R * A / (L * Ecor) # %scattered intensity ''' % whos difspec % whos van % whos dipspec % difspec = difspec.*van; % dipspec = dipspec.*van; % figure(1) % plot(d,difspec) ''' return pkint
[ "def", "pkintread", "(", "hkl", ",", "loc", ")", ":", "# A = np.genfromtxt('diamond_reflist.csv', delimiter=',', skip_header=True)", "# print A", "A", "=", "np", ".", "array", "(", "[", "[", "1.00000000e+00", ",", "1.00000000e+00", ",", "1.00000000e+00", ",", "8.00000000e+00", ",", "2.06110000e+00", ",", "5.54000000e+04", "]", ",", "[", "2.00000000e+00", ",", "2.00000000e+00", ",", "0.00000000e+00", ",", "1.20000000e+01", ",", "1.26220000e+00", ",", "7.52000000e+04", "]", ",", "[", "3.00000000e+00", ",", "1.00000000e+00", ",", "1.00000000e+00", ",", "2.40000000e+01", ",", "1.07640000e+00", ",", "2.98000000e+04", "]", ",", "[", "2.00000000e+00", ",", "2.00000000e+00", ",", "2.00000000e+00", ",", "8.00000000e+00", ",", "1.03060000e+00", ",", "2.50000000e-25", "]", ",", "[", "4.00000000e+00", ",", "0.00000000e+00", ",", "0.00000000e+00", ",", "6.00000000e+00", ",", "8.92500000e-01", ",", "4.05000000e+04", "]", ",", "[", "3.00000000e+00", ",", "3.00000000e+00", ",", "1.00000000e+00", ",", "2.40000000e+01", ",", "8.19000000e-01", ",", "1.61000000e+04", "]", ",", "[", "4.00000000e+00", ",", "2.00000000e+00", ",", "2.00000000e+00", ",", "2.40000000e+01", ",", "7.28700000e-01", ",", "2.18000000e+04", "]", ",", "[", "5.00000000e+00", ",", "1.00000000e+00", ",", "1.00000000e+00", ",", "2.40000000e+01", ",", "6.87000000e-01", ",", "8.64000000e+03", "]", ",", "[", "3.00000000e+00", ",", "3.00000000e+00", ",", "3.00000000e+00", ",", "8.00000000e+00", ",", "6.87000000e-01", ",", "8.64000000e+03", "]", ",", "[", "4.00000000e+00", ",", "4.00000000e+00", ",", "0.00000000e+00", ",", "1.20000000e+01", ",", "6.31100000e-01", ",", "1.17000000e+04", "]", ",", "[", "5.00000000e+00", ",", "3.00000000e+00", ",", "1.00000000e+00", ",", "4.80000000e+01", ",", "6.03400000e-01", ",", "4.65000000e+03", "]", ",", "[", "4.00000000e+00", ",", "4.00000000e+00", ",", "2.00000000e+00", ",", "2.40000000e+01", ",", "5.95000000e-01", ",", "1.83000000e-12", "]", ",", "[", "6.00000000e+00", ",", "2.00000000e+00", ",", "0.00000000e+00", ",", "2.40000000e+01", ",", "5.64500000e-01", ",", "6.31000000e+03", "]", ",", "[", "5.00000000e+00", ",", "3.00000000e+00", ",", "3.00000000e+00", ",", "2.40000000e+01", ",", "5.44400000e-01", ",", "2.50000000e+03", "]", ",", "[", "6.00000000e+00", ",", "2.00000000e+00", ",", "2.00000000e+00", ",", "2.40000000e+01", ",", "5.38200000e-01", ",", "8.80000000e-26", "]", ",", "[", "4.00000000e+00", ",", "4.00000000e+00", ",", "4.00000000e+00", ",", "8.00000000e+00", ",", "5.15300000e-01", ",", "3.40000000e+03", "]", ",", "[", "5.00000000e+00", ",", "5.00000000e+00", ",", "1.00000000e+00", ",", "2.40000000e+01", ",", "4.99900000e-01", ",", "1.35000000e+03", "]", ",", "[", "7.00000000e+00", ",", "1.00000000e+00", ",", "1.00000000e+00", ",", "2.40000000e+01", ",", "4.99900000e-01", ",", "1.35000000e+03", "]", ",", "[", "6.00000000e+00", ",", "4.00000000e+00", ",", "2.00000000e+00", ",", "4.80000000e+01", ",", "4.77100000e-01", ",", "1.83000000e+03", "]", ",", "[", "7.00000000e+00", ",", "3.00000000e+00", ",", "1.00000000e+00", ",", "4.80000000e+01", ",", "4.64800000e-01", ",", "7.25000000e+02", "]", ",", "[", "5.00000000e+00", ",", "5.00000000e+00", ",", "3.00000000e+00", ",", "2.40000000e+01", ",", "4.64800000e-01", ",", "7.25000000e+02", "]", ",", "[", "8.00000000e+00", ",", "0.00000000e+00", ",", "0.00000000e+00", ",", "6.00000000e+00", ",", "4.46200000e-01", ",", "9.84000000e+02", "]", ",", "[", "7.00000000e+00", ",", "3.00000000e+00", ",", "3.00000000e+00", ",", "2.40000000e+01", ",", "4.36100000e-01", ",", "3.90000000e+02", "]", ",", "[", "6.00000000e+00", ",", "4.00000000e+00", ",", "4.00000000e+00", ",", "2.40000000e+01", ",", "4.32900000e-01", ",", "1.53000000e-13", "]", ",", "[", "6.00000000e+00", ",", "6.00000000e+00", ",", "0.00000000e+00", ",", "1.20000000e+01", ",", "4.20700000e-01", ",", "5.30000000e+02", "]", ",", "[", "8.00000000e+00", ",", "2.00000000e+00", ",", "2.00000000e+00", ",", "2.40000000e+01", ",", "4.20700000e-01", ",", "5.30000000e+02", "]", ",", "[", "5.00000000e+00", ",", "5.00000000e+00", ",", "5.00000000e+00", ",", "8.00000000e+00", ",", "4.12200000e-01", ",", "2.10000000e+02", "]", ",", "[", "7.00000000e+00", ",", "5.00000000e+00", ",", "1.00000000e+00", ",", "4.80000000e+01", ",", "4.12200000e-01", ",", "2.10000000e+02", "]", ",", "[", "6.00000000e+00", ",", "6.00000000e+00", ",", "2.00000000e+00", ",", "2.40000000e+01", ",", "4.09500000e-01", ",", "1.98000000e-26", "]", ",", "[", "8.00000000e+00", ",", "4.00000000e+00", ",", "0.00000000e+00", ",", "2.40000000e+01", ",", "3.99100000e-01", ",", "2.85000000e+02", "]", ",", "[", "7.00000000e+00", ",", "5.00000000e+00", ",", "3.00000000e+00", ",", "4.80000000e+01", ",", "3.91900000e-01", ",", "1.13000000e+02", "]", ",", "[", "9.00000000e+00", ",", "1.00000000e+00", ",", "1.00000000e+00", ",", "2.40000000e+01", ",", "3.91900000e-01", ",", "1.13000000e+02", "]", ",", "[", "8.00000000e+00", ",", "4.00000000e+00", ",", "2.00000000e+00", ",", "4.80000000e+01", ",", "3.89500000e-01", ",", "4.44000000e-14", "]", ",", "[", "6.00000000e+00", ",", "6.00000000e+00", ",", "4.00000000e+00", ",", "2.40000000e+01", ",", "3.80600000e-01", ",", "1.53000000e+02", "]", ",", "[", "9.00000000e+00", ",", "3.00000000e+00", ",", "1.00000000e+00", ",", "4.80000000e+01", ",", "3.74200000e-01", ",", "6.08000000e+01", "]", ",", "[", "8.00000000e+00", ",", "4.00000000e+00", ",", "4.00000000e+00", ",", "2.40000000e+01", ",", "3.64400000e-01", ",", "8.26000000e+01", "]", ",", "[", "9.00000000e+00", ",", "3.00000000e+00", ",", "3.00000000e+00", ",", "2.40000000e+01", ",", "3.58800000e-01", ",", "3.27000000e+01", "]", ",", "[", "7.00000000e+00", ",", "5.00000000e+00", ",", "5.00000000e+00", ",", "2.40000000e+01", ",", "3.58800000e-01", ",", "3.27000000e+01", "]", ",", "[", "7.00000000e+00", ",", "7.00000000e+00", ",", "1.00000000e+00", ",", "2.40000000e+01", ",", "3.58800000e-01", ",", "3.27000000e+01", "]", "]", ")", "diamd", "=", "A", "[", ":", ",", "4", "]", "# diamMult = A[:, 3] # unused variable", "diamFCalcSq", "=", "A", "[", ":", ",", "5", "]", "nref", "=", "hkl", ".", "shape", "[", "0", "]", "# % disp(['there are: ' num2str(nref) ' reflections']);", "# % whos loc", "'''\n % [i,j] = size(x);\n % dipspec = zeros(i,j); %array containing dip spectrum\n % difspec = zeros(i,j); %array containing diffraction spectrum\n % d = x/sqrt(2); %dspacings for this lamda range at 90 degrees\n\n % In order to calculate the scattered intensity I from the Fcalc^2, need to\n % apply the Buras-Gerward formula:\n %\n % Fcalc^2 = I*2*sin(theta)^2/(lamda^2*A*E*incFlux*detEffic)\n '''", "pkint", "=", "np", ".", "zeros", "(", "nref", ")", "for", "i", "in", "range", "(", "nref", ")", ":", "if", "loc", "[", "i", "]", "[", "0", "]", ">", "0", ":", "# % satisfies Bragg condition (otherwise ignore)", "Fsq", "=", "Fsqcalc", "(", "loc", "[", "i", "]", "[", "1", "]", ",", "diamd", ",", "diamFCalcSq", ")", "# % Fsq = 1;", "L", "=", "(", "np", ".", "sin", "(", "np", ".", "radians", "(", "loc", "[", "i", "]", "[", "2", "]", "/", "2.0", ")", ")", ")", "**", "2", "# Lorentz correction", "R", "=", "1.0", "# %dipLam(i)^4; %reflectivity correction", "A", "=", "1.0", "# %Absorption correction", "Ecor", "=", "1", "pkint", "[", "i", "]", "=", "Fsq", "*", "R", "*", "A", "/", "(", "L", "*", "Ecor", ")", "# %scattered intensity", "'''\n % whos difspec\n % whos van\n % whos dipspec\n\n % difspec = difspec.*van;\n % dipspec = dipspec.*van;\n\n % figure(1)\n % plot(d,difspec)\n '''", "return", "pkint" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/DiamondAttenuationCorrection/FitTransReadUB.py#L255-L394
echronos/echronos
c996f1d2c8af6c6536205eb319c1bf1d4d84569c
external_tools/ply_info/example/ansic/cparse.py
python
p_empty
(t)
empty :
empty :
[ "empty", ":" ]
def p_empty(t): 'empty : ' pass
[ "def", "p_empty", "(", "t", ")", ":", "pass" ]
https://github.com/echronos/echronos/blob/c996f1d2c8af6c6536205eb319c1bf1d4d84569c/external_tools/ply_info/example/ansic/cparse.py#L847-L849
Tencent/CMONGO
c40380caa14e05509f46993aa8b8da966b09b0b5
src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/cc.py
python
add_common_cc_variables
(env)
Add underlying common "C compiler" variables that are used by multiple tools (specifically, c++).
Add underlying common "C compiler" variables that are used by multiple tools (specifically, c++).
[ "Add", "underlying", "common", "C", "compiler", "variables", "that", "are", "used", "by", "multiple", "tools", "(", "specifically", "c", "++", ")", "." ]
def add_common_cc_variables(env): """ Add underlying common "C compiler" variables that are used by multiple tools (specifically, c++). """ if '_CCCOMCOM' not in env: env['_CCCOMCOM'] = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS' # It's a hack to test for darwin here, but the alternative # of creating an applecc.py to contain this seems overkill. # Maybe someday the Apple platform will require more setup and # this logic will be moved. env['FRAMEWORKS'] = SCons.Util.CLVar('') env['FRAMEWORKPATH'] = SCons.Util.CLVar('') if env['PLATFORM'] == 'darwin': env['_CCCOMCOM'] = env['_CCCOMCOM'] + ' $_FRAMEWORKPATH' if 'CCFLAGS' not in env: env['CCFLAGS'] = SCons.Util.CLVar('') if 'SHCCFLAGS' not in env: env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
[ "def", "add_common_cc_variables", "(", "env", ")", ":", "if", "'_CCCOMCOM'", "not", "in", "env", ":", "env", "[", "'_CCCOMCOM'", "]", "=", "'$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS'", "# It's a hack to test for darwin here, but the alternative", "# of creating an applecc.py to contain this seems overkill.", "# Maybe someday the Apple platform will require more setup and", "# this logic will be moved.", "env", "[", "'FRAMEWORKS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "''", ")", "env", "[", "'FRAMEWORKPATH'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "''", ")", "if", "env", "[", "'PLATFORM'", "]", "==", "'darwin'", ":", "env", "[", "'_CCCOMCOM'", "]", "=", "env", "[", "'_CCCOMCOM'", "]", "+", "' $_FRAMEWORKPATH'", "if", "'CCFLAGS'", "not", "in", "env", ":", "env", "[", "'CCFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "''", ")", "if", "'SHCCFLAGS'", "not", "in", "env", ":", "env", "[", "'SHCCFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "'$CCFLAGS'", ")" ]
https://github.com/Tencent/CMONGO/blob/c40380caa14e05509f46993aa8b8da966b09b0b5/src/third_party/scons-2.5.0/scons-local-2.5.0/SCons/Tool/cc.py#L43-L63
eomahony/Numberjack
53fa9e994a36f881ffd320d8d04158097190aad8
Numberjack/__init__.py
python
Domain.__init__
(self, arg1, arg2=None)
\internal This class is used to wrap the domain of variables in order to print them and/or iterate over values Initialised from a list of values, or a lower and an upper bound
\internal This class is used to wrap the domain of variables in order to print them and/or iterate over values
[ "\\", "internal", "This", "class", "is", "used", "to", "wrap", "the", "domain", "of", "variables", "in", "order", "to", "print", "them", "and", "/", "or", "iterate", "over", "values" ]
def __init__(self, arg1, arg2=None): """ \internal This class is used to wrap the domain of variables in order to print them and/or iterate over values Initialised from a list of values, or a lower and an upper bound """ if arg2 is None: list.__init__(self, arg1) self.sort() self.is_bound = False else: list.__init__(self, [arg1, arg2]) self.is_bound = True self.current = -1
[ "def", "__init__", "(", "self", ",", "arg1", ",", "arg2", "=", "None", ")", ":", "if", "arg2", "is", "None", ":", "list", ".", "__init__", "(", "self", ",", "arg1", ")", "self", ".", "sort", "(", ")", "self", ".", "is_bound", "=", "False", "else", ":", "list", ".", "__init__", "(", "self", ",", "[", "arg1", ",", "arg2", "]", ")", "self", ".", "is_bound", "=", "True", "self", ".", "current", "=", "-", "1" ]
https://github.com/eomahony/Numberjack/blob/53fa9e994a36f881ffd320d8d04158097190aad8/Numberjack/__init__.py#L146-L161
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/lib2to3/pytree.py
python
WildcardPattern._bare_name_matches
(self, nodes)
return count, r
Special optimized matcher for bare_name.
Special optimized matcher for bare_name.
[ "Special", "optimized", "matcher", "for", "bare_name", "." ]
def _bare_name_matches(self, nodes): """Special optimized matcher for bare_name.""" count = 0 r = {} done = False max = len(nodes) while not done and count < max: done = True for leaf in self.content: if leaf[0].match(nodes[count], r): count += 1 done = False break r[self.name] = nodes[:count] return count, r
[ "def", "_bare_name_matches", "(", "self", ",", "nodes", ")", ":", "count", "=", "0", "r", "=", "{", "}", "done", "=", "False", "max", "=", "len", "(", "nodes", ")", "while", "not", "done", "and", "count", "<", "max", ":", "done", "=", "True", "for", "leaf", "in", "self", ".", "content", ":", "if", "leaf", "[", "0", "]", ".", "match", "(", "nodes", "[", "count", "]", ",", "r", ")", ":", "count", "+=", "1", "done", "=", "False", "break", "r", "[", "self", ".", "name", "]", "=", "nodes", "[", ":", "count", "]", "return", "count", ",", "r" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/lib2to3/pytree.py#L770-L784
microsoft/ELL
a1d6bacc37a14879cc025d9be2ba40b1a0632315
tools/utilities/pythonPlugins/src/imageConverter.py
python
main
(argv)
return list(resized)
This is a plugin for the debugCompiler tool. It expects a list of string arguments as input and it returns the image preprocessed and prepared for input to an ELL test model. The result has to be a list of floats.
This is a plugin for the debugCompiler tool. It expects a list of string arguments as input and it returns the image preprocessed and prepared for input to an ELL test model. The result has to be a list of floats.
[ "This", "is", "a", "plugin", "for", "the", "debugCompiler", "tool", ".", "It", "expects", "a", "list", "of", "string", "arguments", "as", "input", "and", "it", "returns", "the", "image", "preprocessed", "and", "prepared", "for", "input", "to", "an", "ELL", "test", "model", ".", "The", "result", "has", "to", "be", "a", "list", "of", "floats", "." ]
def main(argv): """ This is a plugin for the debugCompiler tool. It expects a list of string arguments as input and it returns the image preprocessed and prepared for input to an ELL test model. The result has to be a list of floats. """ arg_parser = argparse.ArgumentParser("imageConverter takes an image as input and converts it to an array of \ floating point numbers") arg_parser.add_argument("--bgr", default="False", help="specify True if input data should be in BGR format (default False)") arg_parser.add_argument("--width", type=int, default=0, help="resize the image to this new width (default None)") arg_parser.add_argument("--height", type=int, default=0, help="resize the image to this new height (default None)") arg_parser.add_argument("--scale", type=float, default=0, help="scale the floating point numbers by this amount (default None)") arg_parser.add_argument("--image", default=None, required=True, help="name of file containing image as png, jpg, etc (default None)") arg_parser.add_argument("--outputData", "-od", default=None, help="name of file to write the resulting raw floating point data (default None)") args = arg_parser.parse_args(argv) image = cv2.imread(args.image) if image is None: print("Error reading image {}".format(args.image)) resized = prepare_image_for_predictor(image, (args.height, args.width), args.scale, args.bgr) if args.outputData: save_raw(args.outputData, resized) return list(resized)
[ "def", "main", "(", "argv", ")", ":", "arg_parser", "=", "argparse", ".", "ArgumentParser", "(", "\"imageConverter takes an image as input and converts it to an array of \\\nfloating point numbers\"", ")", "arg_parser", ".", "add_argument", "(", "\"--bgr\"", ",", "default", "=", "\"False\"", ",", "help", "=", "\"specify True if input data should be in BGR format (default False)\"", ")", "arg_parser", ".", "add_argument", "(", "\"--width\"", ",", "type", "=", "int", ",", "default", "=", "0", ",", "help", "=", "\"resize the image to this new width (default None)\"", ")", "arg_parser", ".", "add_argument", "(", "\"--height\"", ",", "type", "=", "int", ",", "default", "=", "0", ",", "help", "=", "\"resize the image to this new height (default None)\"", ")", "arg_parser", ".", "add_argument", "(", "\"--scale\"", ",", "type", "=", "float", ",", "default", "=", "0", ",", "help", "=", "\"scale the floating point numbers by this amount (default None)\"", ")", "arg_parser", ".", "add_argument", "(", "\"--image\"", ",", "default", "=", "None", ",", "required", "=", "True", ",", "help", "=", "\"name of file containing image as png, jpg, etc (default None)\"", ")", "arg_parser", ".", "add_argument", "(", "\"--outputData\"", ",", "\"-od\"", ",", "default", "=", "None", ",", "help", "=", "\"name of file to write the resulting raw floating point data (default None)\"", ")", "args", "=", "arg_parser", ".", "parse_args", "(", "argv", ")", "image", "=", "cv2", ".", "imread", "(", "args", ".", "image", ")", "if", "image", "is", "None", ":", "print", "(", "\"Error reading image {}\"", ".", "format", "(", "args", ".", "image", ")", ")", "resized", "=", "prepare_image_for_predictor", "(", "image", ",", "(", "args", ".", "height", ",", "args", ".", "width", ")", ",", "args", ".", "scale", ",", "args", ".", "bgr", ")", "if", "args", ".", "outputData", ":", "save_raw", "(", "args", ".", "outputData", ",", "resized", ")", "return", "list", "(", "resized", ")" ]
https://github.com/microsoft/ELL/blob/a1d6bacc37a14879cc025d9be2ba40b1a0632315/tools/utilities/pythonPlugins/src/imageConverter.py#L55-L84
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/ops.py
python
get_from_proto_function
(collection_name)
Returns the from_proto function for collection_name.
Returns the from_proto function for collection_name.
[ "Returns", "the", "from_proto", "function", "for", "collection_name", "." ]
def get_from_proto_function(collection_name): """Returns the from_proto function for collection_name.""" try: return _proto_function_registry.lookup(collection_name)[2] except LookupError: return None
[ "def", "get_from_proto_function", "(", "collection_name", ")", ":", "try", ":", "return", "_proto_function_registry", ".", "lookup", "(", "collection_name", ")", "[", "2", "]", "except", "LookupError", ":", "return", "None" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/framework/ops.py#L6568-L6573
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/gyp/MakefileWriter.py
python
EscapeMakeVariableExpansion
(s)
return s.replace('$', '$$')
Make has its own variable expansion syntax using $. We must escape it for string to be interpreted literally.
Make has its own variable expansion syntax using $. We must escape it for string to be interpreted literally.
[ "Make", "has", "its", "own", "variable", "expansion", "syntax", "using", "$", ".", "We", "must", "escape", "it", "for", "string", "to", "be", "interpreted", "literally", "." ]
def EscapeMakeVariableExpansion(s): """Make has its own variable expansion syntax using $. We must escape it for string to be interpreted literally.""" return s.replace('$', '$$')
[ "def", "EscapeMakeVariableExpansion", "(", "s", ")", ":", "return", "s", ".", "replace", "(", "'$'", ",", "'$$'", ")" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/MakefileWriter.py#L110-L112
ros-perception/image_pipeline
cd4aa7ab38726d88e8e0144aa0d45ad2f236535a
camera_calibration/src/camera_calibration/calibrator.py
python
StereoCalibrator.cal
(self, limages, rimages)
:param limages: source left images containing chessboards :type limages: list of :class:`cvMat` :param rimages: source right images containing chessboards :type rimages: list of :class:`cvMat` Find chessboards in images, and runs the OpenCV calibration solver.
:param limages: source left images containing chessboards :type limages: list of :class:`cvMat` :param rimages: source right images containing chessboards :type rimages: list of :class:`cvMat`
[ ":", "param", "limages", ":", "source", "left", "images", "containing", "chessboards", ":", "type", "limages", ":", "list", "of", ":", "class", ":", "cvMat", ":", "param", "rimages", ":", "source", "right", "images", "containing", "chessboards", ":", "type", "rimages", ":", "list", "of", ":", "class", ":", "cvMat" ]
def cal(self, limages, rimages): """ :param limages: source left images containing chessboards :type limages: list of :class:`cvMat` :param rimages: source right images containing chessboards :type rimages: list of :class:`cvMat` Find chessboards in images, and runs the OpenCV calibration solver. """ goodcorners = self.collect_corners(limages, rimages) self.size = (limages[0].shape[1], limages[0].shape[0]) self.l.size = self.size self.r.size = self.size self.cal_fromcorners(goodcorners) self.calibrated = True
[ "def", "cal", "(", "self", ",", "limages", ",", "rimages", ")", ":", "goodcorners", "=", "self", ".", "collect_corners", "(", "limages", ",", "rimages", ")", "self", ".", "size", "=", "(", "limages", "[", "0", "]", ".", "shape", "[", "1", "]", ",", "limages", "[", "0", "]", ".", "shape", "[", "0", "]", ")", "self", ".", "l", ".", "size", "=", "self", ".", "size", "self", ".", "r", ".", "size", "=", "self", ".", "size", "self", ".", "cal_fromcorners", "(", "goodcorners", ")", "self", ".", "calibrated", "=", "True" ]
https://github.com/ros-perception/image_pipeline/blob/cd4aa7ab38726d88e8e0144aa0d45ad2f236535a/camera_calibration/src/camera_calibration/calibrator.py#L1072-L1086
SIPp/sipp
f44d0cf5dec0013eff8fd7b4da885d455aa82e0e
cpplint.py
python
_SetFilters
(filters)
Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die.
Sets the module's error-message filters.
[ "Sets", "the", "module", "s", "error", "-", "message", "filters", "." ]
def _SetFilters(filters): """Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.SetFilters(filters)
[ "def", "_SetFilters", "(", "filters", ")", ":", "_cpplint_state", ".", "SetFilters", "(", "filters", ")" ]
https://github.com/SIPp/sipp/blob/f44d0cf5dec0013eff8fd7b4da885d455aa82e0e/cpplint.py#L661-L671
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Tools/CryVersionSelector/backup_project_gui.py
python
configure_backup
(export_path)
return path
Opens a GUI in which the user can select where the backup is saved.
Opens a GUI in which the user can select where the backup is saved.
[ "Opens", "a", "GUI", "in", "which", "the", "user", "can", "select", "where", "the", "backup", "is", "saved", "." ]
def configure_backup(export_path): """ Opens a GUI in which the user can select where the backup is saved. """ # Return the default export_path if no GUI can be made. if not HAS_TK: return export_path iconfile = "editor_icon16.ico" if not hasattr(sys, "frozen"): iconfile = os.path.join(os.path.dirname(__file__), iconfile) else: iconfile = os.path.join(sys.prefix, iconfile) root = tk.Tk() root.iconbitmap(iconfile) app = CryConfigureBackup(export_path=export_path, master=root) app.mainloop() path = app.export_path return path
[ "def", "configure_backup", "(", "export_path", ")", ":", "# Return the default export_path if no GUI can be made.", "if", "not", "HAS_TK", ":", "return", "export_path", "iconfile", "=", "\"editor_icon16.ico\"", "if", "not", "hasattr", "(", "sys", ",", "\"frozen\"", ")", ":", "iconfile", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "iconfile", ")", "else", ":", "iconfile", "=", "os", ".", "path", ".", "join", "(", "sys", ".", "prefix", ",", "iconfile", ")", "root", "=", "tk", ".", "Tk", "(", ")", "root", ".", "iconbitmap", "(", "iconfile", ")", "app", "=", "CryConfigureBackup", "(", "export_path", "=", "export_path", ",", "master", "=", "root", ")", "app", ".", "mainloop", "(", ")", "path", "=", "app", ".", "export_path", "return", "path" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Tools/CryVersionSelector/backup_project_gui.py#L20-L41
kevinlin311tw/caffe-cvprw15
45c2a1bf0368569c54e0be4edf8d34285cf79e70
scripts/cpp_lint.py
python
ProcessLine
(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions=[])
Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _IncludeState instance in which the headers are inserted. function_state: A _FunctionState instance which counts function lines, etc. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message 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
Processes a single line in the file.
[ "Processes", "a", "single", "line", "in", "the", "file", "." ]
def ProcessLine(filename, file_extension, clean_lines, line, include_state, function_state, nesting_state, error, extra_check_functions=[]): """Processes a single line in the file. Args: filename: Filename of the file that is being processed. file_extension: The extension (dot not included) of the file. clean_lines: An array of strings, each representing a line of the file, with comments stripped. line: Number of line being processed. include_state: An _IncludeState instance in which the headers are inserted. function_state: A _FunctionState instance which counts function lines, etc. nesting_state: A _NestingState instance which maintains information about the current stack of nested blocks being parsed. error: A callable to which errors are reported, which takes 4 arguments: filename, line number, error level, and message 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 """ raw_lines = clean_lines.raw_lines ParseNolintSuppressions(filename, raw_lines[line], line, error) nesting_state.Update(filename, clean_lines, line, error) if nesting_state.stack and nesting_state.stack[-1].inline_asm != _NO_ASM: return CheckForFunctionLengths(filename, clean_lines, line, function_state, error) CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error) CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error) CheckLanguage(filename, clean_lines, line, file_extension, include_state, nesting_state, error) CheckForNonConstReference(filename, clean_lines, line, nesting_state, error) CheckForNonStandardConstructs(filename, clean_lines, line, nesting_state, error) CheckVlogArguments(filename, clean_lines, line, error) CheckCaffeAlternatives(filename, clean_lines, line, error) CheckCaffeDataLayerSetUp(filename, clean_lines, line, error) CheckCaffeRandom(filename, clean_lines, line, error) CheckPosixThreading(filename, clean_lines, line, error) CheckInvalidIncrement(filename, clean_lines, line, error) CheckMakePairUsesDeduction(filename, clean_lines, line, error) for check_fn in extra_check_functions: check_fn(filename, clean_lines, line, error)
[ "def", "ProcessLine", "(", "filename", ",", "file_extension", ",", "clean_lines", ",", "line", ",", "include_state", ",", "function_state", ",", "nesting_state", ",", "error", ",", "extra_check_functions", "=", "[", "]", ")", ":", "raw_lines", "=", "clean_lines", ".", "raw_lines", "ParseNolintSuppressions", "(", "filename", ",", "raw_lines", "[", "line", "]", ",", "line", ",", "error", ")", "nesting_state", ".", "Update", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "if", "nesting_state", ".", "stack", "and", "nesting_state", ".", "stack", "[", "-", "1", "]", ".", "inline_asm", "!=", "_NO_ASM", ":", "return", "CheckForFunctionLengths", "(", "filename", ",", "clean_lines", ",", "line", ",", "function_state", ",", "error", ")", "CheckForMultilineCommentsAndStrings", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "CheckStyle", "(", "filename", ",", "clean_lines", ",", "line", ",", "file_extension", ",", "nesting_state", ",", "error", ")", "CheckLanguage", "(", "filename", ",", "clean_lines", ",", "line", ",", "file_extension", ",", "include_state", ",", "nesting_state", ",", "error", ")", "CheckForNonConstReference", "(", "filename", ",", "clean_lines", ",", "line", ",", "nesting_state", ",", "error", ")", "CheckForNonStandardConstructs", "(", "filename", ",", "clean_lines", ",", "line", ",", "nesting_state", ",", "error", ")", "CheckVlogArguments", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "CheckCaffeAlternatives", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "CheckCaffeDataLayerSetUp", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "CheckCaffeRandom", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "CheckPosixThreading", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "CheckInvalidIncrement", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "CheckMakePairUsesDeduction", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")", "for", "check_fn", "in", "extra_check_functions", ":", "check_fn", "(", "filename", ",", "clean_lines", ",", "line", ",", "error", ")" ]
https://github.com/kevinlin311tw/caffe-cvprw15/blob/45c2a1bf0368569c54e0be4edf8d34285cf79e70/scripts/cpp_lint.py#L4600-L4642
google/certificate-transparency
2588562fd306a447958471b6f06c1069619c1641
python/ct/client/db/sqlite_temp_db.py
python
SQLiteTempDBFactory.__init__
(self, connection_manager, database_dir)
Initialize the database factory. Args: connection_manager: an SQLiteConnectionManager object database_dir: the directory where the database files reside.
Initialize the database factory. Args: connection_manager: an SQLiteConnectionManager object database_dir: the directory where the database files reside.
[ "Initialize", "the", "database", "factory", ".", "Args", ":", "connection_manager", ":", "an", "SQLiteConnectionManager", "object", "database_dir", ":", "the", "directory", "where", "the", "database", "files", "reside", "." ]
def __init__(self, connection_manager, database_dir): """Initialize the database factory. Args: connection_manager: an SQLiteConnectionManager object database_dir: the directory where the database files reside. """ self.__mgr = connection_manager self.__database_dir = database_dir # This is the meta-table mapping database IDs to server names. with self.__mgr.get_connection() as conn: conn.execute("CREATE TABLE IF NOT EXISTS database_mapping(" "id INTEGER PRIMARY KEY, server_name TEXT UNIQUE)") self.__tables = ["database_mapping"]
[ "def", "__init__", "(", "self", ",", "connection_manager", ",", "database_dir", ")", ":", "self", ".", "__mgr", "=", "connection_manager", "self", ".", "__database_dir", "=", "database_dir", "# This is the meta-table mapping database IDs to server names.", "with", "self", ".", "__mgr", ".", "get_connection", "(", ")", "as", "conn", ":", "conn", ".", "execute", "(", "\"CREATE TABLE IF NOT EXISTS database_mapping(\"", "\"id INTEGER PRIMARY KEY, server_name TEXT UNIQUE)\"", ")", "self", ".", "__tables", "=", "[", "\"database_mapping\"", "]" ]
https://github.com/google/certificate-transparency/blob/2588562fd306a447958471b6f06c1069619c1641/python/ct/client/db/sqlite_temp_db.py#L12-L24
lammps/lammps
b75c3065430a75b1b5543a10e10f46d9b4c91913
tools/i-pi/ipi/engine/outputs.py
python
PropertyOutput.open_stream
(self)
Opens the output stream.
Opens the output stream.
[ "Opens", "the", "output", "stream", "." ]
def open_stream(self): """Opens the output stream.""" try: self.out = open(self.filename, "a") except: raise ValueError("Could not open file " + self.filename + " for output") # print nice header if information is available on the properties if (self.simul.step == 0) : icol = 1 for what in self.outlist: ohead = "# " key = getkey(what) prop = self.simul.properties.property_dict[key] if "size" in prop and prop["size"] > 1: ohead += "cols. %3d-%-3d" % ( icol, icol+prop["size"] - 1 ) icol += prop["size"] else: ohead += "column %3d " % ( icol ) icol += 1 ohead += " --> %s " % (what) if "help" in prop: ohead += ": " + prop["help"] self.out.write(ohead + "\n")
[ "def", "open_stream", "(", "self", ")", ":", "try", ":", "self", ".", "out", "=", "open", "(", "self", ".", "filename", ",", "\"a\"", ")", "except", ":", "raise", "ValueError", "(", "\"Could not open file \"", "+", "self", ".", "filename", "+", "\" for output\"", ")", "# print nice header if information is available on the properties", "if", "(", "self", ".", "simul", ".", "step", "==", "0", ")", ":", "icol", "=", "1", "for", "what", "in", "self", ".", "outlist", ":", "ohead", "=", "\"# \"", "key", "=", "getkey", "(", "what", ")", "prop", "=", "self", ".", "simul", ".", "properties", ".", "property_dict", "[", "key", "]", "if", "\"size\"", "in", "prop", "and", "prop", "[", "\"size\"", "]", ">", "1", ":", "ohead", "+=", "\"cols. %3d-%-3d\"", "%", "(", "icol", ",", "icol", "+", "prop", "[", "\"size\"", "]", "-", "1", ")", "icol", "+=", "prop", "[", "\"size\"", "]", "else", ":", "ohead", "+=", "\"column %3d \"", "%", "(", "icol", ")", "icol", "+=", "1", "ohead", "+=", "\" --> %s \"", "%", "(", "what", ")", "if", "\"help\"", "in", "prop", ":", "ohead", "+=", "\": \"", "+", "prop", "[", "\"help\"", "]", "self", ".", "out", ".", "write", "(", "ohead", "+", "\"\\n\"", ")" ]
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/engine/outputs.py#L97-L122
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py
python
removeQuotes
(s,l,t)
return t[0][1:-1]
Helper parse action for removing quotation marks from parsed quoted strings. Example:: # by default, quotation marks are included in parsed results quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"] # use removeQuotes to strip quotation marks from parsed results quotedString.setParseAction(removeQuotes) quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"]
Helper parse action for removing quotation marks from parsed quoted strings.
[ "Helper", "parse", "action", "for", "removing", "quotation", "marks", "from", "parsed", "quoted", "strings", "." ]
def removeQuotes(s,l,t): """ Helper parse action for removing quotation marks from parsed quoted strings. Example:: # by default, quotation marks are included in parsed results quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["'Now is the Winter of our Discontent'"] # use removeQuotes to strip quotation marks from parsed results quotedString.setParseAction(removeQuotes) quotedString.parseString("'Now is the Winter of our Discontent'") # -> ["Now is the Winter of our Discontent"] """ return t[0][1:-1]
[ "def", "removeQuotes", "(", "s", ",", "l", ",", "t", ")", ":", "return", "t", "[", "0", "]", "[", "1", ":", "-", "1", "]" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/_vendor/pyparsing.py#L4811-L4823
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBBreakpointName.GetCommandLineCommands
(self, commands)
return _lldb.SBBreakpointName_GetCommandLineCommands(self, commands)
GetCommandLineCommands(SBBreakpointName self, SBStringList commands) -> bool
GetCommandLineCommands(SBBreakpointName self, SBStringList commands) -> bool
[ "GetCommandLineCommands", "(", "SBBreakpointName", "self", "SBStringList", "commands", ")", "-", ">", "bool" ]
def GetCommandLineCommands(self, commands): """GetCommandLineCommands(SBBreakpointName self, SBStringList commands) -> bool""" return _lldb.SBBreakpointName_GetCommandLineCommands(self, commands)
[ "def", "GetCommandLineCommands", "(", "self", ",", "commands", ")", ":", "return", "_lldb", ".", "SBBreakpointName_GetCommandLineCommands", "(", "self", ",", "commands", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L2309-L2311
ideawu/ssdb
f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4
deps/cpy/antlr3/dfa.py
python
DFA.unpack
(cls, string)
return ret
@brief Unpack the runlength encoded table data. Terence implemented packed table initializers, because Java has a size restriction on .class files and the lookup tables can grow pretty large. The generated JavaLexer.java of the Java.g example would be about 15MB with uncompressed array initializers. Python does not have any size restrictions, but the compilation of such large source files seems to be pretty memory hungry. The memory consumption of the python process grew to >1.5GB when importing a 15MB lexer, eating all my swap space and I was to impacient to see, if it could finish at all. With packed initializers that are unpacked at import time of the lexer module, everything works like a charm.
@brief Unpack the runlength encoded table data.
[ "@brief", "Unpack", "the", "runlength", "encoded", "table", "data", "." ]
def unpack(cls, string): """@brief Unpack the runlength encoded table data. Terence implemented packed table initializers, because Java has a size restriction on .class files and the lookup tables can grow pretty large. The generated JavaLexer.java of the Java.g example would be about 15MB with uncompressed array initializers. Python does not have any size restrictions, but the compilation of such large source files seems to be pretty memory hungry. The memory consumption of the python process grew to >1.5GB when importing a 15MB lexer, eating all my swap space and I was to impacient to see, if it could finish at all. With packed initializers that are unpacked at import time of the lexer module, everything works like a charm. """ ret = [] for i in range(len(string) / 2): (n, v) = ord(string[i*2]), ord(string[i*2+1]) # Is there a bitwise operation to do this? if v == 0xFFFF: v = -1 ret += [v] * n return ret
[ "def", "unpack", "(", "cls", ",", "string", ")", ":", "ret", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "string", ")", "/", "2", ")", ":", "(", "n", ",", "v", ")", "=", "ord", "(", "string", "[", "i", "*", "2", "]", ")", ",", "ord", "(", "string", "[", "i", "*", "2", "+", "1", "]", ")", "# Is there a bitwise operation to do this?", "if", "v", "==", "0xFFFF", ":", "v", "=", "-", "1", "ret", "+=", "[", "v", "]", "*", "n", "return", "ret" ]
https://github.com/ideawu/ssdb/blob/f229ba277c7f7d0ca5a441c0c6fb3d1209af68e4/deps/cpy/antlr3/dfa.py#L184-L211
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/pyct/common_transformers/anf.py
python
AnfTransformer._ensure_node_in_anf
(self, parent, field, node)
Puts `node` in A-normal form, by replacing it with a variable if needed. The exact definition of A-normal form is given by the configuration. The parent and the incoming field name are only needed because the configuration may be context-dependent. Args: parent: An AST node, the parent of `node`. field: The field name under which `node` is the child of `parent`. node: An AST node, potentially to be replaced with a variable reference. Returns: node: An AST node; the argument if transformation was not necessary, or the new variable reference if it was.
Puts `node` in A-normal form, by replacing it with a variable if needed.
[ "Puts", "node", "in", "A", "-", "normal", "form", "by", "replacing", "it", "with", "a", "variable", "if", "needed", "." ]
def _ensure_node_in_anf(self, parent, field, node): """Puts `node` in A-normal form, by replacing it with a variable if needed. The exact definition of A-normal form is given by the configuration. The parent and the incoming field name are only needed because the configuration may be context-dependent. Args: parent: An AST node, the parent of `node`. field: The field name under which `node` is the child of `parent`. node: An AST node, potentially to be replaced with a variable reference. Returns: node: An AST node; the argument if transformation was not necessary, or the new variable reference if it was. """ if node is None: return node if (isinstance(node, self._trivial_nodes) and not _is_py2_name_constant(node)): return node if isinstance(node, list): # If something's field was actually a list, e.g., variadic arguments. return [self._ensure_node_in_anf(parent, field, n) for n in node] if isinstance(node, gast.keyword): node.value = self._ensure_node_in_anf(parent, field, node.value) return node if isinstance(node, (gast.Starred, gast.withitem, gast.slice)): # These nodes aren't really extractable in their own right, but their # subnodes might be. Propagate the parent and field name to the child # nodes, instead of querying the configuration for children of, e.g., # gast.Starred. return self._ensure_fields_in_anf(node, parent, field) if self._should_transform(parent, field, node): return self._do_transform_node(node) else: return node
[ "def", "_ensure_node_in_anf", "(", "self", ",", "parent", ",", "field", ",", "node", ")", ":", "if", "node", "is", "None", ":", "return", "node", "if", "(", "isinstance", "(", "node", ",", "self", ".", "_trivial_nodes", ")", "and", "not", "_is_py2_name_constant", "(", "node", ")", ")", ":", "return", "node", "if", "isinstance", "(", "node", ",", "list", ")", ":", "# If something's field was actually a list, e.g., variadic arguments.", "return", "[", "self", ".", "_ensure_node_in_anf", "(", "parent", ",", "field", ",", "n", ")", "for", "n", "in", "node", "]", "if", "isinstance", "(", "node", ",", "gast", ".", "keyword", ")", ":", "node", ".", "value", "=", "self", ".", "_ensure_node_in_anf", "(", "parent", ",", "field", ",", "node", ".", "value", ")", "return", "node", "if", "isinstance", "(", "node", ",", "(", "gast", ".", "Starred", ",", "gast", ".", "withitem", ",", "gast", ".", "slice", ")", ")", ":", "# These nodes aren't really extractable in their own right, but their", "# subnodes might be. Propagate the parent and field name to the child", "# nodes, instead of querying the configuration for children of, e.g.,", "# gast.Starred.", "return", "self", ".", "_ensure_fields_in_anf", "(", "node", ",", "parent", ",", "field", ")", "if", "self", ".", "_should_transform", "(", "parent", ",", "field", ",", "node", ")", ":", "return", "self", ".", "_do_transform_node", "(", "node", ")", "else", ":", "return", "node" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/autograph/pyct/common_transformers/anf.py#L184-L220
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tkinter/ttk.py
python
Notebook.tabs
(self)
return self.tk.splitlist(self.tk.call(self._w, "tabs") or ())
Returns a list of windows managed by the notebook.
Returns a list of windows managed by the notebook.
[ "Returns", "a", "list", "of", "windows", "managed", "by", "the", "notebook", "." ]
def tabs(self): """Returns a list of windows managed by the notebook.""" return self.tk.splitlist(self.tk.call(self._w, "tabs") or ())
[ "def", "tabs", "(", "self", ")", ":", "return", "self", ".", "tk", ".", "splitlist", "(", "self", ".", "tk", ".", "call", "(", "self", ".", "_w", ",", "\"tabs\"", ")", "or", "(", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/ttk.py#L906-L908
alibaba/weex_js_engine
2bdf4b6f020c1fc99c63f649718f6faf7e27fdde
jni/v8core/v8/build/gyp/pylib/gyp/mac_tool.py
python
MacTool._CopyStringsFile
(self, source, dest)
Copies a .strings file using iconv to reconvert the input into UTF-16.
Copies a .strings file using iconv to reconvert the input into UTF-16.
[ "Copies", "a", ".", "strings", "file", "using", "iconv", "to", "reconvert", "the", "input", "into", "UTF", "-", "16", "." ]
def _CopyStringsFile(self, source, dest): """Copies a .strings file using iconv to reconvert the input into UTF-16.""" input_code = self._DetectInputEncoding(source) or "UTF-8" fp = open(dest, 'w') args = ['/usr/bin/iconv', '--from-code', input_code, '--to-code', 'UTF-16', source] subprocess.call(args, stdout=fp) fp.close()
[ "def", "_CopyStringsFile", "(", "self", ",", "source", ",", "dest", ")", ":", "input_code", "=", "self", ".", "_DetectInputEncoding", "(", "source", ")", "or", "\"UTF-8\"", "fp", "=", "open", "(", "dest", ",", "'w'", ")", "args", "=", "[", "'/usr/bin/iconv'", ",", "'--from-code'", ",", "input_code", ",", "'--to-code'", ",", "'UTF-16'", ",", "source", "]", "subprocess", ".", "call", "(", "args", ",", "stdout", "=", "fp", ")", "fp", ".", "close", "(", ")" ]
https://github.com/alibaba/weex_js_engine/blob/2bdf4b6f020c1fc99c63f649718f6faf7e27fdde/jni/v8core/v8/build/gyp/pylib/gyp/mac_tool.py#L80-L87
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
DateTime.SetYear
(*args, **kwargs)
return _misc_.DateTime_SetYear(*args, **kwargs)
SetYear(self, int year) -> DateTime
SetYear(self, int year) -> DateTime
[ "SetYear", "(", "self", "int", "year", ")", "-", ">", "DateTime" ]
def SetYear(*args, **kwargs): """SetYear(self, int year) -> DateTime""" return _misc_.DateTime_SetYear(*args, **kwargs)
[ "def", "SetYear", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "DateTime_SetYear", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L3817-L3819
DGtal-team/DGtal
b403217bae9a55638a0a8baac69cc7e8d6362af5
wrap/__init__.py
python
SPreCell
(dim=(), point=(), positive=True)
Factory helper function for DGtal::PreCell Parameters ---------- dim: Int Dimension of the space (2D or 3D) point: dgtal.Point of the same dimension If empty (default) returns a default constructed PreCell positive: Bool [True by default] Sign of the cell. Example: spre_cell_empty = dgtal.SPreCell(dim=2) spre_cell_pos = dgtal.SPreCell(point=dgtal.Point(dim=2).diagonal(2)) spre_cell_neg = dgtal.SPreCell(point=dgtal.Point(dim=2).diagonal(2), positive=False)
Factory helper function for DGtal::PreCell
[ "Factory", "helper", "function", "for", "DGtal", "::", "PreCell" ]
def SPreCell(dim=(), point=(), positive=True): """ Factory helper function for DGtal::PreCell Parameters ---------- dim: Int Dimension of the space (2D or 3D) point: dgtal.Point of the same dimension If empty (default) returns a default constructed PreCell positive: Bool [True by default] Sign of the cell. Example: spre_cell_empty = dgtal.SPreCell(dim=2) spre_cell_pos = dgtal.SPreCell(point=dgtal.Point(dim=2).diagonal(2)) spre_cell_neg = dgtal.SPreCell(point=dgtal.Point(dim=2).diagonal(2), positive=False) """ if not dim and not point: raise ValueError("Provide at least one of the following parameters: dim or point") if point: dim_point = point.dimension if dim: if dim != dim_point: raise ValueError("dim and point dimension are different. Provide only a valid point.") _check_dim(dim_point) if dim_point == 2: return topology.SPreCell2D(point=point, positive=positive) elif dim_point == 3: return topology.SPreCell3D(point=point, positive=positive) else: _check_dim(dim) if dim == 2: pre_cell = topology.SPreCell2D() elif dim == 3: pre_cell = topology.SPreCell3D() pre_cell.positive = positive return pre_cell
[ "def", "SPreCell", "(", "dim", "=", "(", ")", ",", "point", "=", "(", ")", ",", "positive", "=", "True", ")", ":", "if", "not", "dim", "and", "not", "point", ":", "raise", "ValueError", "(", "\"Provide at least one of the following parameters: dim or point\"", ")", "if", "point", ":", "dim_point", "=", "point", ".", "dimension", "if", "dim", ":", "if", "dim", "!=", "dim_point", ":", "raise", "ValueError", "(", "\"dim and point dimension are different. Provide only a valid point.\"", ")", "_check_dim", "(", "dim_point", ")", "if", "dim_point", "==", "2", ":", "return", "topology", ".", "SPreCell2D", "(", "point", "=", "point", ",", "positive", "=", "positive", ")", "elif", "dim_point", "==", "3", ":", "return", "topology", ".", "SPreCell3D", "(", "point", "=", "point", ",", "positive", "=", "positive", ")", "else", ":", "_check_dim", "(", "dim", ")", "if", "dim", "==", "2", ":", "pre_cell", "=", "topology", ".", "SPreCell2D", "(", ")", "elif", "dim", "==", "3", ":", "pre_cell", "=", "topology", ".", "SPreCell3D", "(", ")", "pre_cell", ".", "positive", "=", "positive", "return", "pre_cell" ]
https://github.com/DGtal-team/DGtal/blob/b403217bae9a55638a0a8baac69cc7e8d6362af5/wrap/__init__.py#L190-L230
natanielruiz/android-yolo
1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f
jni-build/jni/include/tensorflow/python/framework/tensor_shape.py
python
matrix
(rows, cols)
return TensorShape([rows, cols])
Returns a shape representing a matrix. Args: rows: The number of rows in the matrix, which may be None if unknown. cols: The number of columns in the matrix, which may be None if unknown. Returns: A TensorShape representing a matrix of the given size.
Returns a shape representing a matrix.
[ "Returns", "a", "shape", "representing", "a", "matrix", "." ]
def matrix(rows, cols): """Returns a shape representing a matrix. Args: rows: The number of rows in the matrix, which may be None if unknown. cols: The number of columns in the matrix, which may be None if unknown. Returns: A TensorShape representing a matrix of the given size. """ return TensorShape([rows, cols])
[ "def", "matrix", "(", "rows", ",", "cols", ")", ":", "return", "TensorShape", "(", "[", "rows", ",", "cols", "]", ")" ]
https://github.com/natanielruiz/android-yolo/blob/1ebb54f96a67a20ff83ddfc823ed83a13dc3a47f/jni-build/jni/include/tensorflow/python/framework/tensor_shape.py#L836-L846
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ast.py
python
iter_child_nodes
(node)
Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes.
Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes.
[ "Yield", "all", "direct", "child", "nodes", "of", "*", "node", "*", "that", "is", "all", "fields", "that", "are", "nodes", "and", "all", "items", "of", "fields", "that", "are", "lists", "of", "nodes", "." ]
def iter_child_nodes(node): """ Yield all direct child nodes of *node*, that is, all fields that are nodes and all items of fields that are lists of nodes. """ for name, field in iter_fields(node): if isinstance(field, AST): yield field elif isinstance(field, list): for item in field: if isinstance(item, AST): yield item
[ "def", "iter_child_nodes", "(", "node", ")", ":", "for", "name", ",", "field", "in", "iter_fields", "(", "node", ")", ":", "if", "isinstance", "(", "field", ",", "AST", ")", ":", "yield", "field", "elif", "isinstance", "(", "field", ",", "list", ")", ":", "for", "item", "in", "field", ":", "if", "isinstance", "(", "item", ",", "AST", ")", ":", "yield", "item" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/ast.py#L193-L204
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
tools/gen_keyboard_overlay_data/gen_keyboard_overlay_data.py
python
FetchLayoutsData
(client)
return ret
Fetches the keyboard glyph data from the spreadsheet.
Fetches the keyboard glyph data from the spreadsheet.
[ "Fetches", "the", "keyboard", "glyph", "data", "from", "the", "spreadsheet", "." ]
def FetchLayoutsData(client): """Fetches the keyboard glyph data from the spreadsheet.""" layout_names = ['U_layout', 'J_layout', 'E_layout', 'B_layout'] cols = ['scancode', 'x', 'y', 'w', 'h'] layouts = FetchSpreadsheetFeeds(client, KEYBOARD_GLYPH_SPREADSHEET_KEY, layout_names, cols) ret = {} for layout_name, layout in layouts.items(): ret[layout_name[0]] = [] for row in layout: line = [] for col in cols: value = row.get(col) if not value: line.append('') else: if col != 'scancode': value = float(value) line.append(value) ret[layout_name[0]].append(line) return ret
[ "def", "FetchLayoutsData", "(", "client", ")", ":", "layout_names", "=", "[", "'U_layout'", ",", "'J_layout'", ",", "'E_layout'", ",", "'B_layout'", "]", "cols", "=", "[", "'scancode'", ",", "'x'", ",", "'y'", ",", "'w'", ",", "'h'", "]", "layouts", "=", "FetchSpreadsheetFeeds", "(", "client", ",", "KEYBOARD_GLYPH_SPREADSHEET_KEY", ",", "layout_names", ",", "cols", ")", "ret", "=", "{", "}", "for", "layout_name", ",", "layout", "in", "layouts", ".", "items", "(", ")", ":", "ret", "[", "layout_name", "[", "0", "]", "]", "=", "[", "]", "for", "row", "in", "layout", ":", "line", "=", "[", "]", "for", "col", "in", "cols", ":", "value", "=", "row", ".", "get", "(", "col", ")", "if", "not", "value", ":", "line", ".", "append", "(", "''", ")", "else", ":", "if", "col", "!=", "'scancode'", ":", "value", "=", "float", "(", "value", ")", "line", ".", "append", "(", "value", ")", "ret", "[", "layout_name", "[", "0", "]", "]", ".", "append", "(", "line", ")", "return", "ret" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/tools/gen_keyboard_overlay_data/gen_keyboard_overlay_data.py#L366-L386
wujian16/Cornell-MOE
df299d1be882d2af9796d7a68b3f9505cac7a53e
moe/optimal_learning/python/interfaces/covariance_interface.py
python
CovarianceInterface.get_hyperparameters
(self)
Get the hyperparameters (array of float64 with shape (num_hyperparameters)) of this covariance.
Get the hyperparameters (array of float64 with shape (num_hyperparameters)) of this covariance.
[ "Get", "the", "hyperparameters", "(", "array", "of", "float64", "with", "shape", "(", "num_hyperparameters", "))", "of", "this", "covariance", "." ]
def get_hyperparameters(self): """Get the hyperparameters (array of float64 with shape (num_hyperparameters)) of this covariance.""" pass
[ "def", "get_hyperparameters", "(", "self", ")", ":", "pass" ]
https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/interfaces/covariance_interface.py#L58-L60
mandiant/flare-wmi
b0a5a094ff9ca7d7a1c4fc711dc00c74dec4b6b1
python-cim/cim/objects.py
python
ClassLayout.property_default_values
(self)
return default_values
:rtype: PropertyDefaultValues
:rtype: PropertyDefaultValues
[ ":", "rtype", ":", "PropertyDefaultValues" ]
def property_default_values(self): """ :rtype: PropertyDefaultValues """ props = self.properties.values() props = sorted(props, key=lambda p: p.index) default_values = PropertyDefaultValues(props) d = self.class_definition.property_default_values_data default_values.vsParse(d) return default_values
[ "def", "property_default_values", "(", "self", ")", ":", "props", "=", "self", ".", "properties", ".", "values", "(", ")", "props", "=", "sorted", "(", "props", ",", "key", "=", "lambda", "p", ":", "p", ".", "index", ")", "default_values", "=", "PropertyDefaultValues", "(", "props", ")", "d", "=", "self", ".", "class_definition", ".", "property_default_values_data", "default_values", ".", "vsParse", "(", "d", ")", "return", "default_values" ]
https://github.com/mandiant/flare-wmi/blob/b0a5a094ff9ca7d7a1c4fc711dc00c74dec4b6b1/python-cim/cim/objects.py#L1085-L1092
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/tpu/tensor_tracer.py
python
TensorTracer._get_op_control_flow_context
(self, op)
return op_control_flow_context
Returns the control flow of the given op. Args: op: tf.Operation for which the control flow context is requested. Returns: op_control_flow_context: which the is control flow context of the given op. If the operation type is LoopExit, returns the outer control flow context.
Returns the control flow of the given op.
[ "Returns", "the", "control", "flow", "of", "the", "given", "op", "." ]
def _get_op_control_flow_context(self, op): """Returns the control flow of the given op. Args: op: tf.Operation for which the control flow context is requested. Returns: op_control_flow_context: which the is control flow context of the given op. If the operation type is LoopExit, returns the outer control flow context. """ # pylint: disable=protected-access op_control_flow_context = op._control_flow_context # pylint: enable=protected-access if control_flow_util.IsLoopExit(op): op_control_flow_context = op_control_flow_context.outer_context return op_control_flow_context
[ "def", "_get_op_control_flow_context", "(", "self", ",", "op", ")", ":", "# pylint: disable=protected-access", "op_control_flow_context", "=", "op", ".", "_control_flow_context", "# pylint: enable=protected-access", "if", "control_flow_util", ".", "IsLoopExit", "(", "op", ")", ":", "op_control_flow_context", "=", "op_control_flow_context", ".", "outer_context", "return", "op_control_flow_context" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/tpu/tensor_tracer.py#L1641-L1656
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/_vendor/pyparsing.py
python
ParserElement.setParseAction
( self, *fns, **kwargs )
return self
Define one or more actions to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value. Optional keyword arguments: - callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{parseString}<parseString>} for more information on parsing strings containing C{<TAB>}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. Example:: integer = Word(nums) date_str = integer + '/' + integer + '/' + integer date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # use parse action to convert to ints at parse time integer = Word(nums).setParseAction(lambda toks: int(toks[0])) date_str = integer + '/' + integer + '/' + integer # note that integer fields are now ints, not strings date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31]
[]
def setParseAction( self, *fns, **kwargs ): """ Define one or more actions to perform when successfully matching parse element definition. Parse action fn is a callable method with 0-3 arguments, called as C{fn(s,loc,toks)}, C{fn(loc,toks)}, C{fn(toks)}, or just C{fn()}, where: - s = the original string being parsed (see note below) - loc = the location of the matching substring - toks = a list of the matched tokens, packaged as a C{L{ParseResults}} object If the functions in fns modify the tokens, they can return them as the return value from fn, and the modified list of tokens will replace the original. Otherwise, fn does not need to return any value. Optional keyword arguments: - callDuringTry = (default=C{False}) indicate if parse action should be run during lookaheads and alternate testing Note: the default parsing behavior is to expand tabs in the input string before starting the parsing process. See L{I{parseString}<parseString>} for more information on parsing strings containing C{<TAB>}s, and suggested methods to maintain a consistent view of the parsed string, the parse location, and line and column positions within the parsed string. Example:: integer = Word(nums) date_str = integer + '/' + integer + '/' + integer date_str.parseString("1999/12/31") # -> ['1999', '/', '12', '/', '31'] # use parse action to convert to ints at parse time integer = Word(nums).setParseAction(lambda toks: int(toks[0])) date_str = integer + '/' + integer + '/' + integer # note that integer fields are now ints, not strings date_str.parseString("1999/12/31") # -> [1999, '/', 12, '/', 31] """ self.parseAction = list(map(_trim_arity, list(fns))) self.callDuringTry = kwargs.get("callDuringTry", False) return self
[ "def", "setParseAction", "(", "self", ",", "*", "fns", ",", "*", "*", "kwargs", ")", ":", "self", ".", "parseAction", "=", "list", "(", "map", "(", "_trim_arity", ",", "list", "(", "fns", ")", ")", ")", "self", ".", "callDuringTry", "=", "kwargs", ".", "get", "(", "\"callDuringTry\"", ",", "False", ")", "return", "self" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/_vendor/pyparsing.py#L2499-L2571
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/hmac.py
python
HMAC.update
(self, msg)
Update this hashing object with the string msg.
Update this hashing object with the string msg.
[ "Update", "this", "hashing", "object", "with", "the", "string", "msg", "." ]
def update(self, msg): """Update this hashing object with the string msg. """ self.inner.update(msg)
[ "def", "update", "(", "self", ",", "msg", ")", ":", "self", ".", "inner", ".", "update", "(", "msg", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/hmac.py#L80-L83
krishauser/Klampt
972cc83ea5befac3f653c1ba20f80155768ad519
Python/python2_version/klampt/robotsim.py
python
SimBody.getTransform
(self)
return _robotsim.SimBody_getTransform(self)
getTransform(SimBody self) Gets the body's transformation at the current simulation time step (in center- of-mass centered coordinates).
getTransform(SimBody self)
[ "getTransform", "(", "SimBody", "self", ")" ]
def getTransform(self): """ getTransform(SimBody self) Gets the body's transformation at the current simulation time step (in center- of-mass centered coordinates). """ return _robotsim.SimBody_getTransform(self)
[ "def", "getTransform", "(", "self", ")", ":", "return", "_robotsim", ".", "SimBody_getTransform", "(", "self", ")" ]
https://github.com/krishauser/Klampt/blob/972cc83ea5befac3f653c1ba20f80155768ad519/Python/python2_version/klampt/robotsim.py#L7956-L7966
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py
python
BooleanVar.get
(self)
Return the value of the variable as a bool.
Return the value of the variable as a bool.
[ "Return", "the", "value", "of", "the", "variable", "as", "a", "bool", "." ]
def get(self): """Return the value of the variable as a bool.""" try: return self._tk.getboolean(self._tk.globalgetvar(self._name)) except TclError: raise ValueError("invalid literal for getboolean()")
[ "def", "get", "(", "self", ")", ":", "try", ":", "return", "self", ".", "_tk", ".", "getboolean", "(", "self", ".", "_tk", ".", "globalgetvar", "(", "self", ".", "_name", ")", ")", "except", "TclError", ":", "raise", "ValueError", "(", "\"invalid literal for getboolean()\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L551-L556
domino-team/openwrt-cc
8b181297c34d14d3ca521cc9f31430d561dbc688
package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py
python
AndroidMkWriter.WriteActions
(self, actions, extra_sources, extra_outputs)
Write Makefile code for any 'actions' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these actions (used to make other pieces dependent on these actions)
Write Makefile code for any 'actions' from the gyp input.
[ "Write", "Makefile", "code", "for", "any", "actions", "from", "the", "gyp", "input", "." ]
def WriteActions(self, actions, extra_sources, extra_outputs): """Write Makefile code for any 'actions' from the gyp input. extra_sources: a list that will be filled in with newly generated source files, if any extra_outputs: a list that will be filled in with any outputs of these actions (used to make other pieces dependent on these actions) """ for action in actions: name = make.StringToMakefileVariable('%s_%s' % (self.relative_target, action['action_name'])) self.WriteLn('### Rules for action "%s":' % action['action_name']) inputs = action['inputs'] outputs = action['outputs'] # Build up a list of outputs. # Collect the output dirs we'll need. dirs = set() for out in outputs: if not out.startswith('$'): print ('WARNING: Action for target "%s" writes output to local path ' '"%s".' % (self.target, out)) dir = os.path.split(out)[0] if dir: dirs.add(dir) if int(action.get('process_outputs_as_sources', False)): extra_sources += outputs # Prepare the actual command. command = gyp.common.EncodePOSIXShellList(action['action']) if 'message' in action: quiet_cmd = 'Gyp action: %s ($@)' % action['message'] else: quiet_cmd = 'Gyp action: %s ($@)' % name if len(dirs) > 0: command = 'mkdir -p %s' % ' '.join(dirs) + '; ' + command cd_action = 'cd $(gyp_local_path)/%s; ' % self.path command = cd_action + command # The makefile rules are all relative to the top dir, but the gyp actions # are defined relative to their containing dir. This replaces the gyp_* # variables for the action rule with an absolute version so that the # output goes in the right place. # Only write the gyp_* rules for the "primary" output (:1); # it's superfluous for the "extra outputs", and this avoids accidentally # writing duplicate dummy rules for those outputs. main_output = make.QuoteSpaces(self.LocalPathify(outputs[0])) self.WriteLn('%s: gyp_local_path := $(LOCAL_PATH)' % main_output) self.WriteLn('%s: gyp_var_prefix := $(GYP_VAR_PREFIX)' % main_output) self.WriteLn('%s: gyp_intermediate_dir := ' '$(abspath $(gyp_intermediate_dir))' % main_output) self.WriteLn('%s: gyp_shared_intermediate_dir := ' '$(abspath $(gyp_shared_intermediate_dir))' % main_output) # Android's envsetup.sh adds a number of directories to the path including # the built host binary directory. This causes actions/rules invoked by # gyp to sometimes use these instead of system versions, e.g. bison. # The built host binaries may not be suitable, and can cause errors. # So, we remove them from the PATH using the ANDROID_BUILD_PATHS variable # set by envsetup. self.WriteLn('%s: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))' % main_output) # Don't allow spaces in input/output filenames, but make an exception for # filenames which start with '$(' since it's okay for there to be spaces # inside of make function/macro invocations. for input in inputs: if not input.startswith('$(') and ' ' in input: raise gyp.common.GypError( 'Action input filename "%s" in target %s contains a space' % (input, self.target)) for output in outputs: if not output.startswith('$(') and ' ' in output: raise gyp.common.GypError( 'Action output filename "%s" in target %s contains a space' % (output, self.target)) self.WriteLn('%s: %s $(GYP_TARGET_DEPENDENCIES)' % (main_output, ' '.join(map(self.LocalPathify, inputs)))) self.WriteLn('\t@echo "%s"' % quiet_cmd) self.WriteLn('\t$(hide)%s\n' % command) for output in outputs[1:]: # Make each output depend on the main output, with an empty command # to force make to notice that the mtime has changed. self.WriteLn('%s: %s ;' % (self.LocalPathify(output), main_output)) extra_outputs += outputs self.WriteLn() self.WriteLn()
[ "def", "WriteActions", "(", "self", ",", "actions", ",", "extra_sources", ",", "extra_outputs", ")", ":", "for", "action", "in", "actions", ":", "name", "=", "make", ".", "StringToMakefileVariable", "(", "'%s_%s'", "%", "(", "self", ".", "relative_target", ",", "action", "[", "'action_name'", "]", ")", ")", "self", ".", "WriteLn", "(", "'### Rules for action \"%s\":'", "%", "action", "[", "'action_name'", "]", ")", "inputs", "=", "action", "[", "'inputs'", "]", "outputs", "=", "action", "[", "'outputs'", "]", "# Build up a list of outputs.", "# Collect the output dirs we'll need.", "dirs", "=", "set", "(", ")", "for", "out", "in", "outputs", ":", "if", "not", "out", ".", "startswith", "(", "'$'", ")", ":", "print", "(", "'WARNING: Action for target \"%s\" writes output to local path '", "'\"%s\".'", "%", "(", "self", ".", "target", ",", "out", ")", ")", "dir", "=", "os", ".", "path", ".", "split", "(", "out", ")", "[", "0", "]", "if", "dir", ":", "dirs", ".", "add", "(", "dir", ")", "if", "int", "(", "action", ".", "get", "(", "'process_outputs_as_sources'", ",", "False", ")", ")", ":", "extra_sources", "+=", "outputs", "# Prepare the actual command.", "command", "=", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "action", "[", "'action'", "]", ")", "if", "'message'", "in", "action", ":", "quiet_cmd", "=", "'Gyp action: %s ($@)'", "%", "action", "[", "'message'", "]", "else", ":", "quiet_cmd", "=", "'Gyp action: %s ($@)'", "%", "name", "if", "len", "(", "dirs", ")", ">", "0", ":", "command", "=", "'mkdir -p %s'", "%", "' '", ".", "join", "(", "dirs", ")", "+", "'; '", "+", "command", "cd_action", "=", "'cd $(gyp_local_path)/%s; '", "%", "self", ".", "path", "command", "=", "cd_action", "+", "command", "# The makefile rules are all relative to the top dir, but the gyp actions", "# are defined relative to their containing dir. This replaces the gyp_*", "# variables for the action rule with an absolute version so that the", "# output goes in the right place.", "# Only write the gyp_* rules for the \"primary\" output (:1);", "# it's superfluous for the \"extra outputs\", and this avoids accidentally", "# writing duplicate dummy rules for those outputs.", "main_output", "=", "make", ".", "QuoteSpaces", "(", "self", ".", "LocalPathify", "(", "outputs", "[", "0", "]", ")", ")", "self", ".", "WriteLn", "(", "'%s: gyp_local_path := $(LOCAL_PATH)'", "%", "main_output", ")", "self", ".", "WriteLn", "(", "'%s: gyp_var_prefix := $(GYP_VAR_PREFIX)'", "%", "main_output", ")", "self", ".", "WriteLn", "(", "'%s: gyp_intermediate_dir := '", "'$(abspath $(gyp_intermediate_dir))'", "%", "main_output", ")", "self", ".", "WriteLn", "(", "'%s: gyp_shared_intermediate_dir := '", "'$(abspath $(gyp_shared_intermediate_dir))'", "%", "main_output", ")", "# Android's envsetup.sh adds a number of directories to the path including", "# the built host binary directory. This causes actions/rules invoked by", "# gyp to sometimes use these instead of system versions, e.g. bison.", "# The built host binaries may not be suitable, and can cause errors.", "# So, we remove them from the PATH using the ANDROID_BUILD_PATHS variable", "# set by envsetup.", "self", ".", "WriteLn", "(", "'%s: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))'", "%", "main_output", ")", "# Don't allow spaces in input/output filenames, but make an exception for", "# filenames which start with '$(' since it's okay for there to be spaces", "# inside of make function/macro invocations.", "for", "input", "in", "inputs", ":", "if", "not", "input", ".", "startswith", "(", "'$('", ")", "and", "' '", "in", "input", ":", "raise", "gyp", ".", "common", ".", "GypError", "(", "'Action input filename \"%s\" in target %s contains a space'", "%", "(", "input", ",", "self", ".", "target", ")", ")", "for", "output", "in", "outputs", ":", "if", "not", "output", ".", "startswith", "(", "'$('", ")", "and", "' '", "in", "output", ":", "raise", "gyp", ".", "common", ".", "GypError", "(", "'Action output filename \"%s\" in target %s contains a space'", "%", "(", "output", ",", "self", ".", "target", ")", ")", "self", ".", "WriteLn", "(", "'%s: %s $(GYP_TARGET_DEPENDENCIES)'", "%", "(", "main_output", ",", "' '", ".", "join", "(", "map", "(", "self", ".", "LocalPathify", ",", "inputs", ")", ")", ")", ")", "self", ".", "WriteLn", "(", "'\\t@echo \"%s\"'", "%", "quiet_cmd", ")", "self", ".", "WriteLn", "(", "'\\t$(hide)%s\\n'", "%", "command", ")", "for", "output", "in", "outputs", "[", "1", ":", "]", ":", "# Make each output depend on the main output, with an empty command", "# to force make to notice that the mtime has changed.", "self", ".", "WriteLn", "(", "'%s: %s ;'", "%", "(", "self", ".", "LocalPathify", "(", "output", ")", ",", "main_output", ")", ")", "extra_outputs", "+=", "outputs", "self", ".", "WriteLn", "(", ")", "self", ".", "WriteLn", "(", ")" ]
https://github.com/domino-team/openwrt-cc/blob/8b181297c34d14d3ca521cc9f31430d561dbc688/package/gli-pub/openwrt-node-packages-master/node/node-v6.9.1/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/generator/android.py#L232-L323
liulei01/DRBox
b5c76e033c555c9009590ab384e1f7bd3c66c237
scripts/cpp_lint.py
python
_SetFilters
(filters)
Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die.
Sets the module's error-message filters.
[ "Sets", "the", "module", "s", "error", "-", "message", "filters", "." ]
def _SetFilters(filters): """Sets the module's error-message filters. These filters are applied when deciding whether to emit a given error message. Args: filters: A string of comma-separated filters (eg "whitespace/indent"). Each filter should start with + or -; else we die. """ _cpplint_state.SetFilters(filters)
[ "def", "_SetFilters", "(", "filters", ")", ":", "_cpplint_state", ".", "SetFilters", "(", "filters", ")" ]
https://github.com/liulei01/DRBox/blob/b5c76e033c555c9009590ab384e1f7bd3c66c237/scripts/cpp_lint.py#L797-L807
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/ops/resource_variable_ops.py
python
BaseResourceVariable.sparse_read
(self, indices, name=None)
return array_ops.identity(value)
Reads the value of this variable sparsely, using `gather`.
Reads the value of this variable sparsely, using `gather`.
[ "Reads", "the", "value", "of", "this", "variable", "sparsely", "using", "gather", "." ]
def sparse_read(self, indices, name=None): """Reads the value of this variable sparsely, using `gather`.""" with ops.name_scope("Gather" if name is None else name) as name: variable_accessed(self) value = gen_resource_variable_ops.resource_gather( self.handle, indices, dtype=self._dtype, name=name) if self._dtype == dtypes.variant: # For DT_VARIANT types, the handle's shape_and_type[1:] stores the # variant's handle data. Extract it. handle_data = get_eager_safe_handle_data(self.handle) if handle_data.is_set and len(handle_data.shape_and_type) > 1: value._handle_data = ( # pylint: disable=protected-access cpp_shape_inference_pb2.CppShapeInferenceResult.HandleData( is_set=True, shape_and_type=handle_data.shape_and_type[1:])) return array_ops.identity(value)
[ "def", "sparse_read", "(", "self", ",", "indices", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "\"Gather\"", "if", "name", "is", "None", "else", "name", ")", "as", "name", ":", "variable_accessed", "(", "self", ")", "value", "=", "gen_resource_variable_ops", ".", "resource_gather", "(", "self", ".", "handle", ",", "indices", ",", "dtype", "=", "self", ".", "_dtype", ",", "name", "=", "name", ")", "if", "self", ".", "_dtype", "==", "dtypes", ".", "variant", ":", "# For DT_VARIANT types, the handle's shape_and_type[1:] stores the", "# variant's handle data. Extract it.", "handle_data", "=", "get_eager_safe_handle_data", "(", "self", ".", "handle", ")", "if", "handle_data", ".", "is_set", "and", "len", "(", "handle_data", ".", "shape_and_type", ")", ">", "1", ":", "value", ".", "_handle_data", "=", "(", "# pylint: disable=protected-access", "cpp_shape_inference_pb2", ".", "CppShapeInferenceResult", ".", "HandleData", "(", "is_set", "=", "True", ",", "shape_and_type", "=", "handle_data", ".", "shape_and_type", "[", "1", ":", "]", ")", ")", "return", "array_ops", ".", "identity", "(", "value", ")" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/ops/resource_variable_ops.py#L745-L761
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/_windows.py
python
PrintDialogData.SetMaxPage
(*args, **kwargs)
return _windows_.PrintDialogData_SetMaxPage(*args, **kwargs)
SetMaxPage(self, int v)
SetMaxPage(self, int v)
[ "SetMaxPage", "(", "self", "int", "v", ")" ]
def SetMaxPage(*args, **kwargs): """SetMaxPage(self, int v)""" return _windows_.PrintDialogData_SetMaxPage(*args, **kwargs)
[ "def", "SetMaxPage", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "PrintDialogData_SetMaxPage", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/_windows.py#L5090-L5092
openthread/openthread
9fcdbed9c526c70f1556d1ed84099c1535c7cd32
tools/otci/otci/otci.py
python
OTCI.coap_start
(self)
Starts the application coap service.
Starts the application coap service.
[ "Starts", "the", "application", "coap", "service", "." ]
def coap_start(self): """Starts the application coap service.""" self.execute_command('coap start')
[ "def", "coap_start", "(", "self", ")", ":", "self", ".", "execute_command", "(", "'coap start'", ")" ]
https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/tools/otci/otci/otci.py#L2273-L2275
KDE/krita
10ea63984e00366865769c193ab298de73a59c5c
plugins/python/scripter/uicontroller.py
python
UIController._readSettings
(self)
It's similar to _writeSettings, but reading the settings when the ScripterDialog is closed.
It's similar to _writeSettings, but reading the settings when the ScripterDialog is closed.
[ "It", "s", "similar", "to", "_writeSettings", "but", "reading", "the", "settings", "when", "the", "ScripterDialog", "is", "closed", "." ]
def _readSettings(self): """ It's similar to _writeSettings, but reading the settings when the ScripterDialog is closed. """ self.scripter.settings.beginGroup('scripter') activeDocumentPath = self.scripter.settings.value('activeDocumentPath', '') if activeDocumentPath: if QFileInfo(activeDocumentPath).exists(): document = self.scripter.documentcontroller.openDocument(activeDocumentPath) self.setStatusBar(document.filePath) self.setDocumentEditor(document) for action in self.actions: readSettings = getattr(action['action'], "readSettings", None) if callable(readSettings): readSettings() pointSize = self.scripter.settings.value('editorFontSize', str(self.editor.fontInfo().pointSize())) self.editor.setFontSize(int(pointSize)) # Window Geometry rect = self.scripter.settings.value(KEY_GEOMETRY, DEFAULT_GEOMETRY) self.mainWidget.setGeometry(rect) self.scripter.settings.endGroup()
[ "def", "_readSettings", "(", "self", ")", ":", "self", ".", "scripter", ".", "settings", ".", "beginGroup", "(", "'scripter'", ")", "activeDocumentPath", "=", "self", ".", "scripter", ".", "settings", ".", "value", "(", "'activeDocumentPath'", ",", "''", ")", "if", "activeDocumentPath", ":", "if", "QFileInfo", "(", "activeDocumentPath", ")", ".", "exists", "(", ")", ":", "document", "=", "self", ".", "scripter", ".", "documentcontroller", ".", "openDocument", "(", "activeDocumentPath", ")", "self", ".", "setStatusBar", "(", "document", ".", "filePath", ")", "self", ".", "setDocumentEditor", "(", "document", ")", "for", "action", "in", "self", ".", "actions", ":", "readSettings", "=", "getattr", "(", "action", "[", "'action'", "]", ",", "\"readSettings\"", ",", "None", ")", "if", "callable", "(", "readSettings", ")", ":", "readSettings", "(", ")", "pointSize", "=", "self", ".", "scripter", ".", "settings", ".", "value", "(", "'editorFontSize'", ",", "str", "(", "self", ".", "editor", ".", "fontInfo", "(", ")", ".", "pointSize", "(", ")", ")", ")", "self", ".", "editor", ".", "setFontSize", "(", "int", "(", "pointSize", ")", ")", "# Window Geometry", "rect", "=", "self", ".", "scripter", ".", "settings", ".", "value", "(", "KEY_GEOMETRY", ",", "DEFAULT_GEOMETRY", ")", "self", ".", "mainWidget", ".", "setGeometry", "(", "rect", ")", "self", ".", "scripter", ".", "settings", ".", "endGroup", "(", ")" ]
https://github.com/KDE/krita/blob/10ea63984e00366865769c193ab298de73a59c5c/plugins/python/scripter/uicontroller.py#L227-L252
ucsb-seclab/dr_checker
fe3f1cda247a10a4952e372f1e240709fe4be462
helper_scripts/runner_scripts/components/llvm_build.py
python
_get_llvm_build_str
(src_root_dir, gcc_build_string, output_folder, target_arch, clang_path, build_output_dir=None)
return ' '.join(modified_build_args)
Get LLVM build string from gcc build string :param src_root_dir: Directory containing all sources. :param gcc_build_string: GCC build string. :param output_folder: folder where llvm bitcode should be placed. :param target_arch: [1/2] depending on whether the arch is 32 or 64 bit. :param build_output_dir: Directory from which build commands need to be executed. :return: LLVM build string
Get LLVM build string from gcc build string :param src_root_dir: Directory containing all sources. :param gcc_build_string: GCC build string. :param output_folder: folder where llvm bitcode should be placed. :param target_arch: [1/2] depending on whether the arch is 32 or 64 bit. :param build_output_dir: Directory from which build commands need to be executed. :return: LLVM build string
[ "Get", "LLVM", "build", "string", "from", "gcc", "build", "string", ":", "param", "src_root_dir", ":", "Directory", "containing", "all", "sources", ".", ":", "param", "gcc_build_string", ":", "GCC", "build", "string", ".", ":", "param", "output_folder", ":", "folder", "where", "llvm", "bitcode", "should", "be", "placed", ".", ":", "param", "target_arch", ":", "[", "1", "/", "2", "]", "depending", "on", "whether", "the", "arch", "is", "32", "or", "64", "bit", ".", ":", "param", "build_output_dir", ":", "Directory", "from", "which", "build", "commands", "need", "to", "be", "executed", ".", ":", "return", ":", "LLVM", "build", "string" ]
def _get_llvm_build_str(src_root_dir, gcc_build_string, output_folder, target_arch, clang_path, build_output_dir=None): """ Get LLVM build string from gcc build string :param src_root_dir: Directory containing all sources. :param gcc_build_string: GCC build string. :param output_folder: folder where llvm bitcode should be placed. :param target_arch: [1/2] depending on whether the arch is 32 or 64 bit. :param build_output_dir: Directory from which build commands need to be executed. :return: LLVM build string """ orig_build_args = gcc_build_string.strip().split()[1:] rel_src_file_name = _get_src_file(orig_build_args) if build_output_dir is None: curr_src_file = os.path.join(src_root_dir, rel_src_file_name) else: curr_src_file = os.path.join(build_output_dir, rel_src_file_name) orig_build_args[-1] = curr_src_file modified_build_args = list() modified_build_args.append(clang_path) modified_build_args.append(EMIT_LLVM_FLAG) # Handle Target flags modified_build_args.append(ARCH_TARGET) if target_arch == ARM_32: modified_build_args.append(ARM_32_LLVM_ARCH) if target_arch == ARM_64: modified_build_args.append(ARM_64_LLVM_ARCH) # handle debug flags for curr_d_flg in DEBUG_INFO_FLAGS: modified_build_args.append(curr_d_flg) # handle optimization flags for curr_op in TARGET_OPTIMIZATION_FLAGS: modified_build_args.append(curr_op) for curr_war_op in DISABLE_WARNINGS: modified_build_args.append(curr_war_op) if str(rel_src_file_name).startswith("../"): rel_src_file_name = rel_src_file_name[3:] if str(rel_src_file_name).startswith('/'): rel_src_file_name = os.path.abspath(rel_src_file_name) if src_root_dir[-1] == '/': rel_src_file_name = rel_src_file_name[len(src_root_dir):] else: rel_src_file_name = rel_src_file_name[len(src_root_dir) + 1:] # replace output file with llvm bc file src_dir_name = os.path.dirname(rel_src_file_name) src_file_name = os.path.basename(curr_src_file) curr_output_dir = os.path.join(output_folder, src_dir_name) os.system('mkdir -p ' + curr_output_dir) curr_output_file = os.path.abspath(os.path.join(curr_output_dir, src_file_name[:-2] + '.llvm.bc')) output_file_idx = _get_output_file_idx(orig_build_args) assert (output_file_idx != -1) orig_build_args[output_file_idx] = curr_output_file for curr_op in orig_build_args: if _is_allowed_flag(curr_op): modified_build_args.append(curr_op) return ' '.join(modified_build_args)
[ "def", "_get_llvm_build_str", "(", "src_root_dir", ",", "gcc_build_string", ",", "output_folder", ",", "target_arch", ",", "clang_path", ",", "build_output_dir", "=", "None", ")", ":", "orig_build_args", "=", "gcc_build_string", ".", "strip", "(", ")", ".", "split", "(", ")", "[", "1", ":", "]", "rel_src_file_name", "=", "_get_src_file", "(", "orig_build_args", ")", "if", "build_output_dir", "is", "None", ":", "curr_src_file", "=", "os", ".", "path", ".", "join", "(", "src_root_dir", ",", "rel_src_file_name", ")", "else", ":", "curr_src_file", "=", "os", ".", "path", ".", "join", "(", "build_output_dir", ",", "rel_src_file_name", ")", "orig_build_args", "[", "-", "1", "]", "=", "curr_src_file", "modified_build_args", "=", "list", "(", ")", "modified_build_args", ".", "append", "(", "clang_path", ")", "modified_build_args", ".", "append", "(", "EMIT_LLVM_FLAG", ")", "# Handle Target flags", "modified_build_args", ".", "append", "(", "ARCH_TARGET", ")", "if", "target_arch", "==", "ARM_32", ":", "modified_build_args", ".", "append", "(", "ARM_32_LLVM_ARCH", ")", "if", "target_arch", "==", "ARM_64", ":", "modified_build_args", ".", "append", "(", "ARM_64_LLVM_ARCH", ")", "# handle debug flags", "for", "curr_d_flg", "in", "DEBUG_INFO_FLAGS", ":", "modified_build_args", ".", "append", "(", "curr_d_flg", ")", "# handle optimization flags", "for", "curr_op", "in", "TARGET_OPTIMIZATION_FLAGS", ":", "modified_build_args", ".", "append", "(", "curr_op", ")", "for", "curr_war_op", "in", "DISABLE_WARNINGS", ":", "modified_build_args", ".", "append", "(", "curr_war_op", ")", "if", "str", "(", "rel_src_file_name", ")", ".", "startswith", "(", "\"../\"", ")", ":", "rel_src_file_name", "=", "rel_src_file_name", "[", "3", ":", "]", "if", "str", "(", "rel_src_file_name", ")", ".", "startswith", "(", "'/'", ")", ":", "rel_src_file_name", "=", "os", ".", "path", ".", "abspath", "(", "rel_src_file_name", ")", "if", "src_root_dir", "[", "-", "1", "]", "==", "'/'", ":", "rel_src_file_name", "=", "rel_src_file_name", "[", "len", "(", "src_root_dir", ")", ":", "]", "else", ":", "rel_src_file_name", "=", "rel_src_file_name", "[", "len", "(", "src_root_dir", ")", "+", "1", ":", "]", "# replace output file with llvm bc file", "src_dir_name", "=", "os", ".", "path", ".", "dirname", "(", "rel_src_file_name", ")", "src_file_name", "=", "os", ".", "path", ".", "basename", "(", "curr_src_file", ")", "curr_output_dir", "=", "os", ".", "path", ".", "join", "(", "output_folder", ",", "src_dir_name", ")", "os", ".", "system", "(", "'mkdir -p '", "+", "curr_output_dir", ")", "curr_output_file", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "curr_output_dir", ",", "src_file_name", "[", ":", "-", "2", "]", "+", "'.llvm.bc'", ")", ")", "output_file_idx", "=", "_get_output_file_idx", "(", "orig_build_args", ")", "assert", "(", "output_file_idx", "!=", "-", "1", ")", "orig_build_args", "[", "output_file_idx", "]", "=", "curr_output_file", "for", "curr_op", "in", "orig_build_args", ":", "if", "_is_allowed_flag", "(", "curr_op", ")", ":", "modified_build_args", ".", "append", "(", "curr_op", ")", "return", "' '", ".", "join", "(", "modified_build_args", ")" ]
https://github.com/ucsb-seclab/dr_checker/blob/fe3f1cda247a10a4952e372f1e240709fe4be462/helper_scripts/runner_scripts/components/llvm_build.py#L144-L208
openvinotoolkit/openvino
dedcbeafa8b84cccdc55ca64b8da516682b381c7
src/bindings/python/src/compatibility/ngraph/utils/node_factory.py
python
NodeFactory.__init__
(self, opset_version: str = DEFAULT_OPSET)
Create the NodeFactory object. @param opset_version: The opset version the factory will use to produce ops from.
Create the NodeFactory object.
[ "Create", "the", "NodeFactory", "object", "." ]
def __init__(self, opset_version: str = DEFAULT_OPSET) -> None: """Create the NodeFactory object. @param opset_version: The opset version the factory will use to produce ops from. """ self.factory = _NodeFactory(opset_version)
[ "def", "__init__", "(", "self", ",", "opset_version", ":", "str", "=", "DEFAULT_OPSET", ")", "->", "None", ":", "self", ".", "factory", "=", "_NodeFactory", "(", "opset_version", ")" ]
https://github.com/openvinotoolkit/openvino/blob/dedcbeafa8b84cccdc55ca64b8da516682b381c7/src/bindings/python/src/compatibility/ngraph/utils/node_factory.py#L21-L26
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/browser.py
python
ChildBrowserTreeItem.GetIconName
(self)
Return the name of the icon to display.
Return the name of the icon to display.
[ "Return", "the", "name", "of", "the", "icon", "to", "display", "." ]
def GetIconName(self): "Return the name of the icon to display." if self.isfunction: return "python" else: return "folder"
[ "def", "GetIconName", "(", "self", ")", ":", "if", "self", ".", "isfunction", ":", "return", "\"python\"", "else", ":", "return", "\"folder\"" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/idlelib/browser.py#L207-L212
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/importlib/_common.py
python
as_file
(path)
Given a Traversable object, return that object as a path on the local file system in a context manager.
Given a Traversable object, return that object as a path on the local file system in a context manager.
[ "Given", "a", "Traversable", "object", "return", "that", "object", "as", "a", "path", "on", "the", "local", "file", "system", "in", "a", "context", "manager", "." ]
def as_file(path): """ Given a Traversable object, return that object as a path on the local file system in a context manager. """ with _tempfile(path.read_bytes, suffix=path.name) as local: yield local
[ "def", "as_file", "(", "path", ")", ":", "with", "_tempfile", "(", "path", ".", "read_bytes", ",", "suffix", "=", "path", ".", "name", ")", "as", "local", ":", "yield", "local" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/importlib/_common.py#L47-L53
google/flatbuffers
b3006913369e0a7550795e477011ac5bebb93497
python/flatbuffers/builder.py
python
Builder.PrependInt32
(self, x)
Prepend an `int32` to the Builder buffer. Note: aligns and checks for space.
Prepend an `int32` to the Builder buffer.
[ "Prepend", "an", "int32", "to", "the", "Builder", "buffer", "." ]
def PrependInt32(self, x): """Prepend an `int32` to the Builder buffer. Note: aligns and checks for space. """ self.Prepend(N.Int32Flags, x)
[ "def", "PrependInt32", "(", "self", ",", "x", ")", ":", "self", ".", "Prepend", "(", "N", ".", "Int32Flags", ",", "x", ")" ]
https://github.com/google/flatbuffers/blob/b3006913369e0a7550795e477011ac5bebb93497/python/flatbuffers/builder.py#L678-L683
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/gsutil/third_party/boto/boto/codedeploy/layer1.py
python
CodeDeployConnection.delete_deployment_config
(self, deployment_config_name)
return self.make_request(action='DeleteDeploymentConfig', body=json.dumps(params))
Deletes a deployment configuration. A deployment configuration cannot be deleted if it is currently in use. Also, predefined configurations cannot be deleted. :type deployment_config_name: string :param deployment_config_name: The name of an existing deployment configuration within the AWS user account.
Deletes a deployment configuration.
[ "Deletes", "a", "deployment", "configuration", "." ]
def delete_deployment_config(self, deployment_config_name): """ Deletes a deployment configuration. A deployment configuration cannot be deleted if it is currently in use. Also, predefined configurations cannot be deleted. :type deployment_config_name: string :param deployment_config_name: The name of an existing deployment configuration within the AWS user account. """ params = {'deploymentConfigName': deployment_config_name, } return self.make_request(action='DeleteDeploymentConfig', body=json.dumps(params))
[ "def", "delete_deployment_config", "(", "self", ",", "deployment_config_name", ")", ":", "params", "=", "{", "'deploymentConfigName'", ":", "deployment_config_name", ",", "}", "return", "self", ".", "make_request", "(", "action", "=", "'DeleteDeploymentConfig'", ",", "body", "=", "json", ".", "dumps", "(", "params", ")", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/gsutil/third_party/boto/boto/codedeploy/layer1.py#L396-L411
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
chrome/common/extensions/docs/server2/api_categorizer.py
python
APICategorizer.GetCategory
(self, platform, api_name)
return 'chrome'
Return the type of api.'Chrome' means the public apis, private means the api only used by chrome, and experimental means the apis with "experimental" prefix.
Return the type of api.'Chrome' means the public apis, private means the api only used by chrome, and experimental means the apis with "experimental" prefix.
[ "Return", "the", "type", "of", "api", ".", "Chrome", "means", "the", "public", "apis", "private", "means", "the", "api", "only", "used", "by", "chrome", "and", "experimental", "means", "the", "apis", "with", "experimental", "prefix", "." ]
def GetCategory(self, platform, api_name): '''Return the type of api.'Chrome' means the public apis, private means the api only used by chrome, and experimental means the apis with "experimental" prefix. ''' documented_apis = self._GenerateAPICategories(platform) if (api_name.endswith('Private') or api_name not in documented_apis): return 'private' if api_name.startswith('experimental.'): return 'experimental' return 'chrome'
[ "def", "GetCategory", "(", "self", ",", "platform", ",", "api_name", ")", ":", "documented_apis", "=", "self", ".", "_GenerateAPICategories", "(", "platform", ")", "if", "(", "api_name", ".", "endswith", "(", "'Private'", ")", "or", "api_name", "not", "in", "documented_apis", ")", ":", "return", "'private'", "if", "api_name", ".", "startswith", "(", "'experimental.'", ")", ":", "return", "'experimental'", "return", "'chrome'" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/chrome/common/extensions/docs/server2/api_categorizer.py#L35-L46
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/_vendor/more_itertools/more.py
python
stagger
(iterable, offsets=(-1, 0, 1), longest=False, fillvalue=None)
return zip_offset( *children, offsets=offsets, longest=longest, fillvalue=fillvalue )
Yield tuples whose elements are offset from *iterable*. The amount by which the `i`-th item in each tuple is offset is given by the `i`-th item in *offsets*. >>> list(stagger([0, 1, 2, 3])) [(None, 0, 1), (0, 1, 2), (1, 2, 3)] >>> list(stagger(range(8), offsets=(0, 2, 4))) [(0, 2, 4), (1, 3, 5), (2, 4, 6), (3, 5, 7)] By default, the sequence will end when the final element of a tuple is the last item in the iterable. To continue until the first element of a tuple is the last item in the iterable, set *longest* to ``True``:: >>> list(stagger([0, 1, 2, 3], longest=True)) [(None, 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, None), (3, None, None)] By default, ``None`` will be used to replace offsets beyond the end of the sequence. Specify *fillvalue* to use some other value.
Yield tuples whose elements are offset from *iterable*. The amount by which the `i`-th item in each tuple is offset is given by the `i`-th item in *offsets*.
[ "Yield", "tuples", "whose", "elements", "are", "offset", "from", "*", "iterable", "*", ".", "The", "amount", "by", "which", "the", "i", "-", "th", "item", "in", "each", "tuple", "is", "offset", "is", "given", "by", "the", "i", "-", "th", "item", "in", "*", "offsets", "*", "." ]
def stagger(iterable, offsets=(-1, 0, 1), longest=False, fillvalue=None): """Yield tuples whose elements are offset from *iterable*. The amount by which the `i`-th item in each tuple is offset is given by the `i`-th item in *offsets*. >>> list(stagger([0, 1, 2, 3])) [(None, 0, 1), (0, 1, 2), (1, 2, 3)] >>> list(stagger(range(8), offsets=(0, 2, 4))) [(0, 2, 4), (1, 3, 5), (2, 4, 6), (3, 5, 7)] By default, the sequence will end when the final element of a tuple is the last item in the iterable. To continue until the first element of a tuple is the last item in the iterable, set *longest* to ``True``:: >>> list(stagger([0, 1, 2, 3], longest=True)) [(None, 0, 1), (0, 1, 2), (1, 2, 3), (2, 3, None), (3, None, None)] By default, ``None`` will be used to replace offsets beyond the end of the sequence. Specify *fillvalue* to use some other value. """ children = tee(iterable, len(offsets)) return zip_offset( *children, offsets=offsets, longest=longest, fillvalue=fillvalue )
[ "def", "stagger", "(", "iterable", ",", "offsets", "=", "(", "-", "1", ",", "0", ",", "1", ")", ",", "longest", "=", "False", ",", "fillvalue", "=", "None", ")", ":", "children", "=", "tee", "(", "iterable", ",", "len", "(", "offsets", ")", ")", "return", "zip_offset", "(", "*", "children", ",", "offsets", "=", "offsets", ",", "longest", "=", "longest", ",", "fillvalue", "=", "fillvalue", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/_vendor/more_itertools/more.py#L1454-L1479
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/subprocess.py
python
getoutput
(cmd)
return getstatusoutput(cmd)[1]
Return output (stdout or stderr) of executing cmd in a shell. Like getstatusoutput(), except the exit status is ignored and the return value is a string containing the command's output. Example: >>> import subprocess >>> subprocess.getoutput('ls /bin/ls') '/bin/ls'
Return output (stdout or stderr) of executing cmd in a shell.
[ "Return", "output", "(", "stdout", "or", "stderr", ")", "of", "executing", "cmd", "in", "a", "shell", "." ]
def getoutput(cmd): """Return output (stdout or stderr) of executing cmd in a shell. Like getstatusoutput(), except the exit status is ignored and the return value is a string containing the command's output. Example: >>> import subprocess >>> subprocess.getoutput('ls /bin/ls') '/bin/ls' """ return getstatusoutput(cmd)[1]
[ "def", "getoutput", "(", "cmd", ")", ":", "return", "getstatusoutput", "(", "cmd", ")", "[", "1", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/subprocess.py#L620-L630
openthread/openthread
9fcdbed9c526c70f1556d1ed84099c1535c7cd32
third_party/mbedtls/repo/scripts/assemble_changelog.py
python
ChangeLog.add_categories_from_text
(self, filename, line_offset, text, allow_unknown_category)
Parse a version section or entry file.
Parse a version section or entry file.
[ "Parse", "a", "version", "section", "or", "entry", "file", "." ]
def add_categories_from_text(self, filename, line_offset, text, allow_unknown_category): """Parse a version section or entry file.""" try: categories = self.format.split_categories(text) except CategoryParseError as e: raise InputFormatError(filename, line_offset + e.line_offset, e.error_message) for category in categories: if not allow_unknown_category and \ category.name not in self.categories: raise InputFormatError(filename, line_offset + category.title_line, 'Unknown category: "{}"', category.name.decode('utf8')) self.categories[category.name] += category.body
[ "def", "add_categories_from_text", "(", "self", ",", "filename", ",", "line_offset", ",", "text", ",", "allow_unknown_category", ")", ":", "try", ":", "categories", "=", "self", ".", "format", ".", "split_categories", "(", "text", ")", "except", "CategoryParseError", "as", "e", ":", "raise", "InputFormatError", "(", "filename", ",", "line_offset", "+", "e", ".", "line_offset", ",", "e", ".", "error_message", ")", "for", "category", "in", "categories", ":", "if", "not", "allow_unknown_category", "and", "category", ".", "name", "not", "in", "self", ".", "categories", ":", "raise", "InputFormatError", "(", "filename", ",", "line_offset", "+", "category", ".", "title_line", ",", "'Unknown category: \"{}\"'", ",", "category", ".", "name", ".", "decode", "(", "'utf8'", ")", ")", "self", ".", "categories", "[", "category", ".", "name", "]", "+=", "category", ".", "body" ]
https://github.com/openthread/openthread/blob/9fcdbed9c526c70f1556d1ed84099c1535c7cd32/third_party/mbedtls/repo/scripts/assemble_changelog.py#L202-L217