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
sequence
function
stringlengths
34
151k
function_tokens
sequence
url
stringlengths
90
278
jackaudio/jack2
21b293dbc37d42446141a08922cdec0d2550c6a0
waflib/Configure.py
python
ConfigurationContext.setenv
(self, name, env=None)
Set a new config set for conf.env. If a config set of that name already exists, recall it without modification. The name is the filename prefix to save to ``c4che/NAME_cache.py``, and it is also used as *variants* by the build commands. Though related to variants, whatever kind of data may be stored in the config set:: def configure(cfg): cfg.env.ONE = 1 cfg.setenv('foo') cfg.env.ONE = 2 def build(bld): 2 == bld.env_of_name('foo').ONE :param name: name of the configuration set :type name: string :param env: ConfigSet to copy, or an empty ConfigSet is created :type env: :py:class:`waflib.ConfigSet.ConfigSet`
Set a new config set for conf.env. If a config set of that name already exists, recall it without modification.
[ "Set", "a", "new", "config", "set", "for", "conf", ".", "env", ".", "If", "a", "config", "set", "of", "that", "name", "already", "exists", "recall", "it", "without", "modification", "." ]
def setenv(self, name, env=None): """ Set a new config set for conf.env. If a config set of that name already exists, recall it without modification. The name is the filename prefix to save to ``c4che/NAME_cache.py``, and it is also used as *variants* by the build commands. Though related to variants, whatever kind of data may be stored in the config set:: def configure(cfg): cfg.env.ONE = 1 cfg.setenv('foo') cfg.env.ONE = 2 def build(bld): 2 == bld.env_of_name('foo').ONE :param name: name of the configuration set :type name: string :param env: ConfigSet to copy, or an empty ConfigSet is created :type env: :py:class:`waflib.ConfigSet.ConfigSet` """ if name not in self.all_envs or env: if not env: env = ConfigSet.ConfigSet() self.prepare_env(env) else: env = env.derive() self.all_envs[name] = env self.variant = name
[ "def", "setenv", "(", "self", ",", "name", ",", "env", "=", "None", ")", ":", "if", "name", "not", "in", "self", ".", "all_envs", "or", "env", ":", "if", "not", "env", ":", "env", "=", "ConfigSet", ".", "ConfigSet", "(", ")", "self", ".", "prepare_env", "(", "env", ")", "else", ":", "env", "=", "env", ".", "derive", "(", ")", "self", ".", "all_envs", "[", "name", "]", "=", "env", "self", ".", "variant", "=", "name" ]
https://github.com/jackaudio/jack2/blob/21b293dbc37d42446141a08922cdec0d2550c6a0/waflib/Configure.py#L56-L85
tomahawk-player/tomahawk-resolvers
7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d
archive/spotify/breakpad/third_party/protobuf/protobuf/python/ez_setup.py
python
main
(argv, version=DEFAULT_VERSION)
Install or upgrade setuptools and EasyInstall
Install or upgrade setuptools and EasyInstall
[ "Install", "or", "upgrade", "setuptools", "and", "EasyInstall" ]
def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" try: import setuptools except ImportError: egg = None try: egg = download_setuptools(version, delay=0) sys.path.insert(0,egg) from setuptools.command.easy_install import main return main(list(argv)+[egg]) # we're done here finally: if egg and os.path.exists(egg): os.unlink(egg) else: if setuptools.__version__ == '0.0.1': print >>sys.stderr, ( "You have an obsolete version of setuptools installed. Please\n" "remove it from your system entirely before rerunning this script." ) sys.exit(2) req = "setuptools>="+version import pkg_resources try: pkg_resources.require(req) except pkg_resources.VersionConflict: try: from setuptools.command.easy_install import main except ImportError: from easy_install import main main(list(argv)+[download_setuptools(delay=0)]) sys.exit(0) # try to force an exit else: if argv: from setuptools.command.easy_install import main main(argv) else: print "Setuptools version",version,"or greater has been installed." print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'
[ "def", "main", "(", "argv", ",", "version", "=", "DEFAULT_VERSION", ")", ":", "try", ":", "import", "setuptools", "except", "ImportError", ":", "egg", "=", "None", "try", ":", "egg", "=", "download_setuptools", "(", "version", ",", "delay", "=", "0", ")", "sys", ".", "path", ".", "insert", "(", "0", ",", "egg", ")", "from", "setuptools", ".", "command", ".", "easy_install", "import", "main", "return", "main", "(", "list", "(", "argv", ")", "+", "[", "egg", "]", ")", "# we're done here", "finally", ":", "if", "egg", "and", "os", ".", "path", ".", "exists", "(", "egg", ")", ":", "os", ".", "unlink", "(", "egg", ")", "else", ":", "if", "setuptools", ".", "__version__", "==", "'0.0.1'", ":", "print", ">>", "sys", ".", "stderr", ",", "(", "\"You have an obsolete version of setuptools installed. Please\\n\"", "\"remove it from your system entirely before rerunning this script.\"", ")", "sys", ".", "exit", "(", "2", ")", "req", "=", "\"setuptools>=\"", "+", "version", "import", "pkg_resources", "try", ":", "pkg_resources", ".", "require", "(", "req", ")", "except", "pkg_resources", ".", "VersionConflict", ":", "try", ":", "from", "setuptools", ".", "command", ".", "easy_install", "import", "main", "except", "ImportError", ":", "from", "easy_install", "import", "main", "main", "(", "list", "(", "argv", ")", "+", "[", "download_setuptools", "(", "delay", "=", "0", ")", "]", ")", "sys", ".", "exit", "(", "0", ")", "# try to force an exit", "else", ":", "if", "argv", ":", "from", "setuptools", ".", "command", ".", "easy_install", "import", "main", "main", "(", "argv", ")", "else", ":", "print", "\"Setuptools version\"", ",", "version", ",", "\"or greater has been installed.\"", "print", "'(Run \"ez_setup.py -U setuptools\" to reinstall or upgrade.)'" ]
https://github.com/tomahawk-player/tomahawk-resolvers/blob/7f827bbe410ccfdb0446f7d6a91acc2199c9cc8d/archive/spotify/breakpad/third_party/protobuf/protobuf/python/ez_setup.py#L208-L247
apple/turicreate
cce55aa5311300e3ce6af93cb45ba791fd1bdf49
src/external/coremltools_wrap/coremltools/coremltools/converters/mil/frontend/torch/ops.py
python
_ifzo_to_ifoz
(weights, name)
return mb.transpose( x=weights_concat, perm=([1, 0] if len(weights.shape) > 1 else [0]), name=name )
i, f, z, o -> i, f, o, z where weights_split[0] == i, etc. Used to transform lstm weights from pytorch to CoreML format
i, f, z, o -> i, f, o, z where weights_split[0] == i, etc. Used to transform lstm weights from pytorch to CoreML format
[ "i", "f", "z", "o", "-", ">", "i", "f", "o", "z", "where", "weights_split", "[", "0", "]", "==", "i", "etc", ".", "Used", "to", "transform", "lstm", "weights", "from", "pytorch", "to", "CoreML", "format" ]
def _ifzo_to_ifoz(weights, name): """ i, f, z, o -> i, f, o, z where weights_split[0] == i, etc. Used to transform lstm weights from pytorch to CoreML format """ split_size = weights.shape[0] // 4 weights_split = mb.split(x=weights, split_sizes=_np.array([split_size] * 4), axis=0) weights_concat = mb.concat( values=[weights_split[0], weights_split[1], weights_split[3], weights_split[2]], axis=0, ) # make transpose a noOP for 0/1d tensors return mb.transpose( x=weights_concat, perm=([1, 0] if len(weights.shape) > 1 else [0]), name=name )
[ "def", "_ifzo_to_ifoz", "(", "weights", ",", "name", ")", ":", "split_size", "=", "weights", ".", "shape", "[", "0", "]", "//", "4", "weights_split", "=", "mb", ".", "split", "(", "x", "=", "weights", ",", "split_sizes", "=", "_np", ".", "array", "(", "[", "split_size", "]", "*", "4", ")", ",", "axis", "=", "0", ")", "weights_concat", "=", "mb", ".", "concat", "(", "values", "=", "[", "weights_split", "[", "0", "]", ",", "weights_split", "[", "1", "]", ",", "weights_split", "[", "3", "]", ",", "weights_split", "[", "2", "]", "]", ",", "axis", "=", "0", ",", ")", "# make transpose a noOP for 0/1d tensors", "return", "mb", ".", "transpose", "(", "x", "=", "weights_concat", ",", "perm", "=", "(", "[", "1", ",", "0", "]", "if", "len", "(", "weights", ".", "shape", ")", ">", "1", "else", "[", "0", "]", ")", ",", "name", "=", "name", ")" ]
https://github.com/apple/turicreate/blob/cce55aa5311300e3ce6af93cb45ba791fd1bdf49/src/external/coremltools_wrap/coremltools/coremltools/converters/mil/frontend/torch/ops.py#L971-L987
rdiankov/openrave
d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7
python/ikfast_sympy0_6.py
python
IKFastSolver.solve6DIntersectingAxes
(self, T0links, T1links, transvars,rotvars,solveRotationFirst,endbranchtree)
Solve 6D equations using fact that 3 axes are intersecting. The 3 intersecting axes are all part of T0links and will be used to compute the rotation of the robot. The other 3 axes are part of T1links and will be used to first compute the position.
Solve 6D equations using fact that 3 axes are intersecting. The 3 intersecting axes are all part of T0links and will be used to compute the rotation of the robot. The other 3 axes are part of T1links and will be used to first compute the position.
[ "Solve", "6D", "equations", "using", "fact", "that", "3", "axes", "are", "intersecting", ".", "The", "3", "intersecting", "axes", "are", "all", "part", "of", "T0links", "and", "will", "be", "used", "to", "compute", "the", "rotation", "of", "the", "robot", ".", "The", "other", "3", "axes", "are", "part", "of", "T1links", "and", "will", "be", "used", "to", "first", "compute", "the", "position", "." ]
def solve6DIntersectingAxes(self, T0links, T1links, transvars,rotvars,solveRotationFirst,endbranchtree): """Solve 6D equations using fact that 3 axes are intersecting. The 3 intersecting axes are all part of T0links and will be used to compute the rotation of the robot. The other 3 axes are part of T1links and will be used to first compute the position. """ assert(len(transvars)==3 and len(rotvars) == 3) T0 = self.multiplyMatrix(T0links) T0posoffset = eye(4) T0posoffset[0:3,3] = -T0[0:3,3] T0links = [T0posoffset] + T0links T1links = [T0posoffset] + T1links T1 = self.multiplyMatrix(T1links) othersolvedvars = rotvars+self.freejointvars if solveRotationFirst else self.freejointvars[:] T1linksinv = [self.affineInverse(T) for T in T1links] AllEquations = self.buildEquationsFromPositions(T1links,T1linksinv,transvars,othersolvedvars,uselength=True) self.checkSolvability(AllEquations,transvars,self.freejointvars) rottree = [] if solveRotationFirst: newendbranchtree = endbranchtree else: newendbranchtree = [AST.SolverSequence([rottree])] curvars = transvars[:] solsubs=self.freevarsubs[:] transtree = self.solveAllEquations(AllEquations,curvars=curvars,othersolvedvars=othersolvedvars[:],solsubs=solsubs,endbranchtree=newendbranchtree) transtree = self.verifyAllEquations(AllEquations,rotvars if solveRotationFirst else transvars+rotvars,self.freevarsubs[:],transtree) solvertree= [] solvedvarsubs = self.freevarsubs[:] if solveRotationFirst: storesolutiontree = transtree else: solvertree += transtree storesolutiontree = endbranchtree for tvar in transvars: solvedvarsubs += self.Variable(tvar).subs oldglobalsymbols = self.globalsymbols[:] try: T1sub = T1.subs(solvedvarsubs) Ree = zeros((3,3)) for i in range(3): for j in range(3): Ree[i,j] = Symbol('new_r%d%d'%(i,j)) self.globalsymbols.append((Ree[i,j],T1sub[i,j])) othersolvedvars = self.freejointvars if solveRotationFirst else transvars+self.freejointvars AllEquations = self.buildEquationsFromRotation(T0links,Ree,rotvars,othersolvedvars) self.checkSolvability(AllEquations,rotvars,othersolvedvars) currotvars = rotvars[:] rottree += self.solveAllEquations(AllEquations,curvars=currotvars,othersolvedvars=othersolvedvars,solsubs=self.freevarsubs[:],endbranchtree=storesolutiontree) if len(rottree) == 0: raise self.CannotSolveError('could not solve for all rotation variables: %s:%s'%(str(freevar),str(freevalue))) if solveRotationFirst: solvertree.append(AST.SolverRotation(T1sub, rottree)) else: rottree[:] = [AST.SolverRotation(T1sub, rottree[:])] return solvertree finally: self.globalsymbols = oldglobalsymbols
[ "def", "solve6DIntersectingAxes", "(", "self", ",", "T0links", ",", "T1links", ",", "transvars", ",", "rotvars", ",", "solveRotationFirst", ",", "endbranchtree", ")", ":", "assert", "(", "len", "(", "transvars", ")", "==", "3", "and", "len", "(", "rotvars", ")", "==", "3", ")", "T0", "=", "self", ".", "multiplyMatrix", "(", "T0links", ")", "T0posoffset", "=", "eye", "(", "4", ")", "T0posoffset", "[", "0", ":", "3", ",", "3", "]", "=", "-", "T0", "[", "0", ":", "3", ",", "3", "]", "T0links", "=", "[", "T0posoffset", "]", "+", "T0links", "T1links", "=", "[", "T0posoffset", "]", "+", "T1links", "T1", "=", "self", ".", "multiplyMatrix", "(", "T1links", ")", "othersolvedvars", "=", "rotvars", "+", "self", ".", "freejointvars", "if", "solveRotationFirst", "else", "self", ".", "freejointvars", "[", ":", "]", "T1linksinv", "=", "[", "self", ".", "affineInverse", "(", "T", ")", "for", "T", "in", "T1links", "]", "AllEquations", "=", "self", ".", "buildEquationsFromPositions", "(", "T1links", ",", "T1linksinv", ",", "transvars", ",", "othersolvedvars", ",", "uselength", "=", "True", ")", "self", ".", "checkSolvability", "(", "AllEquations", ",", "transvars", ",", "self", ".", "freejointvars", ")", "rottree", "=", "[", "]", "if", "solveRotationFirst", ":", "newendbranchtree", "=", "endbranchtree", "else", ":", "newendbranchtree", "=", "[", "AST", ".", "SolverSequence", "(", "[", "rottree", "]", ")", "]", "curvars", "=", "transvars", "[", ":", "]", "solsubs", "=", "self", ".", "freevarsubs", "[", ":", "]", "transtree", "=", "self", ".", "solveAllEquations", "(", "AllEquations", ",", "curvars", "=", "curvars", ",", "othersolvedvars", "=", "othersolvedvars", "[", ":", "]", ",", "solsubs", "=", "solsubs", ",", "endbranchtree", "=", "newendbranchtree", ")", "transtree", "=", "self", ".", "verifyAllEquations", "(", "AllEquations", ",", "rotvars", "if", "solveRotationFirst", "else", "transvars", "+", "rotvars", ",", "self", ".", "freevarsubs", "[", ":", "]", ",", "transtree", ")", "solvertree", "=", "[", "]", "solvedvarsubs", "=", "self", ".", "freevarsubs", "[", ":", "]", "if", "solveRotationFirst", ":", "storesolutiontree", "=", "transtree", "else", ":", "solvertree", "+=", "transtree", "storesolutiontree", "=", "endbranchtree", "for", "tvar", "in", "transvars", ":", "solvedvarsubs", "+=", "self", ".", "Variable", "(", "tvar", ")", ".", "subs", "oldglobalsymbols", "=", "self", ".", "globalsymbols", "[", ":", "]", "try", ":", "T1sub", "=", "T1", ".", "subs", "(", "solvedvarsubs", ")", "Ree", "=", "zeros", "(", "(", "3", ",", "3", ")", ")", "for", "i", "in", "range", "(", "3", ")", ":", "for", "j", "in", "range", "(", "3", ")", ":", "Ree", "[", "i", ",", "j", "]", "=", "Symbol", "(", "'new_r%d%d'", "%", "(", "i", ",", "j", ")", ")", "self", ".", "globalsymbols", ".", "append", "(", "(", "Ree", "[", "i", ",", "j", "]", ",", "T1sub", "[", "i", ",", "j", "]", ")", ")", "othersolvedvars", "=", "self", ".", "freejointvars", "if", "solveRotationFirst", "else", "transvars", "+", "self", ".", "freejointvars", "AllEquations", "=", "self", ".", "buildEquationsFromRotation", "(", "T0links", ",", "Ree", ",", "rotvars", ",", "othersolvedvars", ")", "self", ".", "checkSolvability", "(", "AllEquations", ",", "rotvars", ",", "othersolvedvars", ")", "currotvars", "=", "rotvars", "[", ":", "]", "rottree", "+=", "self", ".", "solveAllEquations", "(", "AllEquations", ",", "curvars", "=", "currotvars", ",", "othersolvedvars", "=", "othersolvedvars", ",", "solsubs", "=", "self", ".", "freevarsubs", "[", ":", "]", ",", "endbranchtree", "=", "storesolutiontree", ")", "if", "len", "(", "rottree", ")", "==", "0", ":", "raise", "self", ".", "CannotSolveError", "(", "'could not solve for all rotation variables: %s:%s'", "%", "(", "str", "(", "freevar", ")", ",", "str", "(", "freevalue", ")", ")", ")", "if", "solveRotationFirst", ":", "solvertree", ".", "append", "(", "AST", ".", "SolverRotation", "(", "T1sub", ",", "rottree", ")", ")", "else", ":", "rottree", "[", ":", "]", "=", "[", "AST", ".", "SolverRotation", "(", "T1sub", ",", "rottree", "[", ":", "]", ")", "]", "return", "solvertree", "finally", ":", "self", ".", "globalsymbols", "=", "oldglobalsymbols" ]
https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/python/ikfast_sympy0_6.py#L2169-L2225
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python3/src/Lib/threading.py
python
Barrier.reset
(self)
Reset the barrier to the initial state. Any threads currently waiting will get the BrokenBarrier exception raised.
Reset the barrier to the initial state.
[ "Reset", "the", "barrier", "to", "the", "initial", "state", "." ]
def reset(self): """Reset the barrier to the initial state. Any threads currently waiting will get the BrokenBarrier exception raised. """ with self._cond: if self._count > 0: if self._state == 0: #reset the barrier, waking up threads self._state = -1 elif self._state == -2: #was broken, set it to reset state #which clears when the last thread exits self._state = -1 else: self._state = 0 self._cond.notify_all()
[ "def", "reset", "(", "self", ")", ":", "with", "self", ".", "_cond", ":", "if", "self", ".", "_count", ">", "0", ":", "if", "self", ".", "_state", "==", "0", ":", "#reset the barrier, waking up threads", "self", ".", "_state", "=", "-", "1", "elif", "self", ".", "_state", "==", "-", "2", ":", "#was broken, set it to reset state", "#which clears when the last thread exits", "self", ".", "_state", "=", "-", "1", "else", ":", "self", ".", "_state", "=", "0", "self", ".", "_cond", ".", "notify_all", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python3/src/Lib/threading.py#L687-L705
danxuhk/ContinuousCRF-CNN
2b6dcaf179620f118b225ed12c890414ca828e21
scripts/cpp_lint.py
python
ReverseCloseExpression
(clean_lines, linenum, pos)
return (line, 0, -1)
If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening 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 *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. 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 opens it.
[ "If", "input", "points", "to", ")", "or", "}", "or", "]", "or", ">", "finds", "the", "position", "that", "opens", "it", "." ]
def ReverseCloseExpression(clean_lines, linenum, pos): """If input points to ) or } or ] or >, finds the position that opens it. If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the linenum/pos that correspond to the opening 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 *at* the opening brace, or (line, 0, -1) if we never find the matching opening brace. Note we ignore strings and comments when matching; and the line we return is the 'cleansed' line at linenum. """ line = clean_lines.elided[linenum] endchar = line[pos] if endchar not in ')}]>': return (line, 0, -1) if endchar == ')': startchar = '(' if endchar == ']': startchar = '[' if endchar == '}': startchar = '{' if endchar == '>': startchar = '<' # Check last line (start_pos, num_open) = FindStartOfExpressionInLine( line, pos, 0, startchar, endchar) if start_pos > -1: return (line, linenum, start_pos) # Continue scanning backward while linenum > 0: linenum -= 1 line = clean_lines.elided[linenum] (start_pos, num_open) = FindStartOfExpressionInLine( line, len(line) - 1, num_open, startchar, endchar) if start_pos > -1: return (line, linenum, start_pos) # Did not find startchar before beginning of file, give up return (line, 0, -1)
[ "def", "ReverseCloseExpression", "(", "clean_lines", ",", "linenum", ",", "pos", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "endchar", "=", "line", "[", "pos", "]", "if", "endchar", "not", "in", "')}]>'", ":", "return", "(", "line", ",", "0", ",", "-", "1", ")", "if", "endchar", "==", "')'", ":", "startchar", "=", "'('", "if", "endchar", "==", "']'", ":", "startchar", "=", "'['", "if", "endchar", "==", "'}'", ":", "startchar", "=", "'{'", "if", "endchar", "==", "'>'", ":", "startchar", "=", "'<'", "# Check last line", "(", "start_pos", ",", "num_open", ")", "=", "FindStartOfExpressionInLine", "(", "line", ",", "pos", ",", "0", ",", "startchar", ",", "endchar", ")", "if", "start_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "start_pos", ")", "# Continue scanning backward", "while", "linenum", ">", "0", ":", "linenum", "-=", "1", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "(", "start_pos", ",", "num_open", ")", "=", "FindStartOfExpressionInLine", "(", "line", ",", "len", "(", "line", ")", "-", "1", ",", "num_open", ",", "startchar", ",", "endchar", ")", "if", "start_pos", ">", "-", "1", ":", "return", "(", "line", ",", "linenum", ",", "start_pos", ")", "# Did not find startchar before beginning of file, give up", "return", "(", "line", ",", "0", ",", "-", "1", ")" ]
https://github.com/danxuhk/ContinuousCRF-CNN/blob/2b6dcaf179620f118b225ed12c890414ca828e21/scripts/cpp_lint.py#L1331-L1373
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TIntV.QSort
(self, *args)
return _snap.TIntV_QSort(self, *args)
QSort(TIntV self, int const & MnLValN, int const & MxRValN, bool const & Asc) Parameters: MnLValN: int const & MxRValN: int const & Asc: bool const &
QSort(TIntV self, int const & MnLValN, int const & MxRValN, bool const & Asc)
[ "QSort", "(", "TIntV", "self", "int", "const", "&", "MnLValN", "int", "const", "&", "MxRValN", "bool", "const", "&", "Asc", ")" ]
def QSort(self, *args): """ QSort(TIntV self, int const & MnLValN, int const & MxRValN, bool const & Asc) Parameters: MnLValN: int const & MxRValN: int const & Asc: bool const & """ return _snap.TIntV_QSort(self, *args)
[ "def", "QSort", "(", "self", ",", "*", "args", ")", ":", "return", "_snap", ".", "TIntV_QSort", "(", "self", ",", "*", "args", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L15936-L15946
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/html.py
python
HtmlWindow.__init__
(self, *args, **kwargs)
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, int style=HW_DEFAULT_STYLE, String name=HtmlWindowNameStr) -> HtmlWindow
__init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, int style=HW_DEFAULT_STYLE, String name=HtmlWindowNameStr) -> HtmlWindow
[ "__init__", "(", "self", "Window", "parent", "int", "id", "=", "-", "1", "Point", "pos", "=", "DefaultPosition", "Size", "size", "=", "DefaultSize", "int", "style", "=", "HW_DEFAULT_STYLE", "String", "name", "=", "HtmlWindowNameStr", ")", "-", ">", "HtmlWindow" ]
def __init__(self, *args, **kwargs): """ __init__(self, Window parent, int id=-1, Point pos=DefaultPosition, Size size=DefaultSize, int style=HW_DEFAULT_STYLE, String name=HtmlWindowNameStr) -> HtmlWindow """ _html.HtmlWindow_swiginit(self,_html.new_HtmlWindow(*args, **kwargs)) self._setOORInfo(self);HtmlWindow._setCallbackInfo(self, self, HtmlWindow)
[ "def", "__init__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_html", ".", "HtmlWindow_swiginit", "(", "self", ",", "_html", ".", "new_HtmlWindow", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")", "self", ".", "_setOORInfo", "(", "self", ")", "HtmlWindow", ".", "_setCallbackInfo", "(", "self", ",", "self", ",", "HtmlWindow", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/html.py#L965-L972
gnuradio/gnuradio
09c3c4fa4bfb1a02caac74cb5334dfe065391e3b
grc/gui/PropsDialog.py
python
PropsDialog._update_docs_page
(self)
Show documentation from XML and try to display best matching docstring
Show documentation from XML and try to display best matching docstring
[ "Show", "documentation", "from", "XML", "and", "try", "to", "display", "best", "matching", "docstring" ]
def _update_docs_page(self): """Show documentation from XML and try to display best matching docstring""" buf = self._docs_text_display.get_buffer() buf.delete(buf.get_start_iter(), buf.get_end_iter()) pos = buf.get_end_iter() # Add link to wiki page for this block, at the top, as long as it's not an OOT block if self._block.category and self._block.category[0] == "Core": note = "Wiki Page for this Block: " prefix = self._config.wiki_block_docs_url_prefix suffix = self._block.label.replace(" ", "_") href = f'<a href="{prefix+suffix}">Visit Wiki Page</a>' self._docs_link.set_markup(href) else: self._docs_link.set_markup('Out of Tree Block') docstrings = self._block.documentation.copy() if not docstrings: return # show documentation string from block yaml from_yaml = docstrings.pop('', '') for line in from_yaml.splitlines(): if line.lstrip() == line and line.endswith(':'): buf.insert_with_tags_by_name(pos, line + '\n', 'b') else: buf.insert(pos, line + '\n') if from_yaml: buf.insert(pos, '\n') # if given the current parameters an exact match can be made block_constructor = self._block.templates.render( 'make').rsplit('.', 2)[-1] block_class = block_constructor.partition('(')[0].strip() if block_class in docstrings: docstrings = {block_class: docstrings[block_class]} # show docstring(s) extracted from python sources for cls_name, docstring in docstrings.items(): buf.insert_with_tags_by_name(pos, cls_name + '\n', 'b') buf.insert(pos, docstring + '\n\n') pos.backward_chars(2) buf.delete(pos, buf.get_end_iter())
[ "def", "_update_docs_page", "(", "self", ")", ":", "buf", "=", "self", ".", "_docs_text_display", ".", "get_buffer", "(", ")", "buf", ".", "delete", "(", "buf", ".", "get_start_iter", "(", ")", ",", "buf", ".", "get_end_iter", "(", ")", ")", "pos", "=", "buf", ".", "get_end_iter", "(", ")", "# Add link to wiki page for this block, at the top, as long as it's not an OOT block", "if", "self", ".", "_block", ".", "category", "and", "self", ".", "_block", ".", "category", "[", "0", "]", "==", "\"Core\"", ":", "note", "=", "\"Wiki Page for this Block: \"", "prefix", "=", "self", ".", "_config", ".", "wiki_block_docs_url_prefix", "suffix", "=", "self", ".", "_block", ".", "label", ".", "replace", "(", "\" \"", ",", "\"_\"", ")", "href", "=", "f'<a href=\"{prefix+suffix}\">Visit Wiki Page</a>'", "self", ".", "_docs_link", ".", "set_markup", "(", "href", ")", "else", ":", "self", ".", "_docs_link", ".", "set_markup", "(", "'Out of Tree Block'", ")", "docstrings", "=", "self", ".", "_block", ".", "documentation", ".", "copy", "(", ")", "if", "not", "docstrings", ":", "return", "# show documentation string from block yaml", "from_yaml", "=", "docstrings", ".", "pop", "(", "''", ",", "''", ")", "for", "line", "in", "from_yaml", ".", "splitlines", "(", ")", ":", "if", "line", ".", "lstrip", "(", ")", "==", "line", "and", "line", ".", "endswith", "(", "':'", ")", ":", "buf", ".", "insert_with_tags_by_name", "(", "pos", ",", "line", "+", "'\\n'", ",", "'b'", ")", "else", ":", "buf", ".", "insert", "(", "pos", ",", "line", "+", "'\\n'", ")", "if", "from_yaml", ":", "buf", ".", "insert", "(", "pos", ",", "'\\n'", ")", "# if given the current parameters an exact match can be made", "block_constructor", "=", "self", ".", "_block", ".", "templates", ".", "render", "(", "'make'", ")", ".", "rsplit", "(", "'.'", ",", "2", ")", "[", "-", "1", "]", "block_class", "=", "block_constructor", ".", "partition", "(", "'('", ")", "[", "0", "]", ".", "strip", "(", ")", "if", "block_class", "in", "docstrings", ":", "docstrings", "=", "{", "block_class", ":", "docstrings", "[", "block_class", "]", "}", "# show docstring(s) extracted from python sources", "for", "cls_name", ",", "docstring", "in", "docstrings", ".", "items", "(", ")", ":", "buf", ".", "insert_with_tags_by_name", "(", "pos", ",", "cls_name", "+", "'\\n'", ",", "'b'", ")", "buf", ".", "insert", "(", "pos", ",", "docstring", "+", "'\\n\\n'", ")", "pos", ".", "backward_chars", "(", "2", ")", "buf", ".", "delete", "(", "pos", ",", "buf", ".", "get_end_iter", "(", ")", ")" ]
https://github.com/gnuradio/gnuradio/blob/09c3c4fa4bfb1a02caac74cb5334dfe065391e3b/grc/gui/PropsDialog.py#L208-L250
PX4/PX4-Autopilot
0b9f60a0370be53d683352c63fd92db3d6586e18
Tools/ecl_ekf/plotting/data_plots.py
python
InnovationPlot.plot
(self)
plots the Innovation data. :return:
plots the Innovation data. :return:
[ "plots", "the", "Innovation", "data", ".", ":", "return", ":" ]
def plot(self): """ plots the Innovation data. :return: """ if self.fig is None: return for i in range(len(self._variable_names)): # create a subplot for every variable plt.subplot(len(self._variable_names), 1, i + 1) if self._sub_titles is not None: plt.title(self._sub_titles[i]) # plot the value and the standard deviation plt.plot( 1e-6 * self.plot_data['timestamp'], self.plot_data[self._variable_names[i][0]], 'b') plt.plot( 1e-6 * self.plot_data['timestamp'], np.sqrt(self.plot_data[self._variable_names[i][1]]), 'r') plt.plot( 1e-6 * self.plot_data['timestamp'], -np.sqrt(self.plot_data[self._variable_names[i][1]]), 'r') plt.xlabel(self._x_labels[i]) plt.ylabel(self._y_labels[i]) plt.grid() # add the maximum and minimum value as an annotation _, max_value, max_time = get_max_arg_time_value( self.plot_data[self._variable_names[i][0]], 1e-6 * self.plot_data['timestamp']) _, min_value, min_time = get_min_arg_time_value( self.plot_data[self._variable_names[i][0]], 1e-6 * self.plot_data['timestamp']) plt.text( max_time, max_value, 'max={:.2f}'.format(max_value), fontsize=12, horizontalalignment='left', verticalalignment='bottom') plt.text( min_time, min_value, 'min={:.2f}'.format(min_value), fontsize=12, horizontalalignment='left', verticalalignment='top') self.fig.tight_layout(rect=[0, 0.03, 1, 0.95])
[ "def", "plot", "(", "self", ")", ":", "if", "self", ".", "fig", "is", "None", ":", "return", "for", "i", "in", "range", "(", "len", "(", "self", ".", "_variable_names", ")", ")", ":", "# create a subplot for every variable", "plt", ".", "subplot", "(", "len", "(", "self", ".", "_variable_names", ")", ",", "1", ",", "i", "+", "1", ")", "if", "self", ".", "_sub_titles", "is", "not", "None", ":", "plt", ".", "title", "(", "self", ".", "_sub_titles", "[", "i", "]", ")", "# plot the value and the standard deviation", "plt", ".", "plot", "(", "1e-6", "*", "self", ".", "plot_data", "[", "'timestamp'", "]", ",", "self", ".", "plot_data", "[", "self", ".", "_variable_names", "[", "i", "]", "[", "0", "]", "]", ",", "'b'", ")", "plt", ".", "plot", "(", "1e-6", "*", "self", ".", "plot_data", "[", "'timestamp'", "]", ",", "np", ".", "sqrt", "(", "self", ".", "plot_data", "[", "self", ".", "_variable_names", "[", "i", "]", "[", "1", "]", "]", ")", ",", "'r'", ")", "plt", ".", "plot", "(", "1e-6", "*", "self", ".", "plot_data", "[", "'timestamp'", "]", ",", "-", "np", ".", "sqrt", "(", "self", ".", "plot_data", "[", "self", ".", "_variable_names", "[", "i", "]", "[", "1", "]", "]", ")", ",", "'r'", ")", "plt", ".", "xlabel", "(", "self", ".", "_x_labels", "[", "i", "]", ")", "plt", ".", "ylabel", "(", "self", ".", "_y_labels", "[", "i", "]", ")", "plt", ".", "grid", "(", ")", "# add the maximum and minimum value as an annotation", "_", ",", "max_value", ",", "max_time", "=", "get_max_arg_time_value", "(", "self", ".", "plot_data", "[", "self", ".", "_variable_names", "[", "i", "]", "[", "0", "]", "]", ",", "1e-6", "*", "self", ".", "plot_data", "[", "'timestamp'", "]", ")", "_", ",", "min_value", ",", "min_time", "=", "get_min_arg_time_value", "(", "self", ".", "plot_data", "[", "self", ".", "_variable_names", "[", "i", "]", "[", "0", "]", "]", ",", "1e-6", "*", "self", ".", "plot_data", "[", "'timestamp'", "]", ")", "plt", ".", "text", "(", "max_time", ",", "max_value", ",", "'max={:.2f}'", ".", "format", "(", "max_value", ")", ",", "fontsize", "=", "12", ",", "horizontalalignment", "=", "'left'", ",", "verticalalignment", "=", "'bottom'", ")", "plt", ".", "text", "(", "min_time", ",", "min_value", ",", "'min={:.2f}'", ".", "format", "(", "min_value", ")", ",", "fontsize", "=", "12", ",", "horizontalalignment", "=", "'left'", ",", "verticalalignment", "=", "'top'", ")", "self", ".", "fig", ".", "tight_layout", "(", "rect", "=", "[", "0", ",", "0.03", ",", "1", ",", "0.95", "]", ")" ]
https://github.com/PX4/PX4-Autopilot/blob/0b9f60a0370be53d683352c63fd92db3d6586e18/Tools/ecl_ekf/plotting/data_plots.py#L208-L252
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
kratos/python_scripts/python_solver.py
python
PythonSolver.__init__
(self, model, settings)
The constructor of the PythonSolver-Object. It is intended to be called from the constructor of deriving classes: super().__init__(settings) Keyword arguments: self -- It signifies an instance of a class. model -- The Model to be used settings -- The solver settings used
The constructor of the PythonSolver-Object.
[ "The", "constructor", "of", "the", "PythonSolver", "-", "Object", "." ]
def __init__(self, model, settings): """The constructor of the PythonSolver-Object. It is intended to be called from the constructor of deriving classes: super().__init__(settings) Keyword arguments: self -- It signifies an instance of a class. model -- The Model to be used settings -- The solver settings used """ if not isinstance(model, KratosMultiphysics.Model): raise Exception("Input is expected to be provided as a Kratos Model object") if not isinstance(settings, KratosMultiphysics.Parameters): raise Exception("Input is expected to be provided as a Kratos Parameters object") self.model = model self.settings = settings self.ValidateSettings() self.echo_level = self.settings["echo_level"].GetInt()
[ "def", "__init__", "(", "self", ",", "model", ",", "settings", ")", ":", "if", "not", "isinstance", "(", "model", ",", "KratosMultiphysics", ".", "Model", ")", ":", "raise", "Exception", "(", "\"Input is expected to be provided as a Kratos Model object\"", ")", "if", "not", "isinstance", "(", "settings", ",", "KratosMultiphysics", ".", "Parameters", ")", ":", "raise", "Exception", "(", "\"Input is expected to be provided as a Kratos Parameters object\"", ")", "self", ".", "model", "=", "model", "self", ".", "settings", "=", "settings", "self", ".", "ValidateSettings", "(", ")", "self", ".", "echo_level", "=", "self", ".", "settings", "[", "\"echo_level\"", "]", ".", "GetInt", "(", ")" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/kratos/python_scripts/python_solver.py#L12-L35
emscripten-core/emscripten
0d413d3c5af8b28349682496edc14656f5700c2f
tools/response_file.py
python
read_response_file
(response_filename)
return args
Reads a response file, and returns the list of cmdline params found in the file. The encoding that the response filename should be read with can be specified as a suffix to the file, e.g. "foo.rsp.utf-8" or "foo.rsp.cp1252". If not specified, first UTF-8 and then Python locale.getpreferredencoding() are attempted. The parameter response_filename may start with '@'.
Reads a response file, and returns the list of cmdline params found in the file.
[ "Reads", "a", "response", "file", "and", "returns", "the", "list", "of", "cmdline", "params", "found", "in", "the", "file", "." ]
def read_response_file(response_filename): """Reads a response file, and returns the list of cmdline params found in the file. The encoding that the response filename should be read with can be specified as a suffix to the file, e.g. "foo.rsp.utf-8" or "foo.rsp.cp1252". If not specified, first UTF-8 and then Python locale.getpreferredencoding() are attempted. The parameter response_filename may start with '@'.""" if response_filename.startswith('@'): response_filename = response_filename[1:] if not os.path.exists(response_filename): raise IOError("response file not found: %s" % response_filename) # Guess encoding based on the file suffix components = os.path.basename(response_filename).split('.') encoding_suffix = components[-1].lower() if len(components) > 1 and (encoding_suffix.startswith('utf') or encoding_suffix.startswith('cp') or encoding_suffix.startswith('iso') or encoding_suffix in ['ascii', 'latin-1']): guessed_encoding = encoding_suffix else: guessed_encoding = 'utf-8' try: # First try with the guessed encoding with open(response_filename, encoding=guessed_encoding) as f: args = f.read() except (ValueError, LookupError): # UnicodeDecodeError is a subclass of ValueError, and Python raises either a ValueError or a UnicodeDecodeError on decode errors. LookupError is raised if guessed encoding is not an encoding. if DEBUG: logging.warning(f'Failed to parse response file {response_filename} with guessed encoding "{guessed_encoding}". Trying default system encoding...') # If that fails, try with the Python default locale.getpreferredencoding() with open(response_filename) as f: args = f.read() args = shlex.split(args) if DEBUG: logging.warning('Read response file ' + response_filename + ': ' + str(args)) return args
[ "def", "read_response_file", "(", "response_filename", ")", ":", "if", "response_filename", ".", "startswith", "(", "'@'", ")", ":", "response_filename", "=", "response_filename", "[", "1", ":", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "response_filename", ")", ":", "raise", "IOError", "(", "\"response file not found: %s\"", "%", "response_filename", ")", "# Guess encoding based on the file suffix", "components", "=", "os", ".", "path", ".", "basename", "(", "response_filename", ")", ".", "split", "(", "'.'", ")", "encoding_suffix", "=", "components", "[", "-", "1", "]", ".", "lower", "(", ")", "if", "len", "(", "components", ")", ">", "1", "and", "(", "encoding_suffix", ".", "startswith", "(", "'utf'", ")", "or", "encoding_suffix", ".", "startswith", "(", "'cp'", ")", "or", "encoding_suffix", ".", "startswith", "(", "'iso'", ")", "or", "encoding_suffix", "in", "[", "'ascii'", ",", "'latin-1'", "]", ")", ":", "guessed_encoding", "=", "encoding_suffix", "else", ":", "guessed_encoding", "=", "'utf-8'", "try", ":", "# First try with the guessed encoding", "with", "open", "(", "response_filename", ",", "encoding", "=", "guessed_encoding", ")", "as", "f", ":", "args", "=", "f", ".", "read", "(", ")", "except", "(", "ValueError", ",", "LookupError", ")", ":", "# UnicodeDecodeError is a subclass of ValueError, and Python raises either a ValueError or a UnicodeDecodeError on decode errors. LookupError is raised if guessed encoding is not an encoding.", "if", "DEBUG", ":", "logging", ".", "warning", "(", "f'Failed to parse response file {response_filename} with guessed encoding \"{guessed_encoding}\". Trying default system encoding...'", ")", "# If that fails, try with the Python default locale.getpreferredencoding()", "with", "open", "(", "response_filename", ")", "as", "f", ":", "args", "=", "f", ".", "read", "(", ")", "args", "=", "shlex", ".", "split", "(", "args", ")", "if", "DEBUG", ":", "logging", ".", "warning", "(", "'Read response file '", "+", "response_filename", "+", "': '", "+", "str", "(", "args", ")", ")", "return", "args" ]
https://github.com/emscripten-core/emscripten/blob/0d413d3c5af8b28349682496edc14656f5700c2f/tools/response_file.py#L68-L108
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py
python
Decimal.__rdivmod__
(self, other, context=None)
return other.__divmod__(self, context=context)
Swaps self/other and returns __divmod__.
Swaps self/other and returns __divmod__.
[ "Swaps", "self", "/", "other", "and", "returns", "__divmod__", "." ]
def __rdivmod__(self, other, context=None): """Swaps self/other and returns __divmod__.""" other = _convert_other(other) if other is NotImplemented: return other return other.__divmod__(self, context=context)
[ "def", "__rdivmod__", "(", "self", ",", "other", ",", "context", "=", "None", ")", ":", "other", "=", "_convert_other", "(", "other", ")", "if", "other", "is", "NotImplemented", ":", "return", "other", "return", "other", ".", "__divmod__", "(", "self", ",", "context", "=", "context", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/_pydecimal.py#L1459-L1464
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_windows.py
python
TopLevelWindow.ShowWithoutActivating
(*args, **kwargs)
return _windows_.TopLevelWindow_ShowWithoutActivating(*args, **kwargs)
ShowWithoutActivating(self)
ShowWithoutActivating(self)
[ "ShowWithoutActivating", "(", "self", ")" ]
def ShowWithoutActivating(*args, **kwargs): """ShowWithoutActivating(self)""" return _windows_.TopLevelWindow_ShowWithoutActivating(*args, **kwargs)
[ "def", "ShowWithoutActivating", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_windows_", ".", "TopLevelWindow_ShowWithoutActivating", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_windows.py#L445-L447
JoseExposito/touchegg
1f3fda214358d071c05da4bf17c070c33d67b5eb
cmake/cpplint.py
python
CheckForHeaderGuard
(filename, clean_lines, error)
Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. clean_lines: A CleansedLines instance containing the file. error: The function to call with any errors found.
Checks that the file contains a header guard.
[ "Checks", "that", "the", "file", "contains", "a", "header", "guard", "." ]
def CheckForHeaderGuard(filename, clean_lines, error): """Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. clean_lines: A CleansedLines instance containing the file. error: The function to call with any errors found. """ # Don't check for header guards if there are error suppression # comments somewhere in this file. # # Because this is silencing a warning for a nonexistent line, we # only support the very specific NOLINT(build/header_guard) syntax, # and not the general NOLINT or NOLINT(*) syntax. raw_lines = clean_lines.lines_without_raw_strings for i in raw_lines: if Search(r'//\s*NOLINT\(build/header_guard\)', i): return cppvar = GetHeaderGuardCPPVariable(filename) ifndef = '' ifndef_linenum = 0 define = '' endif = '' endif_linenum = 0 for linenum, line in enumerate(raw_lines): linesplit = line.split() if len(linesplit) >= 2: # find the first occurrence of #ifndef and #define, save arg if not ifndef and linesplit[0] == '#ifndef': # set ifndef to the header guard presented on the #ifndef line. ifndef = linesplit[1] ifndef_linenum = linenum if not define and linesplit[0] == '#define': define = linesplit[1] # find the last occurrence of #endif, save entire line if line.startswith('#endif'): endif = line endif_linenum = linenum if not ifndef or not define or ifndef != define: error(filename, 0, 'build/header_guard', 5, 'No #ifndef header guard found, suggested CPP variable is: %s' % cppvar) return # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ # for backward compatibility. if ifndef != cppvar: error_level = 0 if ifndef != cppvar + '_': error_level = 5 ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum, error) error(filename, ifndef_linenum, 'build/header_guard', error_level, '#ifndef header guard has wrong style, please use: %s' % cppvar) # Check for "//" comments on endif line. ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum, error) match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif) if match: if match.group(1) == '_': # Issue low severity warning for deprecated double trailing underscore error(filename, endif_linenum, 'build/header_guard', 0, '#endif line should be "#endif // %s"' % cppvar) return # Didn't find the corresponding "//" comment. If this file does not # contain any "//" comments at all, it could be that the compiler # only wants "/**/" comments, look for those instead. no_single_line_comments = True for i in xrange(1, len(raw_lines) - 1): line = raw_lines[i] if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line): no_single_line_comments = False break if no_single_line_comments: match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif) if match: if match.group(1) == '_': # Low severity warning for double trailing underscore error(filename, endif_linenum, 'build/header_guard', 0, '#endif line should be "#endif /* %s */"' % cppvar) return # Didn't find anything error(filename, endif_linenum, 'build/header_guard', 5, '#endif line should be "#endif // %s"' % cppvar)
[ "def", "CheckForHeaderGuard", "(", "filename", ",", "clean_lines", ",", "error", ")", ":", "# Don't check for header guards if there are error suppression", "# comments somewhere in this file.", "#", "# Because this is silencing a warning for a nonexistent line, we", "# only support the very specific NOLINT(build/header_guard) syntax,", "# and not the general NOLINT or NOLINT(*) syntax.", "raw_lines", "=", "clean_lines", ".", "lines_without_raw_strings", "for", "i", "in", "raw_lines", ":", "if", "Search", "(", "r'//\\s*NOLINT\\(build/header_guard\\)'", ",", "i", ")", ":", "return", "cppvar", "=", "GetHeaderGuardCPPVariable", "(", "filename", ")", "ifndef", "=", "''", "ifndef_linenum", "=", "0", "define", "=", "''", "endif", "=", "''", "endif_linenum", "=", "0", "for", "linenum", ",", "line", "in", "enumerate", "(", "raw_lines", ")", ":", "linesplit", "=", "line", ".", "split", "(", ")", "if", "len", "(", "linesplit", ")", ">=", "2", ":", "# find the first occurrence of #ifndef and #define, save arg", "if", "not", "ifndef", "and", "linesplit", "[", "0", "]", "==", "'#ifndef'", ":", "# set ifndef to the header guard presented on the #ifndef line.", "ifndef", "=", "linesplit", "[", "1", "]", "ifndef_linenum", "=", "linenum", "if", "not", "define", "and", "linesplit", "[", "0", "]", "==", "'#define'", ":", "define", "=", "linesplit", "[", "1", "]", "# find the last occurrence of #endif, save entire line", "if", "line", ".", "startswith", "(", "'#endif'", ")", ":", "endif", "=", "line", "endif_linenum", "=", "linenum", "if", "not", "ifndef", "or", "not", "define", "or", "ifndef", "!=", "define", ":", "error", "(", "filename", ",", "0", ",", "'build/header_guard'", ",", "5", ",", "'No #ifndef header guard found, suggested CPP variable is: %s'", "%", "cppvar", ")", "return", "# The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__", "# for backward compatibility.", "if", "ifndef", "!=", "cppvar", ":", "error_level", "=", "0", "if", "ifndef", "!=", "cppvar", "+", "'_'", ":", "error_level", "=", "5", "ParseNolintSuppressions", "(", "filename", ",", "raw_lines", "[", "ifndef_linenum", "]", ",", "ifndef_linenum", ",", "error", ")", "error", "(", "filename", ",", "ifndef_linenum", ",", "'build/header_guard'", ",", "error_level", ",", "'#ifndef header guard has wrong style, please use: %s'", "%", "cppvar", ")", "# Check for \"//\" comments on endif line.", "ParseNolintSuppressions", "(", "filename", ",", "raw_lines", "[", "endif_linenum", "]", ",", "endif_linenum", ",", "error", ")", "match", "=", "Match", "(", "r'#endif\\s*//\\s*'", "+", "cppvar", "+", "r'(_)?\\b'", ",", "endif", ")", "if", "match", ":", "if", "match", ".", "group", "(", "1", ")", "==", "'_'", ":", "# Issue low severity warning for deprecated double trailing underscore", "error", "(", "filename", ",", "endif_linenum", ",", "'build/header_guard'", ",", "0", ",", "'#endif line should be \"#endif // %s\"'", "%", "cppvar", ")", "return", "# Didn't find the corresponding \"//\" comment. If this file does not", "# contain any \"//\" comments at all, it could be that the compiler", "# only wants \"/**/\" comments, look for those instead.", "no_single_line_comments", "=", "True", "for", "i", "in", "xrange", "(", "1", ",", "len", "(", "raw_lines", ")", "-", "1", ")", ":", "line", "=", "raw_lines", "[", "i", "]", "if", "Match", "(", "r'^(?:(?:\\'(?:\\.|[^\\'])*\\')|(?:\"(?:\\.|[^\"])*\")|[^\\'\"])*//'", ",", "line", ")", ":", "no_single_line_comments", "=", "False", "break", "if", "no_single_line_comments", ":", "match", "=", "Match", "(", "r'#endif\\s*/\\*\\s*'", "+", "cppvar", "+", "r'(_)?\\s*\\*/'", ",", "endif", ")", "if", "match", ":", "if", "match", ".", "group", "(", "1", ")", "==", "'_'", ":", "# Low severity warning for double trailing underscore", "error", "(", "filename", ",", "endif_linenum", ",", "'build/header_guard'", ",", "0", ",", "'#endif line should be \"#endif /* %s */\"'", "%", "cppvar", ")", "return", "# Didn't find anything", "error", "(", "filename", ",", "endif_linenum", ",", "'build/header_guard'", ",", "5", ",", "'#endif line should be \"#endif // %s\"'", "%", "cppvar", ")" ]
https://github.com/JoseExposito/touchegg/blob/1f3fda214358d071c05da4bf17c070c33d67b5eb/cmake/cpplint.py#L1885-L1980
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
scripts/SANS/isis_reducer.py
python
ISISReducer.get_instrument
(self)
return self.instrument
Convenience function used by the inst property to make calls shorter
Convenience function used by the inst property to make calls shorter
[ "Convenience", "function", "used", "by", "the", "inst", "property", "to", "make", "calls", "shorter" ]
def get_instrument(self): """ Convenience function used by the inst property to make calls shorter """ return self.instrument
[ "def", "get_instrument", "(", "self", ")", ":", "return", "self", ".", "instrument" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/scripts/SANS/isis_reducer.py#L684-L689
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/Cookie.py
python
BaseCookie.output
(self, attrs=None, header="Set-Cookie:", sep="\015\012")
return sep.join(result)
Return a string suitable for HTTP.
Return a string suitable for HTTP.
[ "Return", "a", "string", "suitable", "for", "HTTP", "." ]
def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"): """Return a string suitable for HTTP.""" result = [] items = self.items() items.sort() for K,V in items: result.append( V.output(attrs, header) ) return sep.join(result)
[ "def", "output", "(", "self", ",", "attrs", "=", "None", ",", "header", "=", "\"Set-Cookie:\"", ",", "sep", "=", "\"\\015\\012\"", ")", ":", "result", "=", "[", "]", "items", "=", "self", ".", "items", "(", ")", "items", ".", "sort", "(", ")", "for", "K", ",", "V", "in", "items", ":", "result", ".", "append", "(", "V", ".", "output", "(", "attrs", ",", "header", ")", ")", "return", "sep", ".", "join", "(", "result", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi-v7a/toolchain/lib/python2.7/Cookie.py#L595-L602
rrwick/Unicycler
96ffea71e3a78d63ade19d6124946773e65cf129
unicycler/string_graph.py
python
StringGraphSegment.rotate_sequence
(self, start_pos, flip)
Rotates the sequence so it begins at start_pos. If flip is True, it also switches the forward and reverse strands. This function assumes that the segment is a circular completed replicon with no overlap.
Rotates the sequence so it begins at start_pos. If flip is True, it also switches the forward and reverse strands. This function assumes that the segment is a circular completed replicon with no overlap.
[ "Rotates", "the", "sequence", "so", "it", "begins", "at", "start_pos", ".", "If", "flip", "is", "True", "it", "also", "switches", "the", "forward", "and", "reverse", "strands", ".", "This", "function", "assumes", "that", "the", "segment", "is", "a", "circular", "completed", "replicon", "with", "no", "overlap", "." ]
def rotate_sequence(self, start_pos, flip): """ Rotates the sequence so it begins at start_pos. If flip is True, it also switches the forward and reverse strands. This function assumes that the segment is a circular completed replicon with no overlap. """ unrotated_seq = self.forward_sequence rotated_seq = unrotated_seq[start_pos:] + unrotated_seq[:start_pos] rev_comp_rotated_seq = reverse_complement(rotated_seq) if flip: self.forward_sequence = rev_comp_rotated_seq self.reverse_sequence = rotated_seq else: self.forward_sequence = rotated_seq self.reverse_sequence = rev_comp_rotated_seq
[ "def", "rotate_sequence", "(", "self", ",", "start_pos", ",", "flip", ")", ":", "unrotated_seq", "=", "self", ".", "forward_sequence", "rotated_seq", "=", "unrotated_seq", "[", "start_pos", ":", "]", "+", "unrotated_seq", "[", ":", "start_pos", "]", "rev_comp_rotated_seq", "=", "reverse_complement", "(", "rotated_seq", ")", "if", "flip", ":", "self", ".", "forward_sequence", "=", "rev_comp_rotated_seq", "self", ".", "reverse_sequence", "=", "rotated_seq", "else", ":", "self", ".", "forward_sequence", "=", "rotated_seq", "self", ".", "reverse_sequence", "=", "rev_comp_rotated_seq" ]
https://github.com/rrwick/Unicycler/blob/96ffea71e3a78d63ade19d6124946773e65cf129/unicycler/string_graph.py#L462-L477
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/interpolate/_bsplines.py
python
_as_float_array
(x, check_finite=False)
return x
Convert the input into a C contiguous float array. NB: Upcasts half- and single-precision floats to double precision.
Convert the input into a C contiguous float array.
[ "Convert", "the", "input", "into", "a", "C", "contiguous", "float", "array", "." ]
def _as_float_array(x, check_finite=False): """Convert the input into a C contiguous float array. NB: Upcasts half- and single-precision floats to double precision. """ x = np.ascontiguousarray(x) dtyp = _get_dtype(x.dtype) x = x.astype(dtyp, copy=False) if check_finite and not np.isfinite(x).all(): raise ValueError("Array must not contain infs or nans.") return x
[ "def", "_as_float_array", "(", "x", ",", "check_finite", "=", "False", ")", ":", "x", "=", "np", ".", "ascontiguousarray", "(", "x", ")", "dtyp", "=", "_get_dtype", "(", "x", ".", "dtype", ")", "x", "=", "x", ".", "astype", "(", "dtyp", ",", "copy", "=", "False", ")", "if", "check_finite", "and", "not", "np", ".", "isfinite", "(", "x", ")", ".", "all", "(", ")", ":", "raise", "ValueError", "(", "\"Array must not contain infs or nans.\"", ")", "return", "x" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/interpolate/_bsplines.py#L33-L43
trilinos/Trilinos
6168be6dd51e35e1cd681e9c4b24433e709df140
packages/seacas/scripts/exomerge2.py
python
ExodusModel._get_thickness_from_volume_and_area
(self, volume, area)
return height
Return the thickness of a disk given the volume and area.
Return the thickness of a disk given the volume and area.
[ "Return", "the", "thickness", "of", "a", "disk", "given", "the", "volume", "and", "area", "." ]
def _get_thickness_from_volume_and_area(self, volume, area): """Return the thickness of a disk given the volume and area.""" # max phi (for a sphere) is 6^(-1/3) * pi^(-1/6) phi = math.pow(volume, 1 / 3.0) / math.pow(area, 1 / 2.0) # find a solution, if possible max_alpha = math.pi ** (-1.0 / 6) * 6.0 ** (-1.0 / 3) low = 0.0 high = max_alpha a = 1.0 b = 1.5 - 1 / (16 * math.pi * phi ** 6) c = 0.75 d = 0.125 high_value = a * high ** 3 + b * high ** 2 + c * high + d for _ in range(53): mid = (low + high) / 2 mid_value = a * high ** 3 + b * high ** 2 + c * high + d if (high_value > 0) == (mid_value > 0): high_value = mid_value high = mid else: low = mid # in the case this fails, return NaN if low == 0 or high == max_alpha: return float('nan') alpha = (low + high) / 2.0 height = (volume * 4 * alpha ** 2 / math.pi) ** (1.0 / 3) return height
[ "def", "_get_thickness_from_volume_and_area", "(", "self", ",", "volume", ",", "area", ")", ":", "# max phi (for a sphere) is 6^(-1/3) * pi^(-1/6)", "phi", "=", "math", ".", "pow", "(", "volume", ",", "1", "/", "3.0", ")", "/", "math", ".", "pow", "(", "area", ",", "1", "/", "2.0", ")", "# find a solution, if possible", "max_alpha", "=", "math", ".", "pi", "**", "(", "-", "1.0", "/", "6", ")", "*", "6.0", "**", "(", "-", "1.0", "/", "3", ")", "low", "=", "0.0", "high", "=", "max_alpha", "a", "=", "1.0", "b", "=", "1.5", "-", "1", "/", "(", "16", "*", "math", ".", "pi", "*", "phi", "**", "6", ")", "c", "=", "0.75", "d", "=", "0.125", "high_value", "=", "a", "*", "high", "**", "3", "+", "b", "*", "high", "**", "2", "+", "c", "*", "high", "+", "d", "for", "_", "in", "range", "(", "53", ")", ":", "mid", "=", "(", "low", "+", "high", ")", "/", "2", "mid_value", "=", "a", "*", "high", "**", "3", "+", "b", "*", "high", "**", "2", "+", "c", "*", "high", "+", "d", "if", "(", "high_value", ">", "0", ")", "==", "(", "mid_value", ">", "0", ")", ":", "high_value", "=", "mid_value", "high", "=", "mid", "else", ":", "low", "=", "mid", "# in the case this fails, return NaN", "if", "low", "==", "0", "or", "high", "==", "max_alpha", ":", "return", "float", "(", "'nan'", ")", "alpha", "=", "(", "low", "+", "high", ")", "/", "2.0", "height", "=", "(", "volume", "*", "4", "*", "alpha", "**", "2", "/", "math", ".", "pi", ")", "**", "(", "1.0", "/", "3", ")", "return", "height" ]
https://github.com/trilinos/Trilinos/blob/6168be6dd51e35e1cd681e9c4b24433e709df140/packages/seacas/scripts/exomerge2.py#L8173-L8199
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/dateutil/rrule.py
python
rruleset.exdate
(self, exdate)
Include the given datetime instance in the recurrence set exclusion list. Dates included that way will not be generated, even if some inclusive rrule or rdate matches them.
Include the given datetime instance in the recurrence set exclusion list. Dates included that way will not be generated, even if some inclusive rrule or rdate matches them.
[ "Include", "the", "given", "datetime", "instance", "in", "the", "recurrence", "set", "exclusion", "list", ".", "Dates", "included", "that", "way", "will", "not", "be", "generated", "even", "if", "some", "inclusive", "rrule", "or", "rdate", "matches", "them", "." ]
def exdate(self, exdate): """ Include the given datetime instance in the recurrence set exclusion list. Dates included that way will not be generated, even if some inclusive rrule or rdate matches them. """ self._exdate.append(exdate)
[ "def", "exdate", "(", "self", ",", "exdate", ")", ":", "self", ".", "_exdate", ".", "append", "(", "exdate", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/dateutil/rrule.py#L1375-L1379
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_carbon/dataview.py
python
DataViewEvent.IsEditCancelled
(*args, **kwargs)
return _dataview.DataViewEvent_IsEditCancelled(*args, **kwargs)
IsEditCancelled(self) -> bool
IsEditCancelled(self) -> bool
[ "IsEditCancelled", "(", "self", ")", "-", ">", "bool" ]
def IsEditCancelled(*args, **kwargs): """IsEditCancelled(self) -> bool""" return _dataview.DataViewEvent_IsEditCancelled(*args, **kwargs)
[ "def", "IsEditCancelled", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_dataview", ".", "DataViewEvent_IsEditCancelled", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_carbon/dataview.py#L1932-L1934
apache/qpid-proton
6bcdfebb55ea3554bc29b1901422532db331a591
python/proton/_utils.py
python
SyncRequestResponse.reply_to
(self)
return self.receiver.remote_source.address
The dynamic address of our receiver.
The dynamic address of our receiver.
[ "The", "dynamic", "address", "of", "our", "receiver", "." ]
def reply_to(self) -> str: """ The dynamic address of our receiver. """ return self.receiver.remote_source.address
[ "def", "reply_to", "(", "self", ")", "->", "str", ":", "return", "self", ".", "receiver", ".", "remote_source", ".", "address" ]
https://github.com/apache/qpid-proton/blob/6bcdfebb55ea3554bc29b1901422532db331a591/python/proton/_utils.py#L627-L631
hpi-xnor/BMXNet
ed0b201da6667887222b8e4b5f997c4f6b61943d
python/mxnet/kvstore.py
python
_ctype_key_value
(keys, vals)
Returns ctype arrays for the key-value args, and the whether string keys are used. For internal use only.
Returns ctype arrays for the key-value args, and the whether string keys are used. For internal use only.
[ "Returns", "ctype", "arrays", "for", "the", "key", "-", "value", "args", "and", "the", "whether", "string", "keys", "are", "used", ".", "For", "internal", "use", "only", "." ]
def _ctype_key_value(keys, vals): """ Returns ctype arrays for the key-value args, and the whether string keys are used. For internal use only. """ if isinstance(keys, (tuple, list)): assert(len(keys) == len(vals)) c_keys = [] c_vals = [] use_str_keys = None for key, val in zip(keys, vals): c_key_i, c_val_i, str_keys_i = _ctype_key_value(key, val) c_keys += c_key_i c_vals += c_val_i use_str_keys = str_keys_i if use_str_keys is None else use_str_keys assert(use_str_keys == str_keys_i), "inconsistent types of keys detected." c_keys_arr = c_array(ctypes.c_char_p, c_keys) if use_str_keys \ else c_array(ctypes.c_int, c_keys) c_vals_arr = c_array(ctypes.c_void_p, c_vals) return (c_keys_arr, c_vals_arr, use_str_keys) assert(isinstance(keys, (int,) + string_types)), \ "unexpected type for keys: " + str(type(keys)) use_str_keys = isinstance(keys, string_types) if isinstance(vals, NDArray): c_keys = c_str_array([keys]) if use_str_keys \ else c_array_buf(ctypes.c_int, array('i', [keys])) return (c_keys, c_handle_array([vals]), use_str_keys) else: for value in vals: assert(isinstance(value, NDArray)) c_keys = c_str_array([keys] * len(vals)) if use_str_keys \ else c_array_buf(ctypes.c_int, array('i', [keys] * len(vals))) return (c_keys, c_handle_array(vals), use_str_keys)
[ "def", "_ctype_key_value", "(", "keys", ",", "vals", ")", ":", "if", "isinstance", "(", "keys", ",", "(", "tuple", ",", "list", ")", ")", ":", "assert", "(", "len", "(", "keys", ")", "==", "len", "(", "vals", ")", ")", "c_keys", "=", "[", "]", "c_vals", "=", "[", "]", "use_str_keys", "=", "None", "for", "key", ",", "val", "in", "zip", "(", "keys", ",", "vals", ")", ":", "c_key_i", ",", "c_val_i", ",", "str_keys_i", "=", "_ctype_key_value", "(", "key", ",", "val", ")", "c_keys", "+=", "c_key_i", "c_vals", "+=", "c_val_i", "use_str_keys", "=", "str_keys_i", "if", "use_str_keys", "is", "None", "else", "use_str_keys", "assert", "(", "use_str_keys", "==", "str_keys_i", ")", ",", "\"inconsistent types of keys detected.\"", "c_keys_arr", "=", "c_array", "(", "ctypes", ".", "c_char_p", ",", "c_keys", ")", "if", "use_str_keys", "else", "c_array", "(", "ctypes", ".", "c_int", ",", "c_keys", ")", "c_vals_arr", "=", "c_array", "(", "ctypes", ".", "c_void_p", ",", "c_vals", ")", "return", "(", "c_keys_arr", ",", "c_vals_arr", ",", "use_str_keys", ")", "assert", "(", "isinstance", "(", "keys", ",", "(", "int", ",", ")", "+", "string_types", ")", ")", ",", "\"unexpected type for keys: \"", "+", "str", "(", "type", "(", "keys", ")", ")", "use_str_keys", "=", "isinstance", "(", "keys", ",", "string_types", ")", "if", "isinstance", "(", "vals", ",", "NDArray", ")", ":", "c_keys", "=", "c_str_array", "(", "[", "keys", "]", ")", "if", "use_str_keys", "else", "c_array_buf", "(", "ctypes", ".", "c_int", ",", "array", "(", "'i'", ",", "[", "keys", "]", ")", ")", "return", "(", "c_keys", ",", "c_handle_array", "(", "[", "vals", "]", ")", ",", "use_str_keys", ")", "else", ":", "for", "value", "in", "vals", ":", "assert", "(", "isinstance", "(", "value", ",", "NDArray", ")", ")", "c_keys", "=", "c_str_array", "(", "[", "keys", "]", "*", "len", "(", "vals", ")", ")", "if", "use_str_keys", "else", "c_array_buf", "(", "ctypes", ".", "c_int", ",", "array", "(", "'i'", ",", "[", "keys", "]", "*", "len", "(", "vals", ")", ")", ")", "return", "(", "c_keys", ",", "c_handle_array", "(", "vals", ")", ",", "use_str_keys", ")" ]
https://github.com/hpi-xnor/BMXNet/blob/ed0b201da6667887222b8e4b5f997c4f6b61943d/python/mxnet/kvstore.py#L32-L65
pytorch/pytorch
7176c92687d3cc847cc046bf002269c6949a21c2
tools/nightly.py
python
_ensure_commit
(git_sha1: str)
Make sure that we actually have the commit locally
Make sure that we actually have the commit locally
[ "Make", "sure", "that", "we", "actually", "have", "the", "commit", "locally" ]
def _ensure_commit(git_sha1: str) -> None: """Make sure that we actually have the commit locally""" cmd = ["git", "cat-file", "-e", git_sha1 + "^{commit}"] p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=False) if p.returncode == 0: # we have the commit locally return # we don't have the commit, must fetch cmd = ["git", "fetch", "https://github.com/pytorch/pytorch.git", git_sha1] p = subprocess.run(cmd, check=True)
[ "def", "_ensure_commit", "(", "git_sha1", ":", "str", ")", "->", "None", ":", "cmd", "=", "[", "\"git\"", ",", "\"cat-file\"", ",", "\"-e\"", ",", "git_sha1", "+", "\"^{commit}\"", "]", "p", "=", "subprocess", ".", "run", "(", "cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ",", "check", "=", "False", ")", "if", "p", ".", "returncode", "==", "0", ":", "# we have the commit locally", "return", "# we don't have the commit, must fetch", "cmd", "=", "[", "\"git\"", ",", "\"fetch\"", ",", "\"https://github.com/pytorch/pytorch.git\"", ",", "git_sha1", "]", "p", "=", "subprocess", ".", "run", "(", "cmd", ",", "check", "=", "True", ")" ]
https://github.com/pytorch/pytorch/blob/7176c92687d3cc847cc046bf002269c6949a21c2/tools/nightly.py#L344-L353
p4lang/behavioral-model
81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9
tools/cpplint.py
python
ProcessFile
(filename, vlevel, extra_check_functions=None)
Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error
Does google-lint on a single file.
[ "Does", "google", "-", "lint", "on", "a", "single", "file", "." ]
def ProcessFile(filename, vlevel, extra_check_functions=None): """Does google-lint on a single file. Args: filename: The name of the file to parse. vlevel: The level of errors to report. Every error of confidence >= verbose_level will be reported. 0 is a good default. extra_check_functions: An array of additional check functions that will be run on each source line. Each function takes 4 arguments: filename, clean_lines, line, error """ _SetVerboseLevel(vlevel) _BackupFilters() old_errors = _cpplint_state.error_count if not ProcessConfigOverrides(filename): _RestoreFilters() return lf_lines = [] crlf_lines = [] try: # Support the UNIX convention of using "-" for stdin. Note that # we are not opening the file with universal newline support # (which codecs doesn't support anyway), so the resulting lines do # contain trailing '\r' characters if we are reading a file that # has CRLF endings. # If after the split a trailing '\r' is present, it is removed # below. if filename == '-': lines = codecs.StreamReaderWriter(sys.stdin, codecs.getreader('utf8'), codecs.getwriter('utf8'), 'replace').read().split('\n') else: with codecs.open(filename, 'r', 'utf8', 'replace') as target_file: lines = target_file.read().split('\n') # Remove trailing '\r'. # The -1 accounts for the extra trailing blank line we get from split() for linenum in range(len(lines) - 1): if lines[linenum].endswith('\r'): lines[linenum] = lines[linenum].rstrip('\r') crlf_lines.append(linenum + 1) else: lf_lines.append(linenum + 1) except IOError: _cpplint_state.PrintError( "Skipping input '%s': Can't open for reading\n" % filename) _RestoreFilters() return # Note, if no dot is found, this will give the entire filename as the ext. file_extension = filename[filename.rfind('.') + 1:] # When reading from stdin, the extension is unknown, so no cpplint tests # should rely on the extension. if filename != '-' and file_extension not in GetAllExtensions(): _cpplint_state.PrintError('Ignoring %s; not a valid file name ' '(%s)\n' % (filename, ', '.join(GetAllExtensions()))) else: ProcessFileData(filename, file_extension, lines, Error, extra_check_functions) # If end-of-line sequences are a mix of LF and CR-LF, issue # warnings on the lines with CR. # # Don't issue any warnings if all lines are uniformly LF or CR-LF, # since critique can handle these just fine, and the style guide # doesn't dictate a particular end of line sequence. # # We can't depend on os.linesep to determine what the desired # end-of-line sequence should be, since that will return the # server-side end-of-line sequence. if lf_lines and crlf_lines: # Warn on every line with CR. An alternative approach might be to # check whether the file is mostly CRLF or just LF, and warn on the # minority, we bias toward LF here since most tools prefer LF. for linenum in crlf_lines: Error(filename, linenum, 'whitespace/newline', 1, 'Unexpected \\r (^M) found; better to use only \\n') # Suppress printing anything if --quiet was passed unless the error # count has increased after processing this file. if not _cpplint_state.quiet or old_errors != _cpplint_state.error_count: _cpplint_state.PrintInfo('Done processing %s\n' % filename) _RestoreFilters()
[ "def", "ProcessFile", "(", "filename", ",", "vlevel", ",", "extra_check_functions", "=", "None", ")", ":", "_SetVerboseLevel", "(", "vlevel", ")", "_BackupFilters", "(", ")", "old_errors", "=", "_cpplint_state", ".", "error_count", "if", "not", "ProcessConfigOverrides", "(", "filename", ")", ":", "_RestoreFilters", "(", ")", "return", "lf_lines", "=", "[", "]", "crlf_lines", "=", "[", "]", "try", ":", "# Support the UNIX convention of using \"-\" for stdin. Note that", "# we are not opening the file with universal newline support", "# (which codecs doesn't support anyway), so the resulting lines do", "# contain trailing '\\r' characters if we are reading a file that", "# has CRLF endings.", "# If after the split a trailing '\\r' is present, it is removed", "# below.", "if", "filename", "==", "'-'", ":", "lines", "=", "codecs", ".", "StreamReaderWriter", "(", "sys", ".", "stdin", ",", "codecs", ".", "getreader", "(", "'utf8'", ")", ",", "codecs", ".", "getwriter", "(", "'utf8'", ")", ",", "'replace'", ")", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "else", ":", "with", "codecs", ".", "open", "(", "filename", ",", "'r'", ",", "'utf8'", ",", "'replace'", ")", "as", "target_file", ":", "lines", "=", "target_file", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "# Remove trailing '\\r'.", "# The -1 accounts for the extra trailing blank line we get from split()", "for", "linenum", "in", "range", "(", "len", "(", "lines", ")", "-", "1", ")", ":", "if", "lines", "[", "linenum", "]", ".", "endswith", "(", "'\\r'", ")", ":", "lines", "[", "linenum", "]", "=", "lines", "[", "linenum", "]", ".", "rstrip", "(", "'\\r'", ")", "crlf_lines", ".", "append", "(", "linenum", "+", "1", ")", "else", ":", "lf_lines", ".", "append", "(", "linenum", "+", "1", ")", "except", "IOError", ":", "_cpplint_state", ".", "PrintError", "(", "\"Skipping input '%s': Can't open for reading\\n\"", "%", "filename", ")", "_RestoreFilters", "(", ")", "return", "# Note, if no dot is found, this will give the entire filename as the ext.", "file_extension", "=", "filename", "[", "filename", ".", "rfind", "(", "'.'", ")", "+", "1", ":", "]", "# When reading from stdin, the extension is unknown, so no cpplint tests", "# should rely on the extension.", "if", "filename", "!=", "'-'", "and", "file_extension", "not", "in", "GetAllExtensions", "(", ")", ":", "_cpplint_state", ".", "PrintError", "(", "'Ignoring %s; not a valid file name '", "'(%s)\\n'", "%", "(", "filename", ",", "', '", ".", "join", "(", "GetAllExtensions", "(", ")", ")", ")", ")", "else", ":", "ProcessFileData", "(", "filename", ",", "file_extension", ",", "lines", ",", "Error", ",", "extra_check_functions", ")", "# If end-of-line sequences are a mix of LF and CR-LF, issue", "# warnings on the lines with CR.", "#", "# Don't issue any warnings if all lines are uniformly LF or CR-LF,", "# since critique can handle these just fine, and the style guide", "# doesn't dictate a particular end of line sequence.", "#", "# We can't depend on os.linesep to determine what the desired", "# end-of-line sequence should be, since that will return the", "# server-side end-of-line sequence.", "if", "lf_lines", "and", "crlf_lines", ":", "# Warn on every line with CR. An alternative approach might be to", "# check whether the file is mostly CRLF or just LF, and warn on the", "# minority, we bias toward LF here since most tools prefer LF.", "for", "linenum", "in", "crlf_lines", ":", "Error", "(", "filename", ",", "linenum", ",", "'whitespace/newline'", ",", "1", ",", "'Unexpected \\\\r (^M) found; better to use only \\\\n'", ")", "# Suppress printing anything if --quiet was passed unless the error", "# count has increased after processing this file.", "if", "not", "_cpplint_state", ".", "quiet", "or", "old_errors", "!=", "_cpplint_state", ".", "error_count", ":", "_cpplint_state", ".", "PrintInfo", "(", "'Done processing %s\\n'", "%", "filename", ")", "_RestoreFilters", "(", ")" ]
https://github.com/p4lang/behavioral-model/blob/81ce0163f0770c6b9d6056a28ce2e0cc035bb6e9/tools/cpplint.py#L6591-L6681
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/copy_reg.py
python
add_extension
(module, name, code)
Register an extension code.
Register an extension code.
[ "Register", "an", "extension", "code", "." ]
def add_extension(module, name, code): """Register an extension code.""" code = int(code) if not 1 <= code <= 0x7fffffff: raise ValueError, "code out of range" key = (module, name) if (_extension_registry.get(key) == code and _inverted_registry.get(code) == key): return # Redundant registrations are benign if key in _extension_registry: raise ValueError("key %s is already registered with code %s" % (key, _extension_registry[key])) if code in _inverted_registry: raise ValueError("code %s is already in use for key %s" % (code, _inverted_registry[code])) _extension_registry[key] = code _inverted_registry[code] = key
[ "def", "add_extension", "(", "module", ",", "name", ",", "code", ")", ":", "code", "=", "int", "(", "code", ")", "if", "not", "1", "<=", "code", "<=", "0x7fffffff", ":", "raise", "ValueError", ",", "\"code out of range\"", "key", "=", "(", "module", ",", "name", ")", "if", "(", "_extension_registry", ".", "get", "(", "key", ")", "==", "code", "and", "_inverted_registry", ".", "get", "(", "code", ")", "==", "key", ")", ":", "return", "# Redundant registrations are benign", "if", "key", "in", "_extension_registry", ":", "raise", "ValueError", "(", "\"key %s is already registered with code %s\"", "%", "(", "key", ",", "_extension_registry", "[", "key", "]", ")", ")", "if", "code", "in", "_inverted_registry", ":", "raise", "ValueError", "(", "\"code %s is already in use for key %s\"", "%", "(", "code", ",", "_inverted_registry", "[", "code", "]", ")", ")", "_extension_registry", "[", "key", "]", "=", "code", "_inverted_registry", "[", "code", "]", "=", "key" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/copy_reg.py#L157-L173
apiaryio/drafter
4634ebd07f6c6f257cc656598ccd535492fdfb55
tools/gyp/pylib/gyp/generator/xcode.py
python
EscapeXcodeDefine
(s)
return re.sub(_xcode_define_re, r'\\\1', s)
We must escape the defines that we give to XCode so that it knows not to split on spaces and to respect backslash and quote literals. However, we must not quote the define, or Xcode will incorrectly intepret variables especially $(inherited).
We must escape the defines that we give to XCode so that it knows not to split on spaces and to respect backslash and quote literals. However, we must not quote the define, or Xcode will incorrectly intepret variables especially $(inherited).
[ "We", "must", "escape", "the", "defines", "that", "we", "give", "to", "XCode", "so", "that", "it", "knows", "not", "to", "split", "on", "spaces", "and", "to", "respect", "backslash", "and", "quote", "literals", ".", "However", "we", "must", "not", "quote", "the", "define", "or", "Xcode", "will", "incorrectly", "intepret", "variables", "especially", "$", "(", "inherited", ")", "." ]
def EscapeXcodeDefine(s): """We must escape the defines that we give to XCode so that it knows not to split on spaces and to respect backslash and quote literals. However, we must not quote the define, or Xcode will incorrectly intepret variables especially $(inherited).""" return re.sub(_xcode_define_re, r'\\\1', s)
[ "def", "EscapeXcodeDefine", "(", "s", ")", ":", "return", "re", ".", "sub", "(", "_xcode_define_re", ",", "r'\\\\\\1'", ",", "s", ")" ]
https://github.com/apiaryio/drafter/blob/4634ebd07f6c6f257cc656598ccd535492fdfb55/tools/gyp/pylib/gyp/generator/xcode.py#L557-L562
kevin-ssy/Optical-Flow-Guided-Feature
07d4501a29002ee7821c38c1820e4a64c1acf6e8
lib/caffe-action/scripts/cpp_lint.py
python
_NestingState.InnermostClass
(self)
return None
Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise.
Get class info on the top of the stack.
[ "Get", "class", "info", "on", "the", "top", "of", "the", "stack", "." ]
def InnermostClass(self): """Get class info on the top of the stack. Returns: A _ClassInfo object if we are inside a class, or None otherwise. """ for i in range(len(self.stack), 0, -1): classinfo = self.stack[i - 1] if isinstance(classinfo, _ClassInfo): return classinfo return None
[ "def", "InnermostClass", "(", "self", ")", ":", "for", "i", "in", "range", "(", "len", "(", "self", ".", "stack", ")", ",", "0", ",", "-", "1", ")", ":", "classinfo", "=", "self", ".", "stack", "[", "i", "-", "1", "]", "if", "isinstance", "(", "classinfo", ",", "_ClassInfo", ")", ":", "return", "classinfo", "return", "None" ]
https://github.com/kevin-ssy/Optical-Flow-Guided-Feature/blob/07d4501a29002ee7821c38c1820e4a64c1acf6e8/lib/caffe-action/scripts/cpp_lint.py#L2160-L2170
indutny/candor
48e7260618f5091c80a3416828e2808cad3ea22e
tools/gyp/pylib/gyp/easy_xml.py
python
XmlToString
(content, encoding='utf-8', pretty=False)
return ''.join(xml_parts)
Writes the XML content to disk, touching the file only if it has changed. Visual Studio files have a lot of pre-defined structures. This function makes it easy to represent these structures as Python data structures, instead of having to create a lot of function calls. Each XML element of the content is represented as a list composed of: 1. The name of the element, a string, 2. The attributes of the element, a dictionary (optional), and 3+. The content of the element, if any. Strings are simple text nodes and lists are child elements. Example 1: <test/> becomes ['test'] Example 2: <myelement a='value1' b='value2'> <childtype>This is</childtype> <childtype>it!</childtype> </myelement> becomes ['myelement', {'a':'value1', 'b':'value2'}, ['childtype', 'This is'], ['childtype', 'it!'], ] Args: content: The structured content to be converted. encoding: The encoding to report on the first XML line. pretty: True if we want pretty printing with indents and new lines. Returns: The XML content as a string.
Writes the XML content to disk, touching the file only if it has changed.
[ "Writes", "the", "XML", "content", "to", "disk", "touching", "the", "file", "only", "if", "it", "has", "changed", "." ]
def XmlToString(content, encoding='utf-8', pretty=False): """ Writes the XML content to disk, touching the file only if it has changed. Visual Studio files have a lot of pre-defined structures. This function makes it easy to represent these structures as Python data structures, instead of having to create a lot of function calls. Each XML element of the content is represented as a list composed of: 1. The name of the element, a string, 2. The attributes of the element, a dictionary (optional), and 3+. The content of the element, if any. Strings are simple text nodes and lists are child elements. Example 1: <test/> becomes ['test'] Example 2: <myelement a='value1' b='value2'> <childtype>This is</childtype> <childtype>it!</childtype> </myelement> becomes ['myelement', {'a':'value1', 'b':'value2'}, ['childtype', 'This is'], ['childtype', 'it!'], ] Args: content: The structured content to be converted. encoding: The encoding to report on the first XML line. pretty: True if we want pretty printing with indents and new lines. Returns: The XML content as a string. """ # We create a huge list of all the elements of the file. xml_parts = ['<?xml version="1.0" encoding="%s"?>' % encoding] if pretty: xml_parts.append('\n') _ConstructContentList(xml_parts, content, pretty) # Convert it to a string return ''.join(xml_parts)
[ "def", "XmlToString", "(", "content", ",", "encoding", "=", "'utf-8'", ",", "pretty", "=", "False", ")", ":", "# We create a huge list of all the elements of the file.", "xml_parts", "=", "[", "'<?xml version=\"1.0\" encoding=\"%s\"?>'", "%", "encoding", "]", "if", "pretty", ":", "xml_parts", ".", "append", "(", "'\\n'", ")", "_ConstructContentList", "(", "xml_parts", ",", "content", ",", "pretty", ")", "# Convert it to a string", "return", "''", ".", "join", "(", "xml_parts", ")" ]
https://github.com/indutny/candor/blob/48e7260618f5091c80a3416828e2808cad3ea22e/tools/gyp/pylib/gyp/easy_xml.py#L9-L54
physercoe/starquant
c00cad64d1de2da05081b3dc320ef264c6295e08
source/data/data_board.py
python
ArrayManager.sma
(self, n, array=False)
return result[-1]
Simple moving average.
Simple moving average.
[ "Simple", "moving", "average", "." ]
def sma(self, n, array=False): """ Simple moving average. """ result = talib.SMA(self.close, n) if array: return result return result[-1]
[ "def", "sma", "(", "self", ",", "n", ",", "array", "=", "False", ")", ":", "result", "=", "talib", ".", "SMA", "(", "self", ".", "close", ",", "n", ")", "if", "array", ":", "return", "result", "return", "result", "[", "-", "1", "]" ]
https://github.com/physercoe/starquant/blob/c00cad64d1de2da05081b3dc320ef264c6295e08/source/data/data_board.py#L245-L252
NicknineTheEagle/TF2-Base
20459c5a7fbc995b6bf54fa85c2f62a101e9fb64
src/thirdparty/protobuf-2.3.0/python/google/protobuf/service.py
python
Service.GetResponseClass
(self, method_descriptor)
Returns the class of the response message for the specified method. This method isn't really needed, as the RpcChannel's CallMethod constructs the response protocol message. It's provided anyway in case it is useful for the caller to know the response type in advance.
Returns the class of the response message for the specified method.
[ "Returns", "the", "class", "of", "the", "response", "message", "for", "the", "specified", "method", "." ]
def GetResponseClass(self, method_descriptor): """Returns the class of the response message for the specified method. This method isn't really needed, as the RpcChannel's CallMethod constructs the response protocol message. It's provided anyway in case it is useful for the caller to know the response type in advance. """ raise NotImplementedError
[ "def", "GetResponseClass", "(", "self", ",", "method_descriptor", ")", ":", "raise", "NotImplementedError" ]
https://github.com/NicknineTheEagle/TF2-Base/blob/20459c5a7fbc995b6bf54fa85c2f62a101e9fb64/src/thirdparty/protobuf-2.3.0/python/google/protobuf/service.py#L108-L115
gnina/gnina
b9ae032f52fc7a8153987bde09c0efa3620d8bb6
caffe/scripts/cpp_lint.py
python
CheckForIncludeWhatYouUse
(filename, clean_lines, include_state, error, io=codecs)
Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection.
Reports for missing stl includes.
[ "Reports", "for", "missing", "stl", "includes", "." ]
def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error, io=codecs): """Reports for missing stl includes. This function will output warnings to make sure you are including the headers necessary for the stl containers and functions that you use. We only give one reason to include a header. For example, if you use both equal_to<> and less<> in a .h file, only one (the latter in the file) of these will be reported as a reason to include the <functional>. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. include_state: An _IncludeState instance. error: The function to call with any errors found. io: The IO factory to use to read the header file. Provided for unittest injection. """ required = {} # A map of header name to linenumber and the template entity. # Example of required: { '<functional>': (1219, 'less<>') } for linenum in xrange(clean_lines.NumLines()): line = clean_lines.elided[linenum] if not line or line[0] == '#': continue # String is special -- it is a non-templatized type in STL. matched = _RE_PATTERN_STRING.search(line) if matched: # Don't warn about strings in non-STL namespaces: # (We check only the first match per line; good enough.) prefix = line[:matched.start()] if prefix.endswith('std::') or not prefix.endswith('::'): required['<string>'] = (linenum, 'string') for pattern, template, header in _re_pattern_algorithm_header: if pattern.search(line): required[header] = (linenum, template) # The following function is just a speed up, no semantics are changed. if not '<' in line: # Reduces the cpu time usage by skipping lines. continue for pattern, template, header in _re_pattern_templates: if pattern.search(line): required[header] = (linenum, template) # The policy is that if you #include something in foo.h you don't need to # include it again in foo.cc. Here, we will look at possible includes. # Let's copy the include_state so it is only messed up within this function. include_state = include_state.copy() # Did we find the header for this file (if any) and successfully load it? header_found = False # Use the absolute path so that matching works properly. abs_filename = FileInfo(filename).FullName() # For Emacs's flymake. # If cpplint is invoked from Emacs's flymake, a temporary file is generated # by flymake and that file name might end with '_flymake.cc'. In that case, # restore original file name here so that the corresponding header file can be # found. # e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h' # instead of 'foo_flymake.h' abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename) # include_state is modified during iteration, so we iterate over a copy of # the keys. header_keys = include_state.keys() for header in header_keys: (same_module, common_path) = FilesBelongToSameModule(abs_filename, header) fullpath = common_path + header if same_module and UpdateIncludeState(fullpath, include_state, io): header_found = True # If we can't find the header file for a .cc, assume it's because we don't # know where to look. In that case we'll give up as we're not sure they # didn't include it in the .h file. # TODO(unknown): Do a better job of finding .h files so we are confident that # not having the .h file means there isn't one. if filename.endswith('.cc') and not header_found: return # All the lines have been processed, report the errors found. for required_header_unstripped in required: template = required[required_header_unstripped][1] if required_header_unstripped.strip('<>"') not in include_state: error(filename, required[required_header_unstripped][0], 'build/include_what_you_use', 4, 'Add #include ' + required_header_unstripped + ' for ' + template)
[ "def", "CheckForIncludeWhatYouUse", "(", "filename", ",", "clean_lines", ",", "include_state", ",", "error", ",", "io", "=", "codecs", ")", ":", "required", "=", "{", "}", "# A map of header name to linenumber and the template entity.", "# Example of required: { '<functional>': (1219, 'less<>') }", "for", "linenum", "in", "xrange", "(", "clean_lines", ".", "NumLines", "(", ")", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "not", "line", "or", "line", "[", "0", "]", "==", "'#'", ":", "continue", "# String is special -- it is a non-templatized type in STL.", "matched", "=", "_RE_PATTERN_STRING", ".", "search", "(", "line", ")", "if", "matched", ":", "# Don't warn about strings in non-STL namespaces:", "# (We check only the first match per line; good enough.)", "prefix", "=", "line", "[", ":", "matched", ".", "start", "(", ")", "]", "if", "prefix", ".", "endswith", "(", "'std::'", ")", "or", "not", "prefix", ".", "endswith", "(", "'::'", ")", ":", "required", "[", "'<string>'", "]", "=", "(", "linenum", ",", "'string'", ")", "for", "pattern", ",", "template", ",", "header", "in", "_re_pattern_algorithm_header", ":", "if", "pattern", ".", "search", "(", "line", ")", ":", "required", "[", "header", "]", "=", "(", "linenum", ",", "template", ")", "# The following function is just a speed up, no semantics are changed.", "if", "not", "'<'", "in", "line", ":", "# Reduces the cpu time usage by skipping lines.", "continue", "for", "pattern", ",", "template", ",", "header", "in", "_re_pattern_templates", ":", "if", "pattern", ".", "search", "(", "line", ")", ":", "required", "[", "header", "]", "=", "(", "linenum", ",", "template", ")", "# The policy is that if you #include something in foo.h you don't need to", "# include it again in foo.cc. Here, we will look at possible includes.", "# Let's copy the include_state so it is only messed up within this function.", "include_state", "=", "include_state", ".", "copy", "(", ")", "# Did we find the header for this file (if any) and successfully load it?", "header_found", "=", "False", "# Use the absolute path so that matching works properly.", "abs_filename", "=", "FileInfo", "(", "filename", ")", ".", "FullName", "(", ")", "# For Emacs's flymake.", "# If cpplint is invoked from Emacs's flymake, a temporary file is generated", "# by flymake and that file name might end with '_flymake.cc'. In that case,", "# restore original file name here so that the corresponding header file can be", "# found.", "# e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'", "# instead of 'foo_flymake.h'", "abs_filename", "=", "re", ".", "sub", "(", "r'_flymake\\.cc$'", ",", "'.cc'", ",", "abs_filename", ")", "# include_state is modified during iteration, so we iterate over a copy of", "# the keys.", "header_keys", "=", "include_state", ".", "keys", "(", ")", "for", "header", "in", "header_keys", ":", "(", "same_module", ",", "common_path", ")", "=", "FilesBelongToSameModule", "(", "abs_filename", ",", "header", ")", "fullpath", "=", "common_path", "+", "header", "if", "same_module", "and", "UpdateIncludeState", "(", "fullpath", ",", "include_state", ",", "io", ")", ":", "header_found", "=", "True", "# If we can't find the header file for a .cc, assume it's because we don't", "# know where to look. In that case we'll give up as we're not sure they", "# didn't include it in the .h file.", "# TODO(unknown): Do a better job of finding .h files so we are confident that", "# not having the .h file means there isn't one.", "if", "filename", ".", "endswith", "(", "'.cc'", ")", "and", "not", "header_found", ":", "return", "# All the lines have been processed, report the errors found.", "for", "required_header_unstripped", "in", "required", ":", "template", "=", "required", "[", "required_header_unstripped", "]", "[", "1", "]", "if", "required_header_unstripped", ".", "strip", "(", "'<>\"'", ")", "not", "in", "include_state", ":", "error", "(", "filename", ",", "required", "[", "required_header_unstripped", "]", "[", "0", "]", ",", "'build/include_what_you_use'", ",", "4", ",", "'Add #include '", "+", "required_header_unstripped", "+", "' for '", "+", "template", ")" ]
https://github.com/gnina/gnina/blob/b9ae032f52fc7a8153987bde09c0efa3620d8bb6/caffe/scripts/cpp_lint.py#L4487-L4577
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/sgmllib.py
python
SGMLParser.setnomoretags
(self)
Enter literal mode (CDATA) till EOF. Intended for derived classes only.
Enter literal mode (CDATA) till EOF.
[ "Enter", "literal", "mode", "(", "CDATA", ")", "till", "EOF", "." ]
def setnomoretags(self): """Enter literal mode (CDATA) till EOF. Intended for derived classes only. """ self.nomoretags = self.literal = 1
[ "def", "setnomoretags", "(", "self", ")", ":", "self", ".", "nomoretags", "=", "self", ".", "literal", "=", "1" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/armeabi/toolchain/lib/python2.7/sgmllib.py#L81-L86
microsoft/CNTK
e9396480025b9ca457d26b6f33dd07c474c6aa04
bindings/python/cntk/axis.py
python
Axis.is_sequence_axis
(self)
return super(Axis, self).is_sequence_axis()
Returns True if the axis is a sequence axis and False otherwise Returns: bool: True if this axis is a sequence axis and False otherwise
Returns True if the axis is a sequence axis and False otherwise
[ "Returns", "True", "if", "the", "axis", "is", "a", "sequence", "axis", "and", "False", "otherwise" ]
def is_sequence_axis(self): ''' Returns True if the axis is a sequence axis and False otherwise Returns: bool: True if this axis is a sequence axis and False otherwise ''' return super(Axis, self).is_sequence_axis()
[ "def", "is_sequence_axis", "(", "self", ")", ":", "return", "super", "(", "Axis", ",", "self", ")", ".", "is_sequence_axis", "(", ")" ]
https://github.com/microsoft/CNTK/blob/e9396480025b9ca457d26b6f33dd07c474c6aa04/bindings/python/cntk/axis.py#L51-L58
amrayn/easyloggingpp
8489989bb26c6371df103f6cbced3fbee1bc3c2f
tools/cpplint.py
python
CheckIncludeLine
(filename, clean_lines, linenum, include_state, error)
Check rules that are applicable to #include lines. Strings on #include lines are NOT removed from elided line, to make certain tasks easier. However, to prevent false positives, checks applicable to #include lines in CheckLanguage must be put here. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found.
Check rules that are applicable to #include lines.
[ "Check", "rules", "that", "are", "applicable", "to", "#include", "lines", "." ]
def CheckIncludeLine(filename, clean_lines, linenum, include_state, error): """Check rules that are applicable to #include lines. Strings on #include lines are NOT removed from elided line, to make certain tasks easier. However, to prevent false positives, checks applicable to #include lines in CheckLanguage must be put here. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. include_state: An _IncludeState instance in which the headers are inserted. error: The function to call with any errors found. """ fileinfo = FileInfo(filename) line = clean_lines.lines[linenum] # "include" should use the new style "foo/bar.h" instead of just "bar.h" if _RE_PATTERN_INCLUDE_NEW_STYLE.search(line): error(filename, linenum, 'build/include', 4, 'Include the directory when naming .h files') # we shouldn't include a file more than once. actually, there are a # handful of instances where doing so is okay, but in general it's # not. match = _RE_PATTERN_INCLUDE.search(line) if match: include = match.group(2) is_system = (match.group(1) == '<') if include in include_state: error(filename, linenum, 'build/include', 4, '"%s" already included at %s:%s' % (include, filename, include_state[include])) else: include_state[include] = linenum # We want to ensure that headers appear in the right order: # 1) for foo.cc, foo.h (preferred location) # 2) c system files # 3) cpp system files # 4) for foo.cc, foo.h (deprecated location) # 5) other google headers # # We classify each include statement as one of those 5 types # using a number of techniques. The include_state object keeps # track of the highest type seen, and complains if we see a # lower type after that. error_message = include_state.CheckNextIncludeOrder( _ClassifyInclude(fileinfo, include, is_system)) if error_message: error(filename, linenum, 'build/include_order', 4, '%s. Should be: %s.h, c system, c++ system, other.' % (error_message, fileinfo.BaseName())) canonical_include = include_state.CanonicalizeAlphabeticalOrder(include) if not include_state.IsInAlphabeticalOrder( clean_lines, linenum, canonical_include): error(filename, linenum, 'build/include_alpha', 4, 'Include "%s" not in alphabetical order' % include) include_state.SetLastHeader(canonical_include) # Look for any of the stream classes that are part of standard C++. match = _RE_PATTERN_INCLUDE.match(line) if match: include = match.group(2) if Match(r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$', include): # Many unit tests use cout, so we exempt them. if not _IsTestFilename(filename): error(filename, linenum, 'readability/streams', 3, 'Streams are highly discouraged.')
[ "def", "CheckIncludeLine", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "include_state", ",", "error", ")", ":", "fileinfo", "=", "FileInfo", "(", "filename", ")", "line", "=", "clean_lines", ".", "lines", "[", "linenum", "]", "# \"include\" should use the new style \"foo/bar.h\" instead of just \"bar.h\"", "if", "_RE_PATTERN_INCLUDE_NEW_STYLE", ".", "search", "(", "line", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/include'", ",", "4", ",", "'Include the directory when naming .h files'", ")", "# we shouldn't include a file more than once. actually, there are a", "# handful of instances where doing so is okay, but in general it's", "# not.", "match", "=", "_RE_PATTERN_INCLUDE", ".", "search", "(", "line", ")", "if", "match", ":", "include", "=", "match", ".", "group", "(", "2", ")", "is_system", "=", "(", "match", ".", "group", "(", "1", ")", "==", "'<'", ")", "if", "include", "in", "include_state", ":", "error", "(", "filename", ",", "linenum", ",", "'build/include'", ",", "4", ",", "'\"%s\" already included at %s:%s'", "%", "(", "include", ",", "filename", ",", "include_state", "[", "include", "]", ")", ")", "else", ":", "include_state", "[", "include", "]", "=", "linenum", "# We want to ensure that headers appear in the right order:", "# 1) for foo.cc, foo.h (preferred location)", "# 2) c system files", "# 3) cpp system files", "# 4) for foo.cc, foo.h (deprecated location)", "# 5) other google headers", "#", "# We classify each include statement as one of those 5 types", "# using a number of techniques. The include_state object keeps", "# track of the highest type seen, and complains if we see a", "# lower type after that.", "error_message", "=", "include_state", ".", "CheckNextIncludeOrder", "(", "_ClassifyInclude", "(", "fileinfo", ",", "include", ",", "is_system", ")", ")", "if", "error_message", ":", "error", "(", "filename", ",", "linenum", ",", "'build/include_order'", ",", "4", ",", "'%s. Should be: %s.h, c system, c++ system, other.'", "%", "(", "error_message", ",", "fileinfo", ".", "BaseName", "(", ")", ")", ")", "canonical_include", "=", "include_state", ".", "CanonicalizeAlphabeticalOrder", "(", "include", ")", "if", "not", "include_state", ".", "IsInAlphabeticalOrder", "(", "clean_lines", ",", "linenum", ",", "canonical_include", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'build/include_alpha'", ",", "4", ",", "'Include \"%s\" not in alphabetical order'", "%", "include", ")", "include_state", ".", "SetLastHeader", "(", "canonical_include", ")", "# Look for any of the stream classes that are part of standard C++.", "match", "=", "_RE_PATTERN_INCLUDE", ".", "match", "(", "line", ")", "if", "match", ":", "include", "=", "match", ".", "group", "(", "2", ")", "if", "Match", "(", "r'(f|ind|io|i|o|parse|pf|stdio|str|)?stream$'", ",", "include", ")", ":", "# Many unit tests use cout, so we exempt them.", "if", "not", "_IsTestFilename", "(", "filename", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/streams'", ",", "3", ",", "'Streams are highly discouraged.'", ")" ]
https://github.com/amrayn/easyloggingpp/blob/8489989bb26c6371df103f6cbced3fbee1bc3c2f/tools/cpplint.py#L3557-L3626
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/richtext.py
python
RichTextHTMLHandler.SetFileCounter
(*args, **kwargs)
return _richtext.RichTextHTMLHandler_SetFileCounter(*args, **kwargs)
SetFileCounter(int counter) Reset the file counter, in case, for example, the same names are required each time
SetFileCounter(int counter)
[ "SetFileCounter", "(", "int", "counter", ")" ]
def SetFileCounter(*args, **kwargs): """ SetFileCounter(int counter) Reset the file counter, in case, for example, the same names are required each time """ return _richtext.RichTextHTMLHandler_SetFileCounter(*args, **kwargs)
[ "def", "SetFileCounter", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextHTMLHandler_SetFileCounter", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/richtext.py#L4356-L4363
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/PublicKey/DSA.py
python
DsaKey.export_key
(self, format='PEM', pkcs8=None, passphrase=None, protection=None, randfunc=None)
Export this DSA key. Args: format (string): The encoding for the output: - *'PEM'* (default). ASCII as per `RFC1421`_/ `RFC1423`_. - *'DER'*. Binary ASN.1 encoding. - *'OpenSSH'*. ASCII one-liner as per `RFC4253`_. Only suitable for public keys, not for private keys. passphrase (string): *Private keys only*. The pass phrase to protect the output. pkcs8 (boolean): *Private keys only*. If ``True`` (default), the key is encoded with `PKCS#8`_. If ``False``, it is encoded in the custom OpenSSL/OpenSSH container. protection (string): *Only in combination with a pass phrase*. The encryption scheme to use to protect the output. If :data:`pkcs8` takes value ``True``, this is the PKCS#8 algorithm to use for deriving the secret and encrypting the private DSA key. For a complete list of algorithms, see :mod:`Crypto.IO.PKCS8`. The default is *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC*. If :data:`pkcs8` is ``False``, the obsolete PEM encryption scheme is used. It is based on MD5 for key derivation, and Triple DES for encryption. Parameter :data:`protection` is then ignored. The combination ``format='DER'`` and ``pkcs8=False`` is not allowed if a passphrase is present. randfunc (callable): A function that returns random bytes. By default it is :func:`Crypto.Random.get_random_bytes`. Returns: byte string : the encoded key Raises: ValueError : when the format is unknown or when you try to encrypt a private key with *DER* format and OpenSSL/OpenSSH. .. warning:: If you don't provide a pass phrase, the private key will be exported in the clear! .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt .. _RFC4253: http://www.ietf.org/rfc/rfc4253.txt .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt
Export this DSA key.
[ "Export", "this", "DSA", "key", "." ]
def export_key(self, format='PEM', pkcs8=None, passphrase=None, protection=None, randfunc=None): """Export this DSA key. Args: format (string): The encoding for the output: - *'PEM'* (default). ASCII as per `RFC1421`_/ `RFC1423`_. - *'DER'*. Binary ASN.1 encoding. - *'OpenSSH'*. ASCII one-liner as per `RFC4253`_. Only suitable for public keys, not for private keys. passphrase (string): *Private keys only*. The pass phrase to protect the output. pkcs8 (boolean): *Private keys only*. If ``True`` (default), the key is encoded with `PKCS#8`_. If ``False``, it is encoded in the custom OpenSSL/OpenSSH container. protection (string): *Only in combination with a pass phrase*. The encryption scheme to use to protect the output. If :data:`pkcs8` takes value ``True``, this is the PKCS#8 algorithm to use for deriving the secret and encrypting the private DSA key. For a complete list of algorithms, see :mod:`Crypto.IO.PKCS8`. The default is *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC*. If :data:`pkcs8` is ``False``, the obsolete PEM encryption scheme is used. It is based on MD5 for key derivation, and Triple DES for encryption. Parameter :data:`protection` is then ignored. The combination ``format='DER'`` and ``pkcs8=False`` is not allowed if a passphrase is present. randfunc (callable): A function that returns random bytes. By default it is :func:`Crypto.Random.get_random_bytes`. Returns: byte string : the encoded key Raises: ValueError : when the format is unknown or when you try to encrypt a private key with *DER* format and OpenSSL/OpenSSH. .. warning:: If you don't provide a pass phrase, the private key will be exported in the clear! .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt .. _RFC4253: http://www.ietf.org/rfc/rfc4253.txt .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt """ if passphrase is not None: passphrase = tobytes(passphrase) if randfunc is None: randfunc = Random.get_random_bytes if format == 'OpenSSH': tup1 = [self._key[x].to_bytes() for x in ('p', 'q', 'g', 'y')] def func(x): if (bord(x[0]) & 0x80): return bchr(0) + x else: return x tup2 = [func(x) for x in tup1] keyparts = [b'ssh-dss'] + tup2 keystring = b''.join( [struct.pack(">I", len(kp)) + kp for kp in keyparts] ) return b'ssh-dss ' + binascii.b2a_base64(keystring)[:-1] # DER format is always used, even in case of PEM, which simply # encodes it into BASE64. params = DerSequence([self.p, self.q, self.g]) if self.has_private(): if pkcs8 is None: pkcs8 = True if pkcs8: if not protection: protection = 'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC' private_key = DerInteger(self.x).encode() binary_key = PKCS8.wrap( private_key, oid, passphrase, protection, key_params=params, randfunc=randfunc ) if passphrase: key_type = 'ENCRYPTED PRIVATE' else: key_type = 'PRIVATE' passphrase = None else: if format != 'PEM' and passphrase: raise ValueError("DSA private key cannot be encrypted") ints = [0, self.p, self.q, self.g, self.y, self.x] binary_key = DerSequence(ints).encode() key_type = "DSA PRIVATE" else: if pkcs8: raise ValueError("PKCS#8 is only meaningful for private keys") binary_key = _create_subject_public_key_info(oid, DerInteger(self.y), params) key_type = "PUBLIC" if format == 'DER': return binary_key if format == 'PEM': pem_str = PEM.encode( binary_key, key_type + " KEY", passphrase, randfunc ) return tobytes(pem_str) raise ValueError("Unknown key format '%s'. Cannot export the DSA key." % format)
[ "def", "export_key", "(", "self", ",", "format", "=", "'PEM'", ",", "pkcs8", "=", "None", ",", "passphrase", "=", "None", ",", "protection", "=", "None", ",", "randfunc", "=", "None", ")", ":", "if", "passphrase", "is", "not", "None", ":", "passphrase", "=", "tobytes", "(", "passphrase", ")", "if", "randfunc", "is", "None", ":", "randfunc", "=", "Random", ".", "get_random_bytes", "if", "format", "==", "'OpenSSH'", ":", "tup1", "=", "[", "self", ".", "_key", "[", "x", "]", ".", "to_bytes", "(", ")", "for", "x", "in", "(", "'p'", ",", "'q'", ",", "'g'", ",", "'y'", ")", "]", "def", "func", "(", "x", ")", ":", "if", "(", "bord", "(", "x", "[", "0", "]", ")", "&", "0x80", ")", ":", "return", "bchr", "(", "0", ")", "+", "x", "else", ":", "return", "x", "tup2", "=", "[", "func", "(", "x", ")", "for", "x", "in", "tup1", "]", "keyparts", "=", "[", "b'ssh-dss'", "]", "+", "tup2", "keystring", "=", "b''", ".", "join", "(", "[", "struct", ".", "pack", "(", "\">I\"", ",", "len", "(", "kp", ")", ")", "+", "kp", "for", "kp", "in", "keyparts", "]", ")", "return", "b'ssh-dss '", "+", "binascii", ".", "b2a_base64", "(", "keystring", ")", "[", ":", "-", "1", "]", "# DER format is always used, even in case of PEM, which simply", "# encodes it into BASE64.", "params", "=", "DerSequence", "(", "[", "self", ".", "p", ",", "self", ".", "q", ",", "self", ".", "g", "]", ")", "if", "self", ".", "has_private", "(", ")", ":", "if", "pkcs8", "is", "None", ":", "pkcs8", "=", "True", "if", "pkcs8", ":", "if", "not", "protection", ":", "protection", "=", "'PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC'", "private_key", "=", "DerInteger", "(", "self", ".", "x", ")", ".", "encode", "(", ")", "binary_key", "=", "PKCS8", ".", "wrap", "(", "private_key", ",", "oid", ",", "passphrase", ",", "protection", ",", "key_params", "=", "params", ",", "randfunc", "=", "randfunc", ")", "if", "passphrase", ":", "key_type", "=", "'ENCRYPTED PRIVATE'", "else", ":", "key_type", "=", "'PRIVATE'", "passphrase", "=", "None", "else", ":", "if", "format", "!=", "'PEM'", "and", "passphrase", ":", "raise", "ValueError", "(", "\"DSA private key cannot be encrypted\"", ")", "ints", "=", "[", "0", ",", "self", ".", "p", ",", "self", ".", "q", ",", "self", ".", "g", ",", "self", ".", "y", ",", "self", ".", "x", "]", "binary_key", "=", "DerSequence", "(", "ints", ")", ".", "encode", "(", ")", "key_type", "=", "\"DSA PRIVATE\"", "else", ":", "if", "pkcs8", ":", "raise", "ValueError", "(", "\"PKCS#8 is only meaningful for private keys\"", ")", "binary_key", "=", "_create_subject_public_key_info", "(", "oid", ",", "DerInteger", "(", "self", ".", "y", ")", ",", "params", ")", "key_type", "=", "\"PUBLIC\"", "if", "format", "==", "'DER'", ":", "return", "binary_key", "if", "format", "==", "'PEM'", ":", "pem_str", "=", "PEM", ".", "encode", "(", "binary_key", ",", "key_type", "+", "\" KEY\"", ",", "passphrase", ",", "randfunc", ")", "return", "tobytes", "(", "pem_str", ")", "raise", "ValueError", "(", "\"Unknown key format '%s'. Cannot export the DSA key.\"", "%", "format", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/ResourceManager/lib/Crypto/PublicKey/DSA.py#L208-L331
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py
python
XcodeSettings.GetCflagsC
(self, configname)
return cflags_c
Returns flags that need to be added to .c, and .m compilations.
Returns flags that need to be added to .c, and .m compilations.
[ "Returns", "flags", "that", "need", "to", "be", "added", "to", ".", "c", "and", ".", "m", "compilations", "." ]
def GetCflagsC(self, configname): """Returns flags that need to be added to .c, and .m compilations.""" self.configname = configname cflags_c = [] self._Appendf(cflags_c, 'GCC_C_LANGUAGE_STANDARD', '-std=%s') cflags_c += self._Settings().get('OTHER_CFLAGS', []) self.configname = None return cflags_c
[ "def", "GetCflagsC", "(", "self", ",", "configname", ")", ":", "self", ".", "configname", "=", "configname", "cflags_c", "=", "[", "]", "self", ".", "_Appendf", "(", "cflags_c", ",", "'GCC_C_LANGUAGE_STANDARD'", ",", "'-std=%s'", ")", "cflags_c", "+=", "self", ".", "_Settings", "(", ")", ".", "get", "(", "'OTHER_CFLAGS'", ",", "[", "]", ")", "self", ".", "configname", "=", "None", "return", "cflags_c" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/media/webrtc/trunk/tools/gyp/pylib/gyp/xcode_emulation.py#L344-L351
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/help.py
python
_implementation
()
return {'name': implementation, 'version': implementation_version}
Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 2.7.5 it will return {'name': 'CPython', 'version': '2.7.5'}. This function works best on CPython and PyPy: in particular, it probably doesn't work for Jython or IronPython. Future investigation should be done to work out the correct shape of the code for those platforms.
Return a dict with the Python implementation and version.
[ "Return", "a", "dict", "with", "the", "Python", "implementation", "and", "version", "." ]
def _implementation(): """Return a dict with the Python implementation and version. Provide both the name and the version of the Python implementation currently running. For example, on CPython 2.7.5 it will return {'name': 'CPython', 'version': '2.7.5'}. This function works best on CPython and PyPy: in particular, it probably doesn't work for Jython or IronPython. Future investigation should be done to work out the correct shape of the code for those platforms. """ implementation = platform.python_implementation() if implementation == 'CPython': implementation_version = platform.python_version() elif implementation == 'PyPy': implementation_version = '%s.%s.%s' % (sys.pypy_version_info.major, sys.pypy_version_info.minor, sys.pypy_version_info.micro) if sys.pypy_version_info.releaselevel != 'final': implementation_version = ''.join([ implementation_version, sys.pypy_version_info.releaselevel ]) elif implementation == 'Jython': implementation_version = platform.python_version() # Complete Guess elif implementation == 'IronPython': implementation_version = platform.python_version() # Complete Guess else: implementation_version = 'Unknown' return {'name': implementation, 'version': implementation_version}
[ "def", "_implementation", "(", ")", ":", "implementation", "=", "platform", ".", "python_implementation", "(", ")", "if", "implementation", "==", "'CPython'", ":", "implementation_version", "=", "platform", ".", "python_version", "(", ")", "elif", "implementation", "==", "'PyPy'", ":", "implementation_version", "=", "'%s.%s.%s'", "%", "(", "sys", ".", "pypy_version_info", ".", "major", ",", "sys", ".", "pypy_version_info", ".", "minor", ",", "sys", ".", "pypy_version_info", ".", "micro", ")", "if", "sys", ".", "pypy_version_info", ".", "releaselevel", "!=", "'final'", ":", "implementation_version", "=", "''", ".", "join", "(", "[", "implementation_version", ",", "sys", ".", "pypy_version_info", ".", "releaselevel", "]", ")", "elif", "implementation", "==", "'Jython'", ":", "implementation_version", "=", "platform", ".", "python_version", "(", ")", "# Complete Guess", "elif", "implementation", "==", "'IronPython'", ":", "implementation_version", "=", "platform", ".", "python_version", "(", ")", "# Complete Guess", "else", ":", "implementation_version", "=", "'Unknown'", "return", "{", "'name'", ":", "implementation", ",", "'version'", ":", "implementation_version", "}" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/help.py#L26-L56
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/backports.shutil-get-terminal-size/backports/shutil_get_terminal_size/get_terminal_size.py
python
get_terminal_size
(fallback=(80, 24))
return terminal_size(columns, lines)
Get the size of the terminal window. For each of the two dimensions, the environment variable, COLUMNS and LINES respectively, is checked. If the variable is defined and the value is a positive integer, it is used. When COLUMNS or LINES is not defined, which is the common case, the terminal connected to sys.__stdout__ is queried by invoking os.get_terminal_size. If the terminal size cannot be successfully queried, either because the system doesn't support querying, or because we are not connected to a terminal, the value given in fallback parameter is used. Fallback defaults to (80, 24) which is the default size used by many terminal emulators. The value returned is a named tuple of type os.terminal_size.
Get the size of the terminal window.
[ "Get", "the", "size", "of", "the", "terminal", "window", "." ]
def get_terminal_size(fallback=(80, 24)): """Get the size of the terminal window. For each of the two dimensions, the environment variable, COLUMNS and LINES respectively, is checked. If the variable is defined and the value is a positive integer, it is used. When COLUMNS or LINES is not defined, which is the common case, the terminal connected to sys.__stdout__ is queried by invoking os.get_terminal_size. If the terminal size cannot be successfully queried, either because the system doesn't support querying, or because we are not connected to a terminal, the value given in fallback parameter is used. Fallback defaults to (80, 24) which is the default size used by many terminal emulators. The value returned is a named tuple of type os.terminal_size. """ # Try the environment first try: columns = int(os.environ["COLUMNS"]) except (KeyError, ValueError): columns = 0 try: lines = int(os.environ["LINES"]) except (KeyError, ValueError): lines = 0 # Only query if necessary if columns <= 0 or lines <= 0: try: size = _get_terminal_size(sys.__stdout__.fileno()) except (NameError, OSError): size = terminal_size(*fallback) if columns <= 0: columns = size.columns if lines <= 0: lines = size.lines return terminal_size(columns, lines)
[ "def", "get_terminal_size", "(", "fallback", "=", "(", "80", ",", "24", ")", ")", ":", "# Try the environment first", "try", ":", "columns", "=", "int", "(", "os", ".", "environ", "[", "\"COLUMNS\"", "]", ")", "except", "(", "KeyError", ",", "ValueError", ")", ":", "columns", "=", "0", "try", ":", "lines", "=", "int", "(", "os", ".", "environ", "[", "\"LINES\"", "]", ")", "except", "(", "KeyError", ",", "ValueError", ")", ":", "lines", "=", "0", "# Only query if necessary", "if", "columns", "<=", "0", "or", "lines", "<=", "0", ":", "try", ":", "size", "=", "_get_terminal_size", "(", "sys", ".", "__stdout__", ".", "fileno", "(", ")", ")", "except", "(", "NameError", ",", "OSError", ")", ":", "size", "=", "terminal_size", "(", "*", "fallback", ")", "if", "columns", "<=", "0", ":", "columns", "=", "size", ".", "columns", "if", "lines", "<=", "0", ":", "lines", "=", "size", ".", "lines", "return", "terminal_size", "(", "columns", ",", "lines", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/backports.shutil-get-terminal-size/backports/shutil_get_terminal_size/get_terminal_size.py#L58-L100
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/python/training/saver.py
python
BaseSaverBuilder.restore_op
(self, filename_tensor, saveable, preferred_shard)
return tensors
Create ops to restore 'saveable'. This is intended to be overridden by subclasses that want to generate different Ops. Args: filename_tensor: String Tensor. saveable: A BaseSaverBuilder.SaveableObject object. preferred_shard: Int. Shard to open first when loading a sharded file. Returns: A list of Tensors resulting from reading 'saveable' from 'filename'.
Create ops to restore 'saveable'.
[ "Create", "ops", "to", "restore", "saveable", "." ]
def restore_op(self, filename_tensor, saveable, preferred_shard): """Create ops to restore 'saveable'. This is intended to be overridden by subclasses that want to generate different Ops. Args: filename_tensor: String Tensor. saveable: A BaseSaverBuilder.SaveableObject object. preferred_shard: Int. Shard to open first when loading a sharded file. Returns: A list of Tensors resulting from reading 'saveable' from 'filename'. """ # pylint: disable=protected-access tensors = [] for spec in saveable.specs: tensors.append( io_ops.restore_v2( filename_tensor, [spec.name], [spec.slice_spec], [spec.tensor.dtype])[0]) return tensors
[ "def", "restore_op", "(", "self", ",", "filename_tensor", ",", "saveable", ",", "preferred_shard", ")", ":", "# pylint: disable=protected-access", "tensors", "=", "[", "]", "for", "spec", "in", "saveable", ".", "specs", ":", "tensors", ".", "append", "(", "io_ops", ".", "restore_v2", "(", "filename_tensor", ",", "[", "spec", ".", "name", "]", ",", "[", "spec", ".", "slice_spec", "]", ",", "[", "spec", ".", "tensor", ".", "dtype", "]", ")", "[", "0", "]", ")", "return", "tensors" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/python/training/saver.py#L224-L249
OpenLightingProject/ola
d1433a1bed73276fbe55ce18c03b1c208237decc
python/ola/RDMAPI.py
python
RDMAPI._GenericHandler
(self, callback, uid, response)
Args: callback: the function to run uid: The uid the request was for response: A RDMResponse object
[]
def _GenericHandler(self, callback, uid, response): """ Args: callback: the function to run uid: The uid the request was for response: A RDMResponse object """ obj = None unpack_exception = None if response.WasAcked(): request_type = self.COMMAND_CLASS_DICT[response.command_class] pid_descriptor = self._pid_store.GetPid(response.pid, uid.manufacturer_id) if pid_descriptor: try: obj = pid_descriptor.Unpack(response.data, request_type) except PidStore.UnpackException as e: obj = None unpack_exception = e else: obj = response.data callback(response, obj, unpack_exception)
[ "def", "_GenericHandler", "(", "self", ",", "callback", ",", "uid", ",", "response", ")", ":", "obj", "=", "None", "unpack_exception", "=", "None", "if", "response", ".", "WasAcked", "(", ")", ":", "request_type", "=", "self", ".", "COMMAND_CLASS_DICT", "[", "response", ".", "command_class", "]", "pid_descriptor", "=", "self", ".", "_pid_store", ".", "GetPid", "(", "response", ".", "pid", ",", "uid", ".", "manufacturer_id", ")", "if", "pid_descriptor", ":", "try", ":", "obj", "=", "pid_descriptor", ".", "Unpack", "(", "response", ".", "data", ",", "request_type", ")", "except", "PidStore", ".", "UnpackException", "as", "e", ":", "obj", "=", "None", "unpack_exception", "=", "e", "else", ":", "obj", "=", "response", ".", "data", "callback", "(", "response", ",", "obj", ",", "unpack_exception", ")" ]
https://github.com/OpenLightingProject/ola/blob/d1433a1bed73276fbe55ce18c03b1c208237decc/python/ola/RDMAPI.py#L242-L266
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/connection.py
python
HTTPSConnection._connect_tls_proxy
(self, hostname, conn)
return ssl_wrap_socket( sock=conn, ca_certs=self.ca_certs, ca_cert_dir=self.ca_cert_dir, ca_cert_data=self.ca_cert_data, server_hostname=hostname, ssl_context=ssl_context, )
Establish a TLS connection to the proxy using the provided SSL context.
Establish a TLS connection to the proxy using the provided SSL context.
[ "Establish", "a", "TLS", "connection", "to", "the", "proxy", "using", "the", "provided", "SSL", "context", "." ]
def _connect_tls_proxy(self, hostname, conn): """ Establish a TLS connection to the proxy using the provided SSL context. """ proxy_config = self.proxy_config ssl_context = proxy_config.ssl_context if ssl_context: # If the user provided a proxy context, we assume CA and client # certificates have already been set return ssl_wrap_socket( sock=conn, server_hostname=hostname, ssl_context=ssl_context, ) ssl_context = create_proxy_ssl_context( self.ssl_version, self.cert_reqs, self.ca_certs, self.ca_cert_dir, self.ca_cert_data, ) # If no cert was provided, use only the default options for server # certificate validation return ssl_wrap_socket( sock=conn, ca_certs=self.ca_certs, ca_cert_dir=self.ca_cert_dir, ca_cert_data=self.ca_cert_data, server_hostname=hostname, ssl_context=ssl_context, )
[ "def", "_connect_tls_proxy", "(", "self", ",", "hostname", ",", "conn", ")", ":", "proxy_config", "=", "self", ".", "proxy_config", "ssl_context", "=", "proxy_config", ".", "ssl_context", "if", "ssl_context", ":", "# If the user provided a proxy context, we assume CA and client", "# certificates have already been set", "return", "ssl_wrap_socket", "(", "sock", "=", "conn", ",", "server_hostname", "=", "hostname", ",", "ssl_context", "=", "ssl_context", ",", ")", "ssl_context", "=", "create_proxy_ssl_context", "(", "self", ".", "ssl_version", ",", "self", ".", "cert_reqs", ",", "self", ".", "ca_certs", ",", "self", ".", "ca_cert_dir", ",", "self", ".", "ca_cert_data", ",", ")", "# If no cert was provided, use only the default options for server", "# certificate validation", "return", "ssl_wrap_socket", "(", "sock", "=", "conn", ",", "ca_certs", "=", "self", ".", "ca_certs", ",", "ca_cert_dir", "=", "self", ".", "ca_cert_dir", ",", "ca_cert_data", "=", "self", ".", "ca_cert_data", ",", "server_hostname", "=", "hostname", ",", "ssl_context", "=", "ssl_context", ",", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/pip/_vendor/urllib3/connection.py#L471-L503
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/tools/Editra/plugins/codebrowser/codebrowser/gentag/taglib.py
python
DocStruct.GetLastClass
(self)
return self.lastclass
Gets the last L{Class} that was added to the document @return: L{Class}
Gets the last L{Class} that was added to the document @return: L{Class}
[ "Gets", "the", "last", "L", "{", "Class", "}", "that", "was", "added", "to", "the", "document", "@return", ":", "L", "{", "Class", "}" ]
def GetLastClass(self): """Gets the last L{Class} that was added to the document @return: L{Class} """ return self.lastclass
[ "def", "GetLastClass", "(", "self", ")", ":", "return", "self", ".", "lastclass" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/tools/Editra/plugins/codebrowser/codebrowser/gentag/taglib.py#L387-L392
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/framework/intpyapp.py
python
InteractivePythonApp.OnFileCheck
( self, id, code )
Called when a FileCheck message is received. Check the current file.
Called when a FileCheck message is received. Check the current file.
[ "Called", "when", "a", "FileCheck", "message", "is", "received", ".", "Check", "the", "current", "file", "." ]
def OnFileCheck( self, id, code ): " Called when a FileCheck message is received. Check the current file." import scriptutils scriptutils.CheckFile()
[ "def", "OnFileCheck", "(", "self", ",", "id", ",", "code", ")", ":", "import", "scriptutils", "scriptutils", ".", "CheckFile", "(", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pythonwin/pywin/framework/intpyapp.py#L332-L335
potassco/clingo
e0c91d8f95cc28de1c480a871f9c97c30de83d40
scratch/mypy.py
python
TypeTemplate.render
(self, *args, **kwargs)
return s.replace("{TYPES}", ", ".join(type_list))
This heuristicly adds types from a curated list used in the template to the import list.
This heuristicly adds types from a curated list used in the template to the import list.
[ "This", "heuristicly", "adds", "types", "from", "a", "curated", "list", "used", "in", "the", "template", "to", "the", "import", "list", "." ]
def render(self, *args, **kwargs): ''' This heuristicly adds types from a curated list used in the template to the import list. ''' s = Template.render(self, *args, **kwargs) type_list = [] for x in TYPING_TYPES: if re.search(r'\b{}\b'.format(x), s): type_list.append(x) return s.replace("{TYPES}", ", ".join(type_list))
[ "def", "render", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "s", "=", "Template", ".", "render", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "type_list", "=", "[", "]", "for", "x", "in", "TYPING_TYPES", ":", "if", "re", ".", "search", "(", "r'\\b{}\\b'", ".", "format", "(", "x", ")", ",", "s", ")", ":", "type_list", ".", "append", "(", "x", ")", "return", "s", ".", "replace", "(", "\"{TYPES}\"", ",", "\", \"", ".", "join", "(", "type_list", ")", ")" ]
https://github.com/potassco/clingo/blob/e0c91d8f95cc28de1c480a871f9c97c30de83d40/scratch/mypy.py#L32-L43
PyMesh/PyMesh
384ba882b7558ba6e8653ed263c419226c22bddf
python/pymesh/wires/WireNetwork.py
python
WireNetwork.load_from_raw
(self, raw_wires)
Load vertex and edges from raw C++ wire data structure.
Load vertex and edges from raw C++ wire data structure.
[ "Load", "vertex", "and", "edges", "from", "raw", "C", "++", "wire", "data", "structure", "." ]
def load_from_raw(self, raw_wires): """ Load vertex and edges from raw C++ wire data structure. """ self.raw_wires = raw_wires self.__initialize_wires()
[ "def", "load_from_raw", "(", "self", ",", "raw_wires", ")", ":", "self", ".", "raw_wires", "=", "raw_wires", "self", ".", "__initialize_wires", "(", ")" ]
https://github.com/PyMesh/PyMesh/blob/384ba882b7558ba6e8653ed263c419226c22bddf/python/pymesh/wires/WireNetwork.py#L122-L126
devpack/android-python27
d42dd67565e104cf7b0b50eb473f615db3e69901
python-build-with-qt/sip-4.11.2/siputils.py
python
ModuleMakefile.__init__
(self, configuration, build_file, install_dir=None, static=0, console=0, qt=0, opengl=0, threaded=0, warnings=1, debug=0, dir=None, makefile="Makefile", installs=None, strip=1, export_all=0, universal=None, arch=None)
Initialise an instance of a module Makefile. build_file is the file containing the target specific information. If it is a dictionary instead then its contents are validated. install_dir is the directory the target will be installed in. static is set if the module should be built as a static library. strip is set if the module should be stripped of unneeded symbols when installed. The default is 1. export_all is set if all the module's symbols should be exported rather than just the module's initialisation function. Exporting all symbols increases the size of the module and slows down module load times but may avoid problems with modules that use exceptions. The default is 0.
Initialise an instance of a module Makefile.
[ "Initialise", "an", "instance", "of", "a", "module", "Makefile", "." ]
def __init__(self, configuration, build_file, install_dir=None, static=0, console=0, qt=0, opengl=0, threaded=0, warnings=1, debug=0, dir=None, makefile="Makefile", installs=None, strip=1, export_all=0, universal=None, arch=None): """Initialise an instance of a module Makefile. build_file is the file containing the target specific information. If it is a dictionary instead then its contents are validated. install_dir is the directory the target will be installed in. static is set if the module should be built as a static library. strip is set if the module should be stripped of unneeded symbols when installed. The default is 1. export_all is set if all the module's symbols should be exported rather than just the module's initialisation function. Exporting all symbols increases the size of the module and slows down module load times but may avoid problems with modules that use exceptions. The default is 0. """ Makefile.__init__(self, configuration, console, qt, opengl, 1, threaded, warnings, debug, dir, makefile, installs, universal, arch) self._build = self.parse_build_file(build_file) self._install_dir = install_dir self.static = static self._manifest = ("embed_manifest_dll" in self.optional_list("CONFIG")) # Don't strip or restrict the exports if this is a debug or static # build. if debug or static: self._strip = 0 self._limit_exports = 0 else: self._strip = strip self._limit_exports = not export_all # Save the target name for later. self._target = self._build["target"] # The name of the module entry point is Python version specific. if self.config.py_version >= 0x030000: self._entry_point = "PyInit_%s" % self._target else: self._entry_point = "init%s" % self._target if sys.platform != "win32" and static: self._target = "lib" + self._target if sys.platform == "win32" and debug: self._target = self._target + "_d"
[ "def", "__init__", "(", "self", ",", "configuration", ",", "build_file", ",", "install_dir", "=", "None", ",", "static", "=", "0", ",", "console", "=", "0", ",", "qt", "=", "0", ",", "opengl", "=", "0", ",", "threaded", "=", "0", ",", "warnings", "=", "1", ",", "debug", "=", "0", ",", "dir", "=", "None", ",", "makefile", "=", "\"Makefile\"", ",", "installs", "=", "None", ",", "strip", "=", "1", ",", "export_all", "=", "0", ",", "universal", "=", "None", ",", "arch", "=", "None", ")", ":", "Makefile", ".", "__init__", "(", "self", ",", "configuration", ",", "console", ",", "qt", ",", "opengl", ",", "1", ",", "threaded", ",", "warnings", ",", "debug", ",", "dir", ",", "makefile", ",", "installs", ",", "universal", ",", "arch", ")", "self", ".", "_build", "=", "self", ".", "parse_build_file", "(", "build_file", ")", "self", ".", "_install_dir", "=", "install_dir", "self", ".", "static", "=", "static", "self", ".", "_manifest", "=", "(", "\"embed_manifest_dll\"", "in", "self", ".", "optional_list", "(", "\"CONFIG\"", ")", ")", "# Don't strip or restrict the exports if this is a debug or static", "# build.", "if", "debug", "or", "static", ":", "self", ".", "_strip", "=", "0", "self", ".", "_limit_exports", "=", "0", "else", ":", "self", ".", "_strip", "=", "strip", "self", ".", "_limit_exports", "=", "not", "export_all", "# Save the target name for later.", "self", ".", "_target", "=", "self", ".", "_build", "[", "\"target\"", "]", "# The name of the module entry point is Python version specific.", "if", "self", ".", "config", ".", "py_version", ">=", "0x030000", ":", "self", ".", "_entry_point", "=", "\"PyInit_%s\"", "%", "self", ".", "_target", "else", ":", "self", ".", "_entry_point", "=", "\"init%s\"", "%", "self", ".", "_target", "if", "sys", ".", "platform", "!=", "\"win32\"", "and", "static", ":", "self", ".", "_target", "=", "\"lib\"", "+", "self", ".", "_target", "if", "sys", ".", "platform", "==", "\"win32\"", "and", "debug", ":", "self", ".", "_target", "=", "self", ".", "_target", "+", "\"_d\"" ]
https://github.com/devpack/android-python27/blob/d42dd67565e104cf7b0b50eb473f615db3e69901/python-build-with-qt/sip-4.11.2/siputils.py#L1331-L1378
snap-stanford/snap-python
d53c51b0a26aa7e3e7400b014cdf728948fde80a
setup/snap.py
python
TChA.ToUc
(self)
return _snap.TChA_ToUc(self)
ToUc(TChA self) -> TChA Parameters: self: TChA *
ToUc(TChA self) -> TChA
[ "ToUc", "(", "TChA", "self", ")", "-", ">", "TChA" ]
def ToUc(self): """ ToUc(TChA self) -> TChA Parameters: self: TChA * """ return _snap.TChA_ToUc(self)
[ "def", "ToUc", "(", "self", ")", ":", "return", "_snap", ".", "TChA_ToUc", "(", "self", ")" ]
https://github.com/snap-stanford/snap-python/blob/d53c51b0a26aa7e3e7400b014cdf728948fde80a/setup/snap.py#L8984-L8992
nvdla/sw
79538ba1b52b040a4a4645f630e457fa01839e90
umd/external/protobuf-2.6/python/google/protobuf/symbol_database.py
python
SymbolDatabase.GetPrototype
(self, descriptor)
return self.GetSymbol(descriptor.full_name)
Builds a proto2 message class based on the passed in descriptor. Passing a descriptor with a fully qualified name matching a previous invocation will cause the same class to be returned. Args: descriptor: The descriptor to build from. Returns: A class describing the passed in descriptor.
Builds a proto2 message class based on the passed in descriptor.
[ "Builds", "a", "proto2", "message", "class", "based", "on", "the", "passed", "in", "descriptor", "." ]
def GetPrototype(self, descriptor): """Builds a proto2 message class based on the passed in descriptor. Passing a descriptor with a fully qualified name matching a previous invocation will cause the same class to be returned. Args: descriptor: The descriptor to build from. Returns: A class describing the passed in descriptor. """ return self.GetSymbol(descriptor.full_name)
[ "def", "GetPrototype", "(", "self", ",", "descriptor", ")", ":", "return", "self", ".", "GetSymbol", "(", "descriptor", ".", "full_name", ")" ]
https://github.com/nvdla/sw/blob/79538ba1b52b040a4a4645f630e457fa01839e90/umd/external/protobuf-2.6/python/google/protobuf/symbol_database.py#L141-L154
KhronosGroup/SPIRV-LLVM
1eb85593f3fe2c39379b9a9b088d51eda4f42b8b
examples/Kaleidoscope/MCJIT/lazy/genk-timing.py
python
KScriptGenerator.updateFunctionCallMap
(self, caller, callee)
Maintains a map of functions that are called from other functions
Maintains a map of functions that are called from other functions
[ "Maintains", "a", "map", "of", "functions", "that", "are", "called", "from", "other", "functions" ]
def updateFunctionCallMap(self, caller, callee): """Maintains a map of functions that are called from other functions""" if not caller in self.calledFunctionTable: self.calledFunctionTable[caller] = [] if not callee in self.calledFunctionTable[caller]: self.calledFunctionTable[caller].append(callee) if not caller in self.comprehensiveCalledFunctionTable: self.comprehensiveCalledFunctionTable[caller] = [] self.comprehensiveCalledFunctionTable[caller].append(callee)
[ "def", "updateFunctionCallMap", "(", "self", ",", "caller", ",", "callee", ")", ":", "if", "not", "caller", "in", "self", ".", "calledFunctionTable", ":", "self", ".", "calledFunctionTable", "[", "caller", "]", "=", "[", "]", "if", "not", "callee", "in", "self", ".", "calledFunctionTable", "[", "caller", "]", ":", "self", ".", "calledFunctionTable", "[", "caller", "]", ".", "append", "(", "callee", ")", "if", "not", "caller", "in", "self", ".", "comprehensiveCalledFunctionTable", ":", "self", ".", "comprehensiveCalledFunctionTable", "[", "caller", "]", "=", "[", "]", "self", ".", "comprehensiveCalledFunctionTable", "[", "caller", "]", ".", "append", "(", "callee", ")" ]
https://github.com/KhronosGroup/SPIRV-LLVM/blob/1eb85593f3fe2c39379b9a9b088d51eda4f42b8b/examples/Kaleidoscope/MCJIT/lazy/genk-timing.py#L56-L64
OAID/Caffe-HRT
aae71e498ab842c6f92bcc23fc668423615a4d65
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/OAID/Caffe-HRT/blob/aae71e498ab842c6f92bcc23fc668423615a4d65/scripts/cpp_lint.py#L1254-L1297
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/SocketServer.py
python
ForkingMixIn.process_request
(self, request, client_address)
Fork a new subprocess to process the request.
Fork a new subprocess to process the request.
[ "Fork", "a", "new", "subprocess", "to", "process", "the", "request", "." ]
def process_request(self, request, client_address): """Fork a new subprocess to process the request.""" self.collect_children() pid = os.fork() if pid: # Parent process if self.active_children is None: self.active_children = [] self.active_children.append(pid) self.close_request(request) #close handle in parent process return else: # Child process. # This must never return, hence os._exit()! try: self.finish_request(request, client_address) self.shutdown_request(request) os._exit(0) except: try: self.handle_error(request, client_address) self.shutdown_request(request) finally: os._exit(1)
[ "def", "process_request", "(", "self", ",", "request", ",", "client_address", ")", ":", "self", ".", "collect_children", "(", ")", "pid", "=", "os", ".", "fork", "(", ")", "if", "pid", ":", "# Parent process", "if", "self", ".", "active_children", "is", "None", ":", "self", ".", "active_children", "=", "[", "]", "self", ".", "active_children", ".", "append", "(", "pid", ")", "self", ".", "close_request", "(", "request", ")", "#close handle in parent process", "return", "else", ":", "# Child process.", "# This must never return, hence os._exit()!", "try", ":", "self", ".", "finish_request", "(", "request", ",", "client_address", ")", "self", ".", "shutdown_request", "(", "request", ")", "os", ".", "_exit", "(", "0", ")", "except", ":", "try", ":", "self", ".", "handle_error", "(", "request", ",", "client_address", ")", "self", ".", "shutdown_request", "(", "request", ")", "finally", ":", "os", ".", "_exit", "(", "1", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/SocketServer.py#L553-L576
zhaoweicai/mscnn
534bcac5710a579d60827f192035f7eef6d8c585
scripts/cpp_lint.py
python
_FunctionState.End
(self)
Stop analyzing function body.
Stop analyzing function body.
[ "Stop", "analyzing", "function", "body", "." ]
def End(self): """Stop analyzing function body.""" self.in_a_function = False
[ "def", "End", "(", "self", ")", ":", "self", ".", "in_a_function", "=", "False" ]
https://github.com/zhaoweicai/mscnn/blob/534bcac5710a579d60827f192035f7eef6d8c585/scripts/cpp_lint.py#L861-L863
hughperkins/tf-coriander
970d3df6c11400ad68405f22b0c42a52374e94ca
tensorflow/python/lib/io/file_io.py
python
list_directory
(dirname)
return [ compat.as_str_any(pywrap_tensorflow.Basename(compat.as_bytes(filename))) for filename in file_list ]
Returns a list of entries contained within a directory. The list is in arbitrary order. It does not contain the special entries "." and "..". Args: dirname: string, path to a directory Returns: [filename1, filename2, ... filenameN] as strings Raises: errors.NotFoundError if directory doesn't exist
Returns a list of entries contained within a directory.
[ "Returns", "a", "list", "of", "entries", "contained", "within", "a", "directory", "." ]
def list_directory(dirname): """Returns a list of entries contained within a directory. The list is in arbitrary order. It does not contain the special entries "." and "..". Args: dirname: string, path to a directory Returns: [filename1, filename2, ... filenameN] as strings Raises: errors.NotFoundError if directory doesn't exist """ if not is_directory(dirname): raise errors.NotFoundError(None, None, "Could not find directory") file_list = get_matching_files(os.path.join(compat.as_str_any(dirname), "*")) return [ compat.as_str_any(pywrap_tensorflow.Basename(compat.as_bytes(filename))) for filename in file_list ]
[ "def", "list_directory", "(", "dirname", ")", ":", "if", "not", "is_directory", "(", "dirname", ")", ":", "raise", "errors", ".", "NotFoundError", "(", "None", ",", "None", ",", "\"Could not find directory\"", ")", "file_list", "=", "get_matching_files", "(", "os", ".", "path", ".", "join", "(", "compat", ".", "as_str_any", "(", "dirname", ")", ",", "\"*\"", ")", ")", "return", "[", "compat", ".", "as_str_any", "(", "pywrap_tensorflow", ".", "Basename", "(", "compat", ".", "as_bytes", "(", "filename", ")", ")", ")", "for", "filename", "in", "file_list", "]" ]
https://github.com/hughperkins/tf-coriander/blob/970d3df6c11400ad68405f22b0c42a52374e94ca/tensorflow/python/lib/io/file_io.py#L350-L371
resiprocate/resiprocate
b3943ce9ed412e2302121f6cc766125a7746edc1
contrib/fmt/support/docopt.py
python
parse_atom
(tokens, options)
atom ::= '(' expr ')' | '[' expr ']' | 'options' | long | shorts | argument | command ;
atom ::= '(' expr ')' | '[' expr ']' | 'options' | long | shorts | argument | command ;
[ "atom", "::", "=", "(", "expr", ")", "|", "[", "expr", "]", "|", "options", "|", "long", "|", "shorts", "|", "argument", "|", "command", ";" ]
def parse_atom(tokens, options): """atom ::= '(' expr ')' | '[' expr ']' | 'options' | long | shorts | argument | command ; """ token = tokens.current() result = [] if token in '([': tokens.move() matching, pattern = {'(': [')', Required], '[': [']', Optional]}[token] result = pattern(*parse_expr(tokens, options)) if tokens.move() != matching: raise tokens.error("unmatched '%s'" % token) return [result] elif token == 'options': tokens.move() return [OptionsShortcut()] elif token.startswith('--') and token != '--': return parse_long(tokens, options) elif token.startswith('-') and token not in ('-', '--'): return parse_shorts(tokens, options) elif token.startswith('<') and token.endswith('>') or token.isupper(): return [Argument(tokens.move())] else: return [Command(tokens.move())]
[ "def", "parse_atom", "(", "tokens", ",", "options", ")", ":", "token", "=", "tokens", ".", "current", "(", ")", "result", "=", "[", "]", "if", "token", "in", "'(['", ":", "tokens", ".", "move", "(", ")", "matching", ",", "pattern", "=", "{", "'('", ":", "[", "')'", ",", "Required", "]", ",", "'['", ":", "[", "']'", ",", "Optional", "]", "}", "[", "token", "]", "result", "=", "pattern", "(", "*", "parse_expr", "(", "tokens", ",", "options", ")", ")", "if", "tokens", ".", "move", "(", ")", "!=", "matching", ":", "raise", "tokens", ".", "error", "(", "\"unmatched '%s'\"", "%", "token", ")", "return", "[", "result", "]", "elif", "token", "==", "'options'", ":", "tokens", ".", "move", "(", ")", "return", "[", "OptionsShortcut", "(", ")", "]", "elif", "token", ".", "startswith", "(", "'--'", ")", "and", "token", "!=", "'--'", ":", "return", "parse_long", "(", "tokens", ",", "options", ")", "elif", "token", ".", "startswith", "(", "'-'", ")", "and", "token", "not", "in", "(", "'-'", ",", "'--'", ")", ":", "return", "parse_shorts", "(", "tokens", ",", "options", ")", "elif", "token", ".", "startswith", "(", "'<'", ")", "and", "token", ".", "endswith", "(", "'>'", ")", "or", "token", ".", "isupper", "(", ")", ":", "return", "[", "Argument", "(", "tokens", ".", "move", "(", ")", ")", "]", "else", ":", "return", "[", "Command", "(", "tokens", ".", "move", "(", ")", ")", "]" ]
https://github.com/resiprocate/resiprocate/blob/b3943ce9ed412e2302121f6cc766125a7746edc1/contrib/fmt/support/docopt.py#L402-L425
telefonicaid/fiware-orion
27c3202b9ddcfb9e3635a0af8d373f76e89b1d24
scripts/cpplint.py
python
CheckForHeaderGuard
(filename, lines, error)
Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found.
Checks that the file contains a header guard.
[ "Checks", "that", "the", "file", "contains", "a", "header", "guard", "." ]
def CheckForHeaderGuard(filename, lines, error): """Checks that the file contains a header guard. Logs an error if no #ifndef header guard is present. For other headers, checks that the full pathname is used. Args: filename: The name of the C++ header file. lines: An array of strings, each representing a line of the file. error: The function to call with any errors found. """ cppvar = GetHeaderGuardCPPVariable(filename) ifndef = None ifndef_linenum = 0 define = None endif = None endif_linenum = 0 for linenum, line in enumerate(lines): linesplit = line.split() if len(linesplit) >= 2: # find the first occurrence of #ifndef and #define, save arg if not ifndef and linesplit[0] == '#ifndef': # set ifndef to the header guard presented on the #ifndef line. ifndef = linesplit[1] ifndef_linenum = linenum if not define and linesplit[0] == '#define': define = linesplit[1] # find the last occurrence of #endif, save entire line if line.startswith('#endif'): endif = line endif_linenum = linenum if not ifndef: error(filename, 0, 'build/header_guard', 5, 'No #ifndef header guard found, suggested CPP variable is: %s' % cppvar) return if not define: error(filename, 0, 'build/header_guard', 5, 'No #define header guard found, suggested CPP variable is: %s' % cppvar) return # The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__ # for backward compatibility. if ifndef != cppvar: error_level = 0 if ifndef != cppvar + '_': error_level = 5 ParseNolintSuppressions(filename, lines[ifndef_linenum], ifndef_linenum, error) error(filename, ifndef_linenum, 'build/header_guard', error_level, '#ifndef header guard has wrong style, please use: %s' % cppvar) if define != ifndef: error(filename, 0, 'build/header_guard', 5, '#ifndef and #define don\'t match, suggested CPP variable is: %s' % cppvar) return if endif != ('#endif // %s' % cppvar): error_level = 0 if endif != ('#endif // %s' % (cppvar + '_')): error_level = 5 ParseNolintSuppressions(filename, lines[endif_linenum], endif_linenum, error) error(filename, endif_linenum, 'build/header_guard', error_level, '#endif line should be "#endif // %s"' % cppvar)
[ "def", "CheckForHeaderGuard", "(", "filename", ",", "lines", ",", "error", ")", ":", "cppvar", "=", "GetHeaderGuardCPPVariable", "(", "filename", ")", "ifndef", "=", "None", "ifndef_linenum", "=", "0", "define", "=", "None", "endif", "=", "None", "endif_linenum", "=", "0", "for", "linenum", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "linesplit", "=", "line", ".", "split", "(", ")", "if", "len", "(", "linesplit", ")", ">=", "2", ":", "# find the first occurrence of #ifndef and #define, save arg", "if", "not", "ifndef", "and", "linesplit", "[", "0", "]", "==", "'#ifndef'", ":", "# set ifndef to the header guard presented on the #ifndef line.", "ifndef", "=", "linesplit", "[", "1", "]", "ifndef_linenum", "=", "linenum", "if", "not", "define", "and", "linesplit", "[", "0", "]", "==", "'#define'", ":", "define", "=", "linesplit", "[", "1", "]", "# find the last occurrence of #endif, save entire line", "if", "line", ".", "startswith", "(", "'#endif'", ")", ":", "endif", "=", "line", "endif_linenum", "=", "linenum", "if", "not", "ifndef", ":", "error", "(", "filename", ",", "0", ",", "'build/header_guard'", ",", "5", ",", "'No #ifndef header guard found, suggested CPP variable is: %s'", "%", "cppvar", ")", "return", "if", "not", "define", ":", "error", "(", "filename", ",", "0", ",", "'build/header_guard'", ",", "5", ",", "'No #define header guard found, suggested CPP variable is: %s'", "%", "cppvar", ")", "return", "# The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__", "# for backward compatibility.", "if", "ifndef", "!=", "cppvar", ":", "error_level", "=", "0", "if", "ifndef", "!=", "cppvar", "+", "'_'", ":", "error_level", "=", "5", "ParseNolintSuppressions", "(", "filename", ",", "lines", "[", "ifndef_linenum", "]", ",", "ifndef_linenum", ",", "error", ")", "error", "(", "filename", ",", "ifndef_linenum", ",", "'build/header_guard'", ",", "error_level", ",", "'#ifndef header guard has wrong style, please use: %s'", "%", "cppvar", ")", "if", "define", "!=", "ifndef", ":", "error", "(", "filename", ",", "0", ",", "'build/header_guard'", ",", "5", ",", "'#ifndef and #define don\\'t match, suggested CPP variable is: %s'", "%", "cppvar", ")", "return", "if", "endif", "!=", "(", "'#endif // %s'", "%", "cppvar", ")", ":", "error_level", "=", "0", "if", "endif", "!=", "(", "'#endif // %s'", "%", "(", "cppvar", "+", "'_'", ")", ")", ":", "error_level", "=", "5", "ParseNolintSuppressions", "(", "filename", ",", "lines", "[", "endif_linenum", "]", ",", "endif_linenum", ",", "error", ")", "error", "(", "filename", ",", "endif_linenum", ",", "'build/header_guard'", ",", "error_level", ",", "'#endif line should be \"#endif // %s\"'", "%", "cppvar", ")" ]
https://github.com/telefonicaid/fiware-orion/blob/27c3202b9ddcfb9e3635a0af8d373f76e89b1d24/scripts/cpplint.py#L1040-L1112
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/ccompiler.py
python
CCompiler.add_library
(self, libname)
Add 'libname' to the list of libraries that will be included in all links driven by this compiler object. Note that 'libname' should *not* be the name of a file containing a library, but the name of the library itself: the actual filename will be inferred by the linker, the compiler, or the compiler class (depending on the platform). The linker will be instructed to link against libraries in the order they were supplied to 'add_library()' and/or 'set_libraries()'. It is perfectly valid to duplicate library names; the linker will be instructed to link against libraries as many times as they are mentioned.
Add 'libname' to the list of libraries that will be included in all links driven by this compiler object. Note that 'libname' should *not* be the name of a file containing a library, but the name of the library itself: the actual filename will be inferred by the linker, the compiler, or the compiler class (depending on the platform).
[ "Add", "libname", "to", "the", "list", "of", "libraries", "that", "will", "be", "included", "in", "all", "links", "driven", "by", "this", "compiler", "object", ".", "Note", "that", "libname", "should", "*", "not", "*", "be", "the", "name", "of", "a", "file", "containing", "a", "library", "but", "the", "name", "of", "the", "library", "itself", ":", "the", "actual", "filename", "will", "be", "inferred", "by", "the", "linker", "the", "compiler", "or", "the", "compiler", "class", "(", "depending", "on", "the", "platform", ")", "." ]
def add_library(self, libname): """Add 'libname' to the list of libraries that will be included in all links driven by this compiler object. Note that 'libname' should *not* be the name of a file containing a library, but the name of the library itself: the actual filename will be inferred by the linker, the compiler, or the compiler class (depending on the platform). The linker will be instructed to link against libraries in the order they were supplied to 'add_library()' and/or 'set_libraries()'. It is perfectly valid to duplicate library names; the linker will be instructed to link against libraries as many times as they are mentioned. """ self.libraries.append(libname)
[ "def", "add_library", "(", "self", ",", "libname", ")", ":", "self", ".", "libraries", ".", "append", "(", "libname", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/distutils/ccompiler.py#L235-L249
arangodb/arangodb
0d658689c7d1b721b314fa3ca27d38303e1570c8
3rdParty/V8/gyp/NinjaWriter.py
python
NinjaWriter._WriteLinkForArch
(self, ninja_file, spec, config_name, config, link_deps, compile_deps, arch=None)
return linked_binary
Write out a link step. Fills out target.binary.
Write out a link step. Fills out target.binary.
[ "Write", "out", "a", "link", "step", ".", "Fills", "out", "target", ".", "binary", "." ]
def _WriteLinkForArch(self, ninja_file, spec, config_name, config, link_deps, compile_deps, arch=None): """Write out a link step. Fills out target.binary. """ command = { 'executable': 'link', 'loadable_module': 'solink_module', 'shared_library': 'solink', }[spec['type']] command_suffix = '' implicit_deps = set() solibs = set() order_deps = set() if compile_deps: # Normally, the compiles of the target already depend on compile_deps, # but a shared_library target might have no sources and only link together # a few static_library deps, so the link step also needs to depend # on compile_deps to make sure actions in the shared_library target # get run before the link. order_deps.add(compile_deps) if 'dependencies' in spec: # Two kinds of dependencies: # - Linkable dependencies (like a .a or a .so): add them to the link line. # - Non-linkable dependencies (like a rule that generates a file # and writes a stamp file): add them to implicit_deps extra_link_deps = set() for dep in spec['dependencies']: target = self.target_outputs.get(dep) if not target: continue linkable = target.Linkable() if linkable: new_deps = [] if self.flavor == 'win' and target.component_objs and self.msvs_settings.IsUseLibraryDependencyInputs(config_name): new_deps = target.component_objs if target.compile_deps: order_deps.add(target.compile_deps) elif self.flavor == 'win' and target.import_lib: new_deps = [target.import_lib] elif target.UsesToc(self.flavor): solibs.add(target.binary) implicit_deps.add(target.binary + '.TOC') else: new_deps = [target.binary] for new_dep in new_deps: if new_dep not in extra_link_deps: extra_link_deps.add(new_dep) link_deps.append(new_dep) final_output = target.FinalOutput() if not linkable or final_output != target.binary: implicit_deps.add(final_output) extra_bindings = [] if self.target.uses_cpp and self.flavor != 'win': extra_bindings.append(('ld', '$ldxx')) output = self._ComputeOutput(spec, arch) if arch is None and not self.is_mac_bundle: self._AppendPostbuildVariable(extra_bindings, spec, output, output) is_executable = spec['type'] == 'executable' # The ldflags config key is not used on mac or win. On those platforms # linker flags are set via xcode_settings and msvs_settings, respectively. if self.toolset == 'target': env_ldflags = os.environ.get('LDFLAGS', '').split() else: # self.toolset == 'host' env_ldflags = os.environ.get('LDFLAGS_host', '').split() if self.flavor == 'mac': ldflags = self.xcode_settings.GetLdflags(config_name, self._ExpandSpecial(generator_default_variables['PRODUCT_DIR']), self._GypPathToNinja, arch) ldflags = env_ldflags + ldflags elif self.flavor == 'win': manifest_base_name = self._GypPathToUniqueOutput(self.ComputeOutputFileName(spec)) ldflags, intermediate_manifest, manifest_files = self.msvs_settings.GetLdflags(config_name, self._GypPathToNinja, self._ExpandSpecial, manifest_base_name, output, is_executable, self.toplevel_build) ldflags = env_ldflags + ldflags self._WriteVariableList(ninja_file, 'manifests', manifest_files) implicit_deps = implicit_deps.union(manifest_files) if intermediate_manifest: self._WriteVariableList(ninja_file, 'intermediatemanifest', [intermediate_manifest]) command_suffix = GetWinLinkRuleNameSuffix(self.msvs_settings.IsEmbedManifest(config_name)) def_file = self.msvs_settings.GetDefFile(self._GypPathToNinja) if def_file: implicit_deps.add(def_file) else: # Respect environment variables related to build, but target-specific # flags can still override them. ldflags = env_ldflags + config.get('ldflags', []) if is_executable and len(solibs): rpath = 'lib/' if self.toolset != 'target': rpath += self.toolset ldflags.append(r'-Wl,-rpath=\$$ORIGIN/%s' % rpath) else: ldflags.append('-Wl,-rpath=%s' % self.target_rpath) ldflags.append('-Wl,-rpath-link=%s' % rpath) self._WriteVariableList(ninja_file, 'ldflags', map(self._ExpandSpecial, ldflags)) library_dirs = config.get('library_dirs', []) if self.flavor == 'win': library_dirs = [self.msvs_settings.ConvertVSMacros(l, config_name) for l in library_dirs] library_dirs = ['/LIBPATH:' + self._QuoteShellArgument(self._GypPathToNinja(l), self.flavor) for l in library_dirs] else: library_dirs = [self._QuoteShellArgument('-L' + self._GypPathToNinja(l), self.flavor) for l in library_dirs] libraries = gyp.common.uniquer(map(self._ExpandSpecial, spec.get('libraries', []))) if self.flavor == 'mac': libraries = self.xcode_settings.AdjustLibraries(libraries, config_name) elif self.flavor == 'win': libraries = self.msvs_settings.AdjustLibraries(libraries) self._WriteVariableList(ninja_file, 'libs', library_dirs + libraries) linked_binary = output if command in ('solink', 'solink_module'): extra_bindings.append(('soname', os.path.split(output)[1])) extra_bindings.append(('lib', gyp.common.EncodePOSIXShellArgument(output))) if self.flavor != 'win': link_file_list = output if self.is_mac_bundle: # 'Dependency Framework.framework/Versions/A/Dependency Framework' -> # 'Dependency Framework.framework.rsp' link_file_list = self.xcode_settings.GetWrapperName() if arch: link_file_list += '.' + arch link_file_list += '.rsp' # If an rspfile contains spaces, ninja surrounds the filename with # quotes around it and then passes it to open(), creating a file with # quotes in its name (and when looking for the rsp file, the name # makes it through bash which strips the quotes) :-/ link_file_list = link_file_list.replace(' ', '_') extra_bindings.append(('link_file_list', gyp.common.EncodePOSIXShellArgument(link_file_list))) if self.flavor == 'win': extra_bindings.append(('binary', output)) if '/NOENTRY' not in ldflags and not self.msvs_settings.GetNoImportLibrary(config_name): self.target.import_lib = output + '.lib' extra_bindings.append(('implibflag', '/IMPLIB:%s' % self.target.import_lib)) pdbname = self.msvs_settings.GetPDBName(config_name, self._ExpandSpecial, output + '.pdb') output = [output, self.target.import_lib] if pdbname: output.append(pdbname) elif not self.is_mac_bundle: output = [output, output + '.TOC'] else: command = command + '_notoc' elif self.flavor == 'win': extra_bindings.append(('binary', output)) pdbname = self.msvs_settings.GetPDBName(config_name, self._ExpandSpecial, output + '.pdb') if pdbname: output = [output, pdbname] if len(solibs): extra_bindings.append(('solibs', gyp.common.EncodePOSIXShellList(sorted(solibs)))) ninja_file.build(output, command + command_suffix, link_deps, implicit=sorted(implicit_deps), order_only=list(order_deps), variables=extra_bindings) return linked_binary
[ "def", "_WriteLinkForArch", "(", "self", ",", "ninja_file", ",", "spec", ",", "config_name", ",", "config", ",", "link_deps", ",", "compile_deps", ",", "arch", "=", "None", ")", ":", "command", "=", "{", "'executable'", ":", "'link'", ",", "'loadable_module'", ":", "'solink_module'", ",", "'shared_library'", ":", "'solink'", ",", "}", "[", "spec", "[", "'type'", "]", "]", "command_suffix", "=", "''", "implicit_deps", "=", "set", "(", ")", "solibs", "=", "set", "(", ")", "order_deps", "=", "set", "(", ")", "if", "compile_deps", ":", "# Normally, the compiles of the target already depend on compile_deps,", "# but a shared_library target might have no sources and only link together", "# a few static_library deps, so the link step also needs to depend", "# on compile_deps to make sure actions in the shared_library target", "# get run before the link.", "order_deps", ".", "add", "(", "compile_deps", ")", "if", "'dependencies'", "in", "spec", ":", "# Two kinds of dependencies:", "# - Linkable dependencies (like a .a or a .so): add them to the link line.", "# - Non-linkable dependencies (like a rule that generates a file", "# and writes a stamp file): add them to implicit_deps", "extra_link_deps", "=", "set", "(", ")", "for", "dep", "in", "spec", "[", "'dependencies'", "]", ":", "target", "=", "self", ".", "target_outputs", ".", "get", "(", "dep", ")", "if", "not", "target", ":", "continue", "linkable", "=", "target", ".", "Linkable", "(", ")", "if", "linkable", ":", "new_deps", "=", "[", "]", "if", "self", ".", "flavor", "==", "'win'", "and", "target", ".", "component_objs", "and", "self", ".", "msvs_settings", ".", "IsUseLibraryDependencyInputs", "(", "config_name", ")", ":", "new_deps", "=", "target", ".", "component_objs", "if", "target", ".", "compile_deps", ":", "order_deps", ".", "add", "(", "target", ".", "compile_deps", ")", "elif", "self", ".", "flavor", "==", "'win'", "and", "target", ".", "import_lib", ":", "new_deps", "=", "[", "target", ".", "import_lib", "]", "elif", "target", ".", "UsesToc", "(", "self", ".", "flavor", ")", ":", "solibs", ".", "add", "(", "target", ".", "binary", ")", "implicit_deps", ".", "add", "(", "target", ".", "binary", "+", "'.TOC'", ")", "else", ":", "new_deps", "=", "[", "target", ".", "binary", "]", "for", "new_dep", "in", "new_deps", ":", "if", "new_dep", "not", "in", "extra_link_deps", ":", "extra_link_deps", ".", "add", "(", "new_dep", ")", "link_deps", ".", "append", "(", "new_dep", ")", "final_output", "=", "target", ".", "FinalOutput", "(", ")", "if", "not", "linkable", "or", "final_output", "!=", "target", ".", "binary", ":", "implicit_deps", ".", "add", "(", "final_output", ")", "extra_bindings", "=", "[", "]", "if", "self", ".", "target", ".", "uses_cpp", "and", "self", ".", "flavor", "!=", "'win'", ":", "extra_bindings", ".", "append", "(", "(", "'ld'", ",", "'$ldxx'", ")", ")", "output", "=", "self", ".", "_ComputeOutput", "(", "spec", ",", "arch", ")", "if", "arch", "is", "None", "and", "not", "self", ".", "is_mac_bundle", ":", "self", ".", "_AppendPostbuildVariable", "(", "extra_bindings", ",", "spec", ",", "output", ",", "output", ")", "is_executable", "=", "spec", "[", "'type'", "]", "==", "'executable'", "# The ldflags config key is not used on mac or win. On those platforms", "# linker flags are set via xcode_settings and msvs_settings, respectively.", "if", "self", ".", "toolset", "==", "'target'", ":", "env_ldflags", "=", "os", ".", "environ", ".", "get", "(", "'LDFLAGS'", ",", "''", ")", ".", "split", "(", ")", "else", ":", "# self.toolset == 'host'", "env_ldflags", "=", "os", ".", "environ", ".", "get", "(", "'LDFLAGS_host'", ",", "''", ")", ".", "split", "(", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "ldflags", "=", "self", ".", "xcode_settings", ".", "GetLdflags", "(", "config_name", ",", "self", ".", "_ExpandSpecial", "(", "generator_default_variables", "[", "'PRODUCT_DIR'", "]", ")", ",", "self", ".", "_GypPathToNinja", ",", "arch", ")", "ldflags", "=", "env_ldflags", "+", "ldflags", "elif", "self", ".", "flavor", "==", "'win'", ":", "manifest_base_name", "=", "self", ".", "_GypPathToUniqueOutput", "(", "self", ".", "ComputeOutputFileName", "(", "spec", ")", ")", "ldflags", ",", "intermediate_manifest", ",", "manifest_files", "=", "self", ".", "msvs_settings", ".", "GetLdflags", "(", "config_name", ",", "self", ".", "_GypPathToNinja", ",", "self", ".", "_ExpandSpecial", ",", "manifest_base_name", ",", "output", ",", "is_executable", ",", "self", ".", "toplevel_build", ")", "ldflags", "=", "env_ldflags", "+", "ldflags", "self", ".", "_WriteVariableList", "(", "ninja_file", ",", "'manifests'", ",", "manifest_files", ")", "implicit_deps", "=", "implicit_deps", ".", "union", "(", "manifest_files", ")", "if", "intermediate_manifest", ":", "self", ".", "_WriteVariableList", "(", "ninja_file", ",", "'intermediatemanifest'", ",", "[", "intermediate_manifest", "]", ")", "command_suffix", "=", "GetWinLinkRuleNameSuffix", "(", "self", ".", "msvs_settings", ".", "IsEmbedManifest", "(", "config_name", ")", ")", "def_file", "=", "self", ".", "msvs_settings", ".", "GetDefFile", "(", "self", ".", "_GypPathToNinja", ")", "if", "def_file", ":", "implicit_deps", ".", "add", "(", "def_file", ")", "else", ":", "# Respect environment variables related to build, but target-specific", "# flags can still override them.", "ldflags", "=", "env_ldflags", "+", "config", ".", "get", "(", "'ldflags'", ",", "[", "]", ")", "if", "is_executable", "and", "len", "(", "solibs", ")", ":", "rpath", "=", "'lib/'", "if", "self", ".", "toolset", "!=", "'target'", ":", "rpath", "+=", "self", ".", "toolset", "ldflags", ".", "append", "(", "r'-Wl,-rpath=\\$$ORIGIN/%s'", "%", "rpath", ")", "else", ":", "ldflags", ".", "append", "(", "'-Wl,-rpath=%s'", "%", "self", ".", "target_rpath", ")", "ldflags", ".", "append", "(", "'-Wl,-rpath-link=%s'", "%", "rpath", ")", "self", ".", "_WriteVariableList", "(", "ninja_file", ",", "'ldflags'", ",", "map", "(", "self", ".", "_ExpandSpecial", ",", "ldflags", ")", ")", "library_dirs", "=", "config", ".", "get", "(", "'library_dirs'", ",", "[", "]", ")", "if", "self", ".", "flavor", "==", "'win'", ":", "library_dirs", "=", "[", "self", ".", "msvs_settings", ".", "ConvertVSMacros", "(", "l", ",", "config_name", ")", "for", "l", "in", "library_dirs", "]", "library_dirs", "=", "[", "'/LIBPATH:'", "+", "self", ".", "_QuoteShellArgument", "(", "self", ".", "_GypPathToNinja", "(", "l", ")", ",", "self", ".", "flavor", ")", "for", "l", "in", "library_dirs", "]", "else", ":", "library_dirs", "=", "[", "self", ".", "_QuoteShellArgument", "(", "'-L'", "+", "self", ".", "_GypPathToNinja", "(", "l", ")", ",", "self", ".", "flavor", ")", "for", "l", "in", "library_dirs", "]", "libraries", "=", "gyp", ".", "common", ".", "uniquer", "(", "map", "(", "self", ".", "_ExpandSpecial", ",", "spec", ".", "get", "(", "'libraries'", ",", "[", "]", ")", ")", ")", "if", "self", ".", "flavor", "==", "'mac'", ":", "libraries", "=", "self", ".", "xcode_settings", ".", "AdjustLibraries", "(", "libraries", ",", "config_name", ")", "elif", "self", ".", "flavor", "==", "'win'", ":", "libraries", "=", "self", ".", "msvs_settings", ".", "AdjustLibraries", "(", "libraries", ")", "self", ".", "_WriteVariableList", "(", "ninja_file", ",", "'libs'", ",", "library_dirs", "+", "libraries", ")", "linked_binary", "=", "output", "if", "command", "in", "(", "'solink'", ",", "'solink_module'", ")", ":", "extra_bindings", ".", "append", "(", "(", "'soname'", ",", "os", ".", "path", ".", "split", "(", "output", ")", "[", "1", "]", ")", ")", "extra_bindings", ".", "append", "(", "(", "'lib'", ",", "gyp", ".", "common", ".", "EncodePOSIXShellArgument", "(", "output", ")", ")", ")", "if", "self", ".", "flavor", "!=", "'win'", ":", "link_file_list", "=", "output", "if", "self", ".", "is_mac_bundle", ":", "# 'Dependency Framework.framework/Versions/A/Dependency Framework' ->", "# 'Dependency Framework.framework.rsp'", "link_file_list", "=", "self", ".", "xcode_settings", ".", "GetWrapperName", "(", ")", "if", "arch", ":", "link_file_list", "+=", "'.'", "+", "arch", "link_file_list", "+=", "'.rsp'", "# If an rspfile contains spaces, ninja surrounds the filename with", "# quotes around it and then passes it to open(), creating a file with", "# quotes in its name (and when looking for the rsp file, the name", "# makes it through bash which strips the quotes) :-/", "link_file_list", "=", "link_file_list", ".", "replace", "(", "' '", ",", "'_'", ")", "extra_bindings", ".", "append", "(", "(", "'link_file_list'", ",", "gyp", ".", "common", ".", "EncodePOSIXShellArgument", "(", "link_file_list", ")", ")", ")", "if", "self", ".", "flavor", "==", "'win'", ":", "extra_bindings", ".", "append", "(", "(", "'binary'", ",", "output", ")", ")", "if", "'/NOENTRY'", "not", "in", "ldflags", "and", "not", "self", ".", "msvs_settings", ".", "GetNoImportLibrary", "(", "config_name", ")", ":", "self", ".", "target", ".", "import_lib", "=", "output", "+", "'.lib'", "extra_bindings", ".", "append", "(", "(", "'implibflag'", ",", "'/IMPLIB:%s'", "%", "self", ".", "target", ".", "import_lib", ")", ")", "pdbname", "=", "self", ".", "msvs_settings", ".", "GetPDBName", "(", "config_name", ",", "self", ".", "_ExpandSpecial", ",", "output", "+", "'.pdb'", ")", "output", "=", "[", "output", ",", "self", ".", "target", ".", "import_lib", "]", "if", "pdbname", ":", "output", ".", "append", "(", "pdbname", ")", "elif", "not", "self", ".", "is_mac_bundle", ":", "output", "=", "[", "output", ",", "output", "+", "'.TOC'", "]", "else", ":", "command", "=", "command", "+", "'_notoc'", "elif", "self", ".", "flavor", "==", "'win'", ":", "extra_bindings", ".", "append", "(", "(", "'binary'", ",", "output", ")", ")", "pdbname", "=", "self", ".", "msvs_settings", ".", "GetPDBName", "(", "config_name", ",", "self", ".", "_ExpandSpecial", ",", "output", "+", "'.pdb'", ")", "if", "pdbname", ":", "output", "=", "[", "output", ",", "pdbname", "]", "if", "len", "(", "solibs", ")", ":", "extra_bindings", ".", "append", "(", "(", "'solibs'", ",", "gyp", ".", "common", ".", "EncodePOSIXShellList", "(", "sorted", "(", "solibs", ")", ")", ")", ")", "ninja_file", ".", "build", "(", "output", ",", "command", "+", "command_suffix", ",", "link_deps", ",", "implicit", "=", "sorted", "(", "implicit_deps", ")", ",", "order_only", "=", "list", "(", "order_deps", ")", ",", "variables", "=", "extra_bindings", ")", "return", "linked_binary" ]
https://github.com/arangodb/arangodb/blob/0d658689c7d1b721b314fa3ca27d38303e1570c8/3rdParty/V8/gyp/NinjaWriter.py#L800-L956
Project-OSRM/osrm-backend
f2e284623e25b5570dd2a5e6985abcb3790fd348
third_party/flatbuffers/python/flatbuffers/builder.py
python
Builder.PrependInt16
(self, x)
Prepend an `int16` to the Builder buffer. Note: aligns and checks for space.
Prepend an `int16` to the Builder buffer.
[ "Prepend", "an", "int16", "to", "the", "Builder", "buffer", "." ]
def PrependInt16(self, x): """Prepend an `int16` to the Builder buffer. Note: aligns and checks for space. """ self.Prepend(N.Int16Flags, x)
[ "def", "PrependInt16", "(", "self", ",", "x", ")", ":", "self", ".", "Prepend", "(", "N", ".", "Int16Flags", ",", "x", ")" ]
https://github.com/Project-OSRM/osrm-backend/blob/f2e284623e25b5570dd2a5e6985abcb3790fd348/third_party/flatbuffers/python/flatbuffers/builder.py#L659-L664
chanyn/3Dpose_ssl
585696676279683a279b1ecca136c0e0d02aef2a
caffe-3dssl/scripts/cpp_lint.py
python
CheckForMultilineCommentsAndStrings
(filename, clean_lines, linenum, error)
Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found.
Logs an error if we see /* ... */ or "..." that extend past one line.
[ "Logs", "an", "error", "if", "we", "see", "/", "*", "...", "*", "/", "or", "...", "that", "extend", "past", "one", "line", "." ]
def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error): """Logs an error if we see /* ... */ or "..." that extend past one line. /* ... */ comments are legit inside macros, for one line. Otherwise, we prefer // comments, so it's ok to warn about the other. Likewise, it's ok for strings to extend across multiple lines, as long as a line continuation character (backslash) terminates each line. Although not currently prohibited by the C++ style guide, it's ugly and unnecessary. We don't do well with either in this lint program, so we warn about both. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. error: The function to call with any errors found. """ line = clean_lines.elided[linenum] # Remove all \\ (escaped backslashes) from the line. They are OK, and the # second (escaped) slash may trigger later \" detection erroneously. line = line.replace('\\\\', '') if line.count('/*') > line.count('*/'): error(filename, linenum, 'readability/multiline_comment', 5, 'Complex multi-line /*...*/-style comment found. ' 'Lint may give bogus warnings. ' 'Consider replacing these with //-style comments, ' 'with #if 0...#endif, ' 'or with more clearly structured multi-line comments.') if (line.count('"') - line.count('\\"')) % 2: error(filename, linenum, 'readability/multiline_string', 5, 'Multi-line string ("...") found. This lint script doesn\'t ' 'do well with such strings, and may give bogus warnings. ' 'Use C++11 raw strings or concatenation instead.')
[ "def", "CheckForMultilineCommentsAndStrings", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "# Remove all \\\\ (escaped backslashes) from the line. They are OK, and the", "# second (escaped) slash may trigger later \\\" detection erroneously.", "line", "=", "line", ".", "replace", "(", "'\\\\\\\\'", ",", "''", ")", "if", "line", ".", "count", "(", "'/*'", ")", ">", "line", ".", "count", "(", "'*/'", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/multiline_comment'", ",", "5", ",", "'Complex multi-line /*...*/-style comment found. '", "'Lint may give bogus warnings. '", "'Consider replacing these with //-style comments, '", "'with #if 0...#endif, '", "'or with more clearly structured multi-line comments.'", ")", "if", "(", "line", ".", "count", "(", "'\"'", ")", "-", "line", ".", "count", "(", "'\\\\\"'", ")", ")", "%", "2", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/multiline_string'", ",", "5", ",", "'Multi-line string (\"...\") found. This lint script doesn\\'t '", "'do well with such strings, and may give bogus warnings. '", "'Use C++11 raw strings or concatenation instead.'", ")" ]
https://github.com/chanyn/3Dpose_ssl/blob/585696676279683a279b1ecca136c0e0d02aef2a/caffe-3dssl/scripts/cpp_lint.py#L1526-L1561
fasiondog/hikyuu
842751aa25283f9fdafc6f560ea262f79e67a307
hikyuu/data/common_mysql.py
python
update_extern_data
(connect, market, code, data_type)
更新周线、月线、15分钟线等扩展数据索引
更新周线、月线、15分钟线等扩展数据索引
[ "更新周线、月线、15分钟线等扩展数据索引" ]
def update_extern_data(connect, market, code, data_type): """更新周线、月线、15分钟线等扩展数据索引""" def getWeekDate(olddate): y = olddate // 100000000 m = olddate // 1000000 - y * 100 d = olddate // 10000 - (y * 10000 + m * 100) tempdate = datetime.date(y, m, d) # python中周一是第0天,周五的第4天 startdate = tempdate + datetime.timedelta(0 - tempdate.weekday()) enddate = tempdate + datetime.timedelta(4 - tempdate.weekday()) return ( startdate.year * 100000000 + startdate.month * 1000000 + startdate.day * 10000, enddate.year * 100000000 + enddate.month * 1000000 + enddate.day * 10000 ) def getMonthDate(olddate): y = olddate // 100000000 m = olddate // 1000000 - y * 100 import calendar _, d = calendar.monthrange(y, m) return (y * 100000000 + m * 1000000 + 10000, y * 100000000 + m * 1000000 + d * 10000) def getQuarterDate(olddate): startDict = {1: 1, 2: 1, 3: 1, 4: 4, 5: 4, 6: 4, 7: 7, 8: 7, 9: 7, 10: 10, 11: 10, 12: 10} endDict = {1: 3, 2: 3, 3: 3, 4: 6, 5: 6, 6: 6, 7: 9, 8: 9, 9: 9, 10: 12, 11: 12, 12: 12} d_dict = {3: 310000, 6: 300000, 9: 300000, 12: 310000} y = olddate // 100000000 m = olddate // 1000000 - y * 100 start_m = startDict[m] end_m = endDict[m] return (y * 100000000 + start_m * 1000000 + 10000, y * 100000000 + end_m * 1000000 + d_dict[end_m]) def getHalfyearDate(olddate): y = olddate // 100000000 m = olddate // 1000000 - y * 100 return (y * 100000000 + (1010000 if m < 7 else 7010000), y * 100000000 + (6300000 if m < 7 else 12310000)) def getYearDate(olddate): y = olddate // 100000000 return (y * 100000000 + 1010000, y * 100000000 + 12310000) def getMin60Date(olddate): mint = olddate - olddate // 10000 * 10000 newdate = olddate // 10000 * 10000 if mint <= 1030: startdate = newdate + 931 enddate = newdate + 1030 elif mint <= 1130: startdate = newdate + 1031 enddate = newdate + 1130 elif mint <= 1400: startdate = newdate + 1301 enddate = newdate + 1400 else: startdate = newdate + 1401 enddate = newdate + 1500 return (startdate, enddate) def getMin15Date(olddate): mint = olddate - olddate // 10000 * 10000 newdate = olddate // 10000 * 10000 if mint <= 945: startdate = newdate + 931 enddate = newdate + 945 elif mint <= 1000: startdate = newdate + 946 enddate = newdate + 1000 elif mint <= 1015: startdate = newdate + 1001 enddate = newdate + 1015 elif mint <= 1030: startdate = newdate + 1016 enddate = newdate + 1030 elif mint <= 1045: startdate = newdate + 1031 enddate = newdate + 1045 elif mint <= 1100: startdate = newdate + 1046 enddate = newdate + 1100 elif mint <= 1115: startdate = newdate + 1101 enddate = newdate + 1115 elif mint <= 1130: startdate = newdate + 1116 enddate = newdate + 1130 elif mint <= 1315: startdate = newdate + 1301 enddate = newdate + 1315 elif mint <= 1330: startdate = newdate + 1316 enddate = newdate + 1330 elif mint <= 1345: startdate = newdate + 1331 enddate = newdate + 1345 elif mint <= 1400: startdate = newdate + 1346 enddate = newdate + 1400 elif mint <= 1415: startdate = newdate + 1401 enddate = newdate + 1415 elif mint <= 1430: startdate = newdate + 1416 enddate = newdate + 1430 elif mint <= 1445: startdate = newdate + 1431 enddate = newdate + 1445 else: startdate = newdate + 1446 enddate = newdate + 1500 return (startdate, enddate) def getMin30Date(olddate): mint = olddate - olddate // 10000 * 10000 newdate = olddate // 10000 * 10000 if mint <= 1000: startdate = newdate + 931 enddate = newdate + 1000 elif mint <= 1030: startdate = newdate + 1001 enddate = newdate + 1030 elif mint <= 1100: startdate = newdate + 1031 enddate = newdate + 1100 elif mint <= 1130: startdate = newdate + 1101 enddate = newdate + 1130 elif mint <= 1330: startdate = newdate + 1301 enddate = newdate + 1330 elif mint <= 1400: startdate = newdate + 1331 enddate = newdate + 1400 elif mint <= 1430: startdate = newdate + 1401 enddate = newdate + 1430 else: startdate = newdate + 1431 enddate = newdate + 1500 return (startdate, enddate) def getNewDate(index_type, olddate): if index_type == 'week': return getWeekDate(olddate) elif index_type == 'month': return getMonthDate(olddate) elif index_type == 'quarter': return getQuarterDate(olddate) elif index_type == 'halfyear': return getHalfyearDate(olddate) elif index_type == 'year': return getYearDate(olddate) elif index_type == 'min15': return getMin15Date(olddate) elif index_type == 'min30': return getMin30Date(olddate) elif index_type == 'min60': return getMin60Date(olddate) else: return None if data_type.lower() == 'day': index_list = ('week', 'month', 'year') #index_list = ('week', 'month', 'quarter', 'halfyear', 'year') base_table = get_table(connect, market, code, 'day') else: index_list = ('min15', 'min30', 'min60') #index_list = ('min15', ) base_table = get_table(connect, market, code, 'min5') base_lastdate = get_lastdatetime(connect, base_table) if base_lastdate is None: return for index_type in index_list: hku_debug("{}{} update {} index".format(market, code, index_type)) index_table = get_table(connect, market, code, index_type) index_last_date = get_lastdatetime(connect, index_table) # 获取当前日期大于等于索引表最大日期的基础表日期列表 cur = connect.cursor() if index_last_date is None: cur.execute( 'select date, open, high, low, close, amount, count from {} order by date asc '.format(base_table) ) else: start_date, _ = getNewDate(index_type, index_last_date) cur.execute( 'select date, open, high, low, close, amount, count from {} where date>={}'.format( base_table, start_date ) ) base_list = [x for x in cur] cur.close() last_start_date = 199012010000 last_end_date = 199012010000 update_buffer = [] insert_buffer = [] #for current_base in base_list: length_base_all = len(base_list) for x in range(length_base_all): current_date = base_list[x][0] if current_date <= last_end_date: continue last_start_date, last_end_date = getNewDate(index_type, current_date) #cur = connect.cursor() #cur.execute( # 'select date, open, high, low, close, amount, count from {} \ # where date>={} and date<={} order by date asc'.format( # base_table, last_start_date, last_end_date # ) #) #base_record_list = [r for r in cur] #cur.close() base_record_list = [] start_ix = x ix_date = current_date while start_ix < length_base_all and \ ix_date >= last_start_date and ix_date <= last_end_date: base_record_list.append(base_list[start_ix]) ix_date = base_list[start_ix][0] start_ix += 1 if not base_record_list: continue length = len(base_record_list) open_price = base_record_list[0][1] high_price = base_record_list[0][2] low_price = base_record_list[0][3] close_price = base_record_list[length - 1][4] amount = base_record_list[0][5] count = base_record_list[0][6] for i in range(1, length): if base_record_list[i][2] > high_price: high_price = base_record_list[i][2] if base_record_list[i][3] < low_price: low_price = base_record_list[i][3] amount += base_record_list[i][5] count += base_record_list[i][6] if last_end_date == index_last_date: update_buffer.append((open_price, high_price, low_price, close_price, amount, count, last_end_date)) else: insert_buffer.append((last_end_date, open_price, high_price, low_price, close_price, amount, count)) if update_buffer: cur = connect.cursor() cur.executemany( "update {} set open=%s, high=%s, low=%s, close=%s, amount=%s, count=%s \ where date=%s".format(index_table), update_buffer ) connect.commit() cur.close() if insert_buffer: cur = connect.cursor() cur.executemany( "insert into {} (date, open, high, low, close, amount, count) \ values (%s, %s, %s, %s, %s, %s, %s)".format(index_table), insert_buffer ) connect.commit() cur.close()
[ "def", "update_extern_data", "(", "connect", ",", "market", ",", "code", ",", "data_type", ")", ":", "def", "getWeekDate", "(", "olddate", ")", ":", "y", "=", "olddate", "//", "100000000", "m", "=", "olddate", "//", "1000000", "-", "y", "*", "100", "d", "=", "olddate", "//", "10000", "-", "(", "y", "*", "10000", "+", "m", "*", "100", ")", "tempdate", "=", "datetime", ".", "date", "(", "y", ",", "m", ",", "d", ")", "# python中周一是第0天,周五的第4天", "startdate", "=", "tempdate", "+", "datetime", ".", "timedelta", "(", "0", "-", "tempdate", ".", "weekday", "(", ")", ")", "enddate", "=", "tempdate", "+", "datetime", ".", "timedelta", "(", "4", "-", "tempdate", ".", "weekday", "(", ")", ")", "return", "(", "startdate", ".", "year", "*", "100000000", "+", "startdate", ".", "month", "*", "1000000", "+", "startdate", ".", "day", "*", "10000", ",", "enddate", ".", "year", "*", "100000000", "+", "enddate", ".", "month", "*", "1000000", "+", "enddate", ".", "day", "*", "10000", ")", "def", "getMonthDate", "(", "olddate", ")", ":", "y", "=", "olddate", "//", "100000000", "m", "=", "olddate", "//", "1000000", "-", "y", "*", "100", "import", "calendar", "_", ",", "d", "=", "calendar", ".", "monthrange", "(", "y", ",", "m", ")", "return", "(", "y", "*", "100000000", "+", "m", "*", "1000000", "+", "10000", ",", "y", "*", "100000000", "+", "m", "*", "1000000", "+", "d", "*", "10000", ")", "def", "getQuarterDate", "(", "olddate", ")", ":", "startDict", "=", "{", "1", ":", "1", ",", "2", ":", "1", ",", "3", ":", "1", ",", "4", ":", "4", ",", "5", ":", "4", ",", "6", ":", "4", ",", "7", ":", "7", ",", "8", ":", "7", ",", "9", ":", "7", ",", "10", ":", "10", ",", "11", ":", "10", ",", "12", ":", "10", "}", "endDict", "=", "{", "1", ":", "3", ",", "2", ":", "3", ",", "3", ":", "3", ",", "4", ":", "6", ",", "5", ":", "6", ",", "6", ":", "6", ",", "7", ":", "9", ",", "8", ":", "9", ",", "9", ":", "9", ",", "10", ":", "12", ",", "11", ":", "12", ",", "12", ":", "12", "}", "d_dict", "=", "{", "3", ":", "310000", ",", "6", ":", "300000", ",", "9", ":", "300000", ",", "12", ":", "310000", "}", "y", "=", "olddate", "//", "100000000", "m", "=", "olddate", "//", "1000000", "-", "y", "*", "100", "start_m", "=", "startDict", "[", "m", "]", "end_m", "=", "endDict", "[", "m", "]", "return", "(", "y", "*", "100000000", "+", "start_m", "*", "1000000", "+", "10000", ",", "y", "*", "100000000", "+", "end_m", "*", "1000000", "+", "d_dict", "[", "end_m", "]", ")", "def", "getHalfyearDate", "(", "olddate", ")", ":", "y", "=", "olddate", "//", "100000000", "m", "=", "olddate", "//", "1000000", "-", "y", "*", "100", "return", "(", "y", "*", "100000000", "+", "(", "1010000", "if", "m", "<", "7", "else", "7010000", ")", ",", "y", "*", "100000000", "+", "(", "6300000", "if", "m", "<", "7", "else", "12310000", ")", ")", "def", "getYearDate", "(", "olddate", ")", ":", "y", "=", "olddate", "//", "100000000", "return", "(", "y", "*", "100000000", "+", "1010000", ",", "y", "*", "100000000", "+", "12310000", ")", "def", "getMin60Date", "(", "olddate", ")", ":", "mint", "=", "olddate", "-", "olddate", "//", "10000", "*", "10000", "newdate", "=", "olddate", "//", "10000", "*", "10000", "if", "mint", "<=", "1030", ":", "startdate", "=", "newdate", "+", "931", "enddate", "=", "newdate", "+", "1030", "elif", "mint", "<=", "1130", ":", "startdate", "=", "newdate", "+", "1031", "enddate", "=", "newdate", "+", "1130", "elif", "mint", "<=", "1400", ":", "startdate", "=", "newdate", "+", "1301", "enddate", "=", "newdate", "+", "1400", "else", ":", "startdate", "=", "newdate", "+", "1401", "enddate", "=", "newdate", "+", "1500", "return", "(", "startdate", ",", "enddate", ")", "def", "getMin15Date", "(", "olddate", ")", ":", "mint", "=", "olddate", "-", "olddate", "//", "10000", "*", "10000", "newdate", "=", "olddate", "//", "10000", "*", "10000", "if", "mint", "<=", "945", ":", "startdate", "=", "newdate", "+", "931", "enddate", "=", "newdate", "+", "945", "elif", "mint", "<=", "1000", ":", "startdate", "=", "newdate", "+", "946", "enddate", "=", "newdate", "+", "1000", "elif", "mint", "<=", "1015", ":", "startdate", "=", "newdate", "+", "1001", "enddate", "=", "newdate", "+", "1015", "elif", "mint", "<=", "1030", ":", "startdate", "=", "newdate", "+", "1016", "enddate", "=", "newdate", "+", "1030", "elif", "mint", "<=", "1045", ":", "startdate", "=", "newdate", "+", "1031", "enddate", "=", "newdate", "+", "1045", "elif", "mint", "<=", "1100", ":", "startdate", "=", "newdate", "+", "1046", "enddate", "=", "newdate", "+", "1100", "elif", "mint", "<=", "1115", ":", "startdate", "=", "newdate", "+", "1101", "enddate", "=", "newdate", "+", "1115", "elif", "mint", "<=", "1130", ":", "startdate", "=", "newdate", "+", "1116", "enddate", "=", "newdate", "+", "1130", "elif", "mint", "<=", "1315", ":", "startdate", "=", "newdate", "+", "1301", "enddate", "=", "newdate", "+", "1315", "elif", "mint", "<=", "1330", ":", "startdate", "=", "newdate", "+", "1316", "enddate", "=", "newdate", "+", "1330", "elif", "mint", "<=", "1345", ":", "startdate", "=", "newdate", "+", "1331", "enddate", "=", "newdate", "+", "1345", "elif", "mint", "<=", "1400", ":", "startdate", "=", "newdate", "+", "1346", "enddate", "=", "newdate", "+", "1400", "elif", "mint", "<=", "1415", ":", "startdate", "=", "newdate", "+", "1401", "enddate", "=", "newdate", "+", "1415", "elif", "mint", "<=", "1430", ":", "startdate", "=", "newdate", "+", "1416", "enddate", "=", "newdate", "+", "1430", "elif", "mint", "<=", "1445", ":", "startdate", "=", "newdate", "+", "1431", "enddate", "=", "newdate", "+", "1445", "else", ":", "startdate", "=", "newdate", "+", "1446", "enddate", "=", "newdate", "+", "1500", "return", "(", "startdate", ",", "enddate", ")", "def", "getMin30Date", "(", "olddate", ")", ":", "mint", "=", "olddate", "-", "olddate", "//", "10000", "*", "10000", "newdate", "=", "olddate", "//", "10000", "*", "10000", "if", "mint", "<=", "1000", ":", "startdate", "=", "newdate", "+", "931", "enddate", "=", "newdate", "+", "1000", "elif", "mint", "<=", "1030", ":", "startdate", "=", "newdate", "+", "1001", "enddate", "=", "newdate", "+", "1030", "elif", "mint", "<=", "1100", ":", "startdate", "=", "newdate", "+", "1031", "enddate", "=", "newdate", "+", "1100", "elif", "mint", "<=", "1130", ":", "startdate", "=", "newdate", "+", "1101", "enddate", "=", "newdate", "+", "1130", "elif", "mint", "<=", "1330", ":", "startdate", "=", "newdate", "+", "1301", "enddate", "=", "newdate", "+", "1330", "elif", "mint", "<=", "1400", ":", "startdate", "=", "newdate", "+", "1331", "enddate", "=", "newdate", "+", "1400", "elif", "mint", "<=", "1430", ":", "startdate", "=", "newdate", "+", "1401", "enddate", "=", "newdate", "+", "1430", "else", ":", "startdate", "=", "newdate", "+", "1431", "enddate", "=", "newdate", "+", "1500", "return", "(", "startdate", ",", "enddate", ")", "def", "getNewDate", "(", "index_type", ",", "olddate", ")", ":", "if", "index_type", "==", "'week'", ":", "return", "getWeekDate", "(", "olddate", ")", "elif", "index_type", "==", "'month'", ":", "return", "getMonthDate", "(", "olddate", ")", "elif", "index_type", "==", "'quarter'", ":", "return", "getQuarterDate", "(", "olddate", ")", "elif", "index_type", "==", "'halfyear'", ":", "return", "getHalfyearDate", "(", "olddate", ")", "elif", "index_type", "==", "'year'", ":", "return", "getYearDate", "(", "olddate", ")", "elif", "index_type", "==", "'min15'", ":", "return", "getMin15Date", "(", "olddate", ")", "elif", "index_type", "==", "'min30'", ":", "return", "getMin30Date", "(", "olddate", ")", "elif", "index_type", "==", "'min60'", ":", "return", "getMin60Date", "(", "olddate", ")", "else", ":", "return", "None", "if", "data_type", ".", "lower", "(", ")", "==", "'day'", ":", "index_list", "=", "(", "'week'", ",", "'month'", ",", "'year'", ")", "#index_list = ('week', 'month', 'quarter', 'halfyear', 'year')", "base_table", "=", "get_table", "(", "connect", ",", "market", ",", "code", ",", "'day'", ")", "else", ":", "index_list", "=", "(", "'min15'", ",", "'min30'", ",", "'min60'", ")", "#index_list = ('min15', )", "base_table", "=", "get_table", "(", "connect", ",", "market", ",", "code", ",", "'min5'", ")", "base_lastdate", "=", "get_lastdatetime", "(", "connect", ",", "base_table", ")", "if", "base_lastdate", "is", "None", ":", "return", "for", "index_type", "in", "index_list", ":", "hku_debug", "(", "\"{}{} update {} index\"", ".", "format", "(", "market", ",", "code", ",", "index_type", ")", ")", "index_table", "=", "get_table", "(", "connect", ",", "market", ",", "code", ",", "index_type", ")", "index_last_date", "=", "get_lastdatetime", "(", "connect", ",", "index_table", ")", "# 获取当前日期大于等于索引表最大日期的基础表日期列表", "cur", "=", "connect", ".", "cursor", "(", ")", "if", "index_last_date", "is", "None", ":", "cur", ".", "execute", "(", "'select date, open, high, low, close, amount, count from {} order by date asc '", ".", "format", "(", "base_table", ")", ")", "else", ":", "start_date", ",", "_", "=", "getNewDate", "(", "index_type", ",", "index_last_date", ")", "cur", ".", "execute", "(", "'select date, open, high, low, close, amount, count from {} where date>={}'", ".", "format", "(", "base_table", ",", "start_date", ")", ")", "base_list", "=", "[", "x", "for", "x", "in", "cur", "]", "cur", ".", "close", "(", ")", "last_start_date", "=", "199012010000", "last_end_date", "=", "199012010000", "update_buffer", "=", "[", "]", "insert_buffer", "=", "[", "]", "#for current_base in base_list:", "length_base_all", "=", "len", "(", "base_list", ")", "for", "x", "in", "range", "(", "length_base_all", ")", ":", "current_date", "=", "base_list", "[", "x", "]", "[", "0", "]", "if", "current_date", "<=", "last_end_date", ":", "continue", "last_start_date", ",", "last_end_date", "=", "getNewDate", "(", "index_type", ",", "current_date", ")", "#cur = connect.cursor()", "#cur.execute(", "# 'select date, open, high, low, close, amount, count from {} \\", "# where date>={} and date<={} order by date asc'.format(", "# base_table, last_start_date, last_end_date", "# )", "#)", "#base_record_list = [r for r in cur]", "#cur.close()", "base_record_list", "=", "[", "]", "start_ix", "=", "x", "ix_date", "=", "current_date", "while", "start_ix", "<", "length_base_all", "and", "ix_date", ">=", "last_start_date", "and", "ix_date", "<=", "last_end_date", ":", "base_record_list", ".", "append", "(", "base_list", "[", "start_ix", "]", ")", "ix_date", "=", "base_list", "[", "start_ix", "]", "[", "0", "]", "start_ix", "+=", "1", "if", "not", "base_record_list", ":", "continue", "length", "=", "len", "(", "base_record_list", ")", "open_price", "=", "base_record_list", "[", "0", "]", "[", "1", "]", "high_price", "=", "base_record_list", "[", "0", "]", "[", "2", "]", "low_price", "=", "base_record_list", "[", "0", "]", "[", "3", "]", "close_price", "=", "base_record_list", "[", "length", "-", "1", "]", "[", "4", "]", "amount", "=", "base_record_list", "[", "0", "]", "[", "5", "]", "count", "=", "base_record_list", "[", "0", "]", "[", "6", "]", "for", "i", "in", "range", "(", "1", ",", "length", ")", ":", "if", "base_record_list", "[", "i", "]", "[", "2", "]", ">", "high_price", ":", "high_price", "=", "base_record_list", "[", "i", "]", "[", "2", "]", "if", "base_record_list", "[", "i", "]", "[", "3", "]", "<", "low_price", ":", "low_price", "=", "base_record_list", "[", "i", "]", "[", "3", "]", "amount", "+=", "base_record_list", "[", "i", "]", "[", "5", "]", "count", "+=", "base_record_list", "[", "i", "]", "[", "6", "]", "if", "last_end_date", "==", "index_last_date", ":", "update_buffer", ".", "append", "(", "(", "open_price", ",", "high_price", ",", "low_price", ",", "close_price", ",", "amount", ",", "count", ",", "last_end_date", ")", ")", "else", ":", "insert_buffer", ".", "append", "(", "(", "last_end_date", ",", "open_price", ",", "high_price", ",", "low_price", ",", "close_price", ",", "amount", ",", "count", ")", ")", "if", "update_buffer", ":", "cur", "=", "connect", ".", "cursor", "(", ")", "cur", ".", "executemany", "(", "\"update {} set open=%s, high=%s, low=%s, close=%s, amount=%s, count=%s \\\n where date=%s\"", ".", "format", "(", "index_table", ")", ",", "update_buffer", ")", "connect", ".", "commit", "(", ")", "cur", ".", "close", "(", ")", "if", "insert_buffer", ":", "cur", "=", "connect", ".", "cursor", "(", ")", "cur", ".", "executemany", "(", "\"insert into {} (date, open, high, low, close, amount, count) \\\n values (%s, %s, %s, %s, %s, %s, %s)\"", ".", "format", "(", "index_table", ")", ",", "insert_buffer", ")", "connect", ".", "commit", "(", ")", "cur", ".", "close", "(", ")" ]
https://github.com/fasiondog/hikyuu/blob/842751aa25283f9fdafc6f560ea262f79e67a307/hikyuu/data/common_mysql.py#L183-L445
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/indexes/base.py
python
Index._validate_fill_value
(self, value)
return value
Check if the value can be inserted into our array without casting, and convert it to an appropriate native type if necessary. Raises ------ TypeError If the value cannot be inserted into an array of this dtype.
Check if the value can be inserted into our array without casting, and convert it to an appropriate native type if necessary.
[ "Check", "if", "the", "value", "can", "be", "inserted", "into", "our", "array", "without", "casting", "and", "convert", "it", "to", "an", "appropriate", "native", "type", "if", "necessary", "." ]
def _validate_fill_value(self, value): """ Check if the value can be inserted into our array without casting, and convert it to an appropriate native type if necessary. Raises ------ TypeError If the value cannot be inserted into an array of this dtype. """ if not can_hold_element(self._values, value): raise TypeError return value
[ "def", "_validate_fill_value", "(", "self", ",", "value", ")", ":", "if", "not", "can_hold_element", "(", "self", ".", "_values", ",", "value", ")", ":", "raise", "TypeError", "return", "value" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/indexes/base.py#L4493-L4505
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/traitlets/py2/traitlets/traitlets.py
python
EventHandler.__call__
(self, *args, **kwargs)
Pass `*args` and `**kwargs` to the handler's function if it exists.
Pass `*args` and `**kwargs` to the handler's function if it exists.
[ "Pass", "*", "args", "and", "**", "kwargs", "to", "the", "handler", "s", "function", "if", "it", "exists", "." ]
def __call__(self, *args, **kwargs): """Pass `*args` and `**kwargs` to the handler's function if it exists.""" if hasattr(self, 'func'): return self.func(*args, **kwargs) else: return self._init_call(*args, **kwargs)
[ "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "hasattr", "(", "self", ",", "'func'", ")", ":", "return", "self", ".", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "return", "self", ".", "_init_call", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/traitlets/py2/traitlets/traitlets.py#L904-L909
OSGeo/gdal
3748fc4ba4fba727492774b2b908a2130c864a83
swig/python/osgeo/gdal.py
python
DecToDMS
(*args)
return _gdal.DecToDMS(*args)
r"""DecToDMS(double arg1, char const * arg2, int arg3=2) -> char const *
r"""DecToDMS(double arg1, char const * arg2, int arg3=2) -> char const *
[ "r", "DecToDMS", "(", "double", "arg1", "char", "const", "*", "arg2", "int", "arg3", "=", "2", ")", "-", ">", "char", "const", "*" ]
def DecToDMS(*args): r"""DecToDMS(double arg1, char const * arg2, int arg3=2) -> char const *""" return _gdal.DecToDMS(*args)
[ "def", "DecToDMS", "(", "*", "args", ")", ":", "return", "_gdal", ".", "DecToDMS", "(", "*", "args", ")" ]
https://github.com/OSGeo/gdal/blob/3748fc4ba4fba727492774b2b908a2130c864a83/swig/python/osgeo/gdal.py#L4089-L4091
apache/incubator-mxnet
f03fb23f1d103fec9541b5ae59ee06b1734a51d9
python/mxnet/ndarray/ndarray.py
python
NDArray._basic_indexing_key_int_to_slice
(idcs)
return tuple(conv_idcs), tuple(int_axes)
Return the converted indexing tuple and the integer axes.
Return the converted indexing tuple and the integer axes.
[ "Return", "the", "converted", "indexing", "tuple", "and", "the", "integer", "axes", "." ]
def _basic_indexing_key_int_to_slice(idcs): """Return the converted indexing tuple and the integer axes.""" int_axes = [] conv_idcs = [] for ax, idx in enumerate(idcs): if isinstance(idx, integer_types): conv_idcs.append(_int_to_slice(idx)) int_axes.append(ax) else: conv_idcs.append(idx) return tuple(conv_idcs), tuple(int_axes)
[ "def", "_basic_indexing_key_int_to_slice", "(", "idcs", ")", ":", "int_axes", "=", "[", "]", "conv_idcs", "=", "[", "]", "for", "ax", ",", "idx", "in", "enumerate", "(", "idcs", ")", ":", "if", "isinstance", "(", "idx", ",", "integer_types", ")", ":", "conv_idcs", ".", "append", "(", "_int_to_slice", "(", "idx", ")", ")", "int_axes", ".", "append", "(", "ax", ")", "else", ":", "conv_idcs", ".", "append", "(", "idx", ")", "return", "tuple", "(", "conv_idcs", ")", ",", "tuple", "(", "int_axes", ")" ]
https://github.com/apache/incubator-mxnet/blob/f03fb23f1d103fec9541b5ae59ee06b1734a51d9/python/mxnet/ndarray/ndarray.py#L837-L848
ukoethe/vigra
093d57d15c8c237adf1704d96daa6393158ce299
vigranumpy/lib/arraytypes.py
python
VigraArray.dropChannelAxis
(self, ignoreMultiChannel=False)
return self.bindAxis(ci, 0)
Drop the channel axis when it is a singleton. This function is for easy transformation of an array shaped (width, height, 1) into (width, height). A RuntimeError is raised when there is more than one channel, unless ignoreMultiChannel=True, in which case 'self' is returned.
Drop the channel axis when it is a singleton. This function is for easy transformation of an array shaped (width, height, 1) into (width, height). A RuntimeError is raised when there is more than one channel, unless ignoreMultiChannel=True, in which case 'self' is returned.
[ "Drop", "the", "channel", "axis", "when", "it", "is", "a", "singleton", ".", "This", "function", "is", "for", "easy", "transformation", "of", "an", "array", "shaped", "(", "width", "height", "1", ")", "into", "(", "width", "height", ")", ".", "A", "RuntimeError", "is", "raised", "when", "there", "is", "more", "than", "one", "channel", "unless", "ignoreMultiChannel", "=", "True", "in", "which", "case", "self", "is", "returned", "." ]
def dropChannelAxis(self, ignoreMultiChannel=False): ''' Drop the channel axis when it is a singleton. This function is for easy transformation of an array shaped (width, height, 1) into (width, height). A RuntimeError is raised when there is more than one channel, unless ignoreMultiChannel=True, in which case 'self' is returned. ''' ci = self.channelIndex if ci == self.ndim: return self if self.shape[ci] != 1: if ignoreMultiChannel: return self raise RuntimeError("dropChannelAxis(): only allowed when there is a single channel.") return self.bindAxis(ci, 0)
[ "def", "dropChannelAxis", "(", "self", ",", "ignoreMultiChannel", "=", "False", ")", ":", "ci", "=", "self", ".", "channelIndex", "if", "ci", "==", "self", ".", "ndim", ":", "return", "self", "if", "self", ".", "shape", "[", "ci", "]", "!=", "1", ":", "if", "ignoreMultiChannel", ":", "return", "self", "raise", "RuntimeError", "(", "\"dropChannelAxis(): only allowed when there is a single channel.\"", ")", "return", "self", ".", "bindAxis", "(", "ci", ",", "0", ")" ]
https://github.com/ukoethe/vigra/blob/093d57d15c8c237adf1704d96daa6393158ce299/vigranumpy/lib/arraytypes.py#L1004-L1020
vnpy/vnpy
f50f2535ed39dd33272e0985ed40c7078e4c19f6
vnpy/chart/widget.py
python
ChartCursor._update_after_move
(self)
Update cursor after moved by left/right.
Update cursor after moved by left/right.
[ "Update", "cursor", "after", "moved", "by", "left", "/", "right", "." ]
def _update_after_move(self) -> None: """ Update cursor after moved by left/right. """ bar = self._manager.get_bar(self._x) self._y = bar.close_price self._update_line() self._update_label()
[ "def", "_update_after_move", "(", "self", ")", "->", "None", ":", "bar", "=", "self", ".", "_manager", ".", "get_bar", "(", "self", ".", "_x", ")", "self", ".", "_y", "=", "bar", ".", "close_price", "self", ".", "_update_line", "(", ")", "self", ".", "_update_label", "(", ")" ]
https://github.com/vnpy/vnpy/blob/f50f2535ed39dd33272e0985ed40c7078e4c19f6/vnpy/chart/widget.py#L513-L521
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/apps/service.py
python
AppsService.__init__
(self, email=None, password=None, domain=None, source=None, server='apps-apis.google.com', additional_headers=None, **kwargs)
Creates a client for the Google Apps Provisioning service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. domain: string (optional) The Google Apps domain name. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'apps-apis.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor.
Creates a client for the Google Apps Provisioning service.
[ "Creates", "a", "client", "for", "the", "Google", "Apps", "Provisioning", "service", "." ]
def __init__(self, email=None, password=None, domain=None, source=None, server='apps-apis.google.com', additional_headers=None, **kwargs): """Creates a client for the Google Apps Provisioning service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. domain: string (optional) The Google Apps domain name. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'apps-apis.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service='apps', source=source, server=server, additional_headers=additional_headers, **kwargs) self.ssl = True self.port = 443 self.domain = domain
[ "def", "__init__", "(", "self", ",", "email", "=", "None", ",", "password", "=", "None", ",", "domain", "=", "None", ",", "source", "=", "None", ",", "server", "=", "'apps-apis.google.com'", ",", "additional_headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "gdata", ".", "service", ".", "GDataService", ".", "__init__", "(", "self", ",", "email", "=", "email", ",", "password", "=", "password", ",", "service", "=", "'apps'", ",", "source", "=", "source", ",", "server", "=", "server", ",", "additional_headers", "=", "additional_headers", ",", "*", "*", "kwargs", ")", "self", ".", "ssl", "=", "True", "self", ".", "port", "=", "443", "self", ".", "domain", "=", "domain" ]
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/apps/service.py#L81-L102
lammps/lammps
b75c3065430a75b1b5543a10e10f46d9b4c91913
tools/i-pi/ipi/engine/properties.py
python
getall
(pstring)
return (pstring, unit, arglist, kwarglist)
Returns the keyword, units and argument list separately. Args: pstring: The string input by the user that specifies an output, which in general will specify units and argument lists. Returns: A tuple giving the keyword for the property, and its units argument list and key word argument list.
Returns the keyword, units and argument list separately.
[ "Returns", "the", "keyword", "units", "and", "argument", "list", "separately", "." ]
def getall(pstring): """Returns the keyword, units and argument list separately. Args: pstring: The string input by the user that specifies an output, which in general will specify units and argument lists. Returns: A tuple giving the keyword for the property, and its units argument list and key word argument list. """ unit = "" arglist = () kwarglist = {} unstart = len(pstring) argstart = unstart if '}' in pstring: # the property has a user-defined unit unstart = pstring.find('{') unstop = pstring.find('}', unstart) if unstop == -1: raise ValueError("Incorrect format in units specification " + pstring) unit = pstring[unstart+1:unstop] if '(' in pstring: # If the property has additional arguments argstart = pstring.find('(') argstop = pstring.find(')', argstart) if argstop == -1: raise ValueError("Incorrect format in argument list " + pstring) argstr = pstring[argstart:argstop+1] arglist = io_xml.read_tuple(argstr, delims="()", split=";", arg_type=str) for arg in arglist: # If a keyword argument is used equals = arg.find('=') if equals >= 0: kwarglist[arg[0:equals].strip()] = arg[equals+1:].strip() arglist = tuple(a for a in arglist if not a == arg) pstring = pstring[0:min(unstart,argstart)].strip() # strips the arguments from pstring name return (pstring, unit, arglist, kwarglist)
[ "def", "getall", "(", "pstring", ")", ":", "unit", "=", "\"\"", "arglist", "=", "(", ")", "kwarglist", "=", "{", "}", "unstart", "=", "len", "(", "pstring", ")", "argstart", "=", "unstart", "if", "'}'", "in", "pstring", ":", "# the property has a user-defined unit", "unstart", "=", "pstring", ".", "find", "(", "'{'", ")", "unstop", "=", "pstring", ".", "find", "(", "'}'", ",", "unstart", ")", "if", "unstop", "==", "-", "1", ":", "raise", "ValueError", "(", "\"Incorrect format in units specification \"", "+", "pstring", ")", "unit", "=", "pstring", "[", "unstart", "+", "1", ":", "unstop", "]", "if", "'('", "in", "pstring", ":", "# If the property has additional arguments", "argstart", "=", "pstring", ".", "find", "(", "'('", ")", "argstop", "=", "pstring", ".", "find", "(", "')'", ",", "argstart", ")", "if", "argstop", "==", "-", "1", ":", "raise", "ValueError", "(", "\"Incorrect format in argument list \"", "+", "pstring", ")", "argstr", "=", "pstring", "[", "argstart", ":", "argstop", "+", "1", "]", "arglist", "=", "io_xml", ".", "read_tuple", "(", "argstr", ",", "delims", "=", "\"()\"", ",", "split", "=", "\";\"", ",", "arg_type", "=", "str", ")", "for", "arg", "in", "arglist", ":", "# If a keyword argument is used", "equals", "=", "arg", ".", "find", "(", "'='", ")", "if", "equals", ">=", "0", ":", "kwarglist", "[", "arg", "[", "0", ":", "equals", "]", ".", "strip", "(", ")", "]", "=", "arg", "[", "equals", "+", "1", ":", "]", ".", "strip", "(", ")", "arglist", "=", "tuple", "(", "a", "for", "a", "in", "arglist", "if", "not", "a", "==", "arg", ")", "pstring", "=", "pstring", "[", "0", ":", "min", "(", "unstart", ",", "argstart", ")", "]", ".", "strip", "(", ")", "# strips the arguments from pstring name", "return", "(", "pstring", ",", "unit", ",", "arglist", ",", "kwarglist", ")" ]
https://github.com/lammps/lammps/blob/b75c3065430a75b1b5543a10e10f46d9b4c91913/tools/i-pi/ipi/engine/properties.py#L68-L110
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/pandas/py3/pandas/core/groupby/groupby.py
python
GroupBy.ohlc
(self)
return self._apply_to_column_groupbys( lambda x: x.ohlc(), self._obj_with_exclusions )
Compute open, high, low and close values of a group, excluding missing values. For multiple groupings, the result index will be a MultiIndex Returns ------- DataFrame Open, high, low and close values within each group.
Compute open, high, low and close values of a group, excluding missing values.
[ "Compute", "open", "high", "low", "and", "close", "values", "of", "a", "group", "excluding", "missing", "values", "." ]
def ohlc(self) -> DataFrame: """ Compute open, high, low and close values of a group, excluding missing values. For multiple groupings, the result index will be a MultiIndex Returns ------- DataFrame Open, high, low and close values within each group. """ if self.obj.ndim == 1: # self._iterate_slices() yields only self._selected_obj obj = self._selected_obj is_numeric = is_numeric_dtype(obj.dtype) if not is_numeric: raise DataError("No numeric types to aggregate") res_values = self.grouper._cython_operation( "aggregate", obj._values, "ohlc", axis=0, min_count=-1 ) agg_names = ["open", "high", "low", "close"] result = self.obj._constructor_expanddim( res_values, index=self.grouper.result_index, columns=agg_names ) return self._reindex_output(result) return self._apply_to_column_groupbys( lambda x: x.ohlc(), self._obj_with_exclusions )
[ "def", "ohlc", "(", "self", ")", "->", "DataFrame", ":", "if", "self", ".", "obj", ".", "ndim", "==", "1", ":", "# self._iterate_slices() yields only self._selected_obj", "obj", "=", "self", ".", "_selected_obj", "is_numeric", "=", "is_numeric_dtype", "(", "obj", ".", "dtype", ")", "if", "not", "is_numeric", ":", "raise", "DataError", "(", "\"No numeric types to aggregate\"", ")", "res_values", "=", "self", ".", "grouper", ".", "_cython_operation", "(", "\"aggregate\"", ",", "obj", ".", "_values", ",", "\"ohlc\"", ",", "axis", "=", "0", ",", "min_count", "=", "-", "1", ")", "agg_names", "=", "[", "\"open\"", ",", "\"high\"", ",", "\"low\"", ",", "\"close\"", "]", "result", "=", "self", ".", "obj", ".", "_constructor_expanddim", "(", "res_values", ",", "index", "=", "self", ".", "grouper", ".", "result_index", ",", "columns", "=", "agg_names", ")", "return", "self", ".", "_reindex_output", "(", "result", ")", "return", "self", ".", "_apply_to_column_groupbys", "(", "lambda", "x", ":", "x", ".", "ohlc", "(", ")", ",", "self", ".", "_obj_with_exclusions", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/pandas/py3/pandas/core/groupby/groupby.py#L1936-L1967
scribusproject/scribus
41ec7c775a060912cf251682a8b1437f753f80f4
scribus/plugins/scriptplugin/scripts/ColorChart.py
python
getColorsFromDocument
()
gets colors from opend document. if there is no document, display dialog to chose a file. returns a list[name,c,m,y,k]
gets colors from opend document. if there is no document, display dialog to chose a file. returns a list[name,c,m,y,k]
[ "gets", "colors", "from", "opend", "document", ".", "if", "there", "is", "no", "document", "display", "dialog", "to", "chose", "a", "file", ".", "returns", "a", "list", "[", "name", "c", "m", "y", "k", "]" ]
def getColorsFromDocument(): """gets colors from opend document. if there is no document, display dialog to chose a file. returns a list[name,c,m,y,k]""" def getColors(): """gets the colors and returns a list[name,c,m,y,k]""" colorNames=scribus.getColorNames() list=[] scribus.statusMessage("Reading Colors...") stepsTotal=len(colorNames) scribus.progressTotal(stepsTotal) steps=0 for name in colorNames: color=scribus.getColor(name) listitem=[name, color[0], color[1], color[2], color[3]] list.append(listitem) #update progress bar steps=steps+1 scribus.progressSet(steps) return list #check if we have a document - otherwise display open file dialog if scribus.haveDoc() > 0: pass list=getColors() return list else: pass #display file open dialog file=scribus.fileDialog("ColorChart by Sebastian Stetter", 'Scribus files(*.sla *.SLA *.sla.gz *.SLA.GZ)') #open file try: scribus.openDoc(file) except: scribus.messageBox("ColorChart by Sebastian Stetter", "could not open file") sys.exit() list=getColors() return list
[ "def", "getColorsFromDocument", "(", ")", ":", "def", "getColors", "(", ")", ":", "\"\"\"gets the colors and returns a list[name,c,m,y,k]\"\"\"", "colorNames", "=", "scribus", ".", "getColorNames", "(", ")", "list", "=", "[", "]", "scribus", ".", "statusMessage", "(", "\"Reading Colors...\"", ")", "stepsTotal", "=", "len", "(", "colorNames", ")", "scribus", ".", "progressTotal", "(", "stepsTotal", ")", "steps", "=", "0", "for", "name", "in", "colorNames", ":", "color", "=", "scribus", ".", "getColor", "(", "name", ")", "listitem", "=", "[", "name", ",", "color", "[", "0", "]", ",", "color", "[", "1", "]", ",", "color", "[", "2", "]", ",", "color", "[", "3", "]", "]", "list", ".", "append", "(", "listitem", ")", "#update progress bar", "steps", "=", "steps", "+", "1", "scribus", ".", "progressSet", "(", "steps", ")", "return", "list", "#check if we have a document - otherwise display open file dialog", "if", "scribus", ".", "haveDoc", "(", ")", ">", "0", ":", "pass", "list", "=", "getColors", "(", ")", "return", "list", "else", ":", "pass", "#display file open dialog", "file", "=", "scribus", ".", "fileDialog", "(", "\"ColorChart by Sebastian Stetter\"", ",", "'Scribus files(*.sla *.SLA *.sla.gz *.SLA.GZ)'", ")", "#open file", "try", ":", "scribus", ".", "openDoc", "(", "file", ")", "except", ":", "scribus", ".", "messageBox", "(", "\"ColorChart by Sebastian Stetter\"", ",", "\"could not open file\"", ")", "sys", ".", "exit", "(", ")", "list", "=", "getColors", "(", ")", "return", "list" ]
https://github.com/scribusproject/scribus/blob/41ec7c775a060912cf251682a8b1437f753f80f4/scribus/plugins/scriptplugin/scripts/ColorChart.py#L114-L149
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/docview.py
python
Document.OnCloseDocument
(self)
return True
The default implementation calls DeleteContents (an empty implementation) sets the modified flag to false. Override this to supply additional behaviour when the document is closed with Close.
The default implementation calls DeleteContents (an empty implementation) sets the modified flag to false. Override this to supply additional behaviour when the document is closed with Close.
[ "The", "default", "implementation", "calls", "DeleteContents", "(", "an", "empty", "implementation", ")", "sets", "the", "modified", "flag", "to", "false", ".", "Override", "this", "to", "supply", "additional", "behaviour", "when", "the", "document", "is", "closed", "with", "Close", "." ]
def OnCloseDocument(self): """ The default implementation calls DeleteContents (an empty implementation) sets the modified flag to false. Override this to supply additional behaviour when the document is closed with Close. """ self.NotifyClosing() self.DeleteContents() self.Modify(False) return True
[ "def", "OnCloseDocument", "(", "self", ")", ":", "self", ".", "NotifyClosing", "(", ")", "self", ".", "DeleteContents", "(", ")", "self", ".", "Modify", "(", "False", ")", "return", "True" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/docview.py#L307-L316
deepmodeling/deepmd-kit
159e45d248b0429844fb6a8cb3b3a201987c8d79
deepmd/entrypoints/config.py
python
suggest_sel
( all_type: List[np.ndarray], all_box: List[np.ndarray], rcut: float, ratio: float = 1.5, )
return [int(ii) for ii in max_den * 4.0 / 3.0 * np.pi * rcut ** 3 * ratio]
Suggest selection parameter. Parameters ---------- all_type : List[np.ndarray] list with arrays specifying elements of structures all_box : List[np.ndarray] list with arrays specifying cells for all structures rcut : float cutoff radius ratio : float, optional safety margin to add to estimated value, by default 1.5 Returns ------- List[int] [description]
Suggest selection parameter.
[ "Suggest", "selection", "parameter", "." ]
def suggest_sel( all_type: List[np.ndarray], all_box: List[np.ndarray], rcut: float, ratio: float = 1.5, ) -> List[int]: """Suggest selection parameter. Parameters ---------- all_type : List[np.ndarray] list with arrays specifying elements of structures all_box : List[np.ndarray] list with arrays specifying cells for all structures rcut : float cutoff radius ratio : float, optional safety margin to add to estimated value, by default 1.5 Returns ------- List[int] [description] """ max_den = get_max_density(all_type, all_box) return [int(ii) for ii in max_den * 4.0 / 3.0 * np.pi * rcut ** 3 * ratio]
[ "def", "suggest_sel", "(", "all_type", ":", "List", "[", "np", ".", "ndarray", "]", ",", "all_box", ":", "List", "[", "np", ".", "ndarray", "]", ",", "rcut", ":", "float", ",", "ratio", ":", "float", "=", "1.5", ",", ")", "->", "List", "[", "int", "]", ":", "max_den", "=", "get_max_density", "(", "all_type", ",", "all_box", ")", "return", "[", "int", "(", "ii", ")", "for", "ii", "in", "max_den", "*", "4.0", "/", "3.0", "*", "np", ".", "pi", "*", "rcut", "**", "3", "*", "ratio", "]" ]
https://github.com/deepmodeling/deepmd-kit/blob/159e45d248b0429844fb6a8cb3b3a201987c8d79/deepmd/entrypoints/config.py#L240-L265
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_controls.py
python
PickerBase.SetPickerCtrlGrowable
(*args, **kwargs)
return _controls_.PickerBase_SetPickerCtrlGrowable(*args, **kwargs)
SetPickerCtrlGrowable(self, bool grow=True)
SetPickerCtrlGrowable(self, bool grow=True)
[ "SetPickerCtrlGrowable", "(", "self", "bool", "grow", "=", "True", ")" ]
def SetPickerCtrlGrowable(*args, **kwargs): """SetPickerCtrlGrowable(self, bool grow=True)""" return _controls_.PickerBase_SetPickerCtrlGrowable(*args, **kwargs)
[ "def", "SetPickerCtrlGrowable", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "PickerBase_SetPickerCtrlGrowable", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_controls.py#L6802-L6804
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
demo/PropertyGrid.py
python
LargeImageEditor.OnEvent
(self, propgrid, property, ctrl, event)
return False
Return True if modified editor value should be committed to the property. To just mark the property value modified, call propgrid.EditorsValueWasModified().
Return True if modified editor value should be committed to the property. To just mark the property value modified, call propgrid.EditorsValueWasModified().
[ "Return", "True", "if", "modified", "editor", "value", "should", "be", "committed", "to", "the", "property", ".", "To", "just", "mark", "the", "property", "value", "modified", "call", "propgrid", ".", "EditorsValueWasModified", "()", "." ]
def OnEvent(self, propgrid, property, ctrl, event): """ Return True if modified editor value should be committed to the property. To just mark the property value modified, call propgrid.EditorsValueWasModified(). """ if not ctrl: return False evtType = event.GetEventType() if evtType == wx.wxEVT_COMMAND_TEXT_ENTER: if propgrid.IsEditorsValueModified(): return True elif evtType == wx.wxEVT_COMMAND_TEXT_UPDATED: # # Pass this event outside wxPropertyGrid so that, # if necessary, program can tell when user is editing # a textctrl. event.Skip() event.SetId(propgrid.GetId()) propgrid.EditorsValueWasModified() return False return False
[ "def", "OnEvent", "(", "self", ",", "propgrid", ",", "property", ",", "ctrl", ",", "event", ")", ":", "if", "not", "ctrl", ":", "return", "False", "evtType", "=", "event", ".", "GetEventType", "(", ")", "if", "evtType", "==", "wx", ".", "wxEVT_COMMAND_TEXT_ENTER", ":", "if", "propgrid", ".", "IsEditorsValueModified", "(", ")", ":", "return", "True", "elif", "evtType", "==", "wx", ".", "wxEVT_COMMAND_TEXT_UPDATED", ":", "#", "# Pass this event outside wxPropertyGrid so that,", "# if necessary, program can tell when user is editing", "# a textctrl.", "event", ".", "Skip", "(", ")", "event", ".", "SetId", "(", "propgrid", ".", "GetId", "(", ")", ")", "propgrid", ".", "EditorsValueWasModified", "(", ")", "return", "False", "return", "False" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/demo/PropertyGrid.py#L606-L630
MegEngine/MegEngine
ce9ad07a27ec909fb8db4dd67943d24ba98fb93a
imperative/python/megengine/functional/loss.py
python
cross_entropy
( pred: Tensor, label: Tensor, axis: int = 1, with_logits: bool = True, label_smooth: float = 0, reduction: str = "mean", )
return logZ - ls * pred.mean(axis) - (1 - ls) * primary_term
r"""Computes the multi-class cross entropy loss (using logits by default). By default(``with_logitis`` is True), ``pred`` is assumed to be logits, class probabilities are given by softmax. It has better numerical stability compared with sequential calls to :func:`~.softmax` and :func:`~.cross_entropy`. When using label smoothing, the label distribution is as follows: .. math:: y^{LS}_{k}=y_{k}\left(1-\alpha\right)+\alpha/K where :math:`y^{LS}` and :math:`y` are new label distribution and origin label distribution respectively. k is the index of label distribution. :math:`\alpha` is ``label_smooth`` and :math:`K` is the number of classes. Args: pred: input tensor representing the predicted probability. label: input tensor representing the classification label. axis: an axis along which softmax will be applied. Default: 1 with_logits: whether to apply softmax first. Default: True label_smooth: a label smoothing of parameter that can re-distribute target distribution. Default: 0 reduction: the reduction to apply to the output: 'none' | 'mean' | 'sum'. Default: 'mean' Returns: loss value. Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data_shape = (1, 2) label_shape = (1, ) pred = tensor(np.array([0, 0], dtype=np.float32).reshape(data_shape)) label = tensor(np.ones(label_shape, dtype=np.int32)) loss = F.nn.cross_entropy(pred, label) print(loss.numpy().round(decimals=4)) Outputs: .. testoutput:: 0.6931
r"""Computes the multi-class cross entropy loss (using logits by default).
[ "r", "Computes", "the", "multi", "-", "class", "cross", "entropy", "loss", "(", "using", "logits", "by", "default", ")", "." ]
def cross_entropy( pred: Tensor, label: Tensor, axis: int = 1, with_logits: bool = True, label_smooth: float = 0, reduction: str = "mean", ) -> Tensor: r"""Computes the multi-class cross entropy loss (using logits by default). By default(``with_logitis`` is True), ``pred`` is assumed to be logits, class probabilities are given by softmax. It has better numerical stability compared with sequential calls to :func:`~.softmax` and :func:`~.cross_entropy`. When using label smoothing, the label distribution is as follows: .. math:: y^{LS}_{k}=y_{k}\left(1-\alpha\right)+\alpha/K where :math:`y^{LS}` and :math:`y` are new label distribution and origin label distribution respectively. k is the index of label distribution. :math:`\alpha` is ``label_smooth`` and :math:`K` is the number of classes. Args: pred: input tensor representing the predicted probability. label: input tensor representing the classification label. axis: an axis along which softmax will be applied. Default: 1 with_logits: whether to apply softmax first. Default: True label_smooth: a label smoothing of parameter that can re-distribute target distribution. Default: 0 reduction: the reduction to apply to the output: 'none' | 'mean' | 'sum'. Default: 'mean' Returns: loss value. Examples: .. testcode:: import numpy as np from megengine import tensor import megengine.functional as F data_shape = (1, 2) label_shape = (1, ) pred = tensor(np.array([0, 0], dtype=np.float32).reshape(data_shape)) label = tensor(np.ones(label_shape, dtype=np.int32)) loss = F.nn.cross_entropy(pred, label) print(loss.numpy().round(decimals=4)) Outputs: .. testoutput:: 0.6931 """ n0 = pred.ndim n1 = label.ndim assert n0 == n1 + 1, ( "target ndim must be one less than input ndim; input_ndim={} " "target_ndim={}".format(n0, n1) ) ls = label_smooth if with_logits: logZ = logsumexp(pred, axis) primary_term = indexing_one_hot(pred, label, axis) else: logZ = 0 primary_term = log(indexing_one_hot(pred, label, axis)) if ls is None or type(ls) in (int, float) and ls == 0: return logZ - primary_term if not with_logits: pred = log(pred) return logZ - ls * pred.mean(axis) - (1 - ls) * primary_term
[ "def", "cross_entropy", "(", "pred", ":", "Tensor", ",", "label", ":", "Tensor", ",", "axis", ":", "int", "=", "1", ",", "with_logits", ":", "bool", "=", "True", ",", "label_smooth", ":", "float", "=", "0", ",", "reduction", ":", "str", "=", "\"mean\"", ",", ")", "->", "Tensor", ":", "n0", "=", "pred", ".", "ndim", "n1", "=", "label", ".", "ndim", "assert", "n0", "==", "n1", "+", "1", ",", "(", "\"target ndim must be one less than input ndim; input_ndim={} \"", "\"target_ndim={}\"", ".", "format", "(", "n0", ",", "n1", ")", ")", "ls", "=", "label_smooth", "if", "with_logits", ":", "logZ", "=", "logsumexp", "(", "pred", ",", "axis", ")", "primary_term", "=", "indexing_one_hot", "(", "pred", ",", "label", ",", "axis", ")", "else", ":", "logZ", "=", "0", "primary_term", "=", "log", "(", "indexing_one_hot", "(", "pred", ",", "label", ",", "axis", ")", ")", "if", "ls", "is", "None", "or", "type", "(", "ls", ")", "in", "(", "int", ",", "float", ")", "and", "ls", "==", "0", ":", "return", "logZ", "-", "primary_term", "if", "not", "with_logits", ":", "pred", "=", "log", "(", "pred", ")", "return", "logZ", "-", "ls", "*", "pred", ".", "mean", "(", "axis", ")", "-", "(", "1", "-", "ls", ")", "*", "primary_term" ]
https://github.com/MegEngine/MegEngine/blob/ce9ad07a27ec909fb8db4dd67943d24ba98fb93a/imperative/python/megengine/functional/loss.py#L155-L228
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/auibar.py
python
AuiDefaultToolBarArt.DrawBackground
(self, dc, wnd, _rect, horizontal=True)
Draws a toolbar background with a gradient shading. :param `dc`: a :class:`DC` device context; :param `wnd`: a :class:`Window` derived window; :param Rect `_rect`: the :class:`AuiToolBarItem` rectangle; :param bool `horizontal`: ``True`` if the toolbar is horizontal, ``False`` if it is vertical.
Draws a toolbar background with a gradient shading.
[ "Draws", "a", "toolbar", "background", "with", "a", "gradient", "shading", "." ]
def DrawBackground(self, dc, wnd, _rect, horizontal=True): """ Draws a toolbar background with a gradient shading. :param `dc`: a :class:`DC` device context; :param `wnd`: a :class:`Window` derived window; :param Rect `_rect`: the :class:`AuiToolBarItem` rectangle; :param bool `horizontal`: ``True`` if the toolbar is horizontal, ``False`` if it is vertical. """ rect = wx.Rect(*_rect) start_colour = StepColour(self._base_colour, 180) end_colour = StepColour(self._base_colour, 85) reflex_colour = StepColour(self._base_colour, 95) dc.GradientFillLinear(rect, start_colour, end_colour, (horizontal and [wx.SOUTH] or [wx.EAST])[0]) left = rect.GetLeft() right = rect.GetRight() top = rect.GetTop() bottom = rect.GetBottom() dc.SetPen(wx.Pen(reflex_colour)) if horizontal: dc.DrawLine(left, bottom, right+1, bottom) else: dc.DrawLine(right, top, right, bottom+1)
[ "def", "DrawBackground", "(", "self", ",", "dc", ",", "wnd", ",", "_rect", ",", "horizontal", "=", "True", ")", ":", "rect", "=", "wx", ".", "Rect", "(", "*", "_rect", ")", "start_colour", "=", "StepColour", "(", "self", ".", "_base_colour", ",", "180", ")", "end_colour", "=", "StepColour", "(", "self", ".", "_base_colour", ",", "85", ")", "reflex_colour", "=", "StepColour", "(", "self", ".", "_base_colour", ",", "95", ")", "dc", ".", "GradientFillLinear", "(", "rect", ",", "start_colour", ",", "end_colour", ",", "(", "horizontal", "and", "[", "wx", ".", "SOUTH", "]", "or", "[", "wx", ".", "EAST", "]", ")", "[", "0", "]", ")", "left", "=", "rect", ".", "GetLeft", "(", ")", "right", "=", "rect", ".", "GetRight", "(", ")", "top", "=", "rect", ".", "GetTop", "(", ")", "bottom", "=", "rect", ".", "GetBottom", "(", ")", "dc", ".", "SetPen", "(", "wx", ".", "Pen", "(", "reflex_colour", ")", ")", "if", "horizontal", ":", "dc", ".", "DrawLine", "(", "left", ",", "bottom", ",", "right", "+", "1", ",", "bottom", ")", "else", ":", "dc", ".", "DrawLine", "(", "right", ",", "top", ",", "right", ",", "bottom", "+", "1", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibar.py#L889-L917
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/html2.py
python
WebView.LoadURL
(*args, **kwargs)
return _html2.WebView_LoadURL(*args, **kwargs)
LoadURL(self, String url)
LoadURL(self, String url)
[ "LoadURL", "(", "self", "String", "url", ")" ]
def LoadURL(*args, **kwargs): """LoadURL(self, String url)""" return _html2.WebView_LoadURL(*args, **kwargs)
[ "def", "LoadURL", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_html2", ".", "WebView_LoadURL", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/html2.py#L179-L181
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/peacock/PostprocessorViewer/plugins/PostprocessorTableWidget.py
python
PostprocessorTableWidget.initialize
(self, data)
Called when the data is changed ,this updates the visible data. @see OutputPlugin
Called when the data is changed ,this updates the visible data.
[ "Called", "when", "the", "data", "is", "changed", "this", "updates", "the", "visible", "data", "." ]
def initialize(self, data): """ Called when the data is changed ,this updates the visible data. @see OutputPlugin """ self._data = data
[ "def", "initialize", "(", "self", ",", "data", ")", ":", "self", ".", "_data", "=", "data" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/PostprocessorViewer/plugins/PostprocessorTableWidget.py#L42-L48
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py
python
readconfig
(cfgdict)
Read config-files, change configuration-dict accordingly. If there is a turtle.cfg file in the current working directory, read it from there. If this contains an importconfig-value, say 'myway', construct filename turtle_mayway.cfg else use turtle.cfg and read it from the import-directory, where turtle.py is located. Update configuration dictionary first according to config-file, in the import directory, then according to config-file in the current working directory. If no config-file is found, the default configuration is used.
Read config-files, change configuration-dict accordingly.
[ "Read", "config", "-", "files", "change", "configuration", "-", "dict", "accordingly", "." ]
def readconfig(cfgdict): """Read config-files, change configuration-dict accordingly. If there is a turtle.cfg file in the current working directory, read it from there. If this contains an importconfig-value, say 'myway', construct filename turtle_mayway.cfg else use turtle.cfg and read it from the import-directory, where turtle.py is located. Update configuration dictionary first according to config-file, in the import directory, then according to config-file in the current working directory. If no config-file is found, the default configuration is used. """ default_cfg = "turtle.cfg" cfgdict1 = {} cfgdict2 = {} if isfile(default_cfg): cfgdict1 = config_dict(default_cfg) #print "1. Loading config-file %s from: %s" % (default_cfg, os.getcwd()) if "importconfig" in cfgdict1: default_cfg = "turtle_%s.cfg" % cfgdict1["importconfig"] try: head, tail = split(__file__) cfg_file2 = join(head, default_cfg) except: cfg_file2 = "" if isfile(cfg_file2): #print "2. Loading config-file %s:" % cfg_file2 cfgdict2 = config_dict(cfg_file2) ## show(_CFG) ## show(cfgdict2) _CFG.update(cfgdict2) ## show(_CFG) ## show(cfgdict1) _CFG.update(cfgdict1)
[ "def", "readconfig", "(", "cfgdict", ")", ":", "default_cfg", "=", "\"turtle.cfg\"", "cfgdict1", "=", "{", "}", "cfgdict2", "=", "{", "}", "if", "isfile", "(", "default_cfg", ")", ":", "cfgdict1", "=", "config_dict", "(", "default_cfg", ")", "#print \"1. Loading config-file %s from: %s\" % (default_cfg, os.getcwd())", "if", "\"importconfig\"", "in", "cfgdict1", ":", "default_cfg", "=", "\"turtle_%s.cfg\"", "%", "cfgdict1", "[", "\"importconfig\"", "]", "try", ":", "head", ",", "tail", "=", "split", "(", "__file__", ")", "cfg_file2", "=", "join", "(", "head", ",", "default_cfg", ")", "except", ":", "cfg_file2", "=", "\"\"", "if", "isfile", "(", "cfg_file2", ")", ":", "#print \"2. Loading config-file %s:\" % cfg_file2", "cfgdict2", "=", "config_dict", "(", "cfg_file2", ")", "## show(_CFG)", "## show(cfgdict2)", "_CFG", ".", "update", "(", "cfgdict2", ")", "## show(_CFG)", "## show(cfgdict1)", "_CFG", ".", "update", "(", "cfgdict1", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py#L213-L247
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py
python
BigBracket.getcell
(self, index)
return TaggedBit().constant(piece, span)
Get the bracket piece as an array cell.
Get the bracket piece as an array cell.
[ "Get", "the", "bracket", "piece", "as", "an", "array", "cell", "." ]
def getcell(self, index): "Get the bracket piece as an array cell." piece = self.getpiece(index) span = 'span class="bracket align-' + self.alignment + '"' return TaggedBit().constant(piece, span)
[ "def", "getcell", "(", "self", ",", "index", ")", ":", "piece", "=", "self", ".", "getpiece", "(", "index", ")", "span", "=", "'span class=\"bracket align-'", "+", "self", ".", "alignment", "+", "'\"'", "return", "TaggedBit", "(", ")", ".", "constant", "(", "piece", ",", "span", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/docutils/utils/math/math2html.py#L4372-L4376
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/_polybase.py
python
ABCPolyBase.roots
(self)
return pu.mapdomain(roots, self.window, self.domain)
Return the roots of the series polynomial. Compute the roots for the series. Note that the accuracy of the roots decrease the further outside the domain they lie. Returns ------- roots : ndarray Array containing the roots of the series.
Return the roots of the series polynomial.
[ "Return", "the", "roots", "of", "the", "series", "polynomial", "." ]
def roots(self): """Return the roots of the series polynomial. Compute the roots for the series. Note that the accuracy of the roots decrease the further outside the domain they lie. Returns ------- roots : ndarray Array containing the roots of the series. """ roots = self._roots(self.coef) return pu.mapdomain(roots, self.window, self.domain)
[ "def", "roots", "(", "self", ")", ":", "roots", "=", "self", ".", "_roots", "(", "self", ".", "coef", ")", "return", "pu", ".", "mapdomain", "(", "roots", ",", "self", ".", "window", ",", "self", ".", "domain", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numpy/polynomial/_polybase.py#L763-L776
larroy/clearskies_core
3574ddf0edc8555454c7044126e786a6c29444dc
tools/gyp/pylib/gyp/MSVSVersion.py
python
VisualStudioVersion.SetupScript
(self, target_arch)
Returns a command (with arguments) to be used to set up the environment.
Returns a command (with arguments) to be used to set up the environment.
[ "Returns", "a", "command", "(", "with", "arguments", ")", "to", "be", "used", "to", "set", "up", "the", "environment", "." ]
def SetupScript(self, target_arch): """Returns a command (with arguments) to be used to set up the environment.""" # Check if we are running in the SDK command line environment and use # the setup script from the SDK if so. |target_arch| should be either # 'x86' or 'x64'. assert target_arch in ('x86', 'x64') sdk_dir = os.environ.get('WindowsSDKDir') if self.sdk_based and sdk_dir: return [os.path.normpath(os.path.join(sdk_dir, 'Bin/SetEnv.Cmd')), '/' + target_arch] else: # We don't use VC/vcvarsall.bat for x86 because vcvarsall calls # vcvars32, which it can only find if VS??COMNTOOLS is set, which it # isn't always. if target_arch == 'x86': if self.short_name == '2013' and ( os.environ.get('PROCESSOR_ARCHITECTURE') == 'AMD64' or os.environ.get('PROCESSOR_ARCHITEW6432') == 'AMD64'): # VS2013 non-Express has a x64-x86 cross that we want to prefer. return [os.path.normpath( os.path.join(self.path, 'VC/vcvarsall.bat')), 'amd64_x86'] # Otherwise, the standard x86 compiler. return [os.path.normpath( os.path.join(self.path, 'Common7/Tools/vsvars32.bat'))] else: assert target_arch == 'x64' arg = 'x86_amd64' # Use the 64-on-64 compiler if we're not using an express # edition and we're running on a 64bit OS. if self.short_name[-1] != 'e' and ( os.environ.get('PROCESSOR_ARCHITECTURE') == 'AMD64' or os.environ.get('PROCESSOR_ARCHITEW6432') == 'AMD64'): arg = 'amd64' return [os.path.normpath( os.path.join(self.path, 'VC/vcvarsall.bat')), arg]
[ "def", "SetupScript", "(", "self", ",", "target_arch", ")", ":", "# Check if we are running in the SDK command line environment and use", "# the setup script from the SDK if so. |target_arch| should be either", "# 'x86' or 'x64'.", "assert", "target_arch", "in", "(", "'x86'", ",", "'x64'", ")", "sdk_dir", "=", "os", ".", "environ", ".", "get", "(", "'WindowsSDKDir'", ")", "if", "self", ".", "sdk_based", "and", "sdk_dir", ":", "return", "[", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "sdk_dir", ",", "'Bin/SetEnv.Cmd'", ")", ")", ",", "'/'", "+", "target_arch", "]", "else", ":", "# We don't use VC/vcvarsall.bat for x86 because vcvarsall calls", "# vcvars32, which it can only find if VS??COMNTOOLS is set, which it", "# isn't always.", "if", "target_arch", "==", "'x86'", ":", "if", "self", ".", "short_name", "==", "'2013'", "and", "(", "os", ".", "environ", ".", "get", "(", "'PROCESSOR_ARCHITECTURE'", ")", "==", "'AMD64'", "or", "os", ".", "environ", ".", "get", "(", "'PROCESSOR_ARCHITEW6432'", ")", "==", "'AMD64'", ")", ":", "# VS2013 non-Express has a x64-x86 cross that we want to prefer.", "return", "[", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "'VC/vcvarsall.bat'", ")", ")", ",", "'amd64_x86'", "]", "# Otherwise, the standard x86 compiler.", "return", "[", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "'Common7/Tools/vsvars32.bat'", ")", ")", "]", "else", ":", "assert", "target_arch", "==", "'x64'", "arg", "=", "'x86_amd64'", "# Use the 64-on-64 compiler if we're not using an express", "# edition and we're running on a 64bit OS.", "if", "self", ".", "short_name", "[", "-", "1", "]", "!=", "'e'", "and", "(", "os", ".", "environ", ".", "get", "(", "'PROCESSOR_ARCHITECTURE'", ")", "==", "'AMD64'", "or", "os", ".", "environ", ".", "get", "(", "'PROCESSOR_ARCHITEW6432'", ")", "==", "'AMD64'", ")", ":", "arg", "=", "'amd64'", "return", "[", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "path", ",", "'VC/vcvarsall.bat'", ")", ")", ",", "arg", "]" ]
https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/MSVSVersion.py#L71-L106
turi-code/SFrame
796b9bdfb2fa1b881d82080754643c7e68629cd2
oss_src/unity/python/sframe/data_structures/sarray.py
python
SArray.random_split
(self, fraction, seed=None)
return (train['X1'], test['X1'])
Randomly split the rows of an SArray into two SArrays. The first SArray contains *M* rows, sampled uniformly (without replacement) from the original SArray. *M* is approximately the fraction times the original number of rows. The second SArray contains the remaining rows of the original SArray. Parameters ---------- fraction : float Approximate fraction of the rows to fetch for the first returned SArray. Must be between 0 and 1. seed : int, optional Seed for the random number generator used to split. Returns ------- out : tuple [SArray] Two new SArrays. Examples -------- Suppose we have an SArray with 1,024 rows and we want to randomly split it into training and testing datasets with about a 90%/10% split. >>> sa = graphlab.SArray(range(1024)) >>> sa_train, sa_test = sa.random_split(.9, seed=5) >>> print(len(sa_train), len(sa_test)) 922 102
Randomly split the rows of an SArray into two SArrays. The first SArray contains *M* rows, sampled uniformly (without replacement) from the original SArray. *M* is approximately the fraction times the original number of rows. The second SArray contains the remaining rows of the original SArray.
[ "Randomly", "split", "the", "rows", "of", "an", "SArray", "into", "two", "SArrays", ".", "The", "first", "SArray", "contains", "*", "M", "*", "rows", "sampled", "uniformly", "(", "without", "replacement", ")", "from", "the", "original", "SArray", ".", "*", "M", "*", "is", "approximately", "the", "fraction", "times", "the", "original", "number", "of", "rows", ".", "The", "second", "SArray", "contains", "the", "remaining", "rows", "of", "the", "original", "SArray", "." ]
def random_split(self, fraction, seed=None): """ Randomly split the rows of an SArray into two SArrays. The first SArray contains *M* rows, sampled uniformly (without replacement) from the original SArray. *M* is approximately the fraction times the original number of rows. The second SArray contains the remaining rows of the original SArray. Parameters ---------- fraction : float Approximate fraction of the rows to fetch for the first returned SArray. Must be between 0 and 1. seed : int, optional Seed for the random number generator used to split. Returns ------- out : tuple [SArray] Two new SArrays. Examples -------- Suppose we have an SArray with 1,024 rows and we want to randomly split it into training and testing datasets with about a 90%/10% split. >>> sa = graphlab.SArray(range(1024)) >>> sa_train, sa_test = sa.random_split(.9, seed=5) >>> print(len(sa_train), len(sa_test)) 922 102 """ from .sframe import SFrame temporary_sf = SFrame() temporary_sf['X1'] = self (train, test) = temporary_sf.random_split(fraction, seed) return (train['X1'], test['X1'])
[ "def", "random_split", "(", "self", ",", "fraction", ",", "seed", "=", "None", ")", ":", "from", ".", "sframe", "import", "SFrame", "temporary_sf", "=", "SFrame", "(", ")", "temporary_sf", "[", "'X1'", "]", "=", "self", "(", "train", ",", "test", ")", "=", "temporary_sf", ".", "random_split", "(", "fraction", ",", "seed", ")", "return", "(", "train", "[", "'X1'", "]", ",", "test", "[", "'X1'", "]", ")" ]
https://github.com/turi-code/SFrame/blob/796b9bdfb2fa1b881d82080754643c7e68629cd2/oss_src/unity/python/sframe/data_structures/sarray.py#L2894-L2930
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Draft/draftguitools/gui_texts.py
python
Text.action
(self, arg)
Handle the 3D scene events. This is installed as an EventCallback in the Inventor view. Parameters ---------- arg: dict Dictionary with strings that indicates the type of event received from the 3D view.
Handle the 3D scene events.
[ "Handle", "the", "3D", "scene", "events", "." ]
def action(self, arg): """Handle the 3D scene events. This is installed as an EventCallback in the Inventor view. Parameters ---------- arg: dict Dictionary with strings that indicates the type of event received from the 3D view. """ if arg["Type"] == "SoKeyboardEvent": if arg["Key"] == "ESCAPE": self.finish() elif arg["Type"] == "SoLocation2Event": # mouse movement detection if self.active: (self.point, ctrlPoint, info) = gui_tool_utils.getPoint(self, arg) gui_tool_utils.redraw3DView() elif arg["Type"] == "SoMouseButtonEvent": if arg["State"] == "DOWN" and arg["Button"] == "BUTTON1": if self.point: self.active = False Gui.Snapper.off() self.node.append(self.point) self.ui.textUi() self.ui.textValue.setFocus()
[ "def", "action", "(", "self", ",", "arg", ")", ":", "if", "arg", "[", "\"Type\"", "]", "==", "\"SoKeyboardEvent\"", ":", "if", "arg", "[", "\"Key\"", "]", "==", "\"ESCAPE\"", ":", "self", ".", "finish", "(", ")", "elif", "arg", "[", "\"Type\"", "]", "==", "\"SoLocation2Event\"", ":", "# mouse movement detection", "if", "self", ".", "active", ":", "(", "self", ".", "point", ",", "ctrlPoint", ",", "info", ")", "=", "gui_tool_utils", ".", "getPoint", "(", "self", ",", "arg", ")", "gui_tool_utils", ".", "redraw3DView", "(", ")", "elif", "arg", "[", "\"Type\"", "]", "==", "\"SoMouseButtonEvent\"", ":", "if", "arg", "[", "\"State\"", "]", "==", "\"DOWN\"", "and", "arg", "[", "\"Button\"", "]", "==", "\"BUTTON1\"", ":", "if", "self", ".", "point", ":", "self", ".", "active", "=", "False", "Gui", ".", "Snapper", ".", "off", "(", ")", "self", ".", "node", ".", "append", "(", "self", ".", "point", ")", "self", ".", "ui", ".", "textUi", "(", ")", "self", ".", "ui", ".", "textValue", ".", "setFocus", "(", ")" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Draft/draftguitools/gui_texts.py#L125-L151
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/gtk/_misc.py
python
ArtProvider.Insert
(*args, **kwargs)
return _misc_.ArtProvider_Insert(*args, **kwargs)
Insert(ArtProvider provider) Add new provider to the bottom of providers stack.
Insert(ArtProvider provider)
[ "Insert", "(", "ArtProvider", "provider", ")" ]
def Insert(*args, **kwargs): """ Insert(ArtProvider provider) Add new provider to the bottom of providers stack. """ return _misc_.ArtProvider_Insert(*args, **kwargs)
[ "def", "Insert", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_misc_", ".", "ArtProvider_Insert", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/gtk/_misc.py#L2786-L2792
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/pycc/cc.py
python
_CCExtension.monkey_patch_distutils
(cls)
Monkey-patch distutils with our own build_ext class knowing about pycc-compiled extensions modules.
Monkey-patch distutils with our own build_ext class knowing about pycc-compiled extensions modules.
[ "Monkey", "-", "patch", "distutils", "with", "our", "own", "build_ext", "class", "knowing", "about", "pycc", "-", "compiled", "extensions", "modules", "." ]
def monkey_patch_distutils(cls): """ Monkey-patch distutils with our own build_ext class knowing about pycc-compiled extensions modules. """ if cls._distutils_monkey_patched: return _orig_build_ext = build_ext.build_ext class _CC_build_ext(_orig_build_ext): def build_extension(self, ext): if isinstance(ext, _CCExtension): ext._prepare_object_files(self) _orig_build_ext.build_extension(self, ext) build_ext.build_ext = _CC_build_ext cls._distutils_monkey_patched = True
[ "def", "monkey_patch_distutils", "(", "cls", ")", ":", "if", "cls", ".", "_distutils_monkey_patched", ":", "return", "_orig_build_ext", "=", "build_ext", ".", "build_ext", "class", "_CC_build_ext", "(", "_orig_build_ext", ")", ":", "def", "build_extension", "(", "self", ",", "ext", ")", ":", "if", "isinstance", "(", "ext", ",", "_CCExtension", ")", ":", "ext", ".", "_prepare_object_files", "(", "self", ")", "_orig_build_ext", ".", "build_extension", "(", "self", ",", "ext", ")", "build_ext", ".", "build_ext", "=", "_CC_build_ext", "cls", ".", "_distutils_monkey_patched", "=", "True" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/numba/pycc/cc.py#L283-L303
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
tools/sort-headers.py
python
IncludeCompareKey
(line)
return '4' + line
Sorting comparator key used for comparing two #include lines. Returns the filename without the #include/#import prefix.
Sorting comparator key used for comparing two #include lines. Returns the filename without the #include/#import prefix.
[ "Sorting", "comparator", "key", "used", "for", "comparing", "two", "#include", "lines", ".", "Returns", "the", "filename", "without", "the", "#include", "/", "#import", "prefix", "." ]
def IncludeCompareKey(line): """Sorting comparator key used for comparing two #include lines. Returns the filename without the #include/#import prefix. """ for prefix in ('#include ', '#import '): if line.startswith(prefix): line = line[len(prefix):] break # The win32 api has all sorts of implicit include order dependencies :-/ # Give a few headers special sort keys that make sure they appear before all # other headers. if line.startswith('<windows.h>'): # Must be before e.g. shellapi.h return '0' if line.startswith('<unknwn.h>'): # Must be before e.g. intshcut.h return '1' # C++ system headers should come after C system headers. if line.startswith('<'): if line.find('.h>') != -1: return '2' + line else: return '3' + line return '4' + line
[ "def", "IncludeCompareKey", "(", "line", ")", ":", "for", "prefix", "in", "(", "'#include '", ",", "'#import '", ")", ":", "if", "line", ".", "startswith", "(", "prefix", ")", ":", "line", "=", "line", "[", "len", "(", "prefix", ")", ":", "]", "break", "# The win32 api has all sorts of implicit include order dependencies :-/", "# Give a few headers special sort keys that make sure they appear before all", "# other headers.", "if", "line", ".", "startswith", "(", "'<windows.h>'", ")", ":", "# Must be before e.g. shellapi.h", "return", "'0'", "if", "line", ".", "startswith", "(", "'<unknwn.h>'", ")", ":", "# Must be before e.g. intshcut.h", "return", "'1'", "# C++ system headers should come after C system headers.", "if", "line", ".", "startswith", "(", "'<'", ")", ":", "if", "line", ".", "find", "(", "'.h>'", ")", "!=", "-", "1", ":", "return", "'2'", "+", "line", "else", ":", "return", "'3'", "+", "line", "return", "'4'", "+", "line" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/tools/sort-headers.py#L36-L60
fengbingchun/NN_Test
d6305825d5273e4569ccd1eda9ffa2a9c72e18d2
src/tiny-dnn/third_party/cpplint.py
python
CheckComment
(line, filename, linenum, next_line_start, error)
Checks for common mistakes in comments. Args: line: The line in question. filename: The name of the current file. linenum: The number of the line to check. next_line_start: The first non-whitespace column of the next line. error: The function to call with any errors found.
Checks for common mistakes in comments.
[ "Checks", "for", "common", "mistakes", "in", "comments", "." ]
def CheckComment(line, filename, linenum, next_line_start, error): """Checks for common mistakes in comments. Args: line: The line in question. filename: The name of the current file. linenum: The number of the line to check. next_line_start: The first non-whitespace column of the next line. error: The function to call with any errors found. """ commentpos = line.find('//') if commentpos != -1: # Check if the // may be in quotes. If so, ignore it if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0: # Allow one space for new scopes, two spaces otherwise: if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and ((commentpos >= 1 and line[commentpos-1] not in string.whitespace) or (commentpos >= 2 and line[commentpos-2] not in string.whitespace))): error(filename, linenum, 'whitespace/comments', 2, 'At least two spaces is best between code and comments') # Checks for common mistakes in TODO comments. comment = line[commentpos:] match = _RE_PATTERN_TODO.match(comment) if match: # One whitespace is correct; zero whitespace is handled elsewhere. leading_whitespace = match.group(1) if len(leading_whitespace) > 1: error(filename, linenum, 'whitespace/todo', 2, 'Too many spaces before TODO') username = match.group(2) if not username: error(filename, linenum, 'readability/todo', 2, 'Missing username in TODO; it should look like ' '"// TODO(my_username): Stuff."') middle_whitespace = match.group(3) # Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison if middle_whitespace != ' ' and middle_whitespace != '': error(filename, linenum, 'whitespace/todo', 2, 'TODO(my_username) should be followed by a space') # If the comment contains an alphanumeric character, there # should be a space somewhere between it and the // unless # it's a /// or //! Doxygen comment. if (Match(r'//[^ ]*\w', comment) and not Match(r'(///|//\!)(\s+|$)', comment)): error(filename, linenum, 'whitespace/comments', 4, 'Should have a space between // and comment')
[ "def", "CheckComment", "(", "line", ",", "filename", ",", "linenum", ",", "next_line_start", ",", "error", ")", ":", "commentpos", "=", "line", ".", "find", "(", "'//'", ")", "if", "commentpos", "!=", "-", "1", ":", "# Check if the // may be in quotes. If so, ignore it", "if", "re", ".", "sub", "(", "r'\\\\.'", ",", "''", ",", "line", "[", "0", ":", "commentpos", "]", ")", ".", "count", "(", "'\"'", ")", "%", "2", "==", "0", ":", "# Allow one space for new scopes, two spaces otherwise:", "if", "(", "not", "(", "Match", "(", "r'^.*{ *//'", ",", "line", ")", "and", "next_line_start", "==", "commentpos", ")", "and", "(", "(", "commentpos", ">=", "1", "and", "line", "[", "commentpos", "-", "1", "]", "not", "in", "string", ".", "whitespace", ")", "or", "(", "commentpos", ">=", "2", "and", "line", "[", "commentpos", "-", "2", "]", "not", "in", "string", ".", "whitespace", ")", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/comments'", ",", "2", ",", "'At least two spaces is best between code and comments'", ")", "# Checks for common mistakes in TODO comments.", "comment", "=", "line", "[", "commentpos", ":", "]", "match", "=", "_RE_PATTERN_TODO", ".", "match", "(", "comment", ")", "if", "match", ":", "# One whitespace is correct; zero whitespace is handled elsewhere.", "leading_whitespace", "=", "match", ".", "group", "(", "1", ")", "if", "len", "(", "leading_whitespace", ")", ">", "1", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/todo'", ",", "2", ",", "'Too many spaces before TODO'", ")", "username", "=", "match", ".", "group", "(", "2", ")", "if", "not", "username", ":", "error", "(", "filename", ",", "linenum", ",", "'readability/todo'", ",", "2", ",", "'Missing username in TODO; it should look like '", "'\"// TODO(my_username): Stuff.\"'", ")", "middle_whitespace", "=", "match", ".", "group", "(", "3", ")", "# Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison", "if", "middle_whitespace", "!=", "' '", "and", "middle_whitespace", "!=", "''", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/todo'", ",", "2", ",", "'TODO(my_username) should be followed by a space'", ")", "# If the comment contains an alphanumeric character, there", "# should be a space somewhere between it and the // unless", "# it's a /// or //! Doxygen comment.", "if", "(", "Match", "(", "r'//[^ ]*\\w'", ",", "comment", ")", "and", "not", "Match", "(", "r'(///|//\\!)(\\s+|$)'", ",", "comment", ")", ")", ":", "error", "(", "filename", ",", "linenum", ",", "'whitespace/comments'", ",", "4", ",", "'Should have a space between // and comment'", ")" ]
https://github.com/fengbingchun/NN_Test/blob/d6305825d5273e4569ccd1eda9ffa2a9c72e18d2/src/tiny-dnn/third_party/cpplint.py#L3228-L3279
swift/swift
12d031cf8177fdec0137f9aa7e2912fa23c4416b
3rdParty/SCons/scons-3.0.1/engine/SCons/exitfuncs.py
python
register
(func, *targs, **kargs)
register a function to be executed upon normal program termination func - function to be called at exit targs - optional arguments to pass to func kargs - optional keyword arguments to pass to func
register a function to be executed upon normal program termination
[ "register", "a", "function", "to", "be", "executed", "upon", "normal", "program", "termination" ]
def register(func, *targs, **kargs): """register a function to be executed upon normal program termination func - function to be called at exit targs - optional arguments to pass to func kargs - optional keyword arguments to pass to func """ _exithandlers.append((func, targs, kargs))
[ "def", "register", "(", "func", ",", "*", "targs", ",", "*", "*", "kargs", ")", ":", "_exithandlers", ".", "append", "(", "(", "func", ",", "targs", ",", "kargs", ")", ")" ]
https://github.com/swift/swift/blob/12d031cf8177fdec0137f9aa7e2912fa23c4416b/3rdParty/SCons/scons-3.0.1/engine/SCons/exitfuncs.py#L47-L54
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/multiprocessing/forkserver.py
python
ForkServer.get_inherited_fds
(self)
return self._inherited_fds
Return list of fds inherited from parent process. This returns None if the current process was not started by fork server.
Return list of fds inherited from parent process.
[ "Return", "list", "of", "fds", "inherited", "from", "parent", "process", "." ]
def get_inherited_fds(self): '''Return list of fds inherited from parent process. This returns None if the current process was not started by fork server. ''' return self._inherited_fds
[ "def", "get_inherited_fds", "(", "self", ")", ":", "return", "self", ".", "_inherited_fds" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/multiprocessing/forkserver.py#L67-L73
eventql/eventql
7ca0dbb2e683b525620ea30dc40540a22d5eb227
deps/3rdparty/spidermonkey/mozjs/python/pystache/setup.py
python
strip_html_comments
(text)
return "".join(new_lines)
Strip HTML comments from a unicode string.
Strip HTML comments from a unicode string.
[ "Strip", "HTML", "comments", "from", "a", "unicode", "string", "." ]
def strip_html_comments(text): """Strip HTML comments from a unicode string.""" lines = text.splitlines(True) # preserve line endings. # Remove HTML comments (which we only allow to take a special form). new_lines = filter(lambda line: not line.startswith("<!--"), lines) return "".join(new_lines)
[ "def", "strip_html_comments", "(", "text", ")", ":", "lines", "=", "text", ".", "splitlines", "(", "True", ")", "# preserve line endings.", "# Remove HTML comments (which we only allow to take a special form).", "new_lines", "=", "filter", "(", "lambda", "line", ":", "not", "line", ".", "startswith", "(", "\"<!--\"", ")", ",", "lines", ")", "return", "\"\"", ".", "join", "(", "new_lines", ")" ]
https://github.com/eventql/eventql/blob/7ca0dbb2e683b525620ea30dc40540a22d5eb227/deps/3rdparty/spidermonkey/mozjs/python/pystache/setup.py#L198-L205
ArduPilot/ardupilot
6e684b3496122b8158ac412b609d00004b7ac306
libraries/AP_MSP/Tools/pymsp.py
python
MSPItem.parse
(self, msp, dataSize)
parse data
parse data
[ "parse", "data" ]
def parse(self, msp, dataSize): '''parse data''' ofs = msp.p for i in range(len(self.format)): fmt = self.format[i] fields = self.fields[i].split(',') if fmt[0] == '{': # we have a repeat count from an earlier variable right = fmt.find('}') vname = fmt[1:right] count = self.values[vname] fmt = "%u%s" % (count, fmt[right+1:]) if fmt[0].isdigit(): repeat = int(re.search(r'\d+', fmt).group()) else: repeat = None fmt = "<" + fmt fmt_size = struct.calcsize(fmt) if dataSize < fmt_size: raise Exception("Format %s needs %u bytes got %u for %s" % (self.name, fmt_size, dataSize, fmt)) values = list(struct.unpack(fmt, msp.inBuf[ofs:ofs+fmt_size])) if repeat is not None: for i in range(len(fields)): self.values[fields[i]] = [] for j in range(repeat): self.values[fields[i]].append(values[j*len(fields)]) else: for i in range(len(fields)): self.values[fields[i]] = values[i] dataSize -= fmt_size ofs += fmt_size msp.by_name[self.name] = self
[ "def", "parse", "(", "self", ",", "msp", ",", "dataSize", ")", ":", "ofs", "=", "msp", ".", "p", "for", "i", "in", "range", "(", "len", "(", "self", ".", "format", ")", ")", ":", "fmt", "=", "self", ".", "format", "[", "i", "]", "fields", "=", "self", ".", "fields", "[", "i", "]", ".", "split", "(", "','", ")", "if", "fmt", "[", "0", "]", "==", "'{'", ":", "# we have a repeat count from an earlier variable", "right", "=", "fmt", ".", "find", "(", "'}'", ")", "vname", "=", "fmt", "[", "1", ":", "right", "]", "count", "=", "self", ".", "values", "[", "vname", "]", "fmt", "=", "\"%u%s\"", "%", "(", "count", ",", "fmt", "[", "right", "+", "1", ":", "]", ")", "if", "fmt", "[", "0", "]", ".", "isdigit", "(", ")", ":", "repeat", "=", "int", "(", "re", ".", "search", "(", "r'\\d+'", ",", "fmt", ")", ".", "group", "(", ")", ")", "else", ":", "repeat", "=", "None", "fmt", "=", "\"<\"", "+", "fmt", "fmt_size", "=", "struct", ".", "calcsize", "(", "fmt", ")", "if", "dataSize", "<", "fmt_size", ":", "raise", "Exception", "(", "\"Format %s needs %u bytes got %u for %s\"", "%", "(", "self", ".", "name", ",", "fmt_size", ",", "dataSize", ",", "fmt", ")", ")", "values", "=", "list", "(", "struct", ".", "unpack", "(", "fmt", ",", "msp", ".", "inBuf", "[", "ofs", ":", "ofs", "+", "fmt_size", "]", ")", ")", "if", "repeat", "is", "not", "None", ":", "for", "i", "in", "range", "(", "len", "(", "fields", ")", ")", ":", "self", ".", "values", "[", "fields", "[", "i", "]", "]", "=", "[", "]", "for", "j", "in", "range", "(", "repeat", ")", ":", "self", ".", "values", "[", "fields", "[", "i", "]", "]", ".", "append", "(", "values", "[", "j", "*", "len", "(", "fields", ")", "]", ")", "else", ":", "for", "i", "in", "range", "(", "len", "(", "fields", ")", ")", ":", "self", ".", "values", "[", "fields", "[", "i", "]", "]", "=", "values", "[", "i", "]", "dataSize", "-=", "fmt_size", "ofs", "+=", "fmt_size", "msp", ".", "by_name", "[", "self", ".", "name", "]", "=", "self" ]
https://github.com/ArduPilot/ardupilot/blob/6e684b3496122b8158ac412b609d00004b7ac306/libraries/AP_MSP/Tools/pymsp.py#L25-L56
microsoft/ivy
9f3c7ecc0b2383129fdd0953e10890d98d09a82d
ivy/ivy_parser.py
python
p_places_places_comma_symbol
(p)
places : places COMMA SYMBOL
places : places COMMA SYMBOL
[ "places", ":", "places", "COMMA", "SYMBOL" ]
def p_places_places_comma_symbol(p): 'places : places COMMA SYMBOL' p[0] = p[1] p[0].append(Atom(p[3])) p[0][-1].lineno = get_lineno(p,3)
[ "def", "p_places_places_comma_symbol", "(", "p", ")", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "p", "[", "0", "]", ".", "append", "(", "Atom", "(", "p", "[", "3", "]", ")", ")", "p", "[", "0", "]", "[", "-", "1", "]", ".", "lineno", "=", "get_lineno", "(", "p", ",", "3", ")" ]
https://github.com/microsoft/ivy/blob/9f3c7ecc0b2383129fdd0953e10890d98d09a82d/ivy/ivy_parser.py#L1941-L1945
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/common.py
python
AllTargets
(target_list, target_dicts, build_file)
return bftargets + deptargets
Returns all targets (direct and dependencies) for the specified build_file.
Returns all targets (direct and dependencies) for the specified build_file.
[ "Returns", "all", "targets", "(", "direct", "and", "dependencies", ")", "for", "the", "specified", "build_file", "." ]
def AllTargets(target_list, target_dicts, build_file): """Returns all targets (direct and dependencies) for the specified build_file. """ bftargets = BuildFileTargets(target_list, build_file) deptargets = DeepDependencyTargets(target_dicts, bftargets) return bftargets + deptargets
[ "def", "AllTargets", "(", "target_list", ",", "target_dicts", ",", "build_file", ")", ":", "bftargets", "=", "BuildFileTargets", "(", "target_list", ",", "build_file", ")", "deptargets", "=", "DeepDependencyTargets", "(", "target_dicts", ",", "bftargets", ")", "return", "bftargets", "+", "deptargets" ]
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/common.py#L314-L319
ApolloAuto/apollo-platform
86d9dc6743b496ead18d597748ebabd34a513289
ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/core.py
python
left_shift
(a, n)
Shift the bits of an integer to the left. This is the masked array version of `numpy.left_shift`, for details see that function. See Also -------- numpy.left_shift
Shift the bits of an integer to the left.
[ "Shift", "the", "bits", "of", "an", "integer", "to", "the", "left", "." ]
def left_shift (a, n): """ Shift the bits of an integer to the left. This is the masked array version of `numpy.left_shift`, for details see that function. See Also -------- numpy.left_shift """ m = getmask(a) if m is nomask: d = umath.left_shift(filled(a), n) return masked_array(d) else: d = umath.left_shift(filled(a, 0), n) return masked_array(d, mask=m)
[ "def", "left_shift", "(", "a", ",", "n", ")", ":", "m", "=", "getmask", "(", "a", ")", "if", "m", "is", "nomask", ":", "d", "=", "umath", ".", "left_shift", "(", "filled", "(", "a", ")", ",", "n", ")", "return", "masked_array", "(", "d", ")", "else", ":", "d", "=", "umath", ".", "left_shift", "(", "filled", "(", "a", ",", "0", ")", ",", "n", ")", "return", "masked_array", "(", "d", ",", "mask", "=", "m", ")" ]
https://github.com/ApolloAuto/apollo-platform/blob/86d9dc6743b496ead18d597748ebabd34a513289/ros/third_party/lib_x86_64/python2.7/dist-packages/numpy/ma/core.py#L6331-L6349
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_controls.py
python
ListBox.GetClassDefaultAttributes
(*args, **kwargs)
return _controls_.ListBox_GetClassDefaultAttributes(*args, **kwargs)
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this.
GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
[ "GetClassDefaultAttributes", "(", "int", "variant", "=", "WINDOW_VARIANT_NORMAL", ")", "-", ">", "VisualAttributes" ]
def GetClassDefaultAttributes(*args, **kwargs): """ GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes Get the default attributes for this class. This is useful if you want to use the same font or colour in your own control as in a standard control -- which is a much better idea than hard coding specific colours or fonts which might look completely out of place on the user's system, especially if it uses themes. The variant parameter is only relevant under Mac currently and is ignore under other platforms. Under Mac, it will change the size of the returned font. See `wx.Window.SetWindowVariant` for more about this. """ return _controls_.ListBox_GetClassDefaultAttributes(*args, **kwargs)
[ "def", "GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_controls_", ".", "ListBox_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_controls.py#L1257-L1272
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/metrics_impl.py
python
_streaming_sparse_average_precision_at_top_k
(labels, predictions_idx, weights=None, metrics_collections=None, updates_collections=None, name=None)
Computes average precision@k of predictions with respect to sparse labels. `sparse_average_precision_at_top_k` creates two local variables, `average_precision_at_<k>/total` and `average_precision_at_<k>/max`, that are used to compute the frequency. This frequency is ultimately returned as `average_precision_at_<k>`: an idempotent operation that simply divides `average_precision_at_<k>/total` by `average_precision_at_<k>/max`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `precision_at_<k>`. Set operations applied to `top_k` and `labels` calculate the true positives and false positives weighted by `weights`. Then `update_op` increments `true_positive_at_<k>` and `false_positive_at_<k>` using these values. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels] or [D1, ... DN], where the latter implies num_labels=1. N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions_idx`. Values should be non-negative. Negative values are ignored. predictions_idx: Integer `Tensor` with shape [D1, ... DN, k] where N >= 1. Commonly, N=1 and `predictions_idx` has shape [batch size, k]. The final dimension contains the top `k` predicted class indices. [D1, ... DN] must match `labels`. Values should be in range [0, num_classes). weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of `labels`. If the latter, it must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). metrics_collections: An optional list of collections that values should be added to. updates_collections: An optional list of collections that updates should be added to. name: Name of new update operation, and namespace for other dependent ops. Returns: mean_average_precision: Scalar `float64` `Tensor` with the mean average precision values. update: `Operation` that increments variables appropriately, and whose value matches `metric`.
Computes average precision@k of predictions with respect to sparse labels.
[ "Computes", "average", "precision@k", "of", "predictions", "with", "respect", "to", "sparse", "labels", "." ]
def _streaming_sparse_average_precision_at_top_k(labels, predictions_idx, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes average precision@k of predictions with respect to sparse labels. `sparse_average_precision_at_top_k` creates two local variables, `average_precision_at_<k>/total` and `average_precision_at_<k>/max`, that are used to compute the frequency. This frequency is ultimately returned as `average_precision_at_<k>`: an idempotent operation that simply divides `average_precision_at_<k>/total` by `average_precision_at_<k>/max`. For estimation of the metric over a stream of data, the function creates an `update_op` operation that updates these variables and returns the `precision_at_<k>`. Set operations applied to `top_k` and `labels` calculate the true positives and false positives weighted by `weights`. Then `update_op` increments `true_positive_at_<k>` and `false_positive_at_<k>` using these values. If `weights` is `None`, weights default to 1. Use weights of 0 to mask values. Args: labels: `int64` `Tensor` or `SparseTensor` with shape [D1, ... DN, num_labels] or [D1, ... DN], where the latter implies num_labels=1. N >= 1 and num_labels is the number of target classes for the associated prediction. Commonly, N=1 and `labels` has shape [batch_size, num_labels]. [D1, ... DN] must match `predictions_idx`. Values should be non-negative. Negative values are ignored. predictions_idx: Integer `Tensor` with shape [D1, ... DN, k] where N >= 1. Commonly, N=1 and `predictions_idx` has shape [batch size, k]. The final dimension contains the top `k` predicted class indices. [D1, ... DN] must match `labels`. Values should be in range [0, num_classes). weights: `Tensor` whose rank is either 0, or n-1, where n is the rank of `labels`. If the latter, it must be broadcastable to `labels` (i.e., all dimensions must be either `1`, or the same as the corresponding `labels` dimension). metrics_collections: An optional list of collections that values should be added to. updates_collections: An optional list of collections that updates should be added to. name: Name of new update operation, and namespace for other dependent ops. Returns: mean_average_precision: Scalar `float64` `Tensor` with the mean average precision values. update: `Operation` that increments variables appropriately, and whose value matches `metric`. """ with ops.name_scope(name, 'average_precision_at_top_k', (predictions_idx, labels, weights)) as scope: # Calculate per-example average precision, and apply weights. average_precision = _sparse_average_precision_at_top_k( predictions_idx=predictions_idx, labels=labels) if weights is not None: weights = weights_broadcast_ops.broadcast_weights( math_ops.cast(weights, dtypes.float64), average_precision) average_precision = math_ops.multiply(average_precision, weights) # Create accumulation variables and update ops for max average precision and # total average precision. with ops.name_scope(None, 'max', (average_precision,)) as max_scope: # `max` is the max possible precision. Since max for any row is 1.0: # - For the unweighted case, this is just the number of rows. # - For the weighted case, it's the sum of the weights broadcast across # `average_precision` rows. max_var = metric_variable([], dtypes.float64, name=max_scope) if weights is None: batch_max = math_ops.cast( array_ops.size(average_precision, name='batch_max'), dtypes.float64) else: batch_max = math_ops.reduce_sum(weights, name='batch_max') max_update = state_ops.assign_add(max_var, batch_max, name='update') with ops.name_scope(None, 'total', (average_precision,)) as total_scope: total_var = metric_variable([], dtypes.float64, name=total_scope) batch_total = math_ops.reduce_sum(average_precision, name='batch_total') total_update = state_ops.assign_add(total_var, batch_total, name='update') # Divide total by max to get mean, for both vars and the update ops. def precision_across_replicas(_, total_var, max_var): return _safe_scalar_div(total_var, max_var, name='mean') mean_average_precision = _aggregate_across_replicas( metrics_collections, precision_across_replicas, total_var, max_var) update = _safe_scalar_div(total_update, max_update, name=scope) if updates_collections: ops.add_to_collections(updates_collections, update) return mean_average_precision, update
[ "def", "_streaming_sparse_average_precision_at_top_k", "(", "labels", ",", "predictions_idx", ",", "weights", "=", "None", ",", "metrics_collections", "=", "None", ",", "updates_collections", "=", "None", ",", "name", "=", "None", ")", ":", "with", "ops", ".", "name_scope", "(", "name", ",", "'average_precision_at_top_k'", ",", "(", "predictions_idx", ",", "labels", ",", "weights", ")", ")", "as", "scope", ":", "# Calculate per-example average precision, and apply weights.", "average_precision", "=", "_sparse_average_precision_at_top_k", "(", "predictions_idx", "=", "predictions_idx", ",", "labels", "=", "labels", ")", "if", "weights", "is", "not", "None", ":", "weights", "=", "weights_broadcast_ops", ".", "broadcast_weights", "(", "math_ops", ".", "cast", "(", "weights", ",", "dtypes", ".", "float64", ")", ",", "average_precision", ")", "average_precision", "=", "math_ops", ".", "multiply", "(", "average_precision", ",", "weights", ")", "# Create accumulation variables and update ops for max average precision and", "# total average precision.", "with", "ops", ".", "name_scope", "(", "None", ",", "'max'", ",", "(", "average_precision", ",", ")", ")", "as", "max_scope", ":", "# `max` is the max possible precision. Since max for any row is 1.0:", "# - For the unweighted case, this is just the number of rows.", "# - For the weighted case, it's the sum of the weights broadcast across", "# `average_precision` rows.", "max_var", "=", "metric_variable", "(", "[", "]", ",", "dtypes", ".", "float64", ",", "name", "=", "max_scope", ")", "if", "weights", "is", "None", ":", "batch_max", "=", "math_ops", ".", "cast", "(", "array_ops", ".", "size", "(", "average_precision", ",", "name", "=", "'batch_max'", ")", ",", "dtypes", ".", "float64", ")", "else", ":", "batch_max", "=", "math_ops", ".", "reduce_sum", "(", "weights", ",", "name", "=", "'batch_max'", ")", "max_update", "=", "state_ops", ".", "assign_add", "(", "max_var", ",", "batch_max", ",", "name", "=", "'update'", ")", "with", "ops", ".", "name_scope", "(", "None", ",", "'total'", ",", "(", "average_precision", ",", ")", ")", "as", "total_scope", ":", "total_var", "=", "metric_variable", "(", "[", "]", ",", "dtypes", ".", "float64", ",", "name", "=", "total_scope", ")", "batch_total", "=", "math_ops", ".", "reduce_sum", "(", "average_precision", ",", "name", "=", "'batch_total'", ")", "total_update", "=", "state_ops", ".", "assign_add", "(", "total_var", ",", "batch_total", ",", "name", "=", "'update'", ")", "# Divide total by max to get mean, for both vars and the update ops.", "def", "precision_across_replicas", "(", "_", ",", "total_var", ",", "max_var", ")", ":", "return", "_safe_scalar_div", "(", "total_var", ",", "max_var", ",", "name", "=", "'mean'", ")", "mean_average_precision", "=", "_aggregate_across_replicas", "(", "metrics_collections", ",", "precision_across_replicas", ",", "total_var", ",", "max_var", ")", "update", "=", "_safe_scalar_div", "(", "total_update", ",", "max_update", ",", "name", "=", "scope", ")", "if", "updates_collections", ":", "ops", ".", "add_to_collections", "(", "updates_collections", ",", "update", ")", "return", "mean_average_precision", ",", "update" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/tensorflow/python/ops/metrics_impl.py#L3083-L3173