nwo
stringlengths
5
86
sha
stringlengths
40
40
path
stringlengths
4
189
language
stringclasses
1 value
identifier
stringlengths
1
94
parameters
stringlengths
2
4.03k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
11.5k
docstring
stringlengths
1
33.2k
docstring_summary
stringlengths
0
5.15k
docstring_tokens
list
function
stringlengths
34
151k
function_tokens
list
url
stringlengths
90
278
FreeCAD/FreeCAD
ba42231b9c6889b89e064d6d563448ed81e376ec
src/Mod/Path/PathScripts/PathGeom.py
python
Side.toString
(cls, side)
return "On"
toString(side) Returns a string representation of the enum value.
toString(side) Returns a string representation of the enum value.
[ "toString", "(", "side", ")", "Returns", "a", "string", "representation", "of", "the", "enum", "value", "." ]
def toString(cls, side): """toString(side) Returns a string representation of the enum value.""" if side == cls.Left: return "Left" if side == cls.Right: return "Right" return "On"
[ "def", "toString", "(", "cls", ",", "side", ")", ":", "if", "side", "==", "cls", ".", "Left", ":", "return", "\"Left\"", "if", "side", "==", "cls", ".", "Right", ":", "return", "\"Right\"", "return", "\"On\"" ]
https://github.com/FreeCAD/FreeCAD/blob/ba42231b9c6889b89e064d6d563448ed81e376ec/src/Mod/Path/PathScripts/PathGeom.py#L62-L69
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/setuptools/command/build_py.py
python
build_py.__getattr__
(self, attr)
return orig.build_py.__getattr__(self, attr)
lazily compute data files
lazily compute data files
[ "lazily", "compute", "data", "files" ]
def __getattr__(self, attr): "lazily compute data files" if attr == 'data_files': self.data_files = self._get_data_files() return self.data_files return orig.build_py.__getattr__(self, attr)
[ "def", "__getattr__", "(", "self", ",", "attr", ")", ":", "if", "attr", "==", "'data_files'", ":", "self", ".", "data_files", "=", "self", ".", "_get_data_files", "(", ")", "return", "self", ".", "data_files", "return", "orig", ".", "build_py", ".", "__getattr__", "(", "self", ",", "attr", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/setuptools/command/build_py.py#L63-L68
kevinlin311tw/cvpr16-deepbit
c60fb3233d7d534cfcee9d3ed47d77af437ee32a
scripts/cpp_lint.py
python
ReplaceAll
(pattern, rep, s)
return _regexp_compile_cache[pattern].sub(rep, s)
Replaces instances of pattern in a string with a replacement. The compiled regex is kept in a cache shared by Match and Search. Args: pattern: regex pattern rep: replacement text s: search string Returns: string with replacements made (or original string if no replacements)
Replaces instances of pattern in a string with a replacement.
[ "Replaces", "instances", "of", "pattern", "in", "a", "string", "with", "a", "replacement", "." ]
def ReplaceAll(pattern, rep, s): """Replaces instances of pattern in a string with a replacement. The compiled regex is kept in a cache shared by Match and Search. Args: pattern: regex pattern rep: replacement text s: search string Returns: string with replacements made (or original string if no replacements) """ if pattern not in _regexp_compile_cache: _regexp_compile_cache[pattern] = sre_compile.compile(pattern) return _regexp_compile_cache[pattern].sub(rep, s)
[ "def", "ReplaceAll", "(", "pattern", ",", "rep", ",", "s", ")", ":", "if", "pattern", "not", "in", "_regexp_compile_cache", ":", "_regexp_compile_cache", "[", "pattern", "]", "=", "sre_compile", ".", "compile", "(", "pattern", ")", "return", "_regexp_compile_cache", "[", "pattern", "]", ".", "sub", "(", "rep", ",", "s", ")" ]
https://github.com/kevinlin311tw/cvpr16-deepbit/blob/c60fb3233d7d534cfcee9d3ed47d77af437ee32a/scripts/cpp_lint.py#L525-L540
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py
python
OptionMenu.__init__
(self, master, variable, value, *values, **kwargs)
Construct an optionmenu widget with the parent MASTER, with the resource textvariable set to VARIABLE, the initially selected value VALUE, the other menu values VALUES and an additional keyword argument command.
Construct an optionmenu widget with the parent MASTER, with the resource textvariable set to VARIABLE, the initially selected value VALUE, the other menu values VALUES and an additional keyword argument command.
[ "Construct", "an", "optionmenu", "widget", "with", "the", "parent", "MASTER", "with", "the", "resource", "textvariable", "set", "to", "VARIABLE", "the", "initially", "selected", "value", "VALUE", "the", "other", "menu", "values", "VALUES", "and", "an", "additional", "keyword", "argument", "command", "." ]
def __init__(self, master, variable, value, *values, **kwargs): """Construct an optionmenu widget with the parent MASTER, with the resource textvariable set to VARIABLE, the initially selected value VALUE, the other menu values VALUES and an additional keyword argument command.""" kw = {"borderwidth": 2, "textvariable": variable, "indicatoron": 1, "relief": RAISED, "anchor": "c", "highlightthickness": 2} Widget.__init__(self, master, "menubutton", kw) self.widgetName = 'tk_optionMenu' menu = self.__menu = Menu(self, name="menu", tearoff=0) self.menuname = menu._w # 'command' is the only supported keyword callback = kwargs.get('command') if 'command' in kwargs: del kwargs['command'] if kwargs: raise TclError('unknown option -'+kwargs.keys()[0]) menu.add_command(label=value, command=_setit(variable, value, callback)) for v in values: menu.add_command(label=v, command=_setit(variable, v, callback)) self["menu"] = menu
[ "def", "__init__", "(", "self", ",", "master", ",", "variable", ",", "value", ",", "*", "values", ",", "*", "*", "kwargs", ")", ":", "kw", "=", "{", "\"borderwidth\"", ":", "2", ",", "\"textvariable\"", ":", "variable", ",", "\"indicatoron\"", ":", "1", ",", "\"relief\"", ":", "RAISED", ",", "\"anchor\"", ":", "\"c\"", ",", "\"highlightthickness\"", ":", "2", "}", "Widget", ".", "__init__", "(", "self", ",", "master", ",", "\"menubutton\"", ",", "kw", ")", "self", ".", "widgetName", "=", "'tk_optionMenu'", "menu", "=", "self", ".", "__menu", "=", "Menu", "(", "self", ",", "name", "=", "\"menu\"", ",", "tearoff", "=", "0", ")", "self", ".", "menuname", "=", "menu", ".", "_w", "# 'command' is the only supported keyword", "callback", "=", "kwargs", ".", "get", "(", "'command'", ")", "if", "'command'", "in", "kwargs", ":", "del", "kwargs", "[", "'command'", "]", "if", "kwargs", ":", "raise", "TclError", "(", "'unknown option -'", "+", "kwargs", ".", "keys", "(", ")", "[", "0", "]", ")", "menu", ".", "add_command", "(", "label", "=", "value", ",", "command", "=", "_setit", "(", "variable", ",", "value", ",", "callback", ")", ")", "for", "v", "in", "values", ":", "menu", ".", "add_command", "(", "label", "=", "v", ",", "command", "=", "_setit", "(", "variable", ",", "v", ",", "callback", ")", ")", "self", "[", "\"menu\"", "]", "=", "menu" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L3446-L3469
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/labelbook.py
python
LabelContainer.Resize
(self, event)
Actually resizes the tab area. :param `event`: an instance of :class:`SizeEvent`.
Actually resizes the tab area.
[ "Actually", "resizes", "the", "tab", "area", "." ]
def Resize(self, event): """ Actually resizes the tab area. :param `event`: an instance of :class:`SizeEvent`. """ # Resize our size self._tabAreaSize = self.GetSize() newWidth = self._tabAreaSize.x x = event.GetX() if self.HasAGWFlag(INB_BOTTOM) or self.HasAGWFlag(INB_RIGHT): newWidth -= event.GetX() else: newWidth = x if newWidth < 100: # Dont allow width to be lower than that newWidth = 100 self.SetSizeHints(newWidth, self._tabAreaSize.y) # Update the tab new area width self._nTabAreaWidth = newWidth self.GetParent().Freeze() self.GetParent().GetSizer().Layout() self.GetParent().Thaw()
[ "def", "Resize", "(", "self", ",", "event", ")", ":", "# Resize our size", "self", ".", "_tabAreaSize", "=", "self", ".", "GetSize", "(", ")", "newWidth", "=", "self", ".", "_tabAreaSize", ".", "x", "x", "=", "event", ".", "GetX", "(", ")", "if", "self", ".", "HasAGWFlag", "(", "INB_BOTTOM", ")", "or", "self", ".", "HasAGWFlag", "(", "INB_RIGHT", ")", ":", "newWidth", "-=", "event", ".", "GetX", "(", ")", "else", ":", "newWidth", "=", "x", "if", "newWidth", "<", "100", ":", "# Dont allow width to be lower than that ", "newWidth", "=", "100", "self", ".", "SetSizeHints", "(", "newWidth", ",", "self", ".", "_tabAreaSize", ".", "y", ")", "# Update the tab new area width", "self", ".", "_nTabAreaWidth", "=", "newWidth", "self", ".", "GetParent", "(", ")", ".", "Freeze", "(", ")", "self", ".", "GetParent", "(", ")", ".", "GetSizer", "(", ")", ".", "Layout", "(", ")", "self", ".", "GetParent", "(", ")", ".", "Thaw", "(", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/labelbook.py#L1761-L1790
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py
python
Wm.wm_iconposition
(self, x=None, y=None)
return self._getints(self.tk.call( 'wm', 'iconposition', self._w, x, y))
Set the position of the icon of this widget to X and Y. Return a tuple of the current values of X and X if None is given.
Set the position of the icon of this widget to X and Y. Return a tuple of the current values of X and X if None is given.
[ "Set", "the", "position", "of", "the", "icon", "of", "this", "widget", "to", "X", "and", "Y", ".", "Return", "a", "tuple", "of", "the", "current", "values", "of", "X", "and", "X", "if", "None", "is", "given", "." ]
def wm_iconposition(self, x=None, y=None): """Set the position of the icon of this widget to X and Y. Return a tuple of the current values of X and X if None is given.""" return self._getints(self.tk.call( 'wm', 'iconposition', self._w, x, y))
[ "def", "wm_iconposition", "(", "self", ",", "x", "=", "None", ",", "y", "=", "None", ")", ":", "return", "self", ".", "_getints", "(", "self", ".", "tk", ".", "call", "(", "'wm'", ",", "'iconposition'", ",", "self", ".", "_w", ",", "x", ",", "y", ")", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L1912-L1916
CRYTEK/CRYENGINE
232227c59a220cbbd311576f0fbeba7bb53b2a8c
Editor/Python/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py
python
WorkingSet.add_entry
(self, entry)
Add a path item to ``.entries``, finding any distributions on it ``find_distributions(entry, True)`` is used to find distributions corresponding to the path entry, and they are added. `entry` is always appended to ``.entries``, even if it is already present. (This is because ``sys.path`` can contain the same value more than once, and the ``.entries`` of the ``sys.path`` WorkingSet should always equal ``sys.path``.)
Add a path item to ``.entries``, finding any distributions on it
[ "Add", "a", "path", "item", "to", ".", "entries", "finding", "any", "distributions", "on", "it" ]
def add_entry(self, entry): """Add a path item to ``.entries``, finding any distributions on it ``find_distributions(entry, True)`` is used to find distributions corresponding to the path entry, and they are added. `entry` is always appended to ``.entries``, even if it is already present. (This is because ``sys.path`` can contain the same value more than once, and the ``.entries`` of the ``sys.path`` WorkingSet should always equal ``sys.path``.) """ self.entry_keys.setdefault(entry, []) self.entries.append(entry) for dist in find_distributions(entry, True): self.add(dist, entry, False)
[ "def", "add_entry", "(", "self", ",", "entry", ")", ":", "self", ".", "entry_keys", ".", "setdefault", "(", "entry", ",", "[", "]", ")", "self", ".", "entries", ".", "append", "(", "entry", ")", "for", "dist", "in", "find_distributions", "(", "entry", ",", "True", ")", ":", "self", ".", "add", "(", "dist", ",", "entry", ",", "False", ")" ]
https://github.com/CRYTEK/CRYENGINE/blob/232227c59a220cbbd311576f0fbeba7bb53b2a8c/Editor/Python/windows/Lib/site-packages/pip/_vendor/pkg_resources/__init__.py#L661-L674
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/auth.py
python
HTTPDigestAuth.handle_redirect
(self, r, **kwargs)
Reset num_401_calls counter on redirects.
Reset num_401_calls counter on redirects.
[ "Reset", "num_401_calls", "counter", "on", "redirects", "." ]
def handle_redirect(self, r, **kwargs): """Reset num_401_calls counter on redirects.""" if r.is_redirect: self.num_401_calls = 1
[ "def", "handle_redirect", "(", "self", ",", "r", ",", "*", "*", "kwargs", ")", ":", "if", "r", ".", "is_redirect", ":", "self", ".", "num_401_calls", "=", "1" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/botocore/vendored/requests/auth.py#L158-L161
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/pytables.py
python
IndexCol.__eq__
(self, other: Any)
return all( getattr(self, a, None) == getattr(other, a, None) for a in ["name", "cname", "axis", "pos"] )
compare 2 col items
compare 2 col items
[ "compare", "2", "col", "items" ]
def __eq__(self, other: Any) -> bool: """ compare 2 col items """ return all( getattr(self, a, None) == getattr(other, a, None) for a in ["name", "cname", "axis", "pos"] )
[ "def", "__eq__", "(", "self", ",", "other", ":", "Any", ")", "->", "bool", ":", "return", "all", "(", "getattr", "(", "self", ",", "a", ",", "None", ")", "==", "getattr", "(", "other", ",", "a", ",", "None", ")", "for", "a", "in", "[", "\"name\"", ",", "\"cname\"", ",", "\"axis\"", ",", "\"pos\"", "]", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/io/pytables.py#L1925-L1930
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/python/ops/gradients_impl.py
python
_VerifyGeneratedGradients
(grads, op)
Verify that gradients are valid in number and type. Args: grads: List of generated gradients. op: Operation for which the gradients where generated. Raises: ValueError: if sizes of gradients and inputs don't match. TypeError: if type of any gradient is not valid for its input.
Verify that gradients are valid in number and type.
[ "Verify", "that", "gradients", "are", "valid", "in", "number", "and", "type", "." ]
def _VerifyGeneratedGradients(grads, op): """Verify that gradients are valid in number and type. Args: grads: List of generated gradients. op: Operation for which the gradients where generated. Raises: ValueError: if sizes of gradients and inputs don't match. TypeError: if type of any gradient is not valid for its input. """ if len(grads) != len(op.inputs): raise ValueError("Num gradients %d generated for op %s do not match num " "inputs %d" % (len(grads), op.node_def, len(op.inputs)))
[ "def", "_VerifyGeneratedGradients", "(", "grads", ",", "op", ")", ":", "if", "len", "(", "grads", ")", "!=", "len", "(", "op", ".", "inputs", ")", ":", "raise", "ValueError", "(", "\"Num gradients %d generated for op %s do not match num \"", "\"inputs %d\"", "%", "(", "len", "(", "grads", ")", ",", "op", ".", "node_def", ",", "len", "(", "op", ".", "inputs", ")", ")", ")" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/python/ops/gradients_impl.py#L286-L299
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/decimal.py
python
Context.compare_total
(self, a, b)
return a.compare_total(b)
Compares two operands using their abstract representation. This is not like the standard compare, which use their numerical value. Note that a total ordering is defined for all possible abstract representations. >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9')) Decimal('-1') >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12')) Decimal('-1') >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3')) Decimal('-1') >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30')) Decimal('0') >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300')) Decimal('1') >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN')) Decimal('-1') >>> ExtendedContext.compare_total(1, 2) Decimal('-1') >>> ExtendedContext.compare_total(Decimal(1), 2) Decimal('-1') >>> ExtendedContext.compare_total(1, Decimal(2)) Decimal('-1')
Compares two operands using their abstract representation.
[ "Compares", "two", "operands", "using", "their", "abstract", "representation", "." ]
def compare_total(self, a, b): """Compares two operands using their abstract representation. This is not like the standard compare, which use their numerical value. Note that a total ordering is defined for all possible abstract representations. >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9')) Decimal('-1') >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12')) Decimal('-1') >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3')) Decimal('-1') >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30')) Decimal('0') >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300')) Decimal('1') >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN')) Decimal('-1') >>> ExtendedContext.compare_total(1, 2) Decimal('-1') >>> ExtendedContext.compare_total(Decimal(1), 2) Decimal('-1') >>> ExtendedContext.compare_total(1, Decimal(2)) Decimal('-1') """ a = _convert_other(a, raiseit=True) return a.compare_total(b)
[ "def", "compare_total", "(", "self", ",", "a", ",", "b", ")", ":", "a", "=", "_convert_other", "(", "a", ",", "raiseit", "=", "True", ")", "return", "a", ".", "compare_total", "(", "b", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/decimal.py#L4084-L4111
cvxpy/cvxpy
5165b4fb750dfd237de8659383ef24b4b2e33aaf
cvxpy/atoms/affine/binary_operators.py
python
multiply.numeric
(self, values)
Multiplies the values elementwise.
Multiplies the values elementwise.
[ "Multiplies", "the", "values", "elementwise", "." ]
def numeric(self, values): """Multiplies the values elementwise. """ if sp.issparse(values[0]): return values[0].multiply(values[1]) elif sp.issparse(values[1]): return values[1].multiply(values[0]) else: return np.multiply(values[0], values[1])
[ "def", "numeric", "(", "self", ",", "values", ")", ":", "if", "sp", ".", "issparse", "(", "values", "[", "0", "]", ")", ":", "return", "values", "[", "0", "]", ".", "multiply", "(", "values", "[", "1", "]", ")", "elif", "sp", ".", "issparse", "(", "values", "[", "1", "]", ")", ":", "return", "values", "[", "1", "]", ".", "multiply", "(", "values", "[", "0", "]", ")", "else", ":", "return", "np", ".", "multiply", "(", "values", "[", "0", "]", ",", "values", "[", "1", "]", ")" ]
https://github.com/cvxpy/cvxpy/blob/5165b4fb750dfd237de8659383ef24b4b2e33aaf/cvxpy/atoms/affine/binary_operators.py#L265-L273
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py3/scipy/odr/odrpack.py
python
ODR.restart
(self, iter=None)
return self.run()
Restarts the run with iter more iterations. Parameters ---------- iter : int, optional ODRPACK's default for the number of new iterations is 10. Returns ------- output : Output instance This object is also assigned to the attribute .output .
Restarts the run with iter more iterations.
[ "Restarts", "the", "run", "with", "iter", "more", "iterations", "." ]
def restart(self, iter=None): """ Restarts the run with iter more iterations. Parameters ---------- iter : int, optional ODRPACK's default for the number of new iterations is 10. Returns ------- output : Output instance This object is also assigned to the attribute .output . """ if self.output is None: raise OdrError("cannot restart: run() has not been called before") self.set_job(restart=1) self.work = self.output.work self.iwork = self.output.iwork self.maxit = iter return self.run()
[ "def", "restart", "(", "self", ",", "iter", "=", "None", ")", ":", "if", "self", ".", "output", "is", "None", ":", "raise", "OdrError", "(", "\"cannot restart: run() has not been called before\"", ")", "self", ".", "set_job", "(", "restart", "=", "1", ")", "self", ".", "work", "=", "self", ".", "output", ".", "work", "self", ".", "iwork", "=", "self", ".", "output", ".", "iwork", "self", ".", "maxit", "=", "iter", "return", "self", ".", "run", "(", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py3/scipy/odr/odrpack.py#L1107-L1130
rdiankov/openrave
d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7
python/ikfast.py
python
IKFastSolver.iterateThreeNonIntersectingAxes
(self, solvejointvars, Links, LinksInv)
check for three consecutive non-intersecting axes. if several points exist, so have to choose one that is least complex?
check for three consecutive non-intersecting axes. if several points exist, so have to choose one that is least complex?
[ "check", "for", "three", "consecutive", "non", "-", "intersecting", "axes", ".", "if", "several", "points", "exist", "so", "have", "to", "choose", "one", "that", "is", "least", "complex?" ]
def iterateThreeNonIntersectingAxes(self, solvejointvars, Links, LinksInv): """check for three consecutive non-intersecting axes. if several points exist, so have to choose one that is least complex? """ ilinks = [i for i,Tlink in enumerate(Links) if self.has(Tlink,*solvejointvars)] usedindices = [] for imode in range(2): for i in range(len(ilinks)-2): if i in usedindices: continue startindex = ilinks[i] endindex = ilinks[i+2]+1 p0 = self.multiplyMatrix(Links[ilinks[i]:ilinks[i+1]])[0:3,3] p1 = self.multiplyMatrix(Links[ilinks[i+1]:ilinks[i+2]])[0:3,3] has0 = self.has(p0,*solvejointvars) has1 = self.has(p1,*solvejointvars) if (imode == 0 and has0 and has1) or (imode == 1 and (has0 or has1)): T0links = Links[startindex:endindex] T1links = LinksInv[:startindex][::-1] T1links.append(self.Tee) T1links += LinksInv[endindex:][::-1] usedindices.append(i) usedvars = [var for var in solvejointvars if any([self.has(T0,var) for T0 in T0links])] log.info('found 3 consecutive non-intersecting axes links[%d:%d], vars=%s',startindex,endindex,str(usedvars)) yield T0links, T1links
[ "def", "iterateThreeNonIntersectingAxes", "(", "self", ",", "solvejointvars", ",", "Links", ",", "LinksInv", ")", ":", "ilinks", "=", "[", "i", "for", "i", ",", "Tlink", "in", "enumerate", "(", "Links", ")", "if", "self", ".", "has", "(", "Tlink", ",", "*", "solvejointvars", ")", "]", "usedindices", "=", "[", "]", "for", "imode", "in", "range", "(", "2", ")", ":", "for", "i", "in", "range", "(", "len", "(", "ilinks", ")", "-", "2", ")", ":", "if", "i", "in", "usedindices", ":", "continue", "startindex", "=", "ilinks", "[", "i", "]", "endindex", "=", "ilinks", "[", "i", "+", "2", "]", "+", "1", "p0", "=", "self", ".", "multiplyMatrix", "(", "Links", "[", "ilinks", "[", "i", "]", ":", "ilinks", "[", "i", "+", "1", "]", "]", ")", "[", "0", ":", "3", ",", "3", "]", "p1", "=", "self", ".", "multiplyMatrix", "(", "Links", "[", "ilinks", "[", "i", "+", "1", "]", ":", "ilinks", "[", "i", "+", "2", "]", "]", ")", "[", "0", ":", "3", ",", "3", "]", "has0", "=", "self", ".", "has", "(", "p0", ",", "*", "solvejointvars", ")", "has1", "=", "self", ".", "has", "(", "p1", ",", "*", "solvejointvars", ")", "if", "(", "imode", "==", "0", "and", "has0", "and", "has1", ")", "or", "(", "imode", "==", "1", "and", "(", "has0", "or", "has1", ")", ")", ":", "T0links", "=", "Links", "[", "startindex", ":", "endindex", "]", "T1links", "=", "LinksInv", "[", ":", "startindex", "]", "[", ":", ":", "-", "1", "]", "T1links", ".", "append", "(", "self", ".", "Tee", ")", "T1links", "+=", "LinksInv", "[", "endindex", ":", "]", "[", ":", ":", "-", "1", "]", "usedindices", ".", "append", "(", "i", ")", "usedvars", "=", "[", "var", "for", "var", "in", "solvejointvars", "if", "any", "(", "[", "self", ".", "has", "(", "T0", ",", "var", ")", "for", "T0", "in", "T0links", "]", ")", "]", "log", ".", "info", "(", "'found 3 consecutive non-intersecting axes links[%d:%d], vars=%s'", ",", "startindex", ",", "endindex", ",", "str", "(", "usedvars", ")", ")", "yield", "T0links", ",", "T1links" ]
https://github.com/rdiankov/openrave/blob/d1a23023fd4b58f077d2ca949ceaf1b91f3f13d7/python/ikfast.py#L3146-L3170
ChromiumWebApps/chromium
c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7
net/tools/quic/benchmark/run_client.py
python
PageloadExperiment.__init__
(self, use_wget, quic_binary_dir, quic_server_address, quic_server_port)
Initialize PageloadExperiment. Args: use_wget: Whether to use wget. quic_binary_dir: Directory for quic_binary. quic_server_address: IP address of quic server. quic_server_port: Port of the quic server.
Initialize PageloadExperiment.
[ "Initialize", "PageloadExperiment", "." ]
def __init__(self, use_wget, quic_binary_dir, quic_server_address, quic_server_port): """Initialize PageloadExperiment. Args: use_wget: Whether to use wget. quic_binary_dir: Directory for quic_binary. quic_server_address: IP address of quic server. quic_server_port: Port of the quic server. """ self.use_wget = use_wget self.quic_binary_dir = quic_binary_dir self.quic_server_address = quic_server_address self.quic_server_port = quic_server_port if not use_wget and not os.path.isfile(quic_binary_dir + '/quic_client'): raise IOError('There is no quic_client in the given dir: %s.' % quic_binary_dir)
[ "def", "__init__", "(", "self", ",", "use_wget", ",", "quic_binary_dir", ",", "quic_server_address", ",", "quic_server_port", ")", ":", "self", ".", "use_wget", "=", "use_wget", "self", ".", "quic_binary_dir", "=", "quic_binary_dir", "self", ".", "quic_server_address", "=", "quic_server_address", "self", ".", "quic_server_port", "=", "quic_server_port", "if", "not", "use_wget", "and", "not", "os", ".", "path", ".", "isfile", "(", "quic_binary_dir", "+", "'/quic_client'", ")", ":", "raise", "IOError", "(", "'There is no quic_client in the given dir: %s.'", "%", "quic_binary_dir", ")" ]
https://github.com/ChromiumWebApps/chromium/blob/c7361d39be8abd1574e6ce8957c8dbddd4c6ccf7/net/tools/quic/benchmark/run_client.py#L44-L60
NVIDIA/TensorRT
42805f078052daad1a98bc5965974fcffaad0960
tools/onnx-graphsurgeon/onnx_graphsurgeon/ir/tensor.py
python
LazyValues.load
(self)
return np.array(onnx.numpy_helper.to_array(self.tensor))
Load a numpy array from the underlying tensor values. Returns: np.array: A numpy array containing the values of the tensor.
Load a numpy array from the underlying tensor values.
[ "Load", "a", "numpy", "array", "from", "the", "underlying", "tensor", "values", "." ]
def load(self): """ Load a numpy array from the underlying tensor values. Returns: np.array: A numpy array containing the values of the tensor. """ import onnx import onnx.numpy_helper return np.array(onnx.numpy_helper.to_array(self.tensor))
[ "def", "load", "(", "self", ")", ":", "import", "onnx", "import", "onnx", ".", "numpy_helper", "return", "np", ".", "array", "(", "onnx", ".", "numpy_helper", ".", "to_array", "(", "self", ".", "tensor", ")", ")" ]
https://github.com/NVIDIA/TensorRT/blob/42805f078052daad1a98bc5965974fcffaad0960/tools/onnx-graphsurgeon/onnx_graphsurgeon/ir/tensor.py#L196-L206
cms-sw/cmssw
fd9de012d503d3405420bcbeec0ec879baa57cf2
CondCore/Utilities/python/CondDBFW/uploads.py
python
uploader.get_hashes_to_send
(self, upload_session_id)
return response
Get the hashes of the payloads we want to send that the server doesn't have yet.
Get the hashes of the payloads we want to send that the server doesn't have yet.
[ "Get", "the", "hashes", "of", "the", "payloads", "we", "want", "to", "send", "that", "the", "server", "doesn", "t", "have", "yet", "." ]
def get_hashes_to_send(self, upload_session_id): """ Get the hashes of the payloads we want to send that the server doesn't have yet. """ self._outputter.write("Getting list of hashes that the server does not have Payloads for, to send to server.") post_data = json.dumps(self.get_all_hashes()) url_data = {"database" : self.data_to_send["destinationDatabase"], "upload_session_id" : upload_session_id} query = url_query(url=self._SERVICE_URL + "check_hashes/", url_data=url_data, body=post_data) response = query.send() return response
[ "def", "get_hashes_to_send", "(", "self", ",", "upload_session_id", ")", ":", "self", ".", "_outputter", ".", "write", "(", "\"Getting list of hashes that the server does not have Payloads for, to send to server.\"", ")", "post_data", "=", "json", ".", "dumps", "(", "self", ".", "get_all_hashes", "(", ")", ")", "url_data", "=", "{", "\"database\"", ":", "self", ".", "data_to_send", "[", "\"destinationDatabase\"", "]", ",", "\"upload_session_id\"", ":", "upload_session_id", "}", "query", "=", "url_query", "(", "url", "=", "self", ".", "_SERVICE_URL", "+", "\"check_hashes/\"", ",", "url_data", "=", "url_data", ",", "body", "=", "post_data", ")", "response", "=", "query", ".", "send", "(", ")", "return", "response" ]
https://github.com/cms-sw/cmssw/blob/fd9de012d503d3405420bcbeec0ec879baa57cf2/CondCore/Utilities/python/CondDBFW/uploads.py#L625-L634
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/decomposition/nmf.py
python
_update_projected_gradient_h
(X, W, H, tolH, nls_max_iter, alpha, l1_ratio, sparseness, beta, eta)
return H, gradH, iterH
Helper function for _fit_projected_gradient
Helper function for _fit_projected_gradient
[ "Helper", "function", "for", "_fit_projected_gradient" ]
def _update_projected_gradient_h(X, W, H, tolH, nls_max_iter, alpha, l1_ratio, sparseness, beta, eta): """Helper function for _fit_projected_gradient""" n_samples, n_features = X.shape n_components_ = W.shape[1] if sparseness is None: H, gradH, iterH = _nls_subproblem(X, W, H, tolH, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio) elif sparseness == 'data': H, gradH, iterH = _nls_subproblem( safe_vstack([X, np.zeros((n_components_, n_features))]), safe_vstack([W, np.sqrt(eta) * np.eye(n_components_)]), H, tolH, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio) elif sparseness == 'components': H, gradH, iterH = _nls_subproblem( safe_vstack([X, np.zeros((1, n_features))]), safe_vstack([W, np.sqrt(beta) * np.ones((1, n_components_))]), H, tolH, nls_max_iter, alpha=alpha, l1_ratio=l1_ratio) return H, gradH, iterH
[ "def", "_update_projected_gradient_h", "(", "X", ",", "W", ",", "H", ",", "tolH", ",", "nls_max_iter", ",", "alpha", ",", "l1_ratio", ",", "sparseness", ",", "beta", ",", "eta", ")", ":", "n_samples", ",", "n_features", "=", "X", ".", "shape", "n_components_", "=", "W", ".", "shape", "[", "1", "]", "if", "sparseness", "is", "None", ":", "H", ",", "gradH", ",", "iterH", "=", "_nls_subproblem", "(", "X", ",", "W", ",", "H", ",", "tolH", ",", "nls_max_iter", ",", "alpha", "=", "alpha", ",", "l1_ratio", "=", "l1_ratio", ")", "elif", "sparseness", "==", "'data'", ":", "H", ",", "gradH", ",", "iterH", "=", "_nls_subproblem", "(", "safe_vstack", "(", "[", "X", ",", "np", ".", "zeros", "(", "(", "n_components_", ",", "n_features", ")", ")", "]", ")", ",", "safe_vstack", "(", "[", "W", ",", "np", ".", "sqrt", "(", "eta", ")", "*", "np", ".", "eye", "(", "n_components_", ")", "]", ")", ",", "H", ",", "tolH", ",", "nls_max_iter", ",", "alpha", "=", "alpha", ",", "l1_ratio", "=", "l1_ratio", ")", "elif", "sparseness", "==", "'components'", ":", "H", ",", "gradH", ",", "iterH", "=", "_nls_subproblem", "(", "safe_vstack", "(", "[", "X", ",", "np", ".", "zeros", "(", "(", "1", ",", "n_features", ")", ")", "]", ")", ",", "safe_vstack", "(", "[", "W", ",", "np", ".", "sqrt", "(", "beta", ")", "*", "np", ".", "ones", "(", "(", "1", ",", "n_components_", ")", ")", "]", ")", ",", "H", ",", "tolH", ",", "nls_max_iter", ",", "alpha", "=", "alpha", ",", "l1_ratio", "=", "l1_ratio", ")", "return", "H", ",", "gradH", ",", "iterH" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/decomposition/nmf.py#L374-L395
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
Pen.GetDashes
(*args, **kwargs)
return _gdi_.Pen_GetDashes(*args, **kwargs)
GetDashes(self) -> PyObject
GetDashes(self) -> PyObject
[ "GetDashes", "(", "self", ")", "-", ">", "PyObject" ]
def GetDashes(*args, **kwargs): """GetDashes(self) -> PyObject""" return _gdi_.Pen_GetDashes(*args, **kwargs)
[ "def", "GetDashes", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "Pen_GetDashes", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L449-L451
larroy/clearskies_core
3574ddf0edc8555454c7044126e786a6c29444dc
tools/gyp/pylib/gyp/msvs_emulation.py
python
MsvsSettings.AdjustIncludeDirs
(self, include_dirs, config)
return [self.ConvertVSMacros(p, config=config) for p in includes]
Updates include_dirs to expand VS specific paths, and adds the system include dirs used for platform SDK and similar.
Updates include_dirs to expand VS specific paths, and adds the system include dirs used for platform SDK and similar.
[ "Updates", "include_dirs", "to", "expand", "VS", "specific", "paths", "and", "adds", "the", "system", "include", "dirs", "used", "for", "platform", "SDK", "and", "similar", "." ]
def AdjustIncludeDirs(self, include_dirs, config): """Updates include_dirs to expand VS specific paths, and adds the system include dirs used for platform SDK and similar.""" config = self._TargetConfig(config) includes = include_dirs + self.msvs_system_include_dirs[config] includes.extend(self._Setting( ('VCCLCompilerTool', 'AdditionalIncludeDirectories'), config, default=[])) return [self.ConvertVSMacros(p, config=config) for p in includes]
[ "def", "AdjustIncludeDirs", "(", "self", ",", "include_dirs", ",", "config", ")", ":", "config", "=", "self", ".", "_TargetConfig", "(", "config", ")", "includes", "=", "include_dirs", "+", "self", ".", "msvs_system_include_dirs", "[", "config", "]", "includes", ".", "extend", "(", "self", ".", "_Setting", "(", "(", "'VCCLCompilerTool'", ",", "'AdditionalIncludeDirectories'", ")", ",", "config", ",", "default", "=", "[", "]", ")", ")", "return", "[", "self", ".", "ConvertVSMacros", "(", "p", ",", "config", "=", "config", ")", "for", "p", "in", "includes", "]" ]
https://github.com/larroy/clearskies_core/blob/3574ddf0edc8555454c7044126e786a6c29444dc/tools/gyp/pylib/gyp/msvs_emulation.py#L279-L286
adobe/chromium
cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7
build/android/android_commands.py
python
AndroidCommands.SearchLogcatRecord
(self, record, message, thread_id=None, proc_id=None, log_level=None, component=None)
return results
Searches the specified logcat output and returns results. This method searches through the logcat output specified by record for a certain message, narrowing results by matching them against any other specified criteria. It returns all matching lines as described below. Args: record: A string generated by Start/StopRecordingLogcat to search. message: An output string to search for. thread_id: The thread id that is the origin of the message. proc_id: The process that is the origin of the message. log_level: The log level of the message. component: The name of the component that would create the message. Returns: A list of dictionaries represeting matching entries, each containing keys thread_id, proc_id, log_level, component, and message.
Searches the specified logcat output and returns results.
[ "Searches", "the", "specified", "logcat", "output", "and", "returns", "results", "." ]
def SearchLogcatRecord(self, record, message, thread_id=None, proc_id=None, log_level=None, component=None): """Searches the specified logcat output and returns results. This method searches through the logcat output specified by record for a certain message, narrowing results by matching them against any other specified criteria. It returns all matching lines as described below. Args: record: A string generated by Start/StopRecordingLogcat to search. message: An output string to search for. thread_id: The thread id that is the origin of the message. proc_id: The process that is the origin of the message. log_level: The log level of the message. component: The name of the component that would create the message. Returns: A list of dictionaries represeting matching entries, each containing keys thread_id, proc_id, log_level, component, and message. """ if thread_id: thread_id = str(thread_id) if proc_id: proc_id = str(proc_id) results = [] reg = re.compile('(\d+)\s+(\d+)\s+([A-Z])\s+([A-Za-z]+)\s*:(.*)$', re.MULTILINE) log_list = reg.findall(record) for (tid, pid, log_lev, comp, msg) in log_list: if ((not thread_id or thread_id == tid) and (not proc_id or proc_id == pid) and (not log_level or log_level == log_lev) and (not component or component == comp) and msg.find(message) > -1): match = dict({'thread_id': tid, 'proc_id': pid, 'log_level': log_lev, 'component': comp, 'message': msg}) results.append(match) return results
[ "def", "SearchLogcatRecord", "(", "self", ",", "record", ",", "message", ",", "thread_id", "=", "None", ",", "proc_id", "=", "None", ",", "log_level", "=", "None", ",", "component", "=", "None", ")", ":", "if", "thread_id", ":", "thread_id", "=", "str", "(", "thread_id", ")", "if", "proc_id", ":", "proc_id", "=", "str", "(", "proc_id", ")", "results", "=", "[", "]", "reg", "=", "re", ".", "compile", "(", "'(\\d+)\\s+(\\d+)\\s+([A-Z])\\s+([A-Za-z]+)\\s*:(.*)$'", ",", "re", ".", "MULTILINE", ")", "log_list", "=", "reg", ".", "findall", "(", "record", ")", "for", "(", "tid", ",", "pid", ",", "log_lev", ",", "comp", ",", "msg", ")", "in", "log_list", ":", "if", "(", "(", "not", "thread_id", "or", "thread_id", "==", "tid", ")", "and", "(", "not", "proc_id", "or", "proc_id", "==", "pid", ")", "and", "(", "not", "log_level", "or", "log_level", "==", "log_lev", ")", "and", "(", "not", "component", "or", "component", "==", "comp", ")", "and", "msg", ".", "find", "(", "message", ")", ">", "-", "1", ")", ":", "match", "=", "dict", "(", "{", "'thread_id'", ":", "tid", ",", "'proc_id'", ":", "pid", ",", "'log_level'", ":", "log_lev", ",", "'component'", ":", "comp", ",", "'message'", ":", "msg", "}", ")", "results", ".", "append", "(", "match", ")", "return", "results" ]
https://github.com/adobe/chromium/blob/cfe5bf0b51b1f6b9fe239c2a3c2f2364da9967d7/build/android/android_commands.py#L629-L666
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/setuptools/py3/setuptools/sandbox.py
python
AbstractSandbox._remap_output
(self, operation, path)
return self._validate_path(path)
Called for path outputs
Called for path outputs
[ "Called", "for", "path", "outputs" ]
def _remap_output(self, operation, path): """Called for path outputs""" return self._validate_path(path)
[ "def", "_remap_output", "(", "self", ",", "operation", ",", "path", ")", ":", "return", "self", ".", "_validate_path", "(", "path", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/setuptools/py3/setuptools/sandbox.py#L390-L392
Kronuz/Xapiand
a71570859dcfc9f48090d845053f359b07f4f78c
contrib/python/xapiand-py/xapiand/client/documents.py
python
DocumentsClient.upsert
(self, index, id, body=None, content_type=None, params=None)
return self.transport.perform_request('UPSERT', make_url(index, id=id), params=params, body=body, headers=content_type and {'content-type': content_type})
Update or create a document based on a partial data provided. :arg index: The name of the index :arg id: Document ID :arg body: The request definition using a partial `doc` :arg selector: A comma-separated list of fields to return in the response :arg timeout: Explicit operation timeout
Update or create a document based on a partial data provided.
[ "Update", "or", "create", "a", "document", "based", "on", "a", "partial", "data", "provided", "." ]
def upsert(self, index, id, body=None, content_type=None, params=None): """ Update or create a document based on a partial data provided. :arg index: The name of the index :arg id: Document ID :arg body: The request definition using a partial `doc` :arg selector: A comma-separated list of fields to return in the response :arg timeout: Explicit operation timeout """ for param in (index, id): if param in SKIP_IN_PATH: raise ValueError("Empty value passed for a required argument.") return self.transport.perform_request('UPSERT', make_url(index, id=id), params=params, body=body, headers=content_type and {'content-type': content_type})
[ "def", "upsert", "(", "self", ",", "index", ",", "id", ",", "body", "=", "None", ",", "content_type", "=", "None", ",", "params", "=", "None", ")", ":", "for", "param", "in", "(", "index", ",", "id", ")", ":", "if", "param", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument.\"", ")", "return", "self", ".", "transport", ".", "perform_request", "(", "'UPSERT'", ",", "make_url", "(", "index", ",", "id", "=", "id", ")", ",", "params", "=", "params", ",", "body", "=", "body", ",", "headers", "=", "content_type", "and", "{", "'content-type'", ":", "content_type", "}", ")" ]
https://github.com/Kronuz/Xapiand/blob/a71570859dcfc9f48090d845053f359b07f4f78c/contrib/python/xapiand-py/xapiand/client/documents.py#L64-L79
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/eager/context.py
python
get_log_device_placement
()
return context().log_device_placement
Get if device placements are logged. Returns: If device placements are logged.
Get if device placements are logged.
[ "Get", "if", "device", "placements", "are", "logged", "." ]
def get_log_device_placement(): """Get if device placements are logged. Returns: If device placements are logged. """ return context().log_device_placement
[ "def", "get_log_device_placement", "(", ")", ":", "return", "context", "(", ")", ".", "log_device_placement" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/context.py#L2348-L2354
GoSSIP-SJTU/TripleDoggy
03648d6b19c812504b14e8b98c8c7b3f443f4e54
tools/clang/tools/scan-build-py/libear/__init__.py
python
Toolset.set_language_standard
(self, standard)
part of public interface
part of public interface
[ "part", "of", "public", "interface" ]
def set_language_standard(self, standard): """ part of public interface """ self.c_flags.append('-std=' + standard)
[ "def", "set_language_standard", "(", "self", ",", "standard", ")", ":", "self", ".", "c_flags", ".", "append", "(", "'-std='", "+", "standard", ")" ]
https://github.com/GoSSIP-SJTU/TripleDoggy/blob/03648d6b19c812504b14e8b98c8c7b3f443f4e54/tools/clang/tools/scan-build-py/libear/__init__.py#L91-L93
albertz/openlierox
d316c14a8eb57848ef56e9bfa7b23a56f694a51b
tools/DedicatedServerVideo/gdata/apps/service.py
python
AppsService.GetGeneratorFromLinkFinder
(self, link_finder, func, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF)
returns a generator for pagination
returns a generator for pagination
[ "returns", "a", "generator", "for", "pagination" ]
def GetGeneratorFromLinkFinder(self, link_finder, func, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """returns a generator for pagination""" yield link_finder next = link_finder.GetNextLink() while next is not None: next_feed = func(str(self.GetWithRetries( next.href, num_retries=num_retries, delay=delay, backoff=backoff))) yield next_feed next = next_feed.GetNextLink()
[ "def", "GetGeneratorFromLinkFinder", "(", "self", ",", "link_finder", ",", "func", ",", "num_retries", "=", "gdata", ".", "service", ".", "DEFAULT_NUM_RETRIES", ",", "delay", "=", "gdata", ".", "service", ".", "DEFAULT_DELAY", ",", "backoff", "=", "gdata", ".", "service", ".", "DEFAULT_BACKOFF", ")", ":", "yield", "link_finder", "next", "=", "link_finder", ".", "GetNextLink", "(", ")", "while", "next", "is", "not", "None", ":", "next_feed", "=", "func", "(", "str", "(", "self", ".", "GetWithRetries", "(", "next", ".", "href", ",", "num_retries", "=", "num_retries", ",", "delay", "=", "delay", ",", "backoff", "=", "backoff", ")", ")", ")", "yield", "next_feed", "next", "=", "next_feed", ".", "GetNextLink", "(", ")" ]
https://github.com/albertz/openlierox/blob/d316c14a8eb57848ef56e9bfa7b23a56f694a51b/tools/DedicatedServerVideo/gdata/apps/service.py#L107-L118
eclipse/sumo
7132a9b8b6eea734bdec38479026b4d8c4336d03
tools/contributed/sumopy/agilepy/lib_wx/objpanel.py
python
NaviPanelMixin.refresh_panel
(self, obj=None, id=None, ids=None, **kwargs)
return None
Deletes previous conents Builds panel for obj Updates path window and history
Deletes previous conents Builds panel for obj Updates path window and history
[ "Deletes", "previous", "conents", "Builds", "panel", "for", "obj", "Updates", "path", "window", "and", "history" ]
def refresh_panel(self, obj=None, id=None, ids=None, **kwargs): """ Deletes previous conents Builds panel for obj Updates path window and history """ if obj is None: if self.get_obj() == self._defaultobj: return None # no changes else: obj = self._defaultobj # print 'Navicanvas.refresh_panel with',obj.ident,kwargs if id is not None: self.path.SetValue(obj.format_ident_row_abs(id)) elif ids is not None: # no id provided, just show identification string self.path.SetValue(obj.format_ident_abs()) else: # object and id provided: compose string with id self.path.SetValue(obj.format_ident_abs()) # self.path.SetSize((len(self.path.GetValue())*10,-1)) # self.path.SetSize((-1,-1)) # remove previous obj panel sizer = self.GetSizer() sizer.Remove(1) self.objpanel.Destroy() #del self.objpanel # build new obj panel # self.objpanel=ObjPanel(self,obj,id=id,attrs=self.attrs,groups=self.groups, # func_change_obj=self.change_obj, # is_modal=self.is_modal, # mainframe=self.mainframe, # immediate_apply=self.immediate_apply, # **self.buttonargs) attrconfigs = obj.get_attrsman().get_configs() # for attrconfig in obj.get_configs()#attrconfigs: # if '_private' not in attrconfig.groups: # attrconfigs.append(attrconfig) args = {'attrconfigs': attrconfigs, # 'tables' : None, # 'table' : None, 'id': id, 'ids': ids, 'groupnames': self.groupnames, 'func_change_obj': self.change_obj, 'show_groupnames': False, 'show_title': True, 'is_modal': self.is_modal, 'mainframe': self.mainframe, 'pos': wx.DefaultPosition, 'size': wx.DefaultSize, 'immediate_apply': self.immediate_apply, 'panelstyle': 'default' } args.update(self.buttonargs) args.update(kwargs) # print ' make ObjPanel\n args =',args self.objpanel = ObjPanel(self, obj=obj, **args) # if id is not None: # self.objpanel=ObjPanel(self,obj,id=id,func_change_obj=self.change_obj) # else: # self.objpanel=ObjPanel(self,obj,func_change_obj=self.change_obj) sizer.Add(self.objpanel, 1, wx.GROW) self.Refresh() # sizer.Fit(self) sizer.Layout() # add to history return None
[ "def", "refresh_panel", "(", "self", ",", "obj", "=", "None", ",", "id", "=", "None", ",", "ids", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "obj", "is", "None", ":", "if", "self", ".", "get_obj", "(", ")", "==", "self", ".", "_defaultobj", ":", "return", "None", "# no changes", "else", ":", "obj", "=", "self", ".", "_defaultobj", "# print 'Navicanvas.refresh_panel with',obj.ident,kwargs", "if", "id", "is", "not", "None", ":", "self", ".", "path", ".", "SetValue", "(", "obj", ".", "format_ident_row_abs", "(", "id", ")", ")", "elif", "ids", "is", "not", "None", ":", "# no id provided, just show identification string", "self", ".", "path", ".", "SetValue", "(", "obj", ".", "format_ident_abs", "(", ")", ")", "else", ":", "# object and id provided: compose string with id", "self", ".", "path", ".", "SetValue", "(", "obj", ".", "format_ident_abs", "(", ")", ")", "# self.path.SetSize((len(self.path.GetValue())*10,-1))", "# self.path.SetSize((-1,-1))", "# remove previous obj panel", "sizer", "=", "self", ".", "GetSizer", "(", ")", "sizer", ".", "Remove", "(", "1", ")", "self", ".", "objpanel", ".", "Destroy", "(", ")", "#del self.objpanel", "# build new obj panel", "# self.objpanel=ObjPanel(self,obj,id=id,attrs=self.attrs,groups=self.groups,", "# func_change_obj=self.change_obj,", "# is_modal=self.is_modal,", "# mainframe=self.mainframe,", "# immediate_apply=self.immediate_apply,", "# **self.buttonargs)", "attrconfigs", "=", "obj", ".", "get_attrsman", "(", ")", ".", "get_configs", "(", ")", "# for attrconfig in obj.get_configs()#attrconfigs:", "# if '_private' not in attrconfig.groups:", "# attrconfigs.append(attrconfig)", "args", "=", "{", "'attrconfigs'", ":", "attrconfigs", ",", "# 'tables' : None,", "# 'table' : None,", "'id'", ":", "id", ",", "'ids'", ":", "ids", ",", "'groupnames'", ":", "self", ".", "groupnames", ",", "'func_change_obj'", ":", "self", ".", "change_obj", ",", "'show_groupnames'", ":", "False", ",", "'show_title'", ":", "True", ",", "'is_modal'", ":", "self", ".", "is_modal", ",", "'mainframe'", ":", "self", ".", "mainframe", ",", "'pos'", ":", "wx", ".", "DefaultPosition", ",", "'size'", ":", "wx", ".", "DefaultSize", ",", "'immediate_apply'", ":", "self", ".", "immediate_apply", ",", "'panelstyle'", ":", "'default'", "}", "args", ".", "update", "(", "self", ".", "buttonargs", ")", "args", ".", "update", "(", "kwargs", ")", "# print ' make ObjPanel\\n args =',args", "self", ".", "objpanel", "=", "ObjPanel", "(", "self", ",", "obj", "=", "obj", ",", "*", "*", "args", ")", "# if id is not None:", "# self.objpanel=ObjPanel(self,obj,id=id,func_change_obj=self.change_obj)", "# else:", "# self.objpanel=ObjPanel(self,obj,func_change_obj=self.change_obj)", "sizer", ".", "Add", "(", "self", ".", "objpanel", ",", "1", ",", "wx", ".", "GROW", ")", "self", ".", "Refresh", "(", ")", "# sizer.Fit(self)", "sizer", ".", "Layout", "(", ")", "# add to history", "return", "None" ]
https://github.com/eclipse/sumo/blob/7132a9b8b6eea734bdec38479026b4d8c4336d03/tools/contributed/sumopy/agilepy/lib_wx/objpanel.py#L4051-L4123
okex/V3-Open-API-SDK
c5abb0db7e2287718e0055e17e57672ce0ec7fd9
okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/six.py
python
remove_move
(name)
Remove item from six.moves.
Remove item from six.moves.
[ "Remove", "item", "from", "six", ".", "moves", "." ]
def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,))
[ "def", "remove_move", "(", "name", ")", ":", "try", ":", "delattr", "(", "_MovedItems", ",", "name", ")", "except", "AttributeError", ":", "try", ":", "del", "moves", ".", "__dict__", "[", "name", "]", "except", "KeyError", ":", "raise", "AttributeError", "(", "\"no such move, %r\"", "%", "(", "name", ",", ")", ")" ]
https://github.com/okex/V3-Open-API-SDK/blob/c5abb0db7e2287718e0055e17e57672ce0ec7fd9/okex-python-sdk-api/venv/Lib/site-packages/pip-19.0.3-py3.8.egg/pip/_vendor/six.py#L497-L505
vgteam/vg
cf4d516a5e9ee5163c783e4437ddf16b18a4b561
scripts/filter_variants_on_repeats.py
python
entrypoint
()
0-argument entry point for setuptools to call.
0-argument entry point for setuptools to call.
[ "0", "-", "argument", "entry", "point", "for", "setuptools", "to", "call", "." ]
def entrypoint(): """ 0-argument entry point for setuptools to call. """ # Provide main with its arguments and handle exit codes sys.exit(main(sys.argv))
[ "def", "entrypoint", "(", ")", ":", "# Provide main with its arguments and handle exit codes", "sys", ".", "exit", "(", "main", "(", "sys", ".", "argv", ")", ")" ]
https://github.com/vgteam/vg/blob/cf4d516a5e9ee5163c783e4437ddf16b18a4b561/scripts/filter_variants_on_repeats.py#L207-L213
Yelp/MOE
5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c
moe/optimal_learning/python/python_version/expected_improvement.py
python
ExpectedImprovement.__init__
( self, gaussian_process, points_to_sample=None, points_being_sampled=None, num_mc_iterations=DEFAULT_EXPECTED_IMPROVEMENT_MC_ITERATIONS, randomness=None, mvndst_parameters=None )
Construct an ExpectedImprovement object that supports q,p-EI. TODO(GH-56): Allow callers to pass in a source of randomness. :param gaussian_process: GaussianProcess describing :type gaussian_process: interfaces.gaussian_process_interface.GaussianProcessInterface subclass :param points_to_sample: points at which to evaluate EI and/or its gradient to check their value in future experiments (i.e., "q" in q,p-EI) :type points_to_sample: array of float64 with shape (num_to_sample, dim) :param points_being_sampled: points being sampled in concurrent experiments (i.e., "p" in q,p-EI) :type points_being_sampled: array of float64 with shape (num_being_sampled, dim) :param num_mc_iterations: number of monte-carlo iterations to use (when monte-carlo integration is used to compute EI) :type num_mc_iterations: int > 0 :param randomness: random source(s) used for monte-carlo integration (when applicable) (UNUSED) :type randomness: (UNUSED)
Construct an ExpectedImprovement object that supports q,p-EI.
[ "Construct", "an", "ExpectedImprovement", "object", "that", "supports", "q", "p", "-", "EI", "." ]
def __init__( self, gaussian_process, points_to_sample=None, points_being_sampled=None, num_mc_iterations=DEFAULT_EXPECTED_IMPROVEMENT_MC_ITERATIONS, randomness=None, mvndst_parameters=None ): """Construct an ExpectedImprovement object that supports q,p-EI. TODO(GH-56): Allow callers to pass in a source of randomness. :param gaussian_process: GaussianProcess describing :type gaussian_process: interfaces.gaussian_process_interface.GaussianProcessInterface subclass :param points_to_sample: points at which to evaluate EI and/or its gradient to check their value in future experiments (i.e., "q" in q,p-EI) :type points_to_sample: array of float64 with shape (num_to_sample, dim) :param points_being_sampled: points being sampled in concurrent experiments (i.e., "p" in q,p-EI) :type points_being_sampled: array of float64 with shape (num_being_sampled, dim) :param num_mc_iterations: number of monte-carlo iterations to use (when monte-carlo integration is used to compute EI) :type num_mc_iterations: int > 0 :param randomness: random source(s) used for monte-carlo integration (when applicable) (UNUSED) :type randomness: (UNUSED) """ self._num_mc_iterations = num_mc_iterations self._gaussian_process = gaussian_process if gaussian_process._points_sampled_value.size > 0: self._best_so_far = numpy.amin(gaussian_process._points_sampled_value) else: self._best_so_far = numpy.finfo(numpy.float64).max if points_being_sampled is None: self._points_being_sampled = numpy.array([]) else: self._points_being_sampled = numpy.copy(points_being_sampled) if points_to_sample is None: self.current_point = numpy.zeros((1, gaussian_process.dim)) else: self.current_point = points_to_sample if mvndst_parameters is None: self._mvndst_parameters = DEFAULT_MVNDST_PARAMS else: self._mvndst_parameters = mvndst_parameters self.log = logging.getLogger(__name__)
[ "def", "__init__", "(", "self", ",", "gaussian_process", ",", "points_to_sample", "=", "None", ",", "points_being_sampled", "=", "None", ",", "num_mc_iterations", "=", "DEFAULT_EXPECTED_IMPROVEMENT_MC_ITERATIONS", ",", "randomness", "=", "None", ",", "mvndst_parameters", "=", "None", ")", ":", "self", ".", "_num_mc_iterations", "=", "num_mc_iterations", "self", ".", "_gaussian_process", "=", "gaussian_process", "if", "gaussian_process", ".", "_points_sampled_value", ".", "size", ">", "0", ":", "self", ".", "_best_so_far", "=", "numpy", ".", "amin", "(", "gaussian_process", ".", "_points_sampled_value", ")", "else", ":", "self", ".", "_best_so_far", "=", "numpy", ".", "finfo", "(", "numpy", ".", "float64", ")", ".", "max", "if", "points_being_sampled", "is", "None", ":", "self", ".", "_points_being_sampled", "=", "numpy", ".", "array", "(", "[", "]", ")", "else", ":", "self", ".", "_points_being_sampled", "=", "numpy", ".", "copy", "(", "points_being_sampled", ")", "if", "points_to_sample", "is", "None", ":", "self", ".", "current_point", "=", "numpy", ".", "zeros", "(", "(", "1", ",", "gaussian_process", ".", "dim", ")", ")", "else", ":", "self", ".", "current_point", "=", "points_to_sample", "if", "mvndst_parameters", "is", "None", ":", "self", ".", "_mvndst_parameters", "=", "DEFAULT_MVNDST_PARAMS", "else", ":", "self", ".", "_mvndst_parameters", "=", "mvndst_parameters", "self", ".", "log", "=", "logging", ".", "getLogger", "(", "__name__", ")" ]
https://github.com/Yelp/MOE/blob/5b5a6a2c6c3cf47320126f7f5894e2a83e347f5c/moe/optimal_learning/python/python_version/expected_improvement.py#L149-L196
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/eager/function.py
python
_shape_relaxed_type_for_composite_tensor
(x)
Returns a shape-relaxed TypeSpec for x (if composite) or x (if not).
Returns a shape-relaxed TypeSpec for x (if composite) or x (if not).
[ "Returns", "a", "shape", "-", "relaxed", "TypeSpec", "for", "x", "(", "if", "composite", ")", "or", "x", "(", "if", "not", ")", "." ]
def _shape_relaxed_type_for_composite_tensor(x): """Returns a shape-relaxed TypeSpec for x (if composite) or x (if not).""" if isinstance(x, composite_tensor.CompositeTensor): # pylint: disable=protected-access return x._type_spec._with_tensor_ranks_only() else: return x
[ "def", "_shape_relaxed_type_for_composite_tensor", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "composite_tensor", ".", "CompositeTensor", ")", ":", "# pylint: disable=protected-access", "return", "x", ".", "_type_spec", ".", "_with_tensor_ranks_only", "(", ")", "else", ":", "return", "x" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/function.py#L119-L125
benoitsteiner/tensorflow-opencl
cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5
tensorflow/contrib/tensor_forest/python/tensor_forest.py
python
RandomForestGraphs.inference_graph
(self, input_data, **inference_args)
Constructs a TF graph for evaluating a random forest. Args: input_data: A tensor or dict of string->Tensor for the input data. This input_data must generate the same spec as the input_data used in training_graph: the dict must have the same keys, for example, and all tensors must have the same size in their first dimension. **inference_args: Keyword arguments to pass through to each tree. Returns: A tuple of (probabilities, tree_paths, variance), where variance is the variance over all the trees for regression problems only. Raises: NotImplementedError: If trying to use feature bagging with sparse features.
Constructs a TF graph for evaluating a random forest.
[ "Constructs", "a", "TF", "graph", "for", "evaluating", "a", "random", "forest", "." ]
def inference_graph(self, input_data, **inference_args): """Constructs a TF graph for evaluating a random forest. Args: input_data: A tensor or dict of string->Tensor for the input data. This input_data must generate the same spec as the input_data used in training_graph: the dict must have the same keys, for example, and all tensors must have the same size in their first dimension. **inference_args: Keyword arguments to pass through to each tree. Returns: A tuple of (probabilities, tree_paths, variance), where variance is the variance over all the trees for regression problems only. Raises: NotImplementedError: If trying to use feature bagging with sparse features. """ processed_dense_features, processed_sparse_features, data_spec = ( data_ops.ParseDataTensorOrDict(input_data)) probabilities = [] paths = [] for i in range(self.params.num_trees): with ops.device(self.variables.device_dummies[i].device): tree_data = processed_dense_features if self.params.bagged_features: if processed_sparse_features is not None: raise NotImplementedError( 'Feature bagging not supported with sparse features.') tree_data = self._bag_features(i, tree_data) probs, path = self.trees[i].inference_graph( tree_data, data_spec, sparse_features=processed_sparse_features, **inference_args) probabilities.append(probs) paths.append(path) with ops.device(self.variables.device_dummies[0].device): # shape of all_predict should be [batch_size, num_trees, num_outputs] all_predict = array_ops.stack(probabilities, axis=1) average_values = math_ops.div( math_ops.reduce_sum(all_predict, 1), self.params.num_trees, name='probabilities') tree_paths = array_ops.stack(paths, axis=1) regression_variance = None if self.params.regression: expected_squares = math_ops.div( math_ops.reduce_sum(all_predict * all_predict, 1), self.params.num_trees) regression_variance = math_ops.maximum( 0., expected_squares - average_values * average_values) return average_values, tree_paths, regression_variance
[ "def", "inference_graph", "(", "self", ",", "input_data", ",", "*", "*", "inference_args", ")", ":", "processed_dense_features", ",", "processed_sparse_features", ",", "data_spec", "=", "(", "data_ops", ".", "ParseDataTensorOrDict", "(", "input_data", ")", ")", "probabilities", "=", "[", "]", "paths", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "params", ".", "num_trees", ")", ":", "with", "ops", ".", "device", "(", "self", ".", "variables", ".", "device_dummies", "[", "i", "]", ".", "device", ")", ":", "tree_data", "=", "processed_dense_features", "if", "self", ".", "params", ".", "bagged_features", ":", "if", "processed_sparse_features", "is", "not", "None", ":", "raise", "NotImplementedError", "(", "'Feature bagging not supported with sparse features.'", ")", "tree_data", "=", "self", ".", "_bag_features", "(", "i", ",", "tree_data", ")", "probs", ",", "path", "=", "self", ".", "trees", "[", "i", "]", ".", "inference_graph", "(", "tree_data", ",", "data_spec", ",", "sparse_features", "=", "processed_sparse_features", ",", "*", "*", "inference_args", ")", "probabilities", ".", "append", "(", "probs", ")", "paths", ".", "append", "(", "path", ")", "with", "ops", ".", "device", "(", "self", ".", "variables", ".", "device_dummies", "[", "0", "]", ".", "device", ")", ":", "# shape of all_predict should be [batch_size, num_trees, num_outputs]", "all_predict", "=", "array_ops", ".", "stack", "(", "probabilities", ",", "axis", "=", "1", ")", "average_values", "=", "math_ops", ".", "div", "(", "math_ops", ".", "reduce_sum", "(", "all_predict", ",", "1", ")", ",", "self", ".", "params", ".", "num_trees", ",", "name", "=", "'probabilities'", ")", "tree_paths", "=", "array_ops", ".", "stack", "(", "paths", ",", "axis", "=", "1", ")", "regression_variance", "=", "None", "if", "self", ".", "params", ".", "regression", ":", "expected_squares", "=", "math_ops", ".", "div", "(", "math_ops", ".", "reduce_sum", "(", "all_predict", "*", "all_predict", ",", "1", ")", ",", "self", ".", "params", ".", "num_trees", ")", "regression_variance", "=", "math_ops", ".", "maximum", "(", "0.", ",", "expected_squares", "-", "average_values", "*", "average_values", ")", "return", "average_values", ",", "tree_paths", ",", "regression_variance" ]
https://github.com/benoitsteiner/tensorflow-opencl/blob/cb7cb40a57fde5cfd4731bc551e82a1e2fef43a5/tensorflow/contrib/tensor_forest/python/tensor_forest.py#L469-L523
OAID/Tengine
66b2c22ad129d25e2fc6de3b22a608bb54dd90db
tools/optimize/yolov3-opt.py
python
cut_nodes_input_output
(node, cut_names)
del nodes from input nodes Args: node: the nodes of ONNX model Returns: optimized graph nodes(inplace)
del nodes from input nodes Args: node: the nodes of ONNX model Returns: optimized graph nodes(inplace)
[ "del", "nodes", "from", "input", "nodes", "Args", ":", "node", ":", "the", "nodes", "of", "ONNX", "model", "Returns", ":", "optimized", "graph", "nodes", "(", "inplace", ")" ]
def cut_nodes_input_output(node, cut_names): """ del nodes from input nodes Args: node: the nodes of ONNX model Returns: optimized graph nodes(inplace) """ for i in range(len(node) - 1, -1, -1): if node[i].name in cut_names: node.pop(i)
[ "def", "cut_nodes_input_output", "(", "node", ",", "cut_names", ")", ":", "for", "i", "in", "range", "(", "len", "(", "node", ")", "-", "1", ",", "-", "1", ",", "-", "1", ")", ":", "if", "node", "[", "i", "]", ".", "name", "in", "cut_names", ":", "node", ".", "pop", "(", "i", ")" ]
https://github.com/OAID/Tengine/blob/66b2c22ad129d25e2fc6de3b22a608bb54dd90db/tools/optimize/yolov3-opt.py#L96-L106
hanpfei/chromium-net
392cc1fa3a8f92f42e4071ab6e674d8e0482f83f
third_party/catapult/third_party/closure_linter/closure_linter/tokenutil.py
python
GetIdentifierForToken
(token)
Get the symbol specified by a token. Given a token, this function additionally concatenates any parts of an identifying symbol being identified that are split by whitespace or a newline. The function will return None if the token is not the first token of an identifier. Args: token: The first token of a symbol. Returns: The whole symbol, as a string.
Get the symbol specified by a token.
[ "Get", "the", "symbol", "specified", "by", "a", "token", "." ]
def GetIdentifierForToken(token): """Get the symbol specified by a token. Given a token, this function additionally concatenates any parts of an identifying symbol being identified that are split by whitespace or a newline. The function will return None if the token is not the first token of an identifier. Args: token: The first token of a symbol. Returns: The whole symbol, as a string. """ # Search backward to determine if this token is the first token of the # identifier. If it is not the first token, return None to signal that this # token should be ignored. prev_token = token.previous while prev_token: if (prev_token.IsType(JavaScriptTokenType.IDENTIFIER) or IsDot(prev_token)): return None if (prev_token.IsType(tokens.TokenType.WHITESPACE) or prev_token.IsAnyType(JavaScriptTokenType.COMMENT_TYPES)): prev_token = prev_token.previous else: break # A "function foo()" declaration. if token.type is JavaScriptTokenType.FUNCTION_NAME: return token.string # A "var foo" declaration (if the previous token is 'var') previous_code_token = GetPreviousCodeToken(token) if previous_code_token and previous_code_token.IsKeyword('var'): return token.string # Otherwise, this is potentially a namespaced (goog.foo.bar) identifier that # could span multiple lines or be broken up by whitespace. We need # to concatenate. identifier_types = set([ JavaScriptTokenType.IDENTIFIER, JavaScriptTokenType.SIMPLE_LVALUE ]) assert token.type in identifier_types # Start with the first token symbol_tokens = [token] if token.next: for t in token.next: last_symbol_token = symbol_tokens[-1] # A dot is part of the previous symbol. if IsDot(t): symbol_tokens.append(t) continue # An identifier is part of the previous symbol if the previous one was a # dot. if t.type in identifier_types: if IsDot(last_symbol_token): symbol_tokens.append(t) continue else: break # Skip any whitespace if t.type in JavaScriptTokenType.NON_CODE_TYPES: continue # This is the end of the identifier. Stop iterating. break if symbol_tokens: return ''.join([t.string for t in symbol_tokens])
[ "def", "GetIdentifierForToken", "(", "token", ")", ":", "# Search backward to determine if this token is the first token of the", "# identifier. If it is not the first token, return None to signal that this", "# token should be ignored.", "prev_token", "=", "token", ".", "previous", "while", "prev_token", ":", "if", "(", "prev_token", ".", "IsType", "(", "JavaScriptTokenType", ".", "IDENTIFIER", ")", "or", "IsDot", "(", "prev_token", ")", ")", ":", "return", "None", "if", "(", "prev_token", ".", "IsType", "(", "tokens", ".", "TokenType", ".", "WHITESPACE", ")", "or", "prev_token", ".", "IsAnyType", "(", "JavaScriptTokenType", ".", "COMMENT_TYPES", ")", ")", ":", "prev_token", "=", "prev_token", ".", "previous", "else", ":", "break", "# A \"function foo()\" declaration.", "if", "token", ".", "type", "is", "JavaScriptTokenType", ".", "FUNCTION_NAME", ":", "return", "token", ".", "string", "# A \"var foo\" declaration (if the previous token is 'var')", "previous_code_token", "=", "GetPreviousCodeToken", "(", "token", ")", "if", "previous_code_token", "and", "previous_code_token", ".", "IsKeyword", "(", "'var'", ")", ":", "return", "token", ".", "string", "# Otherwise, this is potentially a namespaced (goog.foo.bar) identifier that", "# could span multiple lines or be broken up by whitespace. We need", "# to concatenate.", "identifier_types", "=", "set", "(", "[", "JavaScriptTokenType", ".", "IDENTIFIER", ",", "JavaScriptTokenType", ".", "SIMPLE_LVALUE", "]", ")", "assert", "token", ".", "type", "in", "identifier_types", "# Start with the first token", "symbol_tokens", "=", "[", "token", "]", "if", "token", ".", "next", ":", "for", "t", "in", "token", ".", "next", ":", "last_symbol_token", "=", "symbol_tokens", "[", "-", "1", "]", "# A dot is part of the previous symbol.", "if", "IsDot", "(", "t", ")", ":", "symbol_tokens", ".", "append", "(", "t", ")", "continue", "# An identifier is part of the previous symbol if the previous one was a", "# dot.", "if", "t", ".", "type", "in", "identifier_types", ":", "if", "IsDot", "(", "last_symbol_token", ")", ":", "symbol_tokens", ".", "append", "(", "t", ")", "continue", "else", ":", "break", "# Skip any whitespace", "if", "t", ".", "type", "in", "JavaScriptTokenType", ".", "NON_CODE_TYPES", ":", "continue", "# This is the end of the identifier. Stop iterating.", "break", "if", "symbol_tokens", ":", "return", "''", ".", "join", "(", "[", "t", ".", "string", "for", "t", "in", "symbol_tokens", "]", ")" ]
https://github.com/hanpfei/chromium-net/blob/392cc1fa3a8f92f42e4071ab6e674d8e0482f83f/third_party/catapult/third_party/closure_linter/closure_linter/tokenutil.py#L573-L654
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py
python
Misc.grab_current
(self)
return self._nametowidget(name)
Return widget which has currently the grab in this application or None.
Return widget which has currently the grab in this application or None.
[ "Return", "widget", "which", "has", "currently", "the", "grab", "in", "this", "application", "or", "None", "." ]
def grab_current(self): """Return widget which has currently the grab in this application or None.""" name = self.tk.call('grab', 'current', self._w) if not name: return None return self._nametowidget(name)
[ "def", "grab_current", "(", "self", ")", ":", "name", "=", "self", ".", "tk", ".", "call", "(", "'grab'", ",", "'current'", ",", "self", ".", "_w", ")", "if", "not", "name", ":", "return", "None", "return", "self", ".", "_nametowidget", "(", "name", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/tkinter/__init__.py#L826-L831
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scipy/py2/scipy/optimize/_differentialevolution.py
python
DifferentialEvolutionSolver._select_samples
(self, candidate, number_samples)
return idxs
obtain random integers from range(self.num_population_members), without replacement. You can't have the original candidate either.
obtain random integers from range(self.num_population_members), without replacement. You can't have the original candidate either.
[ "obtain", "random", "integers", "from", "range", "(", "self", ".", "num_population_members", ")", "without", "replacement", ".", "You", "can", "t", "have", "the", "original", "candidate", "either", "." ]
def _select_samples(self, candidate, number_samples): """ obtain random integers from range(self.num_population_members), without replacement. You can't have the original candidate either. """ idxs = list(range(self.num_population_members)) idxs.remove(candidate) self.random_number_generator.shuffle(idxs) idxs = idxs[:number_samples] return idxs
[ "def", "_select_samples", "(", "self", ",", "candidate", ",", "number_samples", ")", ":", "idxs", "=", "list", "(", "range", "(", "self", ".", "num_population_members", ")", ")", "idxs", ".", "remove", "(", "candidate", ")", "self", ".", "random_number_generator", ".", "shuffle", "(", "idxs", ")", "idxs", "=", "idxs", "[", ":", "number_samples", "]", "return", "idxs" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scipy/py2/scipy/optimize/_differentialevolution.py#L993-L1002
wujian16/Cornell-MOE
df299d1be882d2af9796d7a68b3f9505cac7a53e
moe/optimal_learning/python/cpp_wrappers/log_likelihood.py
python
GaussianProcessLogLikelihood.set_hyperparameters
(self, hyperparameters)
Set hyperparameters to the specified hyperparameters; ordering must match. :param hyperparameters: hyperparameters at which to evaluate the log likelihood (objective function), ``f(x)`` :type hyperparameters: array of float64 with shape (num_hyperparameters)
Set hyperparameters to the specified hyperparameters; ordering must match.
[ "Set", "hyperparameters", "to", "the", "specified", "hyperparameters", ";", "ordering", "must", "match", "." ]
def set_hyperparameters(self, hyperparameters): """Set hyperparameters to the specified hyperparameters; ordering must match. :param hyperparameters: hyperparameters at which to evaluate the log likelihood (objective function), ``f(x)`` :type hyperparameters: array of float64 with shape (num_hyperparameters) """ self._covariance.hyperparameters = hyperparameters[:self._covariance.num_hyperparameters] self._noise_variance = hyperparameters[self._covariance.num_hyperparameters:]
[ "def", "set_hyperparameters", "(", "self", ",", "hyperparameters", ")", ":", "self", ".", "_covariance", ".", "hyperparameters", "=", "hyperparameters", "[", ":", "self", ".", "_covariance", ".", "num_hyperparameters", "]", "self", ".", "_noise_variance", "=", "hyperparameters", "[", "self", ".", "_covariance", ".", "num_hyperparameters", ":", "]" ]
https://github.com/wujian16/Cornell-MOE/blob/df299d1be882d2af9796d7a68b3f9505cac7a53e/moe/optimal_learning/python/cpp_wrappers/log_likelihood.py#L300-L308
h0x91b/redis-v8
ac8b9d49701d75bcee3719892a2a6a50b437e47a
redis/deps/v8/tools/stats-viewer.py
python
UiCounter.__init__
(self, var, format)
Creates a new ui counter. Args: var: the Tkinter string variable for updating the ui format: the format string used to format this counter
Creates a new ui counter.
[ "Creates", "a", "new", "ui", "counter", "." ]
def __init__(self, var, format): """Creates a new ui counter. Args: var: the Tkinter string variable for updating the ui format: the format string used to format this counter """ self.var = var self.format = format self.last_value = None
[ "def", "__init__", "(", "self", ",", "var", ",", "format", ")", ":", "self", ".", "var", "=", "var", "self", ".", "format", "=", "format", "self", ".", "last_value", "=", "None" ]
https://github.com/h0x91b/redis-v8/blob/ac8b9d49701d75bcee3719892a2a6a50b437e47a/redis/deps/v8/tools/stats-viewer.py#L271-L280
kamyu104/LeetCode-Solutions
77605708a927ea3b85aee5a479db733938c7c211
Python/maximum-number-of-balloons.py
python
Solution.maxNumberOfBalloons
(self, text)
return min(source_count[c]//target_count[c] for c in target_count.iterkeys())
:type text: str :rtype: int
:type text: str :rtype: int
[ ":", "type", "text", ":", "str", ":", "rtype", ":", "int" ]
def maxNumberOfBalloons(self, text): """ :type text: str :rtype: int """ TARGET = "balloon" source_count = collections.Counter(text) target_count = collections.Counter(TARGET) return min(source_count[c]//target_count[c] for c in target_count.iterkeys())
[ "def", "maxNumberOfBalloons", "(", "self", ",", "text", ")", ":", "TARGET", "=", "\"balloon\"", "source_count", "=", "collections", ".", "Counter", "(", "text", ")", "target_count", "=", "collections", ".", "Counter", "(", "TARGET", ")", "return", "min", "(", "source_count", "[", "c", "]", "//", "target_count", "[", "c", "]", "for", "c", "in", "target_count", ".", "iterkeys", "(", ")", ")" ]
https://github.com/kamyu104/LeetCode-Solutions/blob/77605708a927ea3b85aee5a479db733938c7c211/Python/maximum-number-of-balloons.py#L8-L16
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/distribute/distribute_coordinator.py
python
_WorkerContext.experimental_should_init
(self)
return self._strategy.extended.experimental_should_init
Whether to run init ops.
Whether to run init ops.
[ "Whether", "to", "run", "init", "ops", "." ]
def experimental_should_init(self): """Whether to run init ops.""" return self._strategy.extended.experimental_should_init
[ "def", "experimental_should_init", "(", "self", ")", ":", "return", "self", ".", "_strategy", ".", "extended", ".", "experimental_should_init" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/distribute/distribute_coordinator.py#L307-L309
pmq20/node-packer
12c46c6e44fbc14d9ee645ebd17d5296b324f7e0
lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py
python
MacPrefixHeader._Gch
(self, lang, arch)
return self._CompiledHeader(lang, arch) + '.gch'
Returns the actual file name of the prefix header for language |lang|.
Returns the actual file name of the prefix header for language |lang|.
[ "Returns", "the", "actual", "file", "name", "of", "the", "prefix", "header", "for", "language", "|lang|", "." ]
def _Gch(self, lang, arch): """Returns the actual file name of the prefix header for language |lang|.""" assert self.compile_headers return self._CompiledHeader(lang, arch) + '.gch'
[ "def", "_Gch", "(", "self", ",", "lang", ",", "arch", ")", ":", "assert", "self", ".", "compile_headers", "return", "self", ".", "_CompiledHeader", "(", "lang", ",", "arch", ")", "+", "'.gch'" ]
https://github.com/pmq20/node-packer/blob/12c46c6e44fbc14d9ee645ebd17d5296b324f7e0/lts/deps/npm/node_modules/node-gyp/gyp/pylib/gyp/xcode_emulation.py#L1218-L1221
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py
python
PanedWindow.proxy_forget
(self)
return self.proxy("forget")
Remove the proxy from the display.
Remove the proxy from the display.
[ "Remove", "the", "proxy", "from", "the", "display", "." ]
def proxy_forget(self): """Remove the proxy from the display. """ return self.proxy("forget")
[ "def", "proxy_forget", "(", "self", ")", ":", "return", "self", ".", "proxy", "(", "\"forget\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/tkinter/__init__.py#L3855-L3858
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/packaging/py3/packaging/_manylinux.py
python
_parse_glibc_version
(version_str: str)
return int(m.group("major")), int(m.group("minor"))
Parse glibc version. We use a regexp instead of str.split because we want to discard any random junk that might come after the minor version -- this might happen in patched/forked versions of glibc (e.g. Linaro's version of glibc uses version strings like "2.20-2014.11"). See gh-3588.
Parse glibc version.
[ "Parse", "glibc", "version", "." ]
def _parse_glibc_version(version_str: str) -> Tuple[int, int]: """Parse glibc version. We use a regexp instead of str.split because we want to discard any random junk that might come after the minor version -- this might happen in patched/forked versions of glibc (e.g. Linaro's version of glibc uses version strings like "2.20-2014.11"). See gh-3588. """ m = re.match(r"(?P<major>[0-9]+)\.(?P<minor>[0-9]+)", version_str) if not m: warnings.warn( "Expected glibc version with 2 components major.minor," " got: %s" % version_str, RuntimeWarning, ) return -1, -1 return int(m.group("major")), int(m.group("minor"))
[ "def", "_parse_glibc_version", "(", "version_str", ":", "str", ")", "->", "Tuple", "[", "int", ",", "int", "]", ":", "m", "=", "re", ".", "match", "(", "r\"(?P<major>[0-9]+)\\.(?P<minor>[0-9]+)\"", ",", "version_str", ")", "if", "not", "m", ":", "warnings", ".", "warn", "(", "\"Expected glibc version with 2 components major.minor,\"", "\" got: %s\"", "%", "version_str", ",", "RuntimeWarning", ",", ")", "return", "-", "1", ",", "-", "1", "return", "int", "(", "m", ".", "group", "(", "\"major\"", ")", ")", ",", "int", "(", "m", ".", "group", "(", "\"minor\"", ")", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/packaging/py3/packaging/_manylinux.py#L203-L219
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/cookies.py
python
RequestsCookieJar.itervalues
(self)
Dict-like itervalues() that returns an iterator of values of cookies from the jar. .. seealso:: iterkeys() and iteritems().
Dict-like itervalues() that returns an iterator of values of cookies from the jar.
[ "Dict", "-", "like", "itervalues", "()", "that", "returns", "an", "iterator", "of", "values", "of", "cookies", "from", "the", "jar", "." ]
def itervalues(self): """Dict-like itervalues() that returns an iterator of values of cookies from the jar. .. seealso:: iterkeys() and iteritems(). """ for cookie in iter(self): yield cookie.value
[ "def", "itervalues", "(", "self", ")", ":", "for", "cookie", "in", "iter", "(", "self", ")", ":", "yield", "cookie", ".", "value" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/site-packages/requests/cookies.py#L235-L242
apple/swift-lldb
d74be846ef3e62de946df343e8c234bde93a8912
scripts/Python/static-binding/lldb.py
python
SBTypeMemberFunction.GetDemangledName
(self)
return _lldb.SBTypeMemberFunction_GetDemangledName(self)
GetDemangledName(SBTypeMemberFunction self) -> char const *
GetDemangledName(SBTypeMemberFunction self) -> char const *
[ "GetDemangledName", "(", "SBTypeMemberFunction", "self", ")", "-", ">", "char", "const", "*" ]
def GetDemangledName(self): """GetDemangledName(SBTypeMemberFunction self) -> char const *""" return _lldb.SBTypeMemberFunction_GetDemangledName(self)
[ "def", "GetDemangledName", "(", "self", ")", ":", "return", "_lldb", ".", "SBTypeMemberFunction_GetDemangledName", "(", "self", ")" ]
https://github.com/apple/swift-lldb/blob/d74be846ef3e62de946df343e8c234bde93a8912/scripts/Python/static-binding/lldb.py#L12470-L12472
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/numpy/py2/numpy/distutils/line_endings.py
python
unix2dos
(file)
Replace LF with CRLF in argument files. Print names of changed files.
Replace LF with CRLF in argument files. Print names of changed files.
[ "Replace", "LF", "with", "CRLF", "in", "argument", "files", ".", "Print", "names", "of", "changed", "files", "." ]
def unix2dos(file): "Replace LF with CRLF in argument files. Print names of changed files." if os.path.isdir(file): print(file, "Directory!") return data = open(file, "rb").read() if '\0' in data: print(file, "Binary!") return newdata = re.sub("\r\n", "\n", data) newdata = re.sub("\n", "\r\n", newdata) if newdata != data: print('unix2dos:', file) f = open(file, "wb") f.write(newdata) f.close() return file else: print(file, 'ok')
[ "def", "unix2dos", "(", "file", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "file", ")", ":", "print", "(", "file", ",", "\"Directory!\"", ")", "return", "data", "=", "open", "(", "file", ",", "\"rb\"", ")", ".", "read", "(", ")", "if", "'\\0'", "in", "data", ":", "print", "(", "file", ",", "\"Binary!\"", ")", "return", "newdata", "=", "re", ".", "sub", "(", "\"\\r\\n\"", ",", "\"\\n\"", ",", "data", ")", "newdata", "=", "re", ".", "sub", "(", "\"\\n\"", ",", "\"\\r\\n\"", ",", "newdata", ")", "if", "newdata", "!=", "data", ":", "print", "(", "'unix2dos:'", ",", "file", ")", "f", "=", "open", "(", "file", ",", "\"wb\"", ")", "f", ".", "write", "(", "newdata", ")", "f", ".", "close", "(", ")", "return", "file", "else", ":", "print", "(", "file", ",", "'ok'", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/numpy/py2/numpy/distutils/line_endings.py#L42-L61
thalium/icebox
99d147d5b9269222225443ce171b4fd46d8985d4
third_party/virtualbox/src/VBox/VMM/VMMAll/IEMAllInstructionsPython.py
python
InstructionMap.getDisasTableName
(self)
return sName
Returns the disassembler table name for this map.
Returns the disassembler table name for this map.
[ "Returns", "the", "disassembler", "table", "name", "for", "this", "map", "." ]
def getDisasTableName(self): """ Returns the disassembler table name for this map. """ sName = 'g_aDisas'; for sWord in self.sName.split('_'): if sWord == 'm': # suffix indicating modrm.mod==mem sName += '_m'; elif sWord == 'r': # suffix indicating modrm.mod==reg sName += '_r'; elif len(sWord) == 2 and re.match('^[a-f0-9][a-f0-9]$', sWord): sName += '_' + sWord; else: sWord = sWord.replace('grp', 'Grp'); sWord = sWord.replace('map', 'Map'); sName += sWord[0].upper() + sWord[1:]; return sName;
[ "def", "getDisasTableName", "(", "self", ")", ":", "sName", "=", "'g_aDisas'", "for", "sWord", "in", "self", ".", "sName", ".", "split", "(", "'_'", ")", ":", "if", "sWord", "==", "'m'", ":", "# suffix indicating modrm.mod==mem", "sName", "+=", "'_m'", "elif", "sWord", "==", "'r'", ":", "# suffix indicating modrm.mod==reg", "sName", "+=", "'_r'", "elif", "len", "(", "sWord", ")", "==", "2", "and", "re", ".", "match", "(", "'^[a-f0-9][a-f0-9]$'", ",", "sWord", ")", ":", "sName", "+=", "'_'", "+", "sWord", "else", ":", "sWord", "=", "sWord", ".", "replace", "(", "'grp'", ",", "'Grp'", ")", "sWord", "=", "sWord", ".", "replace", "(", "'map'", ",", "'Map'", ")", "sName", "+=", "sWord", "[", "0", "]", ".", "upper", "(", ")", "+", "sWord", "[", "1", ":", "]", "return", "sName" ]
https://github.com/thalium/icebox/blob/99d147d5b9269222225443ce171b4fd46d8985d4/third_party/virtualbox/src/VBox/VMM/VMMAll/IEMAllInstructionsPython.py#L701-L717
y123456yz/reading-and-annotate-mongodb-3.6
93280293672ca7586dc24af18132aa61e4ed7fcf
mongo/src/third_party/scons-2.5.0/scons-time.py
python
SConsTimer.get_debug_times
(self, file, time_string=None)
return result
Fetch times from the --debug=time strings in the specified file.
Fetch times from the --debug=time strings in the specified file.
[ "Fetch", "times", "from", "the", "--", "debug", "=", "time", "strings", "in", "the", "specified", "file", "." ]
def get_debug_times(self, file, time_string=None): """ Fetch times from the --debug=time strings in the specified file. """ if time_string is None: search_string = self.time_string_all else: search_string = time_string contents = open(file).read() if not contents: sys.stderr.write('file %s has no contents!\n' % repr(file)) return None result = re.findall(r'%s: ([\d\.]*)' % search_string, contents)[-4:] result = [ float(r) for r in result ] if not time_string is None: try: result = result[0] except IndexError: sys.stderr.write('file %s has no results!\n' % repr(file)) return None return result
[ "def", "get_debug_times", "(", "self", ",", "file", ",", "time_string", "=", "None", ")", ":", "if", "time_string", "is", "None", ":", "search_string", "=", "self", ".", "time_string_all", "else", ":", "search_string", "=", "time_string", "contents", "=", "open", "(", "file", ")", ".", "read", "(", ")", "if", "not", "contents", ":", "sys", ".", "stderr", ".", "write", "(", "'file %s has no contents!\\n'", "%", "repr", "(", "file", ")", ")", "return", "None", "result", "=", "re", ".", "findall", "(", "r'%s: ([\\d\\.]*)'", "%", "search_string", ",", "contents", ")", "[", "-", "4", ":", "]", "result", "=", "[", "float", "(", "r", ")", "for", "r", "in", "result", "]", "if", "not", "time_string", "is", "None", ":", "try", ":", "result", "=", "result", "[", "0", "]", "except", "IndexError", ":", "sys", ".", "stderr", ".", "write", "(", "'file %s has no results!\\n'", "%", "repr", "(", "file", ")", ")", "return", "None", "return", "result" ]
https://github.com/y123456yz/reading-and-annotate-mongodb-3.6/blob/93280293672ca7586dc24af18132aa61e4ed7fcf/mongo/src/third_party/scons-2.5.0/scons-time.py#L622-L642
idaholab/moose
9eeebc65e098b4c30f8205fb41591fd5b61eb6ff
python/peacock/Execute/ConsoleOutputViewerPlugin.py
python
ConsoleOutputViewerPlugin.viewPositionChanged
(self, val)
The view changed. This can be due to adding additional text or if the user scroll around the text window. If we are at the bottom then we turn on auto scrolling. Input: val[int]: The current position of the vertical bar slider
The view changed. This can be due to adding additional text or if the user scroll around the text window. If we are at the bottom then we turn on auto scrolling. Input: val[int]: The current position of the vertical bar slider
[ "The", "view", "changed", ".", "This", "can", "be", "due", "to", "adding", "additional", "text", "or", "if", "the", "user", "scroll", "around", "the", "text", "window", ".", "If", "we", "are", "at", "the", "bottom", "then", "we", "turn", "on", "auto", "scrolling", ".", "Input", ":", "val", "[", "int", "]", ":", "The", "current", "position", "of", "the", "vertical", "bar", "slider" ]
def viewPositionChanged(self, val): """ The view changed. This can be due to adding additional text or if the user scroll around the text window. If we are at the bottom then we turn on auto scrolling. Input: val[int]: The current position of the vertical bar slider """ self.do_scroll = val == self.vert_bar.maximum()
[ "def", "viewPositionChanged", "(", "self", ",", "val", ")", ":", "self", ".", "do_scroll", "=", "val", "==", "self", ".", "vert_bar", ".", "maximum", "(", ")" ]
https://github.com/idaholab/moose/blob/9eeebc65e098b4c30f8205fb41591fd5b61eb6ff/python/peacock/Execute/ConsoleOutputViewerPlugin.py#L57-L66
KratosMultiphysics/Kratos
0000833054ed0503424eb28205d6508d9ca6cbbc
applications/FemToDemApplication/python_scripts/MainCouplingPfemFemDemAitkenSubstepping.py
python
KratosPrintInfo
(message)
This function prints info on screen
This function prints info on screen
[ "This", "function", "prints", "info", "on", "screen" ]
def KratosPrintInfo(message): """This function prints info on screen """ KM.Logger.Print("", message) KM.Logger.Flush()
[ "def", "KratosPrintInfo", "(", "message", ")", ":", "KM", ".", "Logger", ".", "Print", "(", "\"\"", ",", "message", ")", "KM", ".", "Logger", ".", "Flush", "(", ")" ]
https://github.com/KratosMultiphysics/Kratos/blob/0000833054ed0503424eb28205d6508d9ca6cbbc/applications/FemToDemApplication/python_scripts/MainCouplingPfemFemDemAitkenSubstepping.py#L13-L17
google/usd_from_gltf
6d288cce8b68744494a226574ae1d7ba6a9c46eb
tools/ufgbatch/ufgcommon/process.py
python
get_process_command
(cmd_args)
return cmd
Get command-line text for task process.
Get command-line text for task process.
[ "Get", "command", "-", "line", "text", "for", "task", "process", "." ]
def get_process_command(cmd_args): """Get command-line text for task process.""" # Join arguments into command string, escaping any with spaces. cmd = '' for arg_index, arg in enumerate(cmd_args): if arg_index > 0: cmd += ' ' if ' ' in arg: cmd += '"' + arg + '"' else: cmd += arg return cmd
[ "def", "get_process_command", "(", "cmd_args", ")", ":", "# Join arguments into command string, escaping any with spaces.", "cmd", "=", "''", "for", "arg_index", ",", "arg", "in", "enumerate", "(", "cmd_args", ")", ":", "if", "arg_index", ">", "0", ":", "cmd", "+=", "' '", "if", "' '", "in", "arg", ":", "cmd", "+=", "'\"'", "+", "arg", "+", "'\"'", "else", ":", "cmd", "+=", "arg", "return", "cmd" ]
https://github.com/google/usd_from_gltf/blob/6d288cce8b68744494a226574ae1d7ba6a9c46eb/tools/ufgbatch/ufgcommon/process.py#L117-L128
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/python/scikit-learn/py2/sklearn/neural_network/multilayer_perceptron.py
python
BaseMultilayerPerceptron.fit
(self, X, y)
return self._fit(X, y, incremental=False)
Fit the model to data matrix X and target y. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The input data. y : array-like, shape (n_samples,) The target values. Returns ------- self : returns a trained MLP model.
Fit the model to data matrix X and target y.
[ "Fit", "the", "model", "to", "data", "matrix", "X", "and", "target", "y", "." ]
def fit(self, X, y): """Fit the model to data matrix X and target y. Parameters ---------- X : {array-like, sparse matrix}, shape (n_samples, n_features) The input data. y : array-like, shape (n_samples,) The target values. Returns ------- self : returns a trained MLP model. """ return self._fit(X, y, incremental=False)
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "return", "self", ".", "_fit", "(", "X", ",", "y", ",", "incremental", "=", "False", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/python/scikit-learn/py2/sklearn/neural_network/multilayer_perceptron.py#L603-L618
Xilinx/Vitis-AI
fc74d404563d9951b57245443c73bef389f3657f
tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/third_party/mlir/utils/spirv/gen_spirv_dialect.py
python
map_spec_operand_to_ods_argument
(operand)
return '{}:${}'.format(arg_type, name)
Maps a operand in SPIR-V JSON spec to an op argument in ODS. Arguments: - A dict containing the operand's kind, quantifier, and name Returns: - A string containing both the type and name for the argument
Maps a operand in SPIR-V JSON spec to an op argument in ODS.
[ "Maps", "a", "operand", "in", "SPIR", "-", "V", "JSON", "spec", "to", "an", "op", "argument", "in", "ODS", "." ]
def map_spec_operand_to_ods_argument(operand): """Maps a operand in SPIR-V JSON spec to an op argument in ODS. Arguments: - A dict containing the operand's kind, quantifier, and name Returns: - A string containing both the type and name for the argument """ kind = operand['kind'] quantifier = operand.get('quantifier', '') # These instruction "operands" are for encoding the results; they should # not be handled here. assert kind != 'IdResultType', 'unexpected to handle "IdResultType" kind' assert kind != 'IdResult', 'unexpected to handle "IdResult" kind' if kind == 'IdRef': if quantifier == '': arg_type = 'SPV_Type' elif quantifier == '?': arg_type = 'SPV_Optional<SPV_Type>' else: arg_type = 'Variadic<SPV_Type>' elif kind == 'IdMemorySemantics' or kind == 'IdScope': # TODO(antiagainst): Need to further constrain 'IdMemorySemantics' # and 'IdScope' given that they should be gernated from OpConstant. assert quantifier == '', ('unexpected to have optional/variadic memory ' 'semantics or scope <id>') arg_type = 'I32' elif kind == 'LiteralInteger': if quantifier == '': arg_type = 'I32Attr' elif quantifier == '?': arg_type = 'OptionalAttr<I32Attr>' else: arg_type = 'OptionalAttr<I32ArrayAttr>' elif kind == 'LiteralString' or \ kind == 'LiteralContextDependentNumber' or \ kind == 'LiteralExtInstInteger' or \ kind == 'LiteralSpecConstantOpInteger' or \ kind == 'PairLiteralIntegerIdRef' or \ kind == 'PairIdRefLiteralInteger' or \ kind == 'PairIdRefIdRef': assert False, '"{}" kind unimplemented'.format(kind) else: # The rest are all enum operands that we represent with op attributes. assert quantifier != '*', 'unexpected to have variadic enum attribute' arg_type = 'SPV_{}Attr'.format(kind) if quantifier == '?': arg_type = 'OptionalAttr<{}>'.format(arg_type) name = operand.get('name', '') name = snake_casify(name) if name else kind.lower() return '{}:${}'.format(arg_type, name)
[ "def", "map_spec_operand_to_ods_argument", "(", "operand", ")", ":", "kind", "=", "operand", "[", "'kind'", "]", "quantifier", "=", "operand", ".", "get", "(", "'quantifier'", ",", "''", ")", "# These instruction \"operands\" are for encoding the results; they should", "# not be handled here.", "assert", "kind", "!=", "'IdResultType'", ",", "'unexpected to handle \"IdResultType\" kind'", "assert", "kind", "!=", "'IdResult'", ",", "'unexpected to handle \"IdResult\" kind'", "if", "kind", "==", "'IdRef'", ":", "if", "quantifier", "==", "''", ":", "arg_type", "=", "'SPV_Type'", "elif", "quantifier", "==", "'?'", ":", "arg_type", "=", "'SPV_Optional<SPV_Type>'", "else", ":", "arg_type", "=", "'Variadic<SPV_Type>'", "elif", "kind", "==", "'IdMemorySemantics'", "or", "kind", "==", "'IdScope'", ":", "# TODO(antiagainst): Need to further constrain 'IdMemorySemantics'", "# and 'IdScope' given that they should be gernated from OpConstant.", "assert", "quantifier", "==", "''", ",", "(", "'unexpected to have optional/variadic memory '", "'semantics or scope <id>'", ")", "arg_type", "=", "'I32'", "elif", "kind", "==", "'LiteralInteger'", ":", "if", "quantifier", "==", "''", ":", "arg_type", "=", "'I32Attr'", "elif", "quantifier", "==", "'?'", ":", "arg_type", "=", "'OptionalAttr<I32Attr>'", "else", ":", "arg_type", "=", "'OptionalAttr<I32ArrayAttr>'", "elif", "kind", "==", "'LiteralString'", "or", "kind", "==", "'LiteralContextDependentNumber'", "or", "kind", "==", "'LiteralExtInstInteger'", "or", "kind", "==", "'LiteralSpecConstantOpInteger'", "or", "kind", "==", "'PairLiteralIntegerIdRef'", "or", "kind", "==", "'PairIdRefLiteralInteger'", "or", "kind", "==", "'PairIdRefIdRef'", ":", "assert", "False", ",", "'\"{}\" kind unimplemented'", ".", "format", "(", "kind", ")", "else", ":", "# The rest are all enum operands that we represent with op attributes.", "assert", "quantifier", "!=", "'*'", ",", "'unexpected to have variadic enum attribute'", "arg_type", "=", "'SPV_{}Attr'", ".", "format", "(", "kind", ")", "if", "quantifier", "==", "'?'", ":", "arg_type", "=", "'OptionalAttr<{}>'", ".", "format", "(", "arg_type", ")", "name", "=", "operand", ".", "get", "(", "'name'", ",", "''", ")", "name", "=", "snake_casify", "(", "name", ")", "if", "name", "else", "kind", ".", "lower", "(", ")", "return", "'{}:${}'", ".", "format", "(", "arg_type", ",", "name", ")" ]
https://github.com/Xilinx/Vitis-AI/blob/fc74d404563d9951b57245443c73bef389f3657f/tools/Vitis-AI-Quantizer/vai_q_tensorflow1.x/third_party/mlir/utils/spirv/gen_spirv_dialect.py#L305-L360
windystrife/UnrealEngine_NVIDIAGameWorks
b50e6338a7c5b26374d66306ebc7807541ff815e
Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/html5lib/html5parser.py
python
HTMLParser.parse
(self, stream, encoding=None, parseMeta=True, useChardet=True)
return self.tree.getDocument()
Parse a HTML document into a well-formed tree stream - a filelike object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element)
Parse a HTML document into a well-formed tree
[ "Parse", "a", "HTML", "document", "into", "a", "well", "-", "formed", "tree" ]
def parse(self, stream, encoding=None, parseMeta=True, useChardet=True): """Parse a HTML document into a well-formed tree stream - a filelike object or string containing the HTML to be parsed The optional encoding parameter must be a string that indicates the encoding. If specified, that encoding will be used, regardless of any BOM or later declaration (such as in a meta element) """ self._parse(stream, innerHTML=False, encoding=encoding, parseMeta=parseMeta, useChardet=useChardet) return self.tree.getDocument()
[ "def", "parse", "(", "self", ",", "stream", ",", "encoding", "=", "None", ",", "parseMeta", "=", "True", ",", "useChardet", "=", "True", ")", ":", "self", ".", "_parse", "(", "stream", ",", "innerHTML", "=", "False", ",", "encoding", "=", "encoding", ",", "parseMeta", "=", "parseMeta", ",", "useChardet", "=", "useChardet", ")", "return", "self", ".", "tree", ".", "getDocument", "(", ")" ]
https://github.com/windystrife/UnrealEngine_NVIDIAGameWorks/blob/b50e6338a7c5b26374d66306ebc7807541ff815e/Engine/Extras/ThirdPartyNotUE/emsdk/Win64/python/2.7.5.3_64bit/Lib/site-packages/pip/vendor/html5lib/html5parser.py#L212-L224
weolar/miniblink49
1c4678db0594a4abde23d3ebbcc7cd13c3170777
third_party/WebKit/Source/bindings/scripts/interface_dependency_resolver.py
python
InterfaceDependencyResolver.__init__
(self, interfaces_info, reader)
Initialize dependency resolver. Args: interfaces_info: dict of interfaces information, from compute_dependencies.py reader: IdlReader, used for reading dependency files
Initialize dependency resolver.
[ "Initialize", "dependency", "resolver", "." ]
def __init__(self, interfaces_info, reader): """Initialize dependency resolver. Args: interfaces_info: dict of interfaces information, from compute_dependencies.py reader: IdlReader, used for reading dependency files """ self.interfaces_info = interfaces_info self.reader = reader
[ "def", "__init__", "(", "self", ",", "interfaces_info", ",", "reader", ")", ":", "self", ".", "interfaces_info", "=", "interfaces_info", "self", ".", "reader", "=", "reader" ]
https://github.com/weolar/miniblink49/blob/1c4678db0594a4abde23d3ebbcc7cd13c3170777/third_party/WebKit/Source/bindings/scripts/interface_dependency_resolver.py#L55-L65
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/compat/numpy/function.py
python
validate_argmax_with_skipna
(skipna, args, kwargs)
return skipna
If 'Series.argmax' is called via the 'numpy' library, the third parameter in its signature is 'out', which takes either an ndarray or 'None', so check if the 'skipna' parameter is either an instance of ndarray or is None, since 'skipna' itself should be a boolean
If 'Series.argmax' is called via the 'numpy' library, the third parameter in its signature is 'out', which takes either an ndarray or 'None', so check if the 'skipna' parameter is either an instance of ndarray or is None, since 'skipna' itself should be a boolean
[ "If", "Series", ".", "argmax", "is", "called", "via", "the", "numpy", "library", "the", "third", "parameter", "in", "its", "signature", "is", "out", "which", "takes", "either", "an", "ndarray", "or", "None", "so", "check", "if", "the", "skipna", "parameter", "is", "either", "an", "instance", "of", "ndarray", "or", "is", "None", "since", "skipna", "itself", "should", "be", "a", "boolean" ]
def validate_argmax_with_skipna(skipna, args, kwargs): """ If 'Series.argmax' is called via the 'numpy' library, the third parameter in its signature is 'out', which takes either an ndarray or 'None', so check if the 'skipna' parameter is either an instance of ndarray or is None, since 'skipna' itself should be a boolean """ skipna, args = process_skipna(skipna, args) validate_argmax(args, kwargs) return skipna
[ "def", "validate_argmax_with_skipna", "(", "skipna", ",", "args", ",", "kwargs", ")", ":", "skipna", ",", "args", "=", "process_skipna", "(", "skipna", ",", "args", ")", "validate_argmax", "(", "args", ",", "kwargs", ")", "return", "skipna" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pandas/compat/numpy/function.py#L95-L106
synfig/synfig
a5ec91db5b751dc12e4400ccfb5c063fd6d2d928
synfig-studio/plugins/lottie-exporter/properties/shapePropKeyframe/helper.py
python
convert_tangent_to_lottie
(t1, t2)
return t1, t2
Converts tangent from Synfig format to lottie format Args: t1 (common.Vector.Vector) : tangent 1 of a point t2 (common.Vector.Vector) : tangent 2 of a point Returns: (common.Vector.Vector) : Converted tangent 1 (common.Vector.Vector) : Converted tangent 2
Converts tangent from Synfig format to lottie format
[ "Converts", "tangent", "from", "Synfig", "format", "to", "lottie", "format" ]
def convert_tangent_to_lottie(t1, t2): """ Converts tangent from Synfig format to lottie format Args: t1 (common.Vector.Vector) : tangent 1 of a point t2 (common.Vector.Vector) : tangent 2 of a point Returns: (common.Vector.Vector) : Converted tangent 1 (common.Vector.Vector) : Converted tangent 2 """ # Convert to Lottie format t1 /= 3 t2 /= 3 # Synfig and Lottie use different in tangents SEE DOCUMENTATION t1 *= -1 # Important: t1 and t2 have to be relative # The y-axis is different in lottie t1[1] = -t1[1] t2[1] = -t2[1] return t1, t2
[ "def", "convert_tangent_to_lottie", "(", "t1", ",", "t2", ")", ":", "# Convert to Lottie format", "t1", "/=", "3", "t2", "/=", "3", "# Synfig and Lottie use different in tangents SEE DOCUMENTATION", "t1", "*=", "-", "1", "# Important: t1 and t2 have to be relative", "# The y-axis is different in lottie", "t1", "[", "1", "]", "=", "-", "t1", "[", "1", "]", "t2", "[", "1", "]", "=", "-", "t2", "[", "1", "]", "return", "t1", ",", "t2" ]
https://github.com/synfig/synfig/blob/a5ec91db5b751dc12e4400ccfb5c063fd6d2d928/synfig-studio/plugins/lottie-exporter/properties/shapePropKeyframe/helper.py#L189-L212
miyosuda/TensorFlowAndroidMNIST
7b5a4603d2780a8a2834575706e9001977524007
jni-build/jni/include/tensorflow/python/framework/ops.py
python
SparseTensor.op
(self)
return self.values.op
The `Operation` that produces `values` as an output.
The `Operation` that produces `values` as an output.
[ "The", "Operation", "that", "produces", "values", "as", "an", "output", "." ]
def op(self): """The `Operation` that produces `values` as an output.""" return self.values.op
[ "def", "op", "(", "self", ")", ":", "return", "self", ".", "values", ".", "op" ]
https://github.com/miyosuda/TensorFlowAndroidMNIST/blob/7b5a4603d2780a8a2834575706e9001977524007/jni-build/jni/include/tensorflow/python/framework/ops.py#L1016-L1018
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/decimal.py
python
Decimal.is_subnormal
(self, context=None)
return self.adjusted() < context.Emin
Return True if self is subnormal; otherwise return False.
Return True if self is subnormal; otherwise return False.
[ "Return", "True", "if", "self", "is", "subnormal", ";", "otherwise", "return", "False", "." ]
def is_subnormal(self, context=None): """Return True if self is subnormal; otherwise return False.""" if self._is_special or not self: return False if context is None: context = getcontext() return self.adjusted() < context.Emin
[ "def", "is_subnormal", "(", "self", ",", "context", "=", "None", ")", ":", "if", "self", ".", "_is_special", "or", "not", "self", ":", "return", "False", "if", "context", "is", "None", ":", "context", "=", "getcontext", "(", ")", "return", "self", ".", "adjusted", "(", ")", "<", "context", ".", "Emin" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/decimal.py#L3049-L3055
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/_bootstrap.py
python
BuiltinImporter.get_code
(cls, fullname)
return None
Return None as built-in modules do not have code objects.
Return None as built-in modules do not have code objects.
[ "Return", "None", "as", "built", "-", "in", "modules", "do", "not", "have", "code", "objects", "." ]
def get_code(cls, fullname): """Return None as built-in modules do not have code objects.""" return None
[ "def", "get_code", "(", "cls", ",", "fullname", ")", ":", "return", "None" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/mac/Python.framework/Versions/3.7/lib/python3.7/importlib/_bootstrap.py#L755-L757
QMCPACK/qmcpack
d0948ab455e38364458740cc8e2239600a14c5cd
utils/afqmctools/afqmctools/analysis/average.py
python
average_two_rdm
(filename, estimator='back_propagated', eqlb=1, skip=1, ix=None)
Average AFQMC 2RDM. Returns a list of 2RDMS, where 2RDM[s1s2,i,k,j,l] = <c_{i}^+ c_{j}^+ c_{l} c_{k}>. For closed shell systems, returns [(a,a,a,a),(a,a,b,b)] For collinear systems, returns [(a,a,a,a),(a,a,b,b),(b,b,b,b)] Parameters ---------- filename : string QMCPACK output containing density matrix (*.h5 file). estimator : string Estimator type to analyse. Options: back_propagated or mixed. Default: back_propagated. eqlb : int Number of blocks for equilibration. Default 1. skip : int Number of blocks to skip in between measurements equilibration. Default 1 (use all data). ix : int Back propagation path length to average. Optional. Default: None (chooses longest path). Returns ------- two_rdm : :class:`numpy.ndarray` List of averaged 2RDM. two_rdm_err : :class:`numpy.ndarray` List of error bars for 2RDM elements.
Average AFQMC 2RDM.
[ "Average", "AFQMC", "2RDM", "." ]
def average_two_rdm(filename, estimator='back_propagated', eqlb=1, skip=1, ix=None): """Average AFQMC 2RDM. Returns a list of 2RDMS, where 2RDM[s1s2,i,k,j,l] = <c_{i}^+ c_{j}^+ c_{l} c_{k}>. For closed shell systems, returns [(a,a,a,a),(a,a,b,b)] For collinear systems, returns [(a,a,a,a),(a,a,b,b),(b,b,b,b)] Parameters ---------- filename : string QMCPACK output containing density matrix (*.h5 file). estimator : string Estimator type to analyse. Options: back_propagated or mixed. Default: back_propagated. eqlb : int Number of blocks for equilibration. Default 1. skip : int Number of blocks to skip in between measurements equilibration. Default 1 (use all data). ix : int Back propagation path length to average. Optional. Default: None (chooses longest path). Returns ------- two_rdm : :class:`numpy.ndarray` List of averaged 2RDM. two_rdm_err : :class:`numpy.ndarray` List of error bars for 2RDM elements. """ md = get_metadata(filename) mean, err = average_observable(filename, 'two_rdm', eqlb=eqlb, skip=skip, estimator=estimator, ix=ix) nbasis = md['NMO'] wt = md['WalkerType'] try: walker = WALKER_TYPE[wt] except IndexError: print('Unknown walker type {}'.format(wt)) if walker == 'closed': return mean.reshape(2,nbasis,nbasis,nbasis,nbasis), err.reshape(2,nbasis,nbasis,nbasis,nbasis) elif walker == 'collinear': return mean.reshape(3,nbasis,nbasis,nbasis,nbasis), err.reshape(3,nbasis,nbasis,nbasis,nbasis) elif walker == 'non_collinear': return mean.reshape(2*nbasis,2*nbasis,2*nbasis,2*nbasis), err.reshape(2*nbasis,2*nbasis,2*nbasis, 2*nbasis) else: print('Unknown walker type.') return None
[ "def", "average_two_rdm", "(", "filename", ",", "estimator", "=", "'back_propagated'", ",", "eqlb", "=", "1", ",", "skip", "=", "1", ",", "ix", "=", "None", ")", ":", "md", "=", "get_metadata", "(", "filename", ")", "mean", ",", "err", "=", "average_observable", "(", "filename", ",", "'two_rdm'", ",", "eqlb", "=", "eqlb", ",", "skip", "=", "skip", ",", "estimator", "=", "estimator", ",", "ix", "=", "ix", ")", "nbasis", "=", "md", "[", "'NMO'", "]", "wt", "=", "md", "[", "'WalkerType'", "]", "try", ":", "walker", "=", "WALKER_TYPE", "[", "wt", "]", "except", "IndexError", ":", "print", "(", "'Unknown walker type {}'", ".", "format", "(", "wt", ")", ")", "if", "walker", "==", "'closed'", ":", "return", "mean", ".", "reshape", "(", "2", ",", "nbasis", ",", "nbasis", ",", "nbasis", ",", "nbasis", ")", ",", "err", ".", "reshape", "(", "2", ",", "nbasis", ",", "nbasis", ",", "nbasis", ",", "nbasis", ")", "elif", "walker", "==", "'collinear'", ":", "return", "mean", ".", "reshape", "(", "3", ",", "nbasis", ",", "nbasis", ",", "nbasis", ",", "nbasis", ")", ",", "err", ".", "reshape", "(", "3", ",", "nbasis", ",", "nbasis", ",", "nbasis", ",", "nbasis", ")", "elif", "walker", "==", "'non_collinear'", ":", "return", "mean", ".", "reshape", "(", "2", "*", "nbasis", ",", "2", "*", "nbasis", ",", "2", "*", "nbasis", ",", "2", "*", "nbasis", ")", ",", "err", ".", "reshape", "(", "2", "*", "nbasis", ",", "2", "*", "nbasis", ",", "2", "*", "nbasis", ",", "2", "*", "nbasis", ")", "else", ":", "print", "(", "'Unknown walker type.'", ")", "return", "None" ]
https://github.com/QMCPACK/qmcpack/blob/d0948ab455e38364458740cc8e2239600a14c5cd/utils/afqmctools/afqmctools/analysis/average.py#L66-L115
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleControl.py
python
CWSCDReductionControl.get_single_scan_pt_model
(self, exp_number, scan_number, pt_number, roi_name, integration_direction)
return vec_x, vec_model
get a single-pt scan summed 1D data either vertically or horizontally with model data :param exp_number: :param scan_number: :param pt_number: :param roi_name: :param integration_direction: :return: 2-tuple.. vector model
get a single-pt scan summed 1D data either vertically or horizontally with model data :param exp_number: :param scan_number: :param pt_number: :param roi_name: :param integration_direction: :return: 2-tuple.. vector model
[ "get", "a", "single", "-", "pt", "scan", "summed", "1D", "data", "either", "vertically", "or", "horizontally", "with", "model", "data", ":", "param", "exp_number", ":", ":", "param", "scan_number", ":", ":", "param", "pt_number", ":", ":", "param", "roi_name", ":", ":", "param", "integration_direction", ":", ":", "return", ":", "2", "-", "tuple", "..", "vector", "model" ]
def get_single_scan_pt_model(self, exp_number, scan_number, pt_number, roi_name, integration_direction): """ get a single-pt scan summed 1D data either vertically or horizontally with model data :param exp_number: :param scan_number: :param pt_number: :param roi_name: :param integration_direction: :return: 2-tuple.. vector model """ # get record key ws_record_key = self._current_single_pt_integration_key print('[DB...BAT] Retrieve ws record key: {}'.format(ws_record_key)) # TODO - 20180814 - Check pt number, rio name and integration direction if ws_record_key in self._single_pt_matrix_dict: # check integration manager integration_manager = self._single_pt_matrix_dict[ws_record_key] assert integration_manager.exp_number == exp_number, 'blabla' else: raise RuntimeError('Last single-pt integration manager (key) {} does not exist.' .format(ws_record_key)) matrix_ws = AnalysisDataService.retrieve(integration_manager.get_model_workspace()) ws_index = integration_manager.get_spectrum_number(scan_number, from_zero=True) vec_x = matrix_ws.readX(ws_index) vec_model = matrix_ws.readY(ws_index) return vec_x, vec_model
[ "def", "get_single_scan_pt_model", "(", "self", ",", "exp_number", ",", "scan_number", ",", "pt_number", ",", "roi_name", ",", "integration_direction", ")", ":", "# get record key", "ws_record_key", "=", "self", ".", "_current_single_pt_integration_key", "print", "(", "'[DB...BAT] Retrieve ws record key: {}'", ".", "format", "(", "ws_record_key", ")", ")", "# TODO - 20180814 - Check pt number, rio name and integration direction", "if", "ws_record_key", "in", "self", ".", "_single_pt_matrix_dict", ":", "# check integration manager", "integration_manager", "=", "self", ".", "_single_pt_matrix_dict", "[", "ws_record_key", "]", "assert", "integration_manager", ".", "exp_number", "==", "exp_number", ",", "'blabla'", "else", ":", "raise", "RuntimeError", "(", "'Last single-pt integration manager (key) {} does not exist.'", ".", "format", "(", "ws_record_key", ")", ")", "matrix_ws", "=", "AnalysisDataService", ".", "retrieve", "(", "integration_manager", ".", "get_model_workspace", "(", ")", ")", "ws_index", "=", "integration_manager", ".", "get_spectrum_number", "(", "scan_number", ",", "from_zero", "=", "True", ")", "vec_x", "=", "matrix_ws", ".", "readX", "(", "ws_index", ")", "vec_model", "=", "matrix_ws", ".", "readY", "(", "ws_index", ")", "return", "vec_x", ",", "vec_model" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/reduce4circleControl.py#L484-L513
llvm/llvm-project
ffa6262cb4e2a335d26416fad39a581b4f98c5f4
clang/bindings/python/clang/cindex.py
python
SourceLocation.column
(self)
return self._get_instantiation()[2]
Get the column represented by this source location.
Get the column represented by this source location.
[ "Get", "the", "column", "represented", "by", "this", "source", "location", "." ]
def column(self): """Get the column represented by this source location.""" return self._get_instantiation()[2]
[ "def", "column", "(", "self", ")", ":", "return", "self", ".", "_get_instantiation", "(", ")", "[", "2", "]" ]
https://github.com/llvm/llvm-project/blob/ffa6262cb4e2a335d26416fad39a581b4f98c5f4/clang/bindings/python/clang/cindex.py#L280-L282
crosslife/OpenBird
9e0198a1a2295f03fa1e8676e216e22c9c7d380b
cocos2d/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py
python
Type.translation_unit
(self)
return self._tu
The TranslationUnit to which this Type is associated.
The TranslationUnit to which this Type is associated.
[ "The", "TranslationUnit", "to", "which", "this", "Type", "is", "associated", "." ]
def translation_unit(self): """The TranslationUnit to which this Type is associated.""" # If this triggers an AttributeError, the instance was not properly # instantiated. return self._tu
[ "def", "translation_unit", "(", "self", ")", ":", "# If this triggers an AttributeError, the instance was not properly", "# instantiated.", "return", "self", ".", "_tu" ]
https://github.com/crosslife/OpenBird/blob/9e0198a1a2295f03fa1e8676e216e22c9c7d380b/cocos2d/tools/bindings-generator/backup/clang-llvm-3.3-pybinding/cindex.py#L1531-L1535
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/_core.py
python
BookCtrlBase_GetClassDefaultAttributes
(*args, **kwargs)
return _core_.BookCtrlBase_GetClassDefaultAttributes(*args, **kwargs)
BookCtrlBase_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.
BookCtrlBase_GetClassDefaultAttributes(int variant=WINDOW_VARIANT_NORMAL) -> VisualAttributes
[ "BookCtrlBase_GetClassDefaultAttributes", "(", "int", "variant", "=", "WINDOW_VARIANT_NORMAL", ")", "-", ">", "VisualAttributes" ]
def BookCtrlBase_GetClassDefaultAttributes(*args, **kwargs): """ BookCtrlBase_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 _core_.BookCtrlBase_GetClassDefaultAttributes(*args, **kwargs)
[ "def", "BookCtrlBase_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_core_", ".", "BookCtrlBase_GetClassDefaultAttributes", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/_core.py#L13683-L13698
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/bdist_egg.py
python
iter_symbols
(code)
Yield names and strings used by `code` and its nested code objects
Yield names and strings used by `code` and its nested code objects
[ "Yield", "names", "and", "strings", "used", "by", "code", "and", "its", "nested", "code", "objects" ]
def iter_symbols(code): """Yield names and strings used by `code` and its nested code objects""" for name in code.co_names: yield name for const in code.co_consts: if isinstance(const, six.string_types): yield const elif isinstance(const, CodeType): for name in iter_symbols(const): yield name
[ "def", "iter_symbols", "(", "code", ")", ":", "for", "name", "in", "code", ".", "co_names", ":", "yield", "name", "for", "const", "in", "code", ".", "co_consts", ":", "if", "isinstance", "(", "const", ",", "six", ".", "string_types", ")", ":", "yield", "const", "elif", "isinstance", "(", "const", ",", "CodeType", ")", ":", "for", "name", "in", "iter_symbols", "(", "const", ")", ":", "yield", "name" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/windows/Lib/site-packages/setuptools/command/bdist_egg.py#L449-L458
psi4/psi4
be533f7f426b6ccc263904e55122899b16663395
psi4/driver/qcdb/libmintscoordentry.py
python
NumberValue.rset
(self, val)
Resets value of coordinate if not fixed
Resets value of coordinate if not fixed
[ "Resets", "value", "of", "coordinate", "if", "not", "fixed" ]
def rset(self, val): """Resets value of coordinate if not fixed""" if not self.PYfixed: self.value = val
[ "def", "rset", "(", "self", ",", "val", ")", ":", "if", "not", "self", ".", "PYfixed", ":", "self", ".", "value", "=", "val" ]
https://github.com/psi4/psi4/blob/be533f7f426b6ccc263904e55122899b16663395/psi4/driver/qcdb/libmintscoordentry.py#L80-L83
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/customtreectrl.py
python
GenericTreeItem.Set3StateValue
(self, state)
Sets the checkbox item to the given `state`. :param integer `state`: can be one of: ``wx.CHK_UNCHECKED`` (check is off), ``wx.CHK_CHECKED`` (check is on) or ``wx.CHK_UNDETERMINED`` (check is mixed). :raise: `Exception` when the item is not a 3-state checkbox item. :note: This method raises an exception when the checkbox item is a 2-state checkbox and setting the state to ``wx.CHK_UNDETERMINED``. :note: This method is meaningful only for checkbox-like items.
Sets the checkbox item to the given `state`.
[ "Sets", "the", "checkbox", "item", "to", "the", "given", "state", "." ]
def Set3StateValue(self, state): """ Sets the checkbox item to the given `state`. :param integer `state`: can be one of: ``wx.CHK_UNCHECKED`` (check is off), ``wx.CHK_CHECKED`` (check is on) or ``wx.CHK_UNDETERMINED`` (check is mixed). :raise: `Exception` when the item is not a 3-state checkbox item. :note: This method raises an exception when the checkbox item is a 2-state checkbox and setting the state to ``wx.CHK_UNDETERMINED``. :note: This method is meaningful only for checkbox-like items. """ if not self._is3State and state == wx.CHK_UNDETERMINED: raise Exception("Set3StateValue can only be used with 3-state checkbox items.") self._checked = state
[ "def", "Set3StateValue", "(", "self", ",", "state", ")", ":", "if", "not", "self", ".", "_is3State", "and", "state", "==", "wx", ".", "CHK_UNDETERMINED", ":", "raise", "Exception", "(", "\"Set3StateValue can only be used with 3-state checkbox items.\"", ")", "self", ".", "_checked", "=", "state" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/customtreectrl.py#L2215-L2233
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/osx_cocoa/richtext.py
python
RichTextCtrl.ApplyItalicToSelection
(*args, **kwargs)
return _richtext.RichTextCtrl_ApplyItalicToSelection(*args, **kwargs)
ApplyItalicToSelection(self) -> bool Apply italic to the selection
ApplyItalicToSelection(self) -> bool
[ "ApplyItalicToSelection", "(", "self", ")", "-", ">", "bool" ]
def ApplyItalicToSelection(*args, **kwargs): """ ApplyItalicToSelection(self) -> bool Apply italic to the selection """ return _richtext.RichTextCtrl_ApplyItalicToSelection(*args, **kwargs)
[ "def", "ApplyItalicToSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_richtext", ".", "RichTextCtrl_ApplyItalicToSelection", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/osx_cocoa/richtext.py#L3959-L3965
microsoft/checkedc-clang
a173fefde5d7877b7750e7ce96dd08cf18baebf2
clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
python
find_compilation_database
(path)
return os.path.realpath(result)
Adjusts the directory until a compilation database is found.
Adjusts the directory until a compilation database is found.
[ "Adjusts", "the", "directory", "until", "a", "compilation", "database", "is", "found", "." ]
def find_compilation_database(path): """Adjusts the directory until a compilation database is found.""" result = './' while not os.path.isfile(os.path.join(result, path)): if os.path.realpath(result) == '/': print('Error: could not find compilation database.') sys.exit(1) result += '../' return os.path.realpath(result)
[ "def", "find_compilation_database", "(", "path", ")", ":", "result", "=", "'./'", "while", "not", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "result", ",", "path", ")", ")", ":", "if", "os", ".", "path", ".", "realpath", "(", "result", ")", "==", "'/'", ":", "print", "(", "'Error: could not find compilation database.'", ")", "sys", ".", "exit", "(", "1", ")", "result", "+=", "'../'", "return", "os", ".", "path", ".", "realpath", "(", "result", ")" ]
https://github.com/microsoft/checkedc-clang/blob/a173fefde5d7877b7750e7ce96dd08cf18baebf2/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py#L65-L73
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/AWSPythonSDK/1.5.8/boto3/dynamodb/conditions.py
python
Attr.ne
(self, value)
return NotEquals(self, value)
Creates a condition where the attribute is not equal to the value :param value: The value that the attribute is not equal to.
Creates a condition where the attribute is not equal to the value
[ "Creates", "a", "condition", "where", "the", "attribute", "is", "not", "equal", "to", "the", "value" ]
def ne(self, value): """Creates a condition where the attribute is not equal to the value :param value: The value that the attribute is not equal to. """ return NotEquals(self, value)
[ "def", "ne", "(", "self", ",", "value", ")", ":", "return", "NotEquals", "(", "self", ",", "value", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/AWSPythonSDK/1.5.8/boto3/dynamodb/conditions.py#L230-L235
oracle/graaljs
36a56e8e993d45fc40939a3a4d9c0c24990720f1
graal-nodejs/deps/v8/third_party/jinja2/ext.py
python
Extension.bind
(self, environment)
return rv
Create a copy of this extension bound to another environment.
Create a copy of this extension bound to another environment.
[ "Create", "a", "copy", "of", "this", "extension", "bound", "to", "another", "environment", "." ]
def bind(self, environment): """Create a copy of this extension bound to another environment.""" rv = object.__new__(self.__class__) rv.__dict__.update(self.__dict__) rv.environment = environment return rv
[ "def", "bind", "(", "self", ",", "environment", ")", ":", "rv", "=", "object", ".", "__new__", "(", "self", ".", "__class__", ")", "rv", ".", "__dict__", ".", "update", "(", "self", ".", "__dict__", ")", "rv", ".", "environment", "=", "environment", "return", "rv" ]
https://github.com/oracle/graaljs/blob/36a56e8e993d45fc40939a3a4d9c0c24990720f1/graal-nodejs/deps/v8/third_party/jinja2/ext.py#L75-L80
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/serialize.py
python
_get_function_globals_for_reduction
(func)
return globs
Analyse *func* and return a dictionary of global values suitable for reduction.
Analyse *func* and return a dictionary of global values suitable for reduction.
[ "Analyse", "*", "func", "*", "and", "return", "a", "dictionary", "of", "global", "values", "suitable", "for", "reduction", "." ]
def _get_function_globals_for_reduction(func): """ Analyse *func* and return a dictionary of global values suitable for reduction. """ func_id = bytecode.FunctionIdentity.from_function(func) bc = bytecode.ByteCode(func_id) globs = bc.get_used_globals() for k, v in globs.items(): # Make modules picklable by name if isinstance(v, ModuleType): globs[k] = _ModuleRef(v.__name__) # Remember the module name so that the function gets a proper __module__ # when rebuilding. This is used to recreate the environment. globs['__name__'] = func.__module__ return globs
[ "def", "_get_function_globals_for_reduction", "(", "func", ")", ":", "func_id", "=", "bytecode", ".", "FunctionIdentity", ".", "from_function", "(", "func", ")", "bc", "=", "bytecode", ".", "ByteCode", "(", "func_id", ")", "globs", "=", "bc", ".", "get_used_globals", "(", ")", "for", "k", ",", "v", "in", "globs", ".", "items", "(", ")", ":", "# Make modules picklable by name", "if", "isinstance", "(", "v", ",", "ModuleType", ")", ":", "globs", "[", "k", "]", "=", "_ModuleRef", "(", "v", ".", "__name__", ")", "# Remember the module name so that the function gets a proper __module__", "# when rebuilding. This is used to recreate the environment.", "globs", "[", "'__name__'", "]", "=", "func", ".", "__module__", "return", "globs" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/numba/serialize.py#L50-L65
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/eager/context.py
python
set_log_device_placement
(enabled)
Turns logging for device placement decisions on or off. Operations execute on a particular device, producing and consuming tensors on that device. This may change the performance of the operation or require TensorFlow to copy data to or from an accelerator, so knowing where operations execute is useful for debugging performance issues. For more advanced profiling, use the [TensorFlow profiler](https://www.tensorflow.org/guide/profiler). Device placement for operations is typically controlled by a `tf.device` scope, but there are exceptions, for example operations on a `tf.Variable` which follow the initial placement of the variable. Turning off soft device placement (with `tf.config.set_soft_device_placement`) provides more explicit control. >>> tf.debugging.set_log_device_placement(True) >>> tf.ones([]) >>> # [...] op Fill in device /job:localhost/replica:0/task:0/device:GPU:0 >>> with tf.device("CPU"): ... tf.ones([]) >>> # [...] op Fill in device /job:localhost/replica:0/task:0/device:CPU:0 >>> tf.debugging.set_log_device_placement(False) Turning on `tf.debugging.set_log_device_placement` also logs the placement of ops inside `tf.function` when the function is called. Args: enabled: Whether to enabled device placement logging.
Turns logging for device placement decisions on or off.
[ "Turns", "logging", "for", "device", "placement", "decisions", "on", "or", "off", "." ]
def set_log_device_placement(enabled): """Turns logging for device placement decisions on or off. Operations execute on a particular device, producing and consuming tensors on that device. This may change the performance of the operation or require TensorFlow to copy data to or from an accelerator, so knowing where operations execute is useful for debugging performance issues. For more advanced profiling, use the [TensorFlow profiler](https://www.tensorflow.org/guide/profiler). Device placement for operations is typically controlled by a `tf.device` scope, but there are exceptions, for example operations on a `tf.Variable` which follow the initial placement of the variable. Turning off soft device placement (with `tf.config.set_soft_device_placement`) provides more explicit control. >>> tf.debugging.set_log_device_placement(True) >>> tf.ones([]) >>> # [...] op Fill in device /job:localhost/replica:0/task:0/device:GPU:0 >>> with tf.device("CPU"): ... tf.ones([]) >>> # [...] op Fill in device /job:localhost/replica:0/task:0/device:CPU:0 >>> tf.debugging.set_log_device_placement(False) Turning on `tf.debugging.set_log_device_placement` also logs the placement of ops inside `tf.function` when the function is called. Args: enabled: Whether to enabled device placement logging. """ context().log_device_placement = enabled
[ "def", "set_log_device_placement", "(", "enabled", ")", ":", "context", "(", ")", ".", "log_device_placement", "=", "enabled" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/context.py#L2358-L2389
ValveSoftware/source-sdk-2013
0d8dceea4310fde5706b3ce1c70609d72a38efdf
sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py
python
_AddIsInitializedMethod
(message_descriptor, cls)
Adds the IsInitialized and FindInitializationError methods to the protocol message class.
Adds the IsInitialized and FindInitializationError methods to the protocol message class.
[ "Adds", "the", "IsInitialized", "and", "FindInitializationError", "methods", "to", "the", "protocol", "message", "class", "." ]
def _AddIsInitializedMethod(message_descriptor, cls): """Adds the IsInitialized and FindInitializationError methods to the protocol message class.""" required_fields = [field for field in message_descriptor.fields if field.label == _FieldDescriptor.LABEL_REQUIRED] def IsInitialized(self, errors=None): """Checks if all required fields of a message are set. Args: errors: A list which, if provided, will be populated with the field paths of all missing required fields. Returns: True iff the specified message has all required fields set. """ # Performance is critical so we avoid HasField() and ListFields(). for field in required_fields: if (field not in self._fields or (field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE and not self._fields[field]._is_present_in_parent)): if errors is not None: errors.extend(self.FindInitializationErrors()) return False for field, value in self._fields.iteritems(): if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: if field.label == _FieldDescriptor.LABEL_REPEATED: for element in value: if not element.IsInitialized(): if errors is not None: errors.extend(self.FindInitializationErrors()) return False elif value._is_present_in_parent and not value.IsInitialized(): if errors is not None: errors.extend(self.FindInitializationErrors()) return False return True cls.IsInitialized = IsInitialized def FindInitializationErrors(self): """Finds required fields which are not initialized. Returns: A list of strings. Each string is a path to an uninitialized field from the top-level message, e.g. "foo.bar[5].baz". """ errors = [] # simplify things for field in required_fields: if not self.HasField(field.name): errors.append(field.name) for field, value in self.ListFields(): if field.cpp_type == _FieldDescriptor.CPPTYPE_MESSAGE: if field.is_extension: name = "(%s)" % field.full_name else: name = field.name if field.label == _FieldDescriptor.LABEL_REPEATED: for i in xrange(len(value)): element = value[i] prefix = "%s[%d]." % (name, i) sub_errors = element.FindInitializationErrors() errors += [ prefix + error for error in sub_errors ] else: prefix = name + "." sub_errors = value.FindInitializationErrors() errors += [ prefix + error for error in sub_errors ] return errors cls.FindInitializationErrors = FindInitializationErrors
[ "def", "_AddIsInitializedMethod", "(", "message_descriptor", ",", "cls", ")", ":", "required_fields", "=", "[", "field", "for", "field", "in", "message_descriptor", ".", "fields", "if", "field", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_REQUIRED", "]", "def", "IsInitialized", "(", "self", ",", "errors", "=", "None", ")", ":", "\"\"\"Checks if all required fields of a message are set.\n\n Args:\n errors: A list which, if provided, will be populated with the field\n paths of all missing required fields.\n\n Returns:\n True iff the specified message has all required fields set.\n \"\"\"", "# Performance is critical so we avoid HasField() and ListFields().", "for", "field", "in", "required_fields", ":", "if", "(", "field", "not", "in", "self", ".", "_fields", "or", "(", "field", ".", "cpp_type", "==", "_FieldDescriptor", ".", "CPPTYPE_MESSAGE", "and", "not", "self", ".", "_fields", "[", "field", "]", ".", "_is_present_in_parent", ")", ")", ":", "if", "errors", "is", "not", "None", ":", "errors", ".", "extend", "(", "self", ".", "FindInitializationErrors", "(", ")", ")", "return", "False", "for", "field", ",", "value", "in", "self", ".", "_fields", ".", "iteritems", "(", ")", ":", "if", "field", ".", "cpp_type", "==", "_FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "if", "field", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_REPEATED", ":", "for", "element", "in", "value", ":", "if", "not", "element", ".", "IsInitialized", "(", ")", ":", "if", "errors", "is", "not", "None", ":", "errors", ".", "extend", "(", "self", ".", "FindInitializationErrors", "(", ")", ")", "return", "False", "elif", "value", ".", "_is_present_in_parent", "and", "not", "value", ".", "IsInitialized", "(", ")", ":", "if", "errors", "is", "not", "None", ":", "errors", ".", "extend", "(", "self", ".", "FindInitializationErrors", "(", ")", ")", "return", "False", "return", "True", "cls", ".", "IsInitialized", "=", "IsInitialized", "def", "FindInitializationErrors", "(", "self", ")", ":", "\"\"\"Finds required fields which are not initialized.\n\n Returns:\n A list of strings. Each string is a path to an uninitialized field from\n the top-level message, e.g. \"foo.bar[5].baz\".\n \"\"\"", "errors", "=", "[", "]", "# simplify things", "for", "field", "in", "required_fields", ":", "if", "not", "self", ".", "HasField", "(", "field", ".", "name", ")", ":", "errors", ".", "append", "(", "field", ".", "name", ")", "for", "field", ",", "value", "in", "self", ".", "ListFields", "(", ")", ":", "if", "field", ".", "cpp_type", "==", "_FieldDescriptor", ".", "CPPTYPE_MESSAGE", ":", "if", "field", ".", "is_extension", ":", "name", "=", "\"(%s)\"", "%", "field", ".", "full_name", "else", ":", "name", "=", "field", ".", "name", "if", "field", ".", "label", "==", "_FieldDescriptor", ".", "LABEL_REPEATED", ":", "for", "i", "in", "xrange", "(", "len", "(", "value", ")", ")", ":", "element", "=", "value", "[", "i", "]", "prefix", "=", "\"%s[%d].\"", "%", "(", "name", ",", "i", ")", "sub_errors", "=", "element", ".", "FindInitializationErrors", "(", ")", "errors", "+=", "[", "prefix", "+", "error", "for", "error", "in", "sub_errors", "]", "else", ":", "prefix", "=", "name", "+", "\".\"", "sub_errors", "=", "value", ".", "FindInitializationErrors", "(", ")", "errors", "+=", "[", "prefix", "+", "error", "for", "error", "in", "sub_errors", "]", "return", "errors", "cls", ".", "FindInitializationErrors", "=", "FindInitializationErrors" ]
https://github.com/ValveSoftware/source-sdk-2013/blob/0d8dceea4310fde5706b3ce1c70609d72a38efdf/sp/src/thirdparty/protobuf-2.3.0/python/google/protobuf/reflection.py#L853-L932
Komnomnomnom/swigibpy
cfd307fdbfaffabc69a2dc037538d7e34a8b8daf
swigibpy.py
python
EClientSocketBase.subscribeToGroupEvents
(self, reqId, groupId)
return _swigibpy.EClientSocketBase_subscribeToGroupEvents(self, reqId, groupId)
subscribeToGroupEvents(EClientSocketBase self, int reqId, int groupId)
subscribeToGroupEvents(EClientSocketBase self, int reqId, int groupId)
[ "subscribeToGroupEvents", "(", "EClientSocketBase", "self", "int", "reqId", "int", "groupId", ")" ]
def subscribeToGroupEvents(self, reqId, groupId): """subscribeToGroupEvents(EClientSocketBase self, int reqId, int groupId)""" return _swigibpy.EClientSocketBase_subscribeToGroupEvents(self, reqId, groupId)
[ "def", "subscribeToGroupEvents", "(", "self", ",", "reqId", ",", "groupId", ")", ":", "return", "_swigibpy", ".", "EClientSocketBase_subscribeToGroupEvents", "(", "self", ",", "reqId", ",", "groupId", ")" ]
https://github.com/Komnomnomnom/swigibpy/blob/cfd307fdbfaffabc69a2dc037538d7e34a8b8daf/swigibpy.py#L1672-L1674
fatih/subvim
241b6d170597857105da219c9b7d36059e9f11fb
vim/base/YouCompleteMe/third_party/jedi/jedi/api_classes.py
python
BaseDefinition.__init__
(self, definition, start_pos)
An instance of :class:`jedi.parsing_representation.Base` subclass.
An instance of :class:`jedi.parsing_representation.Base` subclass.
[ "An", "instance", "of", ":", "class", ":", "jedi", ".", "parsing_representation", ".", "Base", "subclass", "." ]
def __init__(self, definition, start_pos): self._start_pos = start_pos self._definition = definition """ An instance of :class:`jedi.parsing_representation.Base` subclass. """ self.is_keyword = isinstance(definition, keywords.Keyword) # generate a path to the definition self._module = definition.get_parent_until() self.module_path = self._module.path """Shows the file path of a module. e.g. ``/usr/lib/python2.7/os.py``"""
[ "def", "__init__", "(", "self", ",", "definition", ",", "start_pos", ")", ":", "self", ".", "_start_pos", "=", "start_pos", "self", ".", "_definition", "=", "definition", "self", ".", "is_keyword", "=", "isinstance", "(", "definition", ",", "keywords", ".", "Keyword", ")", "# generate a path to the definition", "self", ".", "_module", "=", "definition", ".", "get_parent_until", "(", ")", "self", ".", "module_path", "=", "self", ".", "_module", ".", "path", "\"\"\"Shows the file path of a module. e.g. ``/usr/lib/python2.7/os.py``\"\"\"" ]
https://github.com/fatih/subvim/blob/241b6d170597857105da219c9b7d36059e9f11fb/vim/base/YouCompleteMe/third_party/jedi/jedi/api_classes.py#L72-L83
facebookincubator/BOLT
88c70afe9d388ad430cc150cc158641701397f70
lldb/utils/lui/lldbutil.py
python
get_description
(obj, option=None)
return stream.GetData()
Calls lldb_obj.GetDescription() and returns a string, or None. For SBTarget, SBBreakpointLocation, and SBWatchpoint lldb objects, an extra option can be passed in to describe the detailed level of description desired: o lldb.eDescriptionLevelBrief o lldb.eDescriptionLevelFull o lldb.eDescriptionLevelVerbose
Calls lldb_obj.GetDescription() and returns a string, or None.
[ "Calls", "lldb_obj", ".", "GetDescription", "()", "and", "returns", "a", "string", "or", "None", "." ]
def get_description(obj, option=None): """Calls lldb_obj.GetDescription() and returns a string, or None. For SBTarget, SBBreakpointLocation, and SBWatchpoint lldb objects, an extra option can be passed in to describe the detailed level of description desired: o lldb.eDescriptionLevelBrief o lldb.eDescriptionLevelFull o lldb.eDescriptionLevelVerbose """ method = getattr(obj, 'GetDescription') if not method: return None tuple = (lldb.SBTarget, lldb.SBBreakpointLocation, lldb.SBWatchpoint) if isinstance(obj, tuple): if option is None: option = lldb.eDescriptionLevelBrief stream = lldb.SBStream() if option is None: success = method(stream) else: success = method(stream, option) if not success: return None return stream.GetData()
[ "def", "get_description", "(", "obj", ",", "option", "=", "None", ")", ":", "method", "=", "getattr", "(", "obj", ",", "'GetDescription'", ")", "if", "not", "method", ":", "return", "None", "tuple", "=", "(", "lldb", ".", "SBTarget", ",", "lldb", ".", "SBBreakpointLocation", ",", "lldb", ".", "SBWatchpoint", ")", "if", "isinstance", "(", "obj", ",", "tuple", ")", ":", "if", "option", "is", "None", ":", "option", "=", "lldb", ".", "eDescriptionLevelBrief", "stream", "=", "lldb", ".", "SBStream", "(", ")", "if", "option", "is", "None", ":", "success", "=", "method", "(", "stream", ")", "else", ":", "success", "=", "method", "(", "stream", ",", "option", ")", "if", "not", "success", ":", "return", "None", "return", "stream", ".", "GetData", "(", ")" ]
https://github.com/facebookincubator/BOLT/blob/88c70afe9d388ad430cc150cc158641701397f70/lldb/utils/lui/lldbutil.py#L121-L146
smartdevicelink/sdl_core
68f082169e0a40fccd9eb0db3c83911c28870f07
tools/InterfaceGenerator/generator/parsers/JSONRPC.py
python
Parser._provide_enum_element_for_function
(self, enum_name, element_name)
return element
Provide enum element for functions. This implementation replaces the underscore separating interface and function name with dot and sets it as name of enum element leaving the name with underscore as internal_name. For enums other than FunctionID the base implementation is called. Returns EnumElement.
Provide enum element for functions.
[ "Provide", "enum", "element", "for", "functions", "." ]
def _provide_enum_element_for_function(self, enum_name, element_name): """Provide enum element for functions. This implementation replaces the underscore separating interface and function name with dot and sets it as name of enum element leaving the name with underscore as internal_name. For enums other than FunctionID the base implementation is called. Returns EnumElement. """ name = element_name internal_name = None if "FunctionID" == enum_name: prefix_length = len(self._interface_name) + 1 if element_name[:prefix_length] != self._interface_name + '_': raise ParseError( "Unexpected prefix for function id '" + element_name + "'") name = self._interface_name + "." + element_name[prefix_length:] internal_name = element_name element = super(Parser, self)._provide_enum_element_for_function( enum_name, name) if internal_name is not None: element.internal_name = internal_name return element
[ "def", "_provide_enum_element_for_function", "(", "self", ",", "enum_name", ",", "element_name", ")", ":", "name", "=", "element_name", "internal_name", "=", "None", "if", "\"FunctionID\"", "==", "enum_name", ":", "prefix_length", "=", "len", "(", "self", ".", "_interface_name", ")", "+", "1", "if", "element_name", "[", ":", "prefix_length", "]", "!=", "self", ".", "_interface_name", "+", "'_'", ":", "raise", "ParseError", "(", "\"Unexpected prefix for function id '\"", "+", "element_name", "+", "\"'\"", ")", "name", "=", "self", ".", "_interface_name", "+", "\".\"", "+", "element_name", "[", "prefix_length", ":", "]", "internal_name", "=", "element_name", "element", "=", "super", "(", "Parser", ",", "self", ")", ".", "_provide_enum_element_for_function", "(", "enum_name", ",", "name", ")", "if", "internal_name", "is", "not", "None", ":", "element", ".", "internal_name", "=", "internal_name", "return", "element" ]
https://github.com/smartdevicelink/sdl_core/blob/68f082169e0a40fccd9eb0db3c83911c28870f07/tools/InterfaceGenerator/generator/parsers/JSONRPC.py#L60-L91
mantidproject/mantid
03deeb89254ec4289edb8771e0188c2090a02f32
qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py
python
ProcessTableWidget.get_mask
(self, row_index)
return self.get_cell_value(row_index, self._colIndexMask)
get the mask/ROI name that this integration is based on :param row_index: :return:
get the mask/ROI name that this integration is based on :param row_index: :return:
[ "get", "the", "mask", "/", "ROI", "name", "that", "this", "integration", "is", "based", "on", ":", "param", "row_index", ":", ":", "return", ":" ]
def get_mask(self, row_index): """ get the mask/ROI name that this integration is based on :param row_index: :return: """ return self.get_cell_value(row_index, self._colIndexMask)
[ "def", "get_mask", "(", "self", ",", "row_index", ")", ":", "return", "self", ".", "get_cell_value", "(", "row_index", ",", "self", ".", "_colIndexMask", ")" ]
https://github.com/mantidproject/mantid/blob/03deeb89254ec4289edb8771e0188c2090a02f32/qt/python/mantidqtinterfaces/mantidqtinterfaces/HFIR_4Circle_Reduction/hfctables.py#L820-L826
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/decimal.py
python
Context._regard_flags
(self, *flags)
Stop ignoring the flags, if they are raised
Stop ignoring the flags, if they are raised
[ "Stop", "ignoring", "the", "flags", "if", "they", "are", "raised" ]
def _regard_flags(self, *flags): """Stop ignoring the flags, if they are raised""" if flags and isinstance(flags[0], (tuple,list)): flags = flags[0] for flag in flags: self._ignored_flags.remove(flag)
[ "def", "_regard_flags", "(", "self", ",", "*", "flags", ")", ":", "if", "flags", "and", "isinstance", "(", "flags", "[", "0", "]", ",", "(", "tuple", ",", "list", ")", ")", ":", "flags", "=", "flags", "[", "0", "]", "for", "flag", "in", "flags", ":", "self", ".", "_ignored_flags", ".", "remove", "(", "flag", ")" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/decimal.py#L3732-L3737
SequoiaDB/SequoiaDB
2894ed7e5bd6fe57330afc900cf76d0ff0df9f64
tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py
python
xmlTextReader.Prefix
(self)
return ret
A shorthand reference to the namespace associated with the node.
A shorthand reference to the namespace associated with the node.
[ "A", "shorthand", "reference", "to", "the", "namespace", "associated", "with", "the", "node", "." ]
def Prefix(self): """A shorthand reference to the namespace associated with the node. """ ret = libxml2mod.xmlTextReaderConstPrefix(self._o) return ret
[ "def", "Prefix", "(", "self", ")", ":", "ret", "=", "libxml2mod", ".", "xmlTextReaderConstPrefix", "(", "self", ".", "_o", ")", "return", "ret" ]
https://github.com/SequoiaDB/SequoiaDB/blob/2894ed7e5bd6fe57330afc900cf76d0ff0df9f64/tools/server/php_linux/libxml2/lib/python2.4/site-packages/libxml2.py#L6751-L6755
BlzFans/wke
b0fa21158312e40c5fbd84682d643022b6c34a93
cygwin/lib/python2.6/locale.py
python
_build_localename
(localetuple)
Builds a locale code from the given tuple (language code, encoding). No aliasing or normalizing takes place.
Builds a locale code from the given tuple (language code, encoding).
[ "Builds", "a", "locale", "code", "from", "the", "given", "tuple", "(", "language", "code", "encoding", ")", "." ]
def _build_localename(localetuple): """ Builds a locale code from the given tuple (language code, encoding). No aliasing or normalizing takes place. """ language, encoding = localetuple if language is None: language = 'C' if encoding is None: return language else: return language + '.' + encoding
[ "def", "_build_localename", "(", "localetuple", ")", ":", "language", ",", "encoding", "=", "localetuple", "if", "language", "is", "None", ":", "language", "=", "'C'", "if", "encoding", "is", "None", ":", "return", "language", "else", ":", "return", "language", "+", "'.'", "+", "encoding" ]
https://github.com/BlzFans/wke/blob/b0fa21158312e40c5fbd84682d643022b6c34a93/cygwin/lib/python2.6/locale.py#L412-L426
wlanjie/AndroidFFmpeg
7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf
tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py
python
TurtleScreenBase._resize
(self, canvwidth=None, canvheight=None, bg=None)
Resize the canvas the turtles are drawing on. Does not alter the drawing window.
Resize the canvas the turtles are drawing on. Does not alter the drawing window.
[ "Resize", "the", "canvas", "the", "turtles", "are", "drawing", "on", ".", "Does", "not", "alter", "the", "drawing", "window", "." ]
def _resize(self, canvwidth=None, canvheight=None, bg=None): """Resize the canvas the turtles are drawing on. Does not alter the drawing window. """ # needs amendment if not isinstance(self.cv, ScrolledCanvas): return self.canvwidth, self.canvheight if canvwidth is canvheight is bg is None: return self.cv.canvwidth, self.cv.canvheight if canvwidth is not None: self.canvwidth = canvwidth if canvheight is not None: self.canvheight = canvheight self.cv.reset(canvwidth, canvheight, bg)
[ "def", "_resize", "(", "self", ",", "canvwidth", "=", "None", ",", "canvheight", "=", "None", ",", "bg", "=", "None", ")", ":", "# needs amendment", "if", "not", "isinstance", "(", "self", ".", "cv", ",", "ScrolledCanvas", ")", ":", "return", "self", ".", "canvwidth", ",", "self", ".", "canvheight", "if", "canvwidth", "is", "canvheight", "is", "bg", "is", "None", ":", "return", "self", ".", "cv", ".", "canvwidth", ",", "self", ".", "cv", ".", "canvheight", "if", "canvwidth", "is", "not", "None", ":", "self", ".", "canvwidth", "=", "canvwidth", "if", "canvheight", "is", "not", "None", ":", "self", ".", "canvheight", "=", "canvheight", "self", ".", "cv", ".", "reset", "(", "canvwidth", ",", "canvheight", ",", "bg", ")" ]
https://github.com/wlanjie/AndroidFFmpeg/blob/7baf9122f4b8e1c74e7baf4be5c422c7a5ba5aaf/tools/fdk-aac-build/x86/toolchain/lib/python2.7/lib-tk/turtle.py#L779-L792
emlid/Navio
14b96c83ad57a10580655e3af49c9be1f5fc0ad2
Python/navio/adafruit_ads1x15.py
python
ADS1x15.stopContinuousConversion
(self)
return True
Stops the ADC's conversions when in continuous mode \ and resets the configuration to its default value.
Stops the ADC's conversions when in continuous mode \ and resets the configuration to its default value.
[ "Stops", "the", "ADC", "s", "conversions", "when", "in", "continuous", "mode", "\\", "and", "resets", "the", "configuration", "to", "its", "default", "value", "." ]
def stopContinuousConversion(self): "Stops the ADC's conversions when in continuous mode \ and resets the configuration to its default value." # Write the default config register to the ADC # Once we write, the ADC will do a single conversion and # enter power-off mode. config = 0x8583 # Page 18 datasheet. bytes = [(config >> 8) & 0xFF, config & 0xFF] self.i2c.writeList(self.__ADS1015_REG_POINTER_CONFIG, bytes) return True
[ "def", "stopContinuousConversion", "(", "self", ")", ":", "# Write the default config register to the ADC", "# Once we write, the ADC will do a single conversion and", "# enter power-off mode.", "config", "=", "0x8583", "# Page 18 datasheet.", "bytes", "=", "[", "(", "config", ">>", "8", ")", "&", "0xFF", ",", "config", "&", "0xFF", "]", "self", ".", "i2c", ".", "writeList", "(", "self", ".", "__ADS1015_REG_POINTER_CONFIG", ",", "bytes", ")", "return", "True" ]
https://github.com/emlid/Navio/blob/14b96c83ad57a10580655e3af49c9be1f5fc0ad2/Python/navio/adafruit_ads1x15.py#L496-L505
livecode/livecode
4606a10ea10b16d5071d0f9f263ccdd7ede8b31d
gyp/pylib/gyp/generator/analyzer.py
python
_GetBuildTargets
(matching_targets, roots)
return result
Returns the set of Targets that require a build. matching_targets: targets that changed and need to be built. roots: set of root targets in the build files to search from.
Returns the set of Targets that require a build. matching_targets: targets that changed and need to be built. roots: set of root targets in the build files to search from.
[ "Returns", "the", "set", "of", "Targets", "that", "require", "a", "build", ".", "matching_targets", ":", "targets", "that", "changed", "and", "need", "to", "be", "built", ".", "roots", ":", "set", "of", "root", "targets", "in", "the", "build", "files", "to", "search", "from", "." ]
def _GetBuildTargets(matching_targets, roots): """Returns the set of Targets that require a build. matching_targets: targets that changed and need to be built. roots: set of root targets in the build files to search from.""" result = set() for target in matching_targets: _AddBuildTargets(target, roots, True, result) return result
[ "def", "_GetBuildTargets", "(", "matching_targets", ",", "roots", ")", ":", "result", "=", "set", "(", ")", "for", "target", "in", "matching_targets", ":", "_AddBuildTargets", "(", "target", ",", "roots", ",", "True", ",", "result", ")", "return", "result" ]
https://github.com/livecode/livecode/blob/4606a10ea10b16d5071d0f9f263ccdd7ede8b31d/gyp/pylib/gyp/generator/analyzer.py#L426-L433
neopenx/Dragon
0e639a7319035ddc81918bd3df059230436ee0a1
Dragon/python/dragon/vm/caffe/solver.py
python
Solver.iter
(self)
return self._iter
Return or Set the current iteration. [**PyCaffe Style**] Parameters ---------- iter : int The value of iteration to set. Returns ------- The current iteration.
Return or Set the current iteration. [**PyCaffe Style**]
[ "Return", "or", "Set", "the", "current", "iteration", ".", "[", "**", "PyCaffe", "Style", "**", "]" ]
def iter(self): """Return or Set the current iteration. [**PyCaffe Style**] Parameters ---------- iter : int The value of iteration to set. Returns ------- The current iteration. """ return self._iter
[ "def", "iter", "(", "self", ")", ":", "return", "self", ".", "_iter" ]
https://github.com/neopenx/Dragon/blob/0e639a7319035ddc81918bd3df059230436ee0a1/Dragon/python/dragon/vm/caffe/solver.py#L383-L396
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py
python
WorkingSet.__init__
(self, entries=None)
Create working set from list of path entries (default=sys.path)
Create working set from list of path entries (default=sys.path)
[ "Create", "working", "set", "from", "list", "of", "path", "entries", "(", "default", "=", "sys", ".", "path", ")" ]
def __init__(self, entries=None): """Create working set from list of path entries (default=sys.path)""" self.entries = [] self.entry_keys = {} self.by_key = {} self.callbacks = [] if entries is None: entries = sys.path for entry in entries: self.add_entry(entry)
[ "def", "__init__", "(", "self", ",", "entries", "=", "None", ")", ":", "self", ".", "entries", "=", "[", "]", "self", ".", "entry_keys", "=", "{", "}", "self", ".", "by_key", "=", "{", "}", "self", ".", "callbacks", "=", "[", "]", "if", "entries", "is", "None", ":", "entries", "=", "sys", ".", "path", "for", "entry", "in", "entries", ":", "self", ".", "add_entry", "(", "entry", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/common-code/Lib/pkg_resources/__init__.py#L557-L568
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
src/msw/_gdi.py
python
GraphicsGradientStops.SetEndColour
(*args, **kwargs)
return _gdi_.GraphicsGradientStops_SetEndColour(*args, **kwargs)
SetEndColour(self, Colour col)
SetEndColour(self, Colour col)
[ "SetEndColour", "(", "self", "Colour", "col", ")" ]
def SetEndColour(*args, **kwargs): """SetEndColour(self, Colour col)""" return _gdi_.GraphicsGradientStops_SetEndColour(*args, **kwargs)
[ "def", "SetEndColour", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "_gdi_", ".", "GraphicsGradientStops_SetEndColour", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/src/msw/_gdi.py#L6106-L6108
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/base.py
python
IndexOpsMixin.to_numpy
(self, dtype=None, copy=False, na_value=lib.no_default, **kwargs)
return result
A NumPy ndarray representing the values in this Series or Index. .. versionadded:: 0.24.0 Parameters ---------- dtype : str or numpy.dtype, optional The dtype to pass to :meth:`numpy.asarray`. copy : bool, default False Whether to ensure that the returned value is a not a view on another array. Note that ``copy=False`` does not *ensure* that ``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that a copy is made, even if not strictly necessary. na_value : Any, optional The value to use for missing values. The default value depends on `dtype` and the type of the array. .. versionadded:: 1.0.0 **kwargs Additional keywords passed through to the ``to_numpy`` method of the underlying array (for extension arrays). .. versionadded:: 1.0.0 Returns ------- numpy.ndarray See Also -------- Series.array : Get the actual data stored within. Index.array : Get the actual data stored within. DataFrame.to_numpy : Similar method for DataFrame. Notes ----- The returned array will be the same up to equality (values equal in `self` will be equal in the returned array; likewise for values that are not equal). When `self` contains an ExtensionArray, the dtype may be different. For example, for a category-dtype Series, ``to_numpy()`` will return a NumPy array and the categorical dtype will be lost. For NumPy dtypes, this will be a reference to the actual data stored in this Series or Index (assuming ``copy=False``). Modifying the result in place will modify the data stored in the Series or Index (not that we recommend doing that). For extension types, ``to_numpy()`` *may* require copying data and coercing the result to a NumPy type (possibly object), which may be expensive. When you need a no-copy reference to the underlying data, :attr:`Series.array` should be used instead. This table lays out the different dtypes and default return types of ``to_numpy()`` for various dtypes within pandas. ================== ================================ dtype array type ================== ================================ category[T] ndarray[T] (same dtype as input) period ndarray[object] (Periods) interval ndarray[object] (Intervals) IntegerNA ndarray[object] datetime64[ns] datetime64[ns] datetime64[ns, tz] ndarray[object] (Timestamps) ================== ================================ Examples -------- >>> ser = pd.Series(pd.Categorical(['a', 'b', 'a'])) >>> ser.to_numpy() array(['a', 'b', 'a'], dtype=object) Specify the `dtype` to control how datetime-aware data is represented. Use ``dtype=object`` to return an ndarray of pandas :class:`Timestamp` objects, each with the correct ``tz``. >>> ser = pd.Series(pd.date_range('2000', periods=2, tz="CET")) >>> ser.to_numpy(dtype=object) array([Timestamp('2000-01-01 00:00:00+0100', tz='CET', freq='D'), Timestamp('2000-01-02 00:00:00+0100', tz='CET', freq='D')], dtype=object) Or ``dtype='datetime64[ns]'`` to return an ndarray of native datetime64 values. The values are converted to UTC and the timezone info is dropped. >>> ser.to_numpy(dtype="datetime64[ns]") ... # doctest: +ELLIPSIS array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00...'], dtype='datetime64[ns]')
A NumPy ndarray representing the values in this Series or Index.
[ "A", "NumPy", "ndarray", "representing", "the", "values", "in", "this", "Series", "or", "Index", "." ]
def to_numpy(self, dtype=None, copy=False, na_value=lib.no_default, **kwargs): """ A NumPy ndarray representing the values in this Series or Index. .. versionadded:: 0.24.0 Parameters ---------- dtype : str or numpy.dtype, optional The dtype to pass to :meth:`numpy.asarray`. copy : bool, default False Whether to ensure that the returned value is a not a view on another array. Note that ``copy=False`` does not *ensure* that ``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that a copy is made, even if not strictly necessary. na_value : Any, optional The value to use for missing values. The default value depends on `dtype` and the type of the array. .. versionadded:: 1.0.0 **kwargs Additional keywords passed through to the ``to_numpy`` method of the underlying array (for extension arrays). .. versionadded:: 1.0.0 Returns ------- numpy.ndarray See Also -------- Series.array : Get the actual data stored within. Index.array : Get the actual data stored within. DataFrame.to_numpy : Similar method for DataFrame. Notes ----- The returned array will be the same up to equality (values equal in `self` will be equal in the returned array; likewise for values that are not equal). When `self` contains an ExtensionArray, the dtype may be different. For example, for a category-dtype Series, ``to_numpy()`` will return a NumPy array and the categorical dtype will be lost. For NumPy dtypes, this will be a reference to the actual data stored in this Series or Index (assuming ``copy=False``). Modifying the result in place will modify the data stored in the Series or Index (not that we recommend doing that). For extension types, ``to_numpy()`` *may* require copying data and coercing the result to a NumPy type (possibly object), which may be expensive. When you need a no-copy reference to the underlying data, :attr:`Series.array` should be used instead. This table lays out the different dtypes and default return types of ``to_numpy()`` for various dtypes within pandas. ================== ================================ dtype array type ================== ================================ category[T] ndarray[T] (same dtype as input) period ndarray[object] (Periods) interval ndarray[object] (Intervals) IntegerNA ndarray[object] datetime64[ns] datetime64[ns] datetime64[ns, tz] ndarray[object] (Timestamps) ================== ================================ Examples -------- >>> ser = pd.Series(pd.Categorical(['a', 'b', 'a'])) >>> ser.to_numpy() array(['a', 'b', 'a'], dtype=object) Specify the `dtype` to control how datetime-aware data is represented. Use ``dtype=object`` to return an ndarray of pandas :class:`Timestamp` objects, each with the correct ``tz``. >>> ser = pd.Series(pd.date_range('2000', periods=2, tz="CET")) >>> ser.to_numpy(dtype=object) array([Timestamp('2000-01-01 00:00:00+0100', tz='CET', freq='D'), Timestamp('2000-01-02 00:00:00+0100', tz='CET', freq='D')], dtype=object) Or ``dtype='datetime64[ns]'`` to return an ndarray of native datetime64 values. The values are converted to UTC and the timezone info is dropped. >>> ser.to_numpy(dtype="datetime64[ns]") ... # doctest: +ELLIPSIS array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00...'], dtype='datetime64[ns]') """ if is_extension_array_dtype(self.dtype): return self.array.to_numpy(dtype, copy=copy, na_value=na_value, **kwargs) else: if kwargs: msg = "to_numpy() got an unexpected keyword argument '{}'".format( list(kwargs.keys())[0] ) raise TypeError(msg) result = np.asarray(self._values, dtype=dtype) # TODO(GH-24345): Avoid potential double copy if copy or na_value is not lib.no_default: result = result.copy() if na_value is not lib.no_default: result[self.isna()] = na_value return result
[ "def", "to_numpy", "(", "self", ",", "dtype", "=", "None", ",", "copy", "=", "False", ",", "na_value", "=", "lib", ".", "no_default", ",", "*", "*", "kwargs", ")", ":", "if", "is_extension_array_dtype", "(", "self", ".", "dtype", ")", ":", "return", "self", ".", "array", ".", "to_numpy", "(", "dtype", ",", "copy", "=", "copy", ",", "na_value", "=", "na_value", ",", "*", "*", "kwargs", ")", "else", ":", "if", "kwargs", ":", "msg", "=", "\"to_numpy() got an unexpected keyword argument '{}'\"", ".", "format", "(", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "[", "0", "]", ")", "raise", "TypeError", "(", "msg", ")", "result", "=", "np", ".", "asarray", "(", "self", ".", "_values", ",", "dtype", "=", "dtype", ")", "# TODO(GH-24345): Avoid potential double copy", "if", "copy", "or", "na_value", "is", "not", "lib", ".", "no_default", ":", "result", "=", "result", ".", "copy", "(", ")", "if", "na_value", "is", "not", "lib", ".", "no_default", ":", "result", "[", "self", ".", "isna", "(", ")", "]", "=", "na_value", "return", "result" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemMetric/v1/AWS/python/windows/Lib/pandas/core/base.py#L741-L851
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/connection.py
python
HTTPConnection.request_chunked
(self, method, url, body=None, headers=None)
Alternative to the common request method, which sends the body with chunked encoding and not as one block
Alternative to the common request method, which sends the body with chunked encoding and not as one block
[ "Alternative", "to", "the", "common", "request", "method", "which", "sends", "the", "body", "with", "chunked", "encoding", "and", "not", "as", "one", "block" ]
def request_chunked(self, method, url, body=None, headers=None): """ Alternative to the common request method, which sends the body with chunked encoding and not as one block """ headers = HTTPHeaderDict(headers if headers is not None else {}) skip_accept_encoding = "accept-encoding" in headers skip_host = "host" in headers self.putrequest( method, url, skip_accept_encoding=skip_accept_encoding, skip_host=skip_host ) for header, value in headers.items(): self.putheader(header, value) if "transfer-encoding" not in headers: self.putheader("Transfer-Encoding", "chunked") self.endheaders() if body is not None: stringish_types = six.string_types + (bytes,) if isinstance(body, stringish_types): body = (body,) for chunk in body: if not chunk: continue if not isinstance(chunk, bytes): chunk = chunk.encode("utf8") len_str = hex(len(chunk))[2:] self.send(len_str.encode("utf-8")) self.send(b"\r\n") self.send(chunk) self.send(b"\r\n") # After the if clause, to always have a closed body self.send(b"0\r\n\r\n")
[ "def", "request_chunked", "(", "self", ",", "method", ",", "url", ",", "body", "=", "None", ",", "headers", "=", "None", ")", ":", "headers", "=", "HTTPHeaderDict", "(", "headers", "if", "headers", "is", "not", "None", "else", "{", "}", ")", "skip_accept_encoding", "=", "\"accept-encoding\"", "in", "headers", "skip_host", "=", "\"host\"", "in", "headers", "self", ".", "putrequest", "(", "method", ",", "url", ",", "skip_accept_encoding", "=", "skip_accept_encoding", ",", "skip_host", "=", "skip_host", ")", "for", "header", ",", "value", "in", "headers", ".", "items", "(", ")", ":", "self", ".", "putheader", "(", "header", ",", "value", ")", "if", "\"transfer-encoding\"", "not", "in", "headers", ":", "self", ".", "putheader", "(", "\"Transfer-Encoding\"", ",", "\"chunked\"", ")", "self", ".", "endheaders", "(", ")", "if", "body", "is", "not", "None", ":", "stringish_types", "=", "six", ".", "string_types", "+", "(", "bytes", ",", ")", "if", "isinstance", "(", "body", ",", "stringish_types", ")", ":", "body", "=", "(", "body", ",", ")", "for", "chunk", "in", "body", ":", "if", "not", "chunk", ":", "continue", "if", "not", "isinstance", "(", "chunk", ",", "bytes", ")", ":", "chunk", "=", "chunk", ".", "encode", "(", "\"utf8\"", ")", "len_str", "=", "hex", "(", "len", "(", "chunk", ")", ")", "[", "2", ":", "]", "self", ".", "send", "(", "len_str", ".", "encode", "(", "\"utf-8\"", ")", ")", "self", ".", "send", "(", "b\"\\r\\n\"", ")", "self", ".", "send", "(", "chunk", ")", "self", ".", "send", "(", "b\"\\r\\n\"", ")", "# After the if clause, to always have a closed body", "self", ".", "send", "(", "b\"0\\r\\n\\r\\n\"", ")" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Gems/CloudGemFramework/v1/AWS/common-code/lib/urllib3/connection.py#L187-L220
naver/sling
5671cd445a2caae0b4dd0332299e4cfede05062c
webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/standalone.py
python
WebSocketServer.get_request
(self)
return accepted_socket, client_address
Override TCPServer.get_request to wrap OpenSSL.SSL.Connection object with _StandaloneSSLConnection to provide makefile method. We cannot substitute OpenSSL.SSL.Connection.makefile since it's readonly attribute.
Override TCPServer.get_request to wrap OpenSSL.SSL.Connection object with _StandaloneSSLConnection to provide makefile method. We cannot substitute OpenSSL.SSL.Connection.makefile since it's readonly attribute.
[ "Override", "TCPServer", ".", "get_request", "to", "wrap", "OpenSSL", ".", "SSL", ".", "Connection", "object", "with", "_StandaloneSSLConnection", "to", "provide", "makefile", "method", ".", "We", "cannot", "substitute", "OpenSSL", ".", "SSL", ".", "Connection", ".", "makefile", "since", "it", "s", "readonly", "attribute", "." ]
def get_request(self): """Override TCPServer.get_request to wrap OpenSSL.SSL.Connection object with _StandaloneSSLConnection to provide makefile method. We cannot substitute OpenSSL.SSL.Connection.makefile since it's readonly attribute. """ accepted_socket, client_address = self.socket.accept() server_options = self.websocket_server_options if server_options.use_tls: if server_options.tls_module == _TLS_BY_STANDARD_MODULE: try: accepted_socket.do_handshake() except ssl.SSLError, e: self._logger.debug('%r', e) raise # Print cipher in use. Handshake is done on accept. self._logger.debug('Cipher: %s', accepted_socket.cipher()) self._logger.debug('Client cert: %r', accepted_socket.getpeercert()) elif server_options.tls_module == _TLS_BY_PYOPENSSL: # We cannot print the cipher in use. pyOpenSSL doesn't provide # any method to fetch that. ctx = OpenSSL.SSL.Context(OpenSSL.SSL.SSLv23_METHOD) ctx.use_privatekey_file(server_options.private_key) ctx.use_certificate_file(server_options.certificate) def default_callback(conn, cert, errnum, errdepth, ok): return ok == 1 # See the OpenSSL document for SSL_CTX_set_verify. if server_options.tls_client_auth: verify_mode = OpenSSL.SSL.VERIFY_PEER if not server_options.tls_client_cert_optional: verify_mode |= OpenSSL.SSL.VERIFY_FAIL_IF_NO_PEER_CERT ctx.set_verify(verify_mode, default_callback) ctx.load_verify_locations(server_options.tls_client_ca, None) else: ctx.set_verify(OpenSSL.SSL.VERIFY_NONE, default_callback) accepted_socket = OpenSSL.SSL.Connection(ctx, accepted_socket) accepted_socket.set_accept_state() # Convert SSL related error into socket.error so that # SocketServer ignores them and keeps running. # # TODO(tyoshino): Convert all kinds of errors. try: accepted_socket.do_handshake() except OpenSSL.SSL.Error, e: # Set errno part to 1 (SSL_ERROR_SSL) like the ssl module # does. self._logger.debug('%r', e) raise socket.error(1, '%r' % e) cert = accepted_socket.get_peer_certificate() self._logger.debug('Client cert subject: %r', cert.get_subject().get_components()) accepted_socket = _StandaloneSSLConnection(accepted_socket) else: raise ValueError('No TLS support module is available') return accepted_socket, client_address
[ "def", "get_request", "(", "self", ")", ":", "accepted_socket", ",", "client_address", "=", "self", ".", "socket", ".", "accept", "(", ")", "server_options", "=", "self", ".", "websocket_server_options", "if", "server_options", ".", "use_tls", ":", "if", "server_options", ".", "tls_module", "==", "_TLS_BY_STANDARD_MODULE", ":", "try", ":", "accepted_socket", ".", "do_handshake", "(", ")", "except", "ssl", ".", "SSLError", ",", "e", ":", "self", ".", "_logger", ".", "debug", "(", "'%r'", ",", "e", ")", "raise", "# Print cipher in use. Handshake is done on accept.", "self", ".", "_logger", ".", "debug", "(", "'Cipher: %s'", ",", "accepted_socket", ".", "cipher", "(", ")", ")", "self", ".", "_logger", ".", "debug", "(", "'Client cert: %r'", ",", "accepted_socket", ".", "getpeercert", "(", ")", ")", "elif", "server_options", ".", "tls_module", "==", "_TLS_BY_PYOPENSSL", ":", "# We cannot print the cipher in use. pyOpenSSL doesn't provide", "# any method to fetch that.", "ctx", "=", "OpenSSL", ".", "SSL", ".", "Context", "(", "OpenSSL", ".", "SSL", ".", "SSLv23_METHOD", ")", "ctx", ".", "use_privatekey_file", "(", "server_options", ".", "private_key", ")", "ctx", ".", "use_certificate_file", "(", "server_options", ".", "certificate", ")", "def", "default_callback", "(", "conn", ",", "cert", ",", "errnum", ",", "errdepth", ",", "ok", ")", ":", "return", "ok", "==", "1", "# See the OpenSSL document for SSL_CTX_set_verify.", "if", "server_options", ".", "tls_client_auth", ":", "verify_mode", "=", "OpenSSL", ".", "SSL", ".", "VERIFY_PEER", "if", "not", "server_options", ".", "tls_client_cert_optional", ":", "verify_mode", "|=", "OpenSSL", ".", "SSL", ".", "VERIFY_FAIL_IF_NO_PEER_CERT", "ctx", ".", "set_verify", "(", "verify_mode", ",", "default_callback", ")", "ctx", ".", "load_verify_locations", "(", "server_options", ".", "tls_client_ca", ",", "None", ")", "else", ":", "ctx", ".", "set_verify", "(", "OpenSSL", ".", "SSL", ".", "VERIFY_NONE", ",", "default_callback", ")", "accepted_socket", "=", "OpenSSL", ".", "SSL", ".", "Connection", "(", "ctx", ",", "accepted_socket", ")", "accepted_socket", ".", "set_accept_state", "(", ")", "# Convert SSL related error into socket.error so that", "# SocketServer ignores them and keeps running.", "#", "# TODO(tyoshino): Convert all kinds of errors.", "try", ":", "accepted_socket", ".", "do_handshake", "(", ")", "except", "OpenSSL", ".", "SSL", ".", "Error", ",", "e", ":", "# Set errno part to 1 (SSL_ERROR_SSL) like the ssl module", "# does.", "self", ".", "_logger", ".", "debug", "(", "'%r'", ",", "e", ")", "raise", "socket", ".", "error", "(", "1", ",", "'%r'", "%", "e", ")", "cert", "=", "accepted_socket", ".", "get_peer_certificate", "(", ")", "self", ".", "_logger", ".", "debug", "(", "'Client cert subject: %r'", ",", "cert", ".", "get_subject", "(", ")", ".", "get_components", "(", ")", ")", "accepted_socket", "=", "_StandaloneSSLConnection", "(", "accepted_socket", ")", "else", ":", "raise", "ValueError", "(", "'No TLS support module is available'", ")", "return", "accepted_socket", ",", "client_address" ]
https://github.com/naver/sling/blob/5671cd445a2caae0b4dd0332299e4cfede05062c/webkit/Tools/Scripts/webkitpy/thirdparty/mod_pywebsocket/standalone.py#L527-L592
wxWidgets/wxPython-Classic
19571e1ae65f1ac445f5491474121998c97a1bf0
wx/lib/agw/aui/auibook.py
python
AuiTabCtrl.OnMiddleDown
(self, event)
Handles the ``wx.EVT_MIDDLE_DOWN`` event for :class:`AuiTabCtrl`. :param `event`: a :class:`MouseEvent` event to be processed.
Handles the ``wx.EVT_MIDDLE_DOWN`` event for :class:`AuiTabCtrl`.
[ "Handles", "the", "wx", ".", "EVT_MIDDLE_DOWN", "event", "for", ":", "class", ":", "AuiTabCtrl", "." ]
def OnMiddleDown(self, event): """ Handles the ``wx.EVT_MIDDLE_DOWN`` event for :class:`AuiTabCtrl`. :param `event`: a :class:`MouseEvent` event to be processed. """ self.StopTooltipTimer() eventHandler = self.GetEventHandler() if not isinstance(eventHandler, AuiTabCtrl): event.Skip() return x, y = event.GetX(), event.GetY() wnd = self.TabHitTest(x, y) if wnd: e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_TAB_MIDDLE_DOWN, self.GetId()) e.SetEventObject(self) e.Page = wnd e.SetSelection(self.GetIdxFromWindow(wnd)) self.GetEventHandler().ProcessEvent(e) elif not self.ButtonHitTest(x, y): e = AuiNotebookEvent(wxEVT_COMMAND_AUINOTEBOOK_BG_MIDDLE_DOWN, self.GetId()) e.SetEventObject(self) self.GetEventHandler().ProcessEvent(e)
[ "def", "OnMiddleDown", "(", "self", ",", "event", ")", ":", "self", ".", "StopTooltipTimer", "(", ")", "eventHandler", "=", "self", ".", "GetEventHandler", "(", ")", "if", "not", "isinstance", "(", "eventHandler", ",", "AuiTabCtrl", ")", ":", "event", ".", "Skip", "(", ")", "return", "x", ",", "y", "=", "event", ".", "GetX", "(", ")", ",", "event", ".", "GetY", "(", ")", "wnd", "=", "self", ".", "TabHitTest", "(", "x", ",", "y", ")", "if", "wnd", ":", "e", "=", "AuiNotebookEvent", "(", "wxEVT_COMMAND_AUINOTEBOOK_TAB_MIDDLE_DOWN", ",", "self", ".", "GetId", "(", ")", ")", "e", ".", "SetEventObject", "(", "self", ")", "e", ".", "Page", "=", "wnd", "e", ".", "SetSelection", "(", "self", ".", "GetIdxFromWindow", "(", "wnd", ")", ")", "self", ".", "GetEventHandler", "(", ")", ".", "ProcessEvent", "(", "e", ")", "elif", "not", "self", ".", "ButtonHitTest", "(", "x", ",", "y", ")", ":", "e", "=", "AuiNotebookEvent", "(", "wxEVT_COMMAND_AUINOTEBOOK_BG_MIDDLE_DOWN", ",", "self", ".", "GetId", "(", ")", ")", "e", ".", "SetEventObject", "(", "self", ")", "self", ".", "GetEventHandler", "(", ")", ".", "ProcessEvent", "(", "e", ")" ]
https://github.com/wxWidgets/wxPython-Classic/blob/19571e1ae65f1ac445f5491474121998c97a1bf0/wx/lib/agw/aui/auibook.py#L2090-L2116
aws/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/msvc.py
python
EnvironmentInfo.NetFxSDKLibraries
(self)
return [join(self.si.NetFxSdkDir, r'lib\um%s' % arch_subdir)]
Microsoft .Net Framework SDK Libraries. Return ------ list of str paths
Microsoft .Net Framework SDK Libraries.
[ "Microsoft", ".", "Net", "Framework", "SDK", "Libraries", "." ]
def NetFxSDKLibraries(self): """ Microsoft .Net Framework SDK Libraries. Return ------ list of str paths """ if self.vs_ver < 14.0 or not self.si.NetFxSdkDir: return [] arch_subdir = self.pi.target_dir(x64=True) return [join(self.si.NetFxSdkDir, r'lib\um%s' % arch_subdir)]
[ "def", "NetFxSDKLibraries", "(", "self", ")", ":", "if", "self", ".", "vs_ver", "<", "14.0", "or", "not", "self", ".", "si", ".", "NetFxSdkDir", ":", "return", "[", "]", "arch_subdir", "=", "self", ".", "pi", ".", "target_dir", "(", "x64", "=", "True", ")", "return", "[", "join", "(", "self", ".", "si", ".", "NetFxSdkDir", ",", "r'lib\\um%s'", "%", "arch_subdir", ")", "]" ]
https://github.com/aws/lumberyard/blob/f85344403c1c2e77ec8c75deb2c116e97b713217/dev/Tools/Python/3.7.10/linux_x64/lib/python3.7/site-packages/setuptools/msvc.py#L1538-L1551
PolygonTek/BlueshiftEngine
fbc374cbc391e1147c744649f405a66a27c35d89
Source/ThirdParty/freetype/src/tools/glnames.py
python
main
()
main program body
main program body
[ "main", "program", "body" ]
def main(): """main program body""" if len( sys.argv ) != 2: print __doc__ % sys.argv[0] sys.exit( 1 ) file = open( sys.argv[1], "wb" ) write = file.write count_sid = len( sid_standard_names ) # `mac_extras' contains the list of glyph names in the Macintosh standard # encoding which are not in the SID Standard Names. # mac_extras = filter_glyph_names( mac_standard_names, sid_standard_names ) # `base_list' contains the names of our final glyph names table. # It consists of the `mac_extras' glyph names, followed by the SID # standard names. # mac_extras_count = len( mac_extras ) base_list = mac_extras + sid_standard_names write( "/****************************************************************************\n" ) write( " *\n" ) write( " * %-71s\n" % os.path.basename( sys.argv[1] ) ) write( " *\n" ) write( " * PostScript glyph names.\n" ) write( " *\n" ) write( " * Copyright 2005-2019 by\n" ) write( " * David Turner, Robert Wilhelm, and Werner Lemberg.\n" ) write( " *\n" ) write( " * This file is part of the FreeType project, and may only be used,\n" ) write( " * modified, and distributed under the terms of the FreeType project\n" ) write( " * license, LICENSE.TXT. By continuing to use, modify, or distribute\n" ) write( " * this file you indicate that you have read the license and\n" ) write( " * understand and accept it fully.\n" ) write( " *\n" ) write( " */\n" ) write( "\n" ) write( "\n" ) write( " /* This file has been generated automatically -- do not edit! */\n" ) write( "\n" ) write( "\n" ) # dump final glyph list (mac extras + sid standard names) # st = StringTable( base_list, "ft_standard_glyph_names" ) st.dump( file ) st.dump_sublist( file, "ft_mac_names", "FT_NUM_MAC_NAMES", mac_standard_names ) st.dump_sublist( file, "ft_sid_names", "FT_NUM_SID_NAMES", sid_standard_names ) dump_encoding( file, "t1_standard_encoding", t1_standard_encoding ) dump_encoding( file, "t1_expert_encoding", t1_expert_encoding ) # dump the AGL in its compressed form # agl_glyphs, agl_values = adobe_glyph_values() dict = StringNode( "", 0 ) for g in range( len( agl_glyphs ) ): dict.add( agl_glyphs[g], eval( "0x" + agl_values[g] ) ) dict = dict.optimize() dict_len = dict.locate( 0 ) dict_array = dict.store( "" ) write( """\ /* * This table is a compressed version of the Adobe Glyph List (AGL), * optimized for efficient searching. It has been generated by the * `glnames.py' python script located in the `src/tools' directory. * * The lookup function to get the Unicode value for a given string * is defined below the table. */ #ifdef FT_CONFIG_OPTION_ADOBE_GLYPH_LIST """ ) dump_array( dict_array, write, "ft_adobe_glyph_list" ) # write the lookup routine now # write( """\ #ifdef DEFINE_PS_TABLES /* * This function searches the compressed table efficiently. */ static unsigned long ft_get_adobe_glyph_index( const char* name, const char* limit ) { int c = 0; int count, min, max; const unsigned char* p = ft_adobe_glyph_list; if ( name == 0 || name >= limit ) goto NotFound; c = *name++; count = p[1]; p += 2; min = 0; max = count; while ( min < max ) { int mid = ( min + max ) >> 1; const unsigned char* q = p + mid * 2; int c2; q = ft_adobe_glyph_list + ( ( (int)q[0] << 8 ) | q[1] ); c2 = q[0] & 127; if ( c2 == c ) { p = q; goto Found; } if ( c2 < c ) min = mid + 1; else max = mid; } goto NotFound; Found: for (;;) { /* assert (*p & 127) == c */ if ( name >= limit ) { if ( (p[0] & 128) == 0 && (p[1] & 128) != 0 ) return (unsigned long)( ( (int)p[2] << 8 ) | p[3] ); goto NotFound; } c = *name++; if ( p[0] & 128 ) { p++; if ( c != (p[0] & 127) ) goto NotFound; continue; } p++; count = p[0] & 127; if ( p[0] & 128 ) p += 2; p++; for ( ; count > 0; count--, p += 2 ) { int offset = ( (int)p[0] << 8 ) | p[1]; const unsigned char* q = ft_adobe_glyph_list + offset; if ( c == ( q[0] & 127 ) ) { p = q; goto NextIter; } } goto NotFound; NextIter: ; } NotFound: return 0; } #endif /* DEFINE_PS_TABLES */ #endif /* FT_CONFIG_OPTION_ADOBE_GLYPH_LIST */ """ ) if 0: # generate unit test, or don't # # now write the unit test to check that everything works OK # write( "#ifdef TEST\n\n" ) write( "static const char* const the_names[] = {\n" ) for name in agl_glyphs: write( ' "' + name + '",\n' ) write( " 0\n};\n" ) write( "static const unsigned long the_values[] = {\n" ) for val in agl_values: write( ' 0x' + val + ',\n' ) write( " 0\n};\n" ) write( """ #include <stdlib.h> #include <stdio.h> int main( void ) { int result = 0; const char* const* names = the_names; const unsigned long* values = the_values; for ( ; *names; names++, values++ ) { const char* name = *names; unsigned long reference = *values; unsigned long value; value = ft_get_adobe_glyph_index( name, name + strlen( name ) ); if ( value != reference ) { result = 1; fprintf( stderr, "name '%s' => %04x instead of %04x\\n", name, value, reference ); } } return result; } """ ) write( "#endif /* TEST */\n" ) write("\n/* END */\n")
[ "def", "main", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", "!=", "2", ":", "print", "__doc__", "%", "sys", ".", "argv", "[", "0", "]", "sys", ".", "exit", "(", "1", ")", "file", "=", "open", "(", "sys", ".", "argv", "[", "1", "]", ",", "\"wb\"", ")", "write", "=", "file", ".", "write", "count_sid", "=", "len", "(", "sid_standard_names", ")", "# `mac_extras' contains the list of glyph names in the Macintosh standard", "# encoding which are not in the SID Standard Names.", "#", "mac_extras", "=", "filter_glyph_names", "(", "mac_standard_names", ",", "sid_standard_names", ")", "# `base_list' contains the names of our final glyph names table.", "# It consists of the `mac_extras' glyph names, followed by the SID", "# standard names.", "#", "mac_extras_count", "=", "len", "(", "mac_extras", ")", "base_list", "=", "mac_extras", "+", "sid_standard_names", "write", "(", "\"/****************************************************************************\\n\"", ")", "write", "(", "\" *\\n\"", ")", "write", "(", "\" * %-71s\\n\"", "%", "os", ".", "path", ".", "basename", "(", "sys", ".", "argv", "[", "1", "]", ")", ")", "write", "(", "\" *\\n\"", ")", "write", "(", "\" * PostScript glyph names.\\n\"", ")", "write", "(", "\" *\\n\"", ")", "write", "(", "\" * Copyright 2005-2019 by\\n\"", ")", "write", "(", "\" * David Turner, Robert Wilhelm, and Werner Lemberg.\\n\"", ")", "write", "(", "\" *\\n\"", ")", "write", "(", "\" * This file is part of the FreeType project, and may only be used,\\n\"", ")", "write", "(", "\" * modified, and distributed under the terms of the FreeType project\\n\"", ")", "write", "(", "\" * license, LICENSE.TXT. By continuing to use, modify, or distribute\\n\"", ")", "write", "(", "\" * this file you indicate that you have read the license and\\n\"", ")", "write", "(", "\" * understand and accept it fully.\\n\"", ")", "write", "(", "\" *\\n\"", ")", "write", "(", "\" */\\n\"", ")", "write", "(", "\"\\n\"", ")", "write", "(", "\"\\n\"", ")", "write", "(", "\" /* This file has been generated automatically -- do not edit! */\\n\"", ")", "write", "(", "\"\\n\"", ")", "write", "(", "\"\\n\"", ")", "# dump final glyph list (mac extras + sid standard names)", "#", "st", "=", "StringTable", "(", "base_list", ",", "\"ft_standard_glyph_names\"", ")", "st", ".", "dump", "(", "file", ")", "st", ".", "dump_sublist", "(", "file", ",", "\"ft_mac_names\"", ",", "\"FT_NUM_MAC_NAMES\"", ",", "mac_standard_names", ")", "st", ".", "dump_sublist", "(", "file", ",", "\"ft_sid_names\"", ",", "\"FT_NUM_SID_NAMES\"", ",", "sid_standard_names", ")", "dump_encoding", "(", "file", ",", "\"t1_standard_encoding\"", ",", "t1_standard_encoding", ")", "dump_encoding", "(", "file", ",", "\"t1_expert_encoding\"", ",", "t1_expert_encoding", ")", "# dump the AGL in its compressed form", "#", "agl_glyphs", ",", "agl_values", "=", "adobe_glyph_values", "(", ")", "dict", "=", "StringNode", "(", "\"\"", ",", "0", ")", "for", "g", "in", "range", "(", "len", "(", "agl_glyphs", ")", ")", ":", "dict", ".", "add", "(", "agl_glyphs", "[", "g", "]", ",", "eval", "(", "\"0x\"", "+", "agl_values", "[", "g", "]", ")", ")", "dict", "=", "dict", ".", "optimize", "(", ")", "dict_len", "=", "dict", ".", "locate", "(", "0", ")", "dict_array", "=", "dict", ".", "store", "(", "\"\"", ")", "write", "(", "\"\"\"\\\n /*\n * This table is a compressed version of the Adobe Glyph List (AGL),\n * optimized for efficient searching. It has been generated by the\n * `glnames.py' python script located in the `src/tools' directory.\n *\n * The lookup function to get the Unicode value for a given string\n * is defined below the table.\n */\n\n#ifdef FT_CONFIG_OPTION_ADOBE_GLYPH_LIST\n\n\"\"\"", ")", "dump_array", "(", "dict_array", ",", "write", ",", "\"ft_adobe_glyph_list\"", ")", "# write the lookup routine now", "#", "write", "(", "\"\"\"\\\n#ifdef DEFINE_PS_TABLES\n /*\n * This function searches the compressed table efficiently.\n */\n static unsigned long\n ft_get_adobe_glyph_index( const char* name,\n const char* limit )\n {\n int c = 0;\n int count, min, max;\n const unsigned char* p = ft_adobe_glyph_list;\n\n\n if ( name == 0 || name >= limit )\n goto NotFound;\n\n c = *name++;\n count = p[1];\n p += 2;\n\n min = 0;\n max = count;\n\n while ( min < max )\n {\n int mid = ( min + max ) >> 1;\n const unsigned char* q = p + mid * 2;\n int c2;\n\n\n q = ft_adobe_glyph_list + ( ( (int)q[0] << 8 ) | q[1] );\n\n c2 = q[0] & 127;\n if ( c2 == c )\n {\n p = q;\n goto Found;\n }\n if ( c2 < c )\n min = mid + 1;\n else\n max = mid;\n }\n goto NotFound;\n\n Found:\n for (;;)\n {\n /* assert (*p & 127) == c */\n\n if ( name >= limit )\n {\n if ( (p[0] & 128) == 0 &&\n (p[1] & 128) != 0 )\n return (unsigned long)( ( (int)p[2] << 8 ) | p[3] );\n\n goto NotFound;\n }\n c = *name++;\n if ( p[0] & 128 )\n {\n p++;\n if ( c != (p[0] & 127) )\n goto NotFound;\n\n continue;\n }\n\n p++;\n count = p[0] & 127;\n if ( p[0] & 128 )\n p += 2;\n\n p++;\n\n for ( ; count > 0; count--, p += 2 )\n {\n int offset = ( (int)p[0] << 8 ) | p[1];\n const unsigned char* q = ft_adobe_glyph_list + offset;\n\n if ( c == ( q[0] & 127 ) )\n {\n p = q;\n goto NextIter;\n }\n }\n goto NotFound;\n\n NextIter:\n ;\n }\n\n NotFound:\n return 0;\n }\n#endif /* DEFINE_PS_TABLES */\n\n#endif /* FT_CONFIG_OPTION_ADOBE_GLYPH_LIST */\n\n\"\"\"", ")", "if", "0", ":", "# generate unit test, or don't", "#", "# now write the unit test to check that everything works OK", "#", "write", "(", "\"#ifdef TEST\\n\\n\"", ")", "write", "(", "\"static const char* const the_names[] = {\\n\"", ")", "for", "name", "in", "agl_glyphs", ":", "write", "(", "' \"'", "+", "name", "+", "'\",\\n'", ")", "write", "(", "\" 0\\n};\\n\"", ")", "write", "(", "\"static const unsigned long the_values[] = {\\n\"", ")", "for", "val", "in", "agl_values", ":", "write", "(", "' 0x'", "+", "val", "+", "',\\n'", ")", "write", "(", "\" 0\\n};\\n\"", ")", "write", "(", "\"\"\"\n#include <stdlib.h>\n#include <stdio.h>\n\n int\n main( void )\n {\n int result = 0;\n const char* const* names = the_names;\n const unsigned long* values = the_values;\n\n\n for ( ; *names; names++, values++ )\n {\n const char* name = *names;\n unsigned long reference = *values;\n unsigned long value;\n\n\n value = ft_get_adobe_glyph_index( name, name + strlen( name ) );\n if ( value != reference )\n {\n result = 1;\n fprintf( stderr, \"name '%s' => %04x instead of %04x\\\\n\",\n name, value, reference );\n }\n }\n\n return result;\n }\n\"\"\"", ")", "write", "(", "\"#endif /* TEST */\\n\"", ")", "write", "(", "\"\\n/* END */\\n\"", ")" ]
https://github.com/PolygonTek/BlueshiftEngine/blob/fbc374cbc391e1147c744649f405a66a27c35d89/Source/ThirdParty/freetype/src/tools/glnames.py#L5289-L5532
tensorflow/tensorflow
419e3a6b650ea4bd1b0cba23c4348f8a69f3272e
tensorflow/python/eager/function.py
python
ConcreteFunction.set_external_captures
(self, captures)
Updates the function capture values. The new values must have tensor types and shapes consistent with the original captures of the concrete function, but it is allowed to change a value captured with a deferred one and vice-versa. Args: captures: A list of tensors or closures. Tensors are value captures, and closures are call-time (deferred captures).
Updates the function capture values.
[ "Updates", "the", "function", "capture", "values", "." ]
def set_external_captures(self, captures): """Updates the function capture values. The new values must have tensor types and shapes consistent with the original captures of the concrete function, but it is allowed to change a value captured with a deferred one and vice-versa. Args: captures: A list of tensors or closures. Tensors are value captures, and closures are call-time (deferred captures). """ # TODO(wxinyi): 1. verify that the new captures' type spec is compatible # with the original's. However, doing so requires MirroredVariable captures # initialized. 2. replace the original/new captures/deferred # captures in the wrapped graph. Doing such for a capture-to-deferred # capture replacement requires more arguments than the deferred capture # itself, e.g. default value, spec. self._captured_inputs = captures
[ "def", "set_external_captures", "(", "self", ",", "captures", ")", ":", "# TODO(wxinyi): 1. verify that the new captures' type spec is compatible", "# with the original's. However, doing so requires MirroredVariable captures", "# initialized. 2. replace the original/new captures/deferred", "# captures in the wrapped graph. Doing such for a capture-to-deferred", "# capture replacement requires more arguments than the deferred capture", "# itself, e.g. default value, spec.", "self", ".", "_captured_inputs", "=", "captures" ]
https://github.com/tensorflow/tensorflow/blob/419e3a6b650ea4bd1b0cba23c4348f8a69f3272e/tensorflow/python/eager/function.py#L1945-L1962
baidu-research/tensorflow-allreduce
66d5b855e90b0949e9fa5cca5599fd729a70e874
tensorflow/examples/learn/text_classification_character_rnn.py
python
char_rnn_model
(features, labels, mode)
return tf.estimator.EstimatorSpec( mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)
Character level recurrent neural network model to predict classes.
Character level recurrent neural network model to predict classes.
[ "Character", "level", "recurrent", "neural", "network", "model", "to", "predict", "classes", "." ]
def char_rnn_model(features, labels, mode): """Character level recurrent neural network model to predict classes.""" byte_vectors = tf.one_hot(features[CHARS_FEATURE], 256, 1., 0.) byte_list = tf.unstack(byte_vectors, axis=1) cell = tf.contrib.rnn.GRUCell(HIDDEN_SIZE) _, encoding = tf.contrib.rnn.static_rnn(cell, byte_list, dtype=tf.float32) logits = tf.layers.dense(encoding, MAX_LABEL, activation=None) predicted_classes = tf.argmax(logits, 1) if mode == tf.estimator.ModeKeys.PREDICT: return tf.estimator.EstimatorSpec( mode=mode, predictions={ 'class': predicted_classes, 'prob': tf.nn.softmax(logits) }) onehot_labels = tf.one_hot(labels, MAX_LABEL, 1, 0) loss = tf.losses.softmax_cross_entropy( onehot_labels=onehot_labels, logits=logits) if mode == tf.estimator.ModeKeys.TRAIN: optimizer = tf.train.AdamOptimizer(learning_rate=0.01) train_op = optimizer.minimize(loss, global_step=tf.train.get_global_step()) return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op) eval_metric_ops = { 'accuracy': tf.metrics.accuracy( labels=labels, predictions=predicted_classes) } return tf.estimator.EstimatorSpec( mode=mode, loss=loss, eval_metric_ops=eval_metric_ops)
[ "def", "char_rnn_model", "(", "features", ",", "labels", ",", "mode", ")", ":", "byte_vectors", "=", "tf", ".", "one_hot", "(", "features", "[", "CHARS_FEATURE", "]", ",", "256", ",", "1.", ",", "0.", ")", "byte_list", "=", "tf", ".", "unstack", "(", "byte_vectors", ",", "axis", "=", "1", ")", "cell", "=", "tf", ".", "contrib", ".", "rnn", ".", "GRUCell", "(", "HIDDEN_SIZE", ")", "_", ",", "encoding", "=", "tf", ".", "contrib", ".", "rnn", ".", "static_rnn", "(", "cell", ",", "byte_list", ",", "dtype", "=", "tf", ".", "float32", ")", "logits", "=", "tf", ".", "layers", ".", "dense", "(", "encoding", ",", "MAX_LABEL", ",", "activation", "=", "None", ")", "predicted_classes", "=", "tf", ".", "argmax", "(", "logits", ",", "1", ")", "if", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "PREDICT", ":", "return", "tf", ".", "estimator", ".", "EstimatorSpec", "(", "mode", "=", "mode", ",", "predictions", "=", "{", "'class'", ":", "predicted_classes", ",", "'prob'", ":", "tf", ".", "nn", ".", "softmax", "(", "logits", ")", "}", ")", "onehot_labels", "=", "tf", ".", "one_hot", "(", "labels", ",", "MAX_LABEL", ",", "1", ",", "0", ")", "loss", "=", "tf", ".", "losses", ".", "softmax_cross_entropy", "(", "onehot_labels", "=", "onehot_labels", ",", "logits", "=", "logits", ")", "if", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", ":", "optimizer", "=", "tf", ".", "train", ".", "AdamOptimizer", "(", "learning_rate", "=", "0.01", ")", "train_op", "=", "optimizer", ".", "minimize", "(", "loss", ",", "global_step", "=", "tf", ".", "train", ".", "get_global_step", "(", ")", ")", "return", "tf", ".", "estimator", ".", "EstimatorSpec", "(", "mode", ",", "loss", "=", "loss", ",", "train_op", "=", "train_op", ")", "eval_metric_ops", "=", "{", "'accuracy'", ":", "tf", ".", "metrics", ".", "accuracy", "(", "labels", "=", "labels", ",", "predictions", "=", "predicted_classes", ")", "}", "return", "tf", ".", "estimator", ".", "EstimatorSpec", "(", "mode", "=", "mode", ",", "loss", "=", "loss", ",", "eval_metric_ops", "=", "eval_metric_ops", ")" ]
https://github.com/baidu-research/tensorflow-allreduce/blob/66d5b855e90b0949e9fa5cca5599fd729a70e874/tensorflow/examples/learn/text_classification_character_rnn.py#L44-L76
priyankchheda/algorithms
c361aa9071573fa9966d5b02d05e524815abcf2b
dynamic_connectivity/quick_find.py
python
QuickFind.union
(self, elem1, elem2)
When connecting two objects elem1 and elem2, change the id of all objects that have the id of elem1 to that of elem2, or vice-versa. Time Complexity is O(n), which is too expensive. :param elem1: element 1 :param elem2: element 2
When connecting two objects elem1 and elem2, change the id of all objects that have the id of elem1 to that of elem2, or vice-versa. Time Complexity is O(n), which is too expensive.
[ "When", "connecting", "two", "objects", "elem1", "and", "elem2", "change", "the", "id", "of", "all", "objects", "that", "have", "the", "id", "of", "elem1", "to", "that", "of", "elem2", "or", "vice", "-", "versa", ".", "Time", "Complexity", "is", "O", "(", "n", ")", "which", "is", "too", "expensive", "." ]
def union(self, elem1, elem2): """ When connecting two objects elem1 and elem2, change the id of all objects that have the id of elem1 to that of elem2, or vice-versa. Time Complexity is O(n), which is too expensive. :param elem1: element 1 :param elem2: element 2 """ pid = self.data[elem1] qid = self.data[elem2] for i in range(len(self.data)): if self.data[i] == pid: self.data[i] = qid
[ "def", "union", "(", "self", ",", "elem1", ",", "elem2", ")", ":", "pid", "=", "self", ".", "data", "[", "elem1", "]", "qid", "=", "self", ".", "data", "[", "elem2", "]", "for", "i", "in", "range", "(", "len", "(", "self", ".", "data", ")", ")", ":", "if", "self", ".", "data", "[", "i", "]", "==", "pid", ":", "self", ".", "data", "[", "i", "]", "=", "qid" ]
https://github.com/priyankchheda/algorithms/blob/c361aa9071573fa9966d5b02d05e524815abcf2b/dynamic_connectivity/quick_find.py#L35-L47
catboost/catboost
167f64f237114a4d10b2b4ee42adb4569137debe
contrib/tools/python/src/Lib/mailbox.py
python
mbox._post_message_hook
(self, f)
Called after writing each message to file f.
Called after writing each message to file f.
[ "Called", "after", "writing", "each", "message", "to", "file", "f", "." ]
def _post_message_hook(self, f): """Called after writing each message to file f.""" f.write(os.linesep)
[ "def", "_post_message_hook", "(", "self", ",", "f", ")", ":", "f", ".", "write", "(", "os", ".", "linesep", ")" ]
https://github.com/catboost/catboost/blob/167f64f237114a4d10b2b4ee42adb4569137debe/contrib/tools/python/src/Lib/mailbox.py#L834-L836
google/mysql-protobuf
467cda676afaa49e762c5c9164a43f6ad31a1fbf
protobuf/objectivec/DevTools/pddm.py
python
MacroCollection.Expand
(self, macro_ref_str)
return self._Expand(match, [], macro_ref_str)
Expands the macro reference. Args: macro_ref_str: String of a macro reference (i.e. foo(a, b)). Returns: The text from the expansion. Raises: PDDMError if there are any issues.
Expands the macro reference.
[ "Expands", "the", "macro", "reference", "." ]
def Expand(self, macro_ref_str): """Expands the macro reference. Args: macro_ref_str: String of a macro reference (i.e. foo(a, b)). Returns: The text from the expansion. Raises: PDDMError if there are any issues. """ match = _MACRO_RE.match(macro_ref_str) if match is None or match.group(0) != macro_ref_str: raise PDDMError('Failed to parse macro reference: "%s"' % macro_ref_str) if match.group('name') not in self._macros: raise PDDMError('No macro named "%s".' % match.group('name')) return self._Expand(match, [], macro_ref_str)
[ "def", "Expand", "(", "self", ",", "macro_ref_str", ")", ":", "match", "=", "_MACRO_RE", ".", "match", "(", "macro_ref_str", ")", "if", "match", "is", "None", "or", "match", ".", "group", "(", "0", ")", "!=", "macro_ref_str", ":", "raise", "PDDMError", "(", "'Failed to parse macro reference: \"%s\"'", "%", "macro_ref_str", ")", "if", "match", ".", "group", "(", "'name'", ")", "not", "in", "self", ".", "_macros", ":", "raise", "PDDMError", "(", "'No macro named \"%s\".'", "%", "match", ".", "group", "(", "'name'", ")", ")", "return", "self", ".", "_Expand", "(", "match", ",", "[", "]", ",", "macro_ref_str", ")" ]
https://github.com/google/mysql-protobuf/blob/467cda676afaa49e762c5c9164a43f6ad31a1fbf/protobuf/objectivec/DevTools/pddm.py#L259-L276